src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Scanner;
public class E {
static Scanner sc = new Scanner(System.in);
static int N;
static double[][] p;
static DecimalFormat format = new DecimalFormat("0.000000");
public static void main(String[] args) throws Exception {
N = sc.nextInt();
p = new double[N][N];
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
p[i][j] = sc.nextDouble();
}
}
double[] memo = new double[1 << N];
memo[memo.length - 1] = 1;
for (int i = N; i >= 2; --i) {
int[] live = new int[N];
for (int j = 0; j < i; ++j) {
live[N - 1 - j] = 1;
}
do {
int n = toInt(live);
double norm = 2.0 / i / (i - 1);
for (int f1 = 0; f1 < N; ++f1) {
if (live[f1] == 0) continue;
for (int f2 = f1 + 1; f2 < N; ++f2) {
if (live[f2] == 0) continue;
memo[n - (1 << f1)] += memo[n] * p[f2][f1] * norm;
memo[n - (1 << f2)] += memo[n] * p[f1][f2] * norm;
}
}
} while (nextPermutation(live));
// System.out.println(Arrays.toString(memo));
}
for (int i = 0; i < N; ++i) {
System.out.print(format.format(memo[1 << i]));
if (i < N - 1) {
System.out.print(" ");
}
}
}
static int toInt(int[] a) {
int ret = 0;
for (int i = 0; i < N; ++i) {
ret += (1 << i) * a[i];
}
return ret;
}
public static boolean nextPermutation(int[] a) {
for (int i = a.length - 1; i > 0; --i) {
if (a[i - 1] < a[i]) {
int swapIndex = find(a[i - 1], a, i, a.length - 1);
int temp = a[swapIndex];
a[swapIndex] = a[i - 1];
a[i - 1] = temp;
Arrays.sort(a, i, a.length);
return true;
}
}
return false;
}
private static int find(int dest, int[] a, int s, int e) {
if (s == e) {
return s;
}
int m = (s + e + 1) / 2;
return a[m] <= dest ? find(dest, a, s, m - 1) : find(dest, a, m, e);
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.Scanner;
public class A961_Tetris {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int platforms = input.nextInt();
int in = input.nextInt();
int[] cols = new int[platforms];
int[] squares = new int[in];
for (int i = 0; i < in; i ++) {
squares[i] = input.nextInt();
}
boolean hi = false;
int score = 0;
for (int i = 0; i < in; i ++) {
cols[squares[i] - 1] ++;
hi = checkscore(cols);
if (hi == true) {
hi = false;
score ++;
for (int j = 0; j < cols.length; j ++) {
cols[j] --;
}
}
}
System.out.println(score);
}
public static boolean checkscore(int[] cols) {
for (int i = 0; i < cols.length; i ++) {
if (cols[i] == 0) {
return false;
}
}
return true;
}
}
|
quadratic
|
961_A. Tetris
|
CODEFORCES
|
/**
* Created by ankeet on 7/22/16.
*/
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C701 {
static FastReader in = null;
static PrintWriter out = null;
public static void solve()
{
int n = in.nint();
String pk = in.next();
boolean[] occ = new boolean[52];
for(int i=0; i<n; i++)
{
char c = pk.charAt(i);
int val = Character.isUpperCase(c)? (int)(c-'A') : (int)(c-'a'+26);
occ[val] = true;
}
int[][] next = new int[n][52];
for(int i=0; i<n; i++) for(int j=0; j<52; j++) next[i][j] = -1;
for(int i= n-1; i>=0; i--) {
char c = pk.charAt(i);
int val = Character.isUpperCase(c)? (int)(c-'A') : (int)(c-'a'+26);
next[i][val] = i;
if(i<n-1)
for(int j=0; j<52; j++)
{
if(j!=val)
{
next[i][j] = next[i+1][j];
}
}
}
int min = Integer.MAX_VALUE;
for(int i=0; i<n; i++)
{
int maxd = 0;
boolean endearly = false;
for(int j=0; j<52; j++)
{
if(occ[j] && next[i][j] == -1)
{
endearly = true;
break;
}
else if(occ[j])
{
maxd = Math.max(maxd, next[i][j]-i+1);
}
}
if(endearly) break;
min = Math.min(min, maxd);
}
out.println(min);
}
public static void main(String[] args)
{
in = new FastReader(System.in);
out = new PrintWriter(System.out);
solve();
out.flush();
out.close();
}
static class FastReader {
BufferedReader read;
StringTokenizer tokenizer;
public FastReader(InputStream in)
{
read = new BufferedReader(new InputStreamReader(in));
}
public String next()
{
while(tokenizer == null || !tokenizer.hasMoreTokens())
{
try{
tokenizer = new StringTokenizer(read.readLine());
}catch(Exception e){
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nint()
{
return Integer.parseInt(next());
}
public long nlong()
{
return Long.parseLong(next());
}
public double ndouble()
{
return Double.parseDouble(next());
}
public int[] narr(int n)
{
int[] a = new int[n];
for(int i=0; i<n; ++i)
{
a[i] = nint();
}
return a;
}
public long[] nlarr(int n)
{
long[] a = new long[n];
for(int i=0; i<n; ++i)
{
a[i] = nlong();
}
return a;
}
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.IOException;
import java.util.StringTokenizer;
/*
* @author Tnascimento
*/
public class MaeDosDragoes {
public static PrintWriter saida = new PrintWriter(System.out, false);
public static class Escanear {
BufferedReader reader;
StringTokenizer tokenizer;
public Escanear() {
this(new InputStreamReader(System.in));
}
public Escanear(Reader in) {
reader = new BufferedReader(in);
}
String proximo() {
if (tokenizer == null || !tokenizer.hasMoreElements()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(proximo());
}
}
public static void main(String[] args) {
Escanear fastScanner = new Escanear();
int proximoInt = fastScanner.nextInt();
double proximoDouble = fastScanner.nextInt();
long[] graph = new long[proximoInt];
for(Integer i = 0; i < proximoInt; i++) {
for(Integer j =0; j < proximoInt; j++) {
Integer val = fastScanner.nextInt();
if (val.equals(1) || i.equals(j)) {
graph[i] |= 1L << j;
}
}
}
int szLeft = proximoInt/2;
int szRight = proximoInt - 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]);
}
proximoDouble/=ans;
saida.println(proximoDouble * proximoDouble * (ans * (ans-1))/2);
saida.flush();
}
}
|
np
|
839_E. Mother of Dragons
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class P035C {
private class Pair {
private int x;
private int y;
private Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int hashCode() {
return 37 * x + y;
}
public boolean equals(Object other) {
if (other instanceof Pair) {
Pair otherPair = (Pair)other;
return x == otherPair.x && y == otherPair.y;
}
return false;
}
}
private boolean[][] visited;
private final int N;
private final int M;
private final int k;
private ArrayList<Pair> fires = new ArrayList<Pair>();
private ArrayList<Pair> neighbors = new ArrayList<Pair>();
public P035C() throws IOException {
Scanner sc = new Scanner(new File("input.txt"));
N = sc.nextInt();
M = sc.nextInt();
visited = new boolean[N][M];
k = sc.nextInt();
for (int i = 0; i < k; i++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
fires.add(new Pair(x, y));
}
bfs();
}
private void bfs() throws IOException{
java.util.Queue<Pair> queue = new ArrayDeque<Pair>();
for (Pair p : fires) {
queue.add(p);
visited[p.x][p.y] = true;
}
Pair last = fires.get(0);
while (!queue.isEmpty()) {
Pair p = last = queue.poll();
for (Pair pn : getNeighbors(p)) {
if (!visited[pn.x][pn.y]) {
queue.add(pn);
visited[pn.x][pn.y] = true;
}
}
}
PrintWriter output = new PrintWriter(new FileWriter(new File("output.txt")));
output.printf("%d %d\n", last.x + 1, last.y + 1);
output.close();
}
private Collection<Pair> getNeighbors(Pair p) {
neighbors.clear();
if (p.x > 0) neighbors.add(new Pair(p.x-1, p.y));
if (p.x < N-1) neighbors.add(new Pair(p.x+1, p.y));
if (p.y > 0) neighbors.add(new Pair(p.x, p.y-1));
if (p.y < M-1) neighbors.add(new Pair(p.x, p.y+1));
return neighbors;
}
public static void main(String[] args) throws IOException {
P035C solution = new P035C();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.Scanner;
public class ehsan
{
public static BigInteger f(BigInteger m,BigInteger n){
BigInteger s,l;
s=n.multiply(m.add(BigInteger.valueOf(1)));
l=m.multiply(m.add(BigInteger.valueOf(1)));
l=l.divide(BigInteger.valueOf(2));
s=s.subtract(l);
s=s.subtract(m);
return s;
}
public static BigInteger bs(BigInteger a,BigInteger b,BigInteger n,BigInteger d){
BigInteger c,e;
c=a.add(b);
c=c.divide(BigInteger.valueOf(2));
e=f(c,n);
if(e.equals(d))
return c.add(BigInteger.valueOf(1));
if(a.equals(b.add(BigInteger.valueOf(-1))))
return b.add(BigInteger.valueOf(1));
if(e.compareTo(d)>0)
return bs(a,c,n,d);
return bs(c,b,n,d);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
BigInteger bi1 = sc.nextBigInteger();
BigInteger bi2 = sc.nextBigInteger();
BigInteger i,n=bi2;
BigInteger i2=BigInteger.valueOf(1);
BigInteger sum=BigInteger.valueOf(0);
if(bi1.compareTo(bi2)<0){
System.out.println(0);
return;
}
else if( bi1.compareTo(bi2) == 0 )
{
System.out.println(1);
return;
}
bi2=((n.multiply(n.add(BigInteger.valueOf(1)))).divide(BigInteger.valueOf(2))).subtract(n.subtract(BigInteger.valueOf(1)));
if(bi1.compareTo(bi2)>0)
System.out.println(-1);
else{
System.out.println(bs(BigInteger.valueOf(0),n.add(BigInteger.valueOf(-2)),n,bi1));
}
}
}
|
logn
|
287_B. Pipeline
|
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();
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.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a[] = new int[100004];
int b[] = new int[100004];
int n, m, ans = 0, dau, cuoi=-1;
n = sc.nextInt();
m = sc.nextInt();
for(int i=0;i<100004;i++) a[i] = 0;
for(int i=0;i<n;i++){
b[i] = sc.nextInt();
if(a[b[i]]==0){
a[b[i]] = 1;
ans++;
if(ans==m){
cuoi = i+1;
break;
}
}
}
for(int i=cuoi-1;i>=00;i--){
if(a[b[i]]==1){
a[b[i]] = 0;
ans--;
if(ans==0){
System.out.println((i+1)+" "+cuoi);
System.exit(0);
}
}
}
System.out.println("-1 -1");
}
}
|
linear
|
224_B. Array
|
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 Main {
// static int INF=1<<28;
//int x,y;
static int sum=0;
//static ArrayList<Integer> lis = new ArrayList<Integer>();
public static void main(String[] args)throws Exception{
// Scanner sc =new Scanner(new File("input.txt"));
Scanner sc =new Scanner(System.in);
// File file = new File("prime2.txt");
// PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
// sc.useDelimiter("(\\s)+|[,]");
// ArrayList<Integer> lis = new ArrayList<Integer>();
//ArrayList<String> lis = new ArrayList<String>();
//System.out.println();
// for(int i=0;i<;i++)
while(sc.hasNext()){
int n=ni(sc),x[]=new int[n+1];
for(int i=1;i<=n;i++)x[i]=ni(sc);
sort(x);
if(x[n]==1){x[n]=2;for(int i=1;i<=n;i++)System.out.print(x[i]+" ");}
else{x[0]=1;
for(int i=0;i<n;i++)System.out.print(x[i]+" ");
}
}
}
static void db(Object... os){
System.err.println(Arrays.deepToString(os));
}
static int ni(Scanner in){
return in.nextInt();
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class D1517 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int[][] costRight = new int[n][m - 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m - 1; j++) {
costRight[i][j] = sc.nextInt();
}
}
int[][] costDown = new int[n - 1][m];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m; j++) {
costDown[i][j] = sc.nextInt();
}
}
if (k % 2 == 1) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
pw.print(-1 + " ");
}
pw.println();
}
pw.close();
return;
}
int[][][] dp = new int[k + 1][n][m];
for (int w = 2; w <= k; w += 2) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dp[w][i][j] = (int) 1e9;
if (i + 1 < n)
dp[w][i][j] = Math.min(dp[w][i][j], 2 * costDown[i][j] + dp[w - 2][i + 1][j]);
if (i - 1 >= 0)
dp[w][i][j] = Math.min(dp[w][i][j], 2 * costDown[i - 1][j] + dp[w - 2][i - 1][j]);
if (j + 1 < m)
dp[w][i][j] = Math.min(dp[w][i][j], 2 * costRight[i][j] + dp[w - 2][i][j + 1]);
if (j - 1 >= 0)
dp[w][i][j] = Math.min(dp[w][i][j], 2 * costRight[i][j - 1] + dp[w - 2][i][j - 1]);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
pw.print(dp[k][i][j] + " ");
}
pw.println();
}
pw.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader f) {
br = new BufferedReader(f);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(next());
}
return arr;
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.util.*;
public class TwentyFive {
public static void main(String[] args)
{
System.out.println("25");
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.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);
C908 solver = new C908();
solver.solve(1, in, out);
out.close();
}
static class C908 {
int N;
int R;
int[] x;
double[] ans;
public void solve(int testNumber, FastScanner s, PrintWriter out) {
N = s.nextInt();
R = s.nextInt();
x = s.nextIntArray(N);
ans = new double[N];
Arrays.fill(ans, R);
for (int i = 0; i < N; i++) {
// placing circle i
for (int j = 0; j < i; j++) {
// testing collision with placed circles
if (Math.abs(x[i] - x[j]) <= 2 * R) {
// they will collide
// compute the increase in y that will be had
double dy = Math.sqrt(Math.pow(2 * R, 2) - Math.pow(x[i] - x[j], 2));
ans[i] = Math.max(ans[i], ans[j] + dy);
}
}
}
for (double d : ans)
out.print(d + " ");
out.println();
}
}
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public int[] nextIntArray(int N) {
int[] ret = new int[N];
for (int i = 0; i < N; i++)
ret[i] = this.nextInt();
return ret;
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.lang.reflect.Array;
public class codeforces
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt();
long U = in.nextLong();
long[] E = new long[n];
double max = -1;
for(int i=0;i<n;i++)
E[i] = in.nextLong();
for(int k=1;k<n-1;k++)
{
int i = k + 1, j = n - 1, mid = 0;
double T = 0;
while(i < j)
{
mid = (int)Math.ceil((double)(i+j)/2);
if(E[mid] - E[k-1] <= U)
i = mid;
else
j = mid - 1;
}
j = k;
k = i;
i = j - 1;
T = E[k] - E[j];
T /= E[k] - E[i];
if(E[k] - E[i] <= U)
max = Math.max(max, T);
k = j;
}
pw.println(max);
pw.flush();
pw.close();
}
/* public static void DFS(int sourse)
{
int count = 0;
visited[sourse] = true;
for(int u : adj[sourse])
{
if(!visited[u])
{
DFS(u);
}
}
}*/
public static ArrayList Divisors(long n)
{
ArrayList<Long> div = new ArrayList<>();
for (long i=1; i<=Math.sqrt(n); i++)
{
if (n%i == 0)
{
div.add(i);
if(n/i != i)
div.add(n/i);
}
}
return div;
}
public static int BinarySearch(long[] a, long k)
{
int n = a.length;
int i = 0, j = n-1;
int mid = 0;
if(k < a[0])
return 0;
else if(k >= a[n-1])
return n;
else
{
while(j - i > 1)
{
mid = (i+j)/2;
if(k >= a[mid])
i = mid;
else
j = mid;
}
}
return i+1;
}
public static long GCD(long a,long b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
static class pair implements Comparable<pair>
{
Integer x, y;
pair(int x,int y)
{
this.x=x;
this.y=y;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return x+" "+y;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return p.x - x == 0 && p.y - y == 0 ;
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
static class CodeX {
public static void sort(long arr[]) {
merge_sort(arr, 0, arr.length - 1);
}
private static void merge_sort(long A[], long start, long end) {
if (start < end) {
long mid = (start + end) / 2;
merge_sort(A, start, mid);
merge_sort(A, mid + 1, end);
merge(A, start, mid, end);
}
}
private static void merge(long A[], long start,long mid, long end) {
long p = start, q = mid + 1;
long Arr[] = new long[(int)(end - start + 1)];
long k = 0;
for (int i = (int)start; i <= end; i++) {
if (p > mid)
Arr[(int)k++] = A[(int)q++];
else if (q > end)
Arr[(int)k++] = A[(int)p++];
else if (A[(int)p] < A[(int)q])
Arr[(int)k++] = A[(int)p++];
else
Arr[(int)k++] = A[(int)q++];
}
for (int i = 0; i < k; i++) {
A[(int)start++] = Arr[i];
}
}
}
}
|
nlogn
|
957_C. Three-level Laser
|
CODEFORCES
|
import java.io.IOException;
import java.io.PrintWriter;
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.NoSuchElementException;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BiFunction;
public class Main{
static Scanner scn = new Scanner(System.in);
static FastScanner sc = new FastScanner();
static Mathplus mp = new Mathplus();
static PrintWriter ot = new PrintWriter(System.out);
static Random rand = new Random();
static int mod = 1000000007;
static long inf = (long)1e17;
static int[] dx = {0,1,0,-1};
static int[] dy = {1,0,-1,0};
static int max;
public static void main(String[] args) {
int N = sc.nextInt();
ArrayList<Integer>[] l = new ArrayList[N];
HashMap<Long,Integer> map = new HashMap<Long,Integer>();
long sum = 0;
long[] s = new long[N];
for(int i=0;i<N;i++) {
l[i] = new ArrayList<Integer>();
int n = sc.nextInt();
for(int j=0;j<n;j++) {
int a = sc.nextInt();
map.put((long)a, i);
s[i] += a;
sum += a;
l[i].add(a);
}
}
if(Math.abs(sum)%N!=0) {
System.out.println("NO");
return;
}
long make = sum/N;
boolean[] dp = new boolean[(1<<N)];
int[] first = new int[(1<<N)];
int[] bef = new int[(1<<N)];
Arrays.fill(first,mod);
for(int i=0;i<N;i++) {
for(int a:l[i]) {
int used = 0;
boolean f = true;
long now = a;
int see = i;
while(true) {
long next = make-(s[see]-now);
if(next==a) {
break;
}
if(!map.containsKey(next)) {
f = false;
break;
}else {
int k = map.get(next);
if(mp.contains(used,k)&&k!=i) {
f = false;
break;
}else {
used = mp.bitadd(used,k);
now = next;
see = k;
}
}
}
if(f) {
dp[mp.bitadd(used,i)] = true;
first[mp.bitadd(used,i)] = a;
}
}
}
dp[0] = true;
for(int i=1;i<(1<<N);i++) {
for(int j=i;j>0;j=(j-1)&i) {
if(dp[i^j]&&dp[j]) {
dp[i]=true;
bef[i] = j;
}
}
}
if(!dp[(1<<N)-1]) {
System.out.println("NO");
}else {
System.out.println("YES");
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
int[] ans1 = new int[N];
int[] ans2 = new int[N];
q.add((1<<N)-1);
while(!q.isEmpty()) {
int Q = q.poll();
if(first[Q]==mod) {
q.add(bef[Q]);
q.add(Q^bef[Q]);
}else {
int a = first[Q];
long now = a;
int befo = map.get((long)a);
while(true) {
long next = make-(s[befo]-now);
if(next==a) {
int k = map.get(next);
ans1[k] = (int)next;
ans2[k] = befo;
break;
}
int k = map.get(next);
ans1[k] = (int)next;
ans2[k] = befo;
now = next;
befo = k;
}
}
}
for(int i=0;i<N;i++) {
System.out.println(ans1[i]+" "+(ans2[i]+1));
}
}
}
}
class GridGraph extends Graph{
int N;
int M;
String[] S;
HashMap<Character,Integer> map;
GridGraph(int n,int m,String[] s,char[] c){
super(n*m);
N = n;
M = m;
S = s;
map = new HashMap<Character,Integer>();
for(int i=0;i<n-1;i++) {
for(int j=0;j<m;j++) {
if(S[i].charAt(j)!='#'&&S[i+1].charAt(j)!='#') {
addEdge(toint(i,j),toint(i+1,j));
addEdge(toint(i+1,j),toint(i,j));
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<m-1;j++) {
if(S[i].charAt(j)!='#'&&S[i].charAt(j+1)!='#') {
addEdge(toint(i,j),toint(i,j+1));
addEdge(toint(i,j+1),toint(i,j));
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
for(int k=0;k<c.length;k++) {
if(S[i].charAt(j)==c[k])map.put(c[k],toint(i,j));
}
}
}
}
int toint(int i,int j) {
return i*M+j;
}
}
class BetterGridGraph{
int N;
int M;
char[][] S;
HashMap<Character,Integer> map;
int[] dx = {0,1,0,-1};
int[] dy = {1,0,-1,0};
char w;
char b = '#';
BetterGridGraph(int n,int m,String[] s,char[] c){
N = n;
M = m;
for(int i=0;i<s.length;i++) {
S[i] = s[i].toCharArray();
}
map = new HashMap<Character,Integer>();
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
for(int k=0;k<c.length;k++) {
if(S[i][j]==c[k])map.put(c[k],toint(i,j));
}
}
}
}
BetterGridGraph(int n,int m,char[][] s,char[] c){
N = n;
M = m;
S = s;
map = new HashMap<Character,Integer>();
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
for(int k=0;k<c.length;k++) {
if(S[i][j]==c[k])map.put(c[k],toint(i,j));
}
}
}
}
BetterGridGraph(int n,int m,String[] s,char[] c,char W,char B){
N = n;
M = m;
for(int i=0;i<s.length;i++) {
S[i] = s[i].toCharArray();
}
w = W;
b = B;
map = new HashMap<Character,Integer>();
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
for(int k=0;k<c.length;k++) {
if(S[i][j]==c[k])map.put(c[k],toint(i,j));
}
}
}
}
BetterGridGraph(int n,int m,char[][] s,char[] c,char W,char B){
N = n;
M = m;
S = s;
w = W;
b = B;
map = new HashMap<Character,Integer>();
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
for(int k=0;k<c.length;k++) {
if(S[i][j]==c[k])map.put(c[k],toint(i,j));
}
}
}
}
int toint(int i,int j) {
return i*M+j;
}
int[] bfs(char C) {
int s = map.get(C);
int[] L = new int[N*M];
for(int i=0;i<N*M;i++){
L[i] = -1;
}
L[s] = 0;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(s);
Range X = new Range(0,N-1);
Range Y = new Range(0,M-1);
while(!Q.isEmpty()){
int v = Q.poll();
for(int i=0;i<4;i++){
int x = v/M;
int y = v%M;
int nx = x+dx[i];
int ny = y+dy[i];
if(X.isIn(nx)&&Y.isIn(ny)&&S[nx][ny]!=b) {
int w = toint(nx,ny);
if(L[w]==-1){
L[w] = L[v] + 1;
Q.add(w);
}
}
}
}
return L;
}
int[][] bfs2(char C,int K){
int s = map.get(C);
int[][] L = new int[N*M][K+1];
for(int i=0;i<N*M;i++){
for(int j=0;j<=K;j++)
L[i][j] = 1000000007;
}
L[s][0] = 0;
ArrayDeque<IntIntPair> Q = new ArrayDeque<IntIntPair>();
Q.add(new IntIntPair(s,0));
Range X = new Range(0,N-1);
Range Y = new Range(0,M-1);
while(!Q.isEmpty()){
IntIntPair v = Q.poll();
for(int i=0;i<4;i++){
int x = v.a/M;
int y = v.a%M;
int h = v.b;
int nx = x+dx[i];
int ny = y+dy[i];
if(X.isIn(nx)&&Y.isIn(ny)&&S[nx][ny]!=b) {
int ni = toint(nx,ny);
int nh = S[nx][ny]==w?h+1:h;
if(nh>K) continue;
if(L[ni][nh]==1000000007){
L[ni][nh] = L[v.a][h] + 1;
Q.add(new IntIntPair(ni,nh));
}
}
}
}
for(int i=0;i<N*M;i++) {
for(int j=1;j<=K;j++) {
L[i][j] = Math.min(L[i][j],L[i][j-1]);
}
}
return L;
}
}
class StringManager{
ArrayList<Character> S;
static Mathplus mp;
static boolean calced;
static int base;
static long baserev;
ArrayList<Long> l;
StringManager(String s){
S = new ArrayList<Character>();
for(int i=0;i<s.length();i++) {
S.add(s.charAt(i));
}
if(!calced) {
calced = true;
mp = new Mathplus();
base = 1000003;
baserev = mp.rev(base);
mp.buildpow(base,1000050);
mp.buildrevpow((int) baserev,1000050);
}
l = new ArrayList<Long>();
l.add((long)S.get(0));
for(int i=1;i<S.size();i++) {
char c = S.get(i);
l.add((l.get(i-1) + mp.pow[i] * c)%mp.mod);
}
}
void add(char C){
int i = S.size();
S.add(C);
l.add((l.get(i-1) + mp.pow[i] * C)%mp.mod);
}
long gethash(int le,int ri) {
long res = l.get(ri);
if(le!=0) {
res -= l.get(le-1);
res += mp.mod;
res %= mp.mod;
res *= mp.revpow[le];
res %= mp.mod;
}
return res;
}
}
class Trie{
int nodenumber = 1;
ArrayList<TrieNode> l;
Trie(){
l = new ArrayList<TrieNode>();
l.add(new TrieNode());
}
void add(String S,int W){
int now = 0;
for(int i=0;i<S.length();i++) {
TrieNode n = l.get(now);
char c = S.charAt(i);
if(n.Exist[c-'a']!=-1) {
now = n.Exist[c-'a'];
}else {
l.add(new TrieNode());
n.Exist[c-'a'] = nodenumber;
now = nodenumber;
nodenumber++;
}
}
l.get(now).weight = W;
}
void find(String S,int i,int[] dp) {
int now = 0;
dp[i+1] = Math.max(dp[i],dp[i+1]);
for(int j=0;;j++) {
TrieNode n = l.get(now);
dp[i+j] = Math.max(dp[i+j],dp[i]+n.weight);
int slook = i+j;
if(slook>=S.length())return;
char c = S.charAt(slook);
if(n.Exist[c-'a']==-1)return;
now = n.Exist[c-'a'];
}
}
}
class TrieNode{
int[] Exist = new int[26];
int weight = 0;
TrieNode(){
for(int i=0;i<26;i++) {
Exist[i] = -1;
}
}
}
class SizeComparator implements Comparator<Edge>{
int[] size;
SizeComparator(int[] s) {
size = s;
}
public int compare(Edge o1, Edge o2) {
return size[o1.to]-size[o2.to];
}
}
class ConvexHullTrick {
long[] A, B;
int len;
public ConvexHullTrick(int n) {
A = new long[n];
B = new long[n];
}
private boolean check(long a, long b) {
return (B[len - 2] - B[len - 1]) * (a - A[len - 1]) >= (B[len - 1] - b) * (A[len - 1] - A[len - 2]);
}
public void add(long a, long b) {
while (len >= 2 && check(a, b)) {
len--;
}
A[len] = a;
B[len] = b;
len++;
}
public long query(long x) {
int l = -1, r = len - 1;
while (r - l > 1) {
int mid = (r + l) / 2;
if (get(mid,x)>=get(mid+1,x)) {
l = mid;
} else {
r = mid;
}
}
return get(r,x);
}
private long get(int k, long x) {
return A[k] * x + B[k];
}
}
class Range{
int l;
int r;
int length;
Range(int L,int R){
l = L;
r = R;
length = R-L+1;
}
boolean isIn(int x) {
return (l<=x&&x<=r);
}
}
class LeftComparator implements Comparator<Range>{
public int compare(Range P, Range Q) {
return P.l-Q.l;
}
}
class RightComparator implements Comparator<Range>{
public int compare(Range P, Range Q) {
return P.r-Q.r;
}
}
class LengthComparator implements Comparator<Range>{
public int compare(Range P, Range Q) {
return P.length-Q.length;
}
}
class SegmentTree<T,E>{
int N;
BiFunction<T,T,T> f;
BiFunction<T,E,T> g;
T d1;
ArrayList<T> dat;
SegmentTree(BiFunction<T,T,T> F,BiFunction<T,E,T> G,T D1,T[] v){
int n = v.length;
f = F;
g = G;
d1 = D1;
init(n);
build(v);
}
void init(int n) {
N = 1;
while(N<n)N*=2;
dat = new ArrayList<T>();
}
void build(T[] v) {
for(int i=0;i<2*N;i++) {
dat.add(d1);
}
for(int i=0;i<v.length;i++) {
dat.set(N+i-1,v[i]);
}
for(int i=N-2;i>=0;i--) {
dat.set(i,f.apply(dat.get(i*2+1),dat.get(i*2+2)));
}
}
void update(int k,E a) {
k += N-1;
dat.set(k,g.apply(dat.get(k),a));
while(k>0){
k = (k-1)/2;
dat.set(k,f.apply(dat.get(k*2+1),dat.get(k*2+2)));
}
}
T query(int a,int b, int k, int l ,int r) {
if(r<=a||b<=l) return d1;
if(a<=l&&r<=b) return dat.get(k);
T vl = query(a,b,k*2+1,l,(l+r)/2);
T vr = query(a,b,k*2+2,(l+r)/2,r);
return f.apply(vl, vr);
}
T query(int a,int b){
return query(a,b,0,0,N);
}
}
class LazySegmentTree<T,E> extends SegmentTree<T,E>{
BiFunction<E,E,E> h;
BiFunction<E,Integer,E> p = (E a,Integer b) ->{return a;};
E d0;
ArrayList<E> laz;
LazySegmentTree(BiFunction<T,T,T> F,BiFunction<T,E,T> G,BiFunction<E,E,E> H,T D1,E D0,T[] v){
super(F,G,D1,v);
int n = v.length;
h = H;
d0 = D0;
Init(n);
}
void build() {
}
void Init(int n){
laz = new ArrayList<E>();
for(int i=0;i<2*N;i++) {
laz.add(d0);
}
}
void eval(int len,int k) {
if(laz.get(k).equals(d0)) return;
if(k*2+1<N*2-1) {
laz.set(k*2+1,h.apply(laz.get(k*2+1),laz.get(k)));
laz.set(k*2+2,h.apply(laz.get(k*2+2),laz.get(k)));
}
dat.set(k,g.apply(dat.get(k), p.apply(laz.get(k), len)));
laz.set(k,d0);
}
T update(int a,int b,E x,int k,int l,int r) {
eval(r-l,k);
if(r<=a||b<=l) {
return dat.get(k);
}
if(a<=l&&r<=b) {
laz.set(k,h.apply(laz.get(k),x));
return g.apply(dat.get(k),p.apply(laz.get(k),r-l));
}
T vl = update(a,b,x,k*2+1,l,(l+r)/2);
T vr = update(a,b,x,k*2+2,(l+r)/2,r);
dat.set(k,f.apply(vl,vr));
return dat.get(k);
}
T update(int a,int b,E x) {
return update(a,b,x,0,0,N);
}
T query(int a,int b,int k,int l,int r) {
eval(r-l,k);
if(r<=a||b<=l) return d1;
if(a<=l&&r<=b) return dat.get(k);
T vl = query(a,b,k*2+1,l,(l+r)/2);
T vr = query(a,b,k*2+2,(l+r)/2,r);
return f.apply(vl, vr);
}
T query(int a,int b){
return query(a,b,0,0,N);
}
}
class AddSumSegmentTree{
int N;
int d1;
ArrayList<Integer> dat;
AddSumSegmentTree(int[] v){
int n = v.length;
init(n);
build(v);
}
void init(int n) {
N = 1;
while(N<n)N*=2;
dat = new ArrayList<Integer>();
}
void build(int[] v) {
for(int i=0;i<2*N;i++) {
dat.add(d1);
}
for(int i=0;i<v.length;i++) {
dat.set(N+i-1,v[i]);
}
for(int i=N-2;i>=0;i--) {
dat.set(i,dat.get(i*2+1)+dat.get(i*2+2));
}
}
void update(int k,int a) {
k += N-1;
dat.set(k,dat.get(k)+a);
while(k>0){
k = (k-1)/2;
dat.set(k,dat.get(k*2+1)+dat.get(k*2+2));
}
}
int query(int a,int b, int k, int l ,int r) {
if(r<=a||b<=l) return d1;
if(a<=l&&r<=b) return dat.get(k);
int vl = query(a,b,k*2+1,l,(l+r)/2);
int vr = query(a,b,k*2+2,(l+r)/2,r);
return vl+vr;
}
int query(int a,int b){
return query(a,b,0,0,N);
}
}
class AddSumLazySegmentTree {
int N;
long[] dat;
long[] laz;
AddSumLazySegmentTree(long[] v){
init(v.length);
for(int i=0;i<v.length;i++) {
dat[N+i-1]=v[i];
}
for(int i=N-2;i>=0;i--) {
dat[i]=dat[i*2+1]+dat[i*2+2];
}
}
void init(int n) {
N = 1;
while(N<n)N*=2;
dat = new long[2*N];
laz = new long[2*N];
}
void eval(int len,int k) {
if(laz[k]==0) return;
if(k*2+1<N*2-1) {
laz[k*2+1] += laz[k];
laz[k*2+2] += laz[k];
}
dat[k] += laz[k] * len;
laz[k] = 0;
}
long update(int a,int b,long x,int k,int l,int r) {
eval(r-l,k);
if(r<=a||b<=l) {
return dat[k];
}
if(a<=l&&r<=b) {
laz[k] += x;
return dat[k]+laz[k]*(r-l);
}
long vl = update(a,b,x,k*2+1,l,(l+r)/2);
long vr = update(a,b,x,k*2+2,(l+r)/2,r);
return dat[k] = vl+vr;
}
long update(int a,int b,long x) {
return update(a,b,x,0,0,N);
}
long query(int a,int b,int k,int l,int r) {
eval(r-l,k);
if(r<=a||b<=l) return 0;
if(a<=l&&r<=b) return dat[k];
long vl = query(a,b,k*2+1,l,(l+r)/2);
long vr = query(a,b,k*2+2,(l+r)/2,r);
return vl+vr;
}
long query(int a,int b){
return query(a,b,0,0,N);
}
}
class BinaryIndexedTree{
int[] val;
BinaryIndexedTree(int N){
val = new int[N+1];
}
long sum(int i) {
if(i==0)return 0;
long s = 0;
while(i>0) {
s += val[i];
i -= i & (-i);
}
return s;
}
void add(int x,int i) {
if(i==0)return;
while(i<val.length){
val[i] += x;
i += i & (-i);
}
}
}
class UnionFindTree {
int[] root;
int[] rank;
int[] size;
int[] edge;
int num;
UnionFindTree(int N){
root = new int[N];
rank = new int[N];
size = new int[N];
edge = new int[N];
num = N;
for(int i=0;i<N;i++){
root[i] = i;
size[i] = 1;
}
}
public boolean isRoot(int x) {
return x==find(x);
}
public int extraEdge(int x) {
int r = find(x);
return edge[r] - size[r] + 1;
}
public int find(int x){
if(root[x]==x){
return x;
}else{
return find(root[x]);
}
}
public void unite(int x,int y){
x = find(x);
y = find(y);
if(x==y){
edge[x]++;
return;
}else{
num--;
if(rank[x]<rank[y]){
root[x] = y;
size[y] += size[x];
edge[y] += edge[x]+1;
}else{
root[y] = x;
size[x] += size[y];
edge[x] += edge[y]+1;
if(rank[x]==rank[y]){
rank[x]++;
}
}
}
}
public boolean same(int x,int y){
return find(x)==find(y);
}
}
class ParticalEternalLastingUnionFindTree extends UnionFindTree{
int[] time;
int now;
ParticalEternalLastingUnionFindTree(int N){
super(N);
time = new int[N];
for(int i=0;i<N;i++) {
time[i] = 1000000007;
}
}
public int find(int t,int i) {
if(time[i]>t) {
return i;
}else {
return find(t,root[i]);
}
}
public void unite(int x,int y,int t) {
now = t;
x = find(t,x);
y = find(t,y);
if(x==y)return;
if(rank[x]<rank[y]){
root[x] = y;
size[y] += size[x];
time[x] = t;
}else{
root[y] = x;
size[x] += size[y];
if(rank[x]==rank[y]){
rank[x]++;
}
time[y] = t;
}
}
public int sametime(int x,int y) {
if(find(now,x)!=find(now,y)) return -1;
int ok = now;
int ng = 0;
while(ok-ng>1) {
int mid = (ok+ng)/2;
if(find(mid,x)==find(mid,y)) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
}
class Graph {
ArrayList<Edge>[] list;
int size;
TreeSet<LinkEdge> Edges = new TreeSet<LinkEdge>(new LinkEdgeComparator());
@SuppressWarnings("unchecked")
Graph(int N){
size = N;
list = new ArrayList[N];
for(int i=0;i<N;i++){
list[i] = new ArrayList<Edge>();
}
}
void addEdge(int a,int b){
list[a].add(new Edge(b,1));
}
void addWeightedEdge(int a,int b,long c){
list[a].add(new Edge(b,c));
}
void addEgdes(int[] a,int[] b){
for(int i=0;i<a.length;i++){
list[a[i]].add(new Edge(b[i],1));
}
}
void addWeighterEdges(int[] a ,int[] b ,int[] c){
for(int i=0;i<a.length;i++){
list[a[i]].add(new Edge(b[i],c[i]));
}
}
long[][] bfs(int s){
long[][] L = new long[2][size];
for(int i=0;i<size;i++){
L[0][i] = -1;
L[1][i] = -1;
}
L[0][s] = 0;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(s);
while(!Q.isEmpty()){
int v = Q.poll();
for(Edge e:list[v]){
int w = e.to;
long c = e.cost;
if(L[0][w]==-1){
L[0][w] = L[0][v] + c;
L[1][w] = v;
Q.add(w);
}
}
}
return L;
}
long[] bfs2(int[] d,int s){
long[] L = new long[size];
for(int i=0;i<size;i++){
L[i] = -1;
}
int p = 0;
L[s] = 0;
d[s] = p;
p++;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(s);
while(!Q.isEmpty()){
int v = Q.poll();
for(Edge e:list[v]){
int w = e.to;
long c = e.cost;
if(L[w]==-1){
d[w] = p;
p++;
L[w] = L[v] + c;
Q.add(w);
}
}
}
return L;
}
int[] isTwoColor(){
int[] L = new int[size];
for(int i=0;i<size;i++){
L[i] = -1;
}
L[0] = 0;
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(0);
while(!Q.isEmpty()){
int v = Q.poll();
for(Edge e:list[v]){
int w = e.to;
if(L[w]==-1){
L[w] = 1-L[v];
Q.add(w);
}else{
if(L[v]+L[w]!=1){
L[0] = -2;
}
}
}
}
return L;
}
long[] dijkstra(int s){
long[] L = new long[size];
for(int i=0;i<size;i++){
L[i] = -1;
}
int[] v = new int[size];
L[s] = 0;
PriorityQueue<LongIntPair> Q = new PriorityQueue<LongIntPair>(new LongIntSampleComparator());
Q.add(new LongIntPair(0,s));
while(!Q.isEmpty()){
LongIntPair C = Q.poll();
if(v[C.b]==0){
L[C.b] = C.a;
v[C.b] = 1;
for(Edge D:list[C.b]) {
if(L[D.to]==-1||L[D.to]>L[C.b]+D.cost) {
L[D.to]=L[C.b]+D.cost;
Q.add(new LongIntPair(L[C.b]+D.cost,D.to));
}
}
}
}
return L;
}
ArrayList<Graph> makeapart(){
ArrayList<Graph> ans = new ArrayList<Graph>();
boolean[] b = new boolean[size];
int[] num = new int[size];
for(int i=0;i<size;i++){
if(b[i])continue;
int sz = 0;
ArrayList<Integer> l = new ArrayList<Integer>();
ArrayDeque<Integer> Q = new ArrayDeque<Integer>();
Q.add(i);
b[i] = true;
while(!Q.isEmpty()){
int v = Q.poll();
num[v] = sz;
sz++;
l.add(v);
for(Edge e:list[v]){
if(!b[e.to]){
Q.add(e.to);
b[e.to] = true;
}
}
}
Graph H = new Graph(sz);
for(int e:l){
for(Edge E:list[e]){
H.addWeightedEdge(num[e],num[E.to],E.cost);
}
}
ans.add(H);
}
return ans;
}
long[] bellmanFord(int s) {
long inf = 1000000000;
inf *= inf;
long[] d = new long[size];
boolean[] n = new boolean[size];
d[s] = 0;
for(int i=1;i<size;i++){
d[i] = inf;
d[i] *= d[i];
}
for(int i=0;i<size-1;i++){
for(int j=0;j<size;j++){
for(Edge E:list[j]){
if(d[j]!=inf&&d[E.to]>d[j]+E.cost){
d[E.to]=d[j]+E.cost;
}
}
}
}
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
for(Edge e:list[j]){
if(d[j]==inf) continue;
if(d[e.to]>d[j]+e.cost) {
d[e.to]=d[j]+e.cost;
n[e.to] = true;
}
if(n[j])n[e.to] = true;
}
}
}
for(int i=0;i<size;i++) {
if(n[i])d[i] = inf;
}
return d;
}
long[][] WarshallFloyd(long[][] a){
int n = a.length;
long[][] ans = new long[n][n];
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
ans[i][j] = a[i][j]==0?(long)1e16:a[i][j];
if(i==j)ans[i][j]=0;
}
}
for(int k=0;k<n;k++) {
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
ans[i][j] = Math.min(ans[i][j],ans[i][k]+ans[k][j]);
}
}
}
return ans;
}
long[] maxtra(int s,long l){
long[] L = new long[size];
for(int i=0;i<size;i++){
L[i] = -1;
}
int[] v = new int[size];
L[s] = -1;
PriorityQueue<Pair> Q = new PriorityQueue<Pair>(new SampleComparator());
Q.add(new Pair(l,s));
while(!Q.isEmpty()){
Pair C = Q.poll();
if(v[(int)C.b]==0){
L[(int)C.b] = C.a;
v[(int) C.b] = 1;
for(Edge D:list[(int) C.b])Q.add(new Pair(Math.max(L[(int)C.b],D.cost),D.to));
}
}
return L;
}
long[] mintra(int s){
long[] L = new long[size];
for(int i=0;i<size;i++){
L[i] = -1;
}
int[] v = new int[size];
L[s] = s;
PriorityQueue<Pair> Q = new PriorityQueue<Pair>(new SampleComparator().reversed());
Q.add(new Pair(s,s));
while(!Q.isEmpty()){
Pair C = Q.poll();
if(v[(int)C.b]==0){
L[(int)C.b] = C.a;
v[(int) C.b] = 1;
for(Edge D:list[(int) C.b])Q.add(new Pair(Math.min(L[(int)C.b],D.cost),D.to));
}
}
return L;
}
long Kruskal(){
long r = 0;
for(int i=0;i<size;i++) {
for(Edge e:list[i]) {
Edges.add(new LinkEdge(e.cost,i,e.to));
}
}
UnionFindTree UF = new UnionFindTree(size);
for(LinkEdge e:Edges){
if(e.a>=0&&e.b>=0) {
if(!UF.same(e.a,e.b)){
r += e.L;
UF.unite(e.a,e.b);
}
}
}
return r;
}
ArrayList<Integer> Kahntsort(){
ArrayList<Integer> ans = new ArrayList<Integer>();
PriorityQueue<Integer> q = new PriorityQueue<Integer>();
int[] in = new int[size];
for(int i=0;i<size;i++) {
for(Edge e:list[i])in[e.to]++;
}
for(int i=0;i<size;i++) {
if(in[i]==0)q.add(i);
}
while(!q.isEmpty()) {
int v = q.poll();
ans.add(v);
for(Edge e:list[v]) {
in[e.to]--;
if(in[e.to]==0)q.add(e.to);
}
}
for(int i=0;i<size;i++) {
if(in[i]>0)return new ArrayList<Integer>();
}
return ans;
}
RootedTree dfsTree(int i) {
int[] u = new int[size];
RootedTree r = new RootedTree(size);
dfsTree(i,u,r);
return r;
}
private void dfsTree(int i, int[] u, RootedTree r) {
u[i] = 1;
for(Edge e:list[i]) {
if(u[e.to]==0) {
r.list[i].add(e);
u[e.to] = 1;
dfsTree(e.to,u,r);
}
}
}
}
class Tree extends Graph{
public Tree(int N) {
super(N);
}
long[] tyokkei(){
long[][] a = bfs(0);
System.out.println();
int md = -1;
long m = 0;
for(int i=0;i<size;i++){
if(m<a[0][i]){
m = a[0][i];
md = i;
}
}
long[][] b = bfs(md);
int md2 = -1;
long m2 = 0;
for(int i=0;i<size;i++){
if(m2<b[0][i]){
m2 = b[0][i];
md2 = i;
}
}
long[] r = {m2,md,md2};
return r;
}
}
class RootedTree extends Graph{
RootedTree(int N){
super(N);
}
}
class LinkEdge{
long L;
int a ;
int b;
LinkEdge(long l,int A,int B){
L = l;
a = A;
b = B;
}
public boolean equals(Object o){
LinkEdge O = (LinkEdge) o;
return O.a==this.a&&O.b==this.b&&O.L==this.L;
}
public int hashCode(){
return Objects.hash(L,a,b);
}
}
class Edge{
int to;
long cost;
Edge(int a,long b){
to = a;
cost = b;
}
}
class LinkEdgeComparator implements Comparator<LinkEdge>{
public int compare(LinkEdge P, LinkEdge Q) {
long t = P.L-Q.L;
if(t==0){
if(P.a>Q.a){
return 1;
}else{
return P.b>Q.b?1:-1;
}
}
return t>=0?1:-1;
}
}
class Triplet{
long a;
long b;
long c;
Triplet(long p,long q,long r){
a = p;
b = q;
c = r;
}
public boolean equals(Object o){
Triplet O = (Triplet) o;
return O.a==this.a&&O.b==this.b&&O.c==this.c?true:false;
}
public int hashCode(){
return Objects.hash(a,b,c);
}
}
class TripletComparator implements Comparator<Triplet>{
public int compare(Triplet P, Triplet Q) {
long t = P.a-Q.a;
if(t==0){
long tt = P.b-Q.b;
if(tt==0) {
if(P.c>Q.c) {
return 1;
}else if(P.c<Q.c){
return -1;
}else {
return 0;
}
}
return tt>0?1:-1;
}
return t>=0?1:-1;
}
}
class Pair{
long a;
long b;
Pair(long p,long q){
this.a = p;
this.b = q;
}
public boolean equals(Object o){
Pair O = (Pair) o;
return O.a==this.a&&O.b==this.b;
}
public int hashCode(){
return Objects.hash(a,b);
}
}
class SampleComparator implements Comparator<Pair>{
public int compare(Pair P, Pair Q) {
long t = P.a-Q.a;
if(t==0){
return P.b>=Q.b?1:-1;
}
return t>=0?1:-1;
}
}
class LongIntPair{
long a;
int b;
LongIntPair(long p,int q){
this.a = p;
this.b = q;
}
public boolean equals(Object o){
Pair O = (Pair) o;
return O.a==this.a&&O.b==this.b;
}
public int hashCode(){
return Objects.hash(a,b);
}
}
class LongIntSampleComparator implements Comparator<LongIntPair>{
public int compare(LongIntPair P, LongIntPair Q) {
long t = P.a-Q.a;
if(t==0){
if(P.b>Q.b){
return 1;
}else{
return -1;
}
}
return t>=0?1:-1;
}
}
class IntIntPair{
int a;
int b;
IntIntPair(int p,int q){
this.a = p;
this.b = q;
}
public boolean equals(Object o){
Pair O = (Pair) o;
return O.a==this.a&&O.b==this.b;
}
public int hashCode(){
return Objects.hash(a,b);
}
}
class IntIntSampleComparator implements Comparator<IntIntPair>{
public int compare(IntIntPair P, IntIntPair Q) {
int t = P.a-Q.a;
if(t==0){
return P.b-Q.b;
}
return t;
}
}
class DoublePair{
double a;
double b;
DoublePair(double p,double q){
this.a = p;
this.b = q;
}
public boolean equals(Object o){
Pair O = (Pair) o;
return O.a==this.a&&O.b==this.b;
}
public int hashCode(){
return Objects.hash(a,b);
}
}
class DDSampleComparator implements Comparator<DoublePair>{
public int compare(DoublePair P, DoublePair Q) {
return P.b-Q.b>=0?1:-1;
}
}
class DoubleTriplet{
double a;
double b;
double c;
DoubleTriplet(double p,double q,double r){
this.a = p;
this.b = q;
this.c = r;
}
public boolean equals(Object o){
DoubleTriplet O = (DoubleTriplet) o;
return O.a==this.a&&O.b==this.b&&O.c==this.c;
}
public int hashCode(){
return Objects.hash(a,b,c);
}
}
class FastScanner {
private final java.io.InputStream in = System.in;
private final byte[] b = new byte[1024];
private int p = 0;
private int bl = 0;
private boolean hNB() {
if (p<bl) {
return true;
}else{
p = 0;
try {
bl = in.read(b);
} catch (IOException e) {
e.printStackTrace();
}
if (bl<=0) {
return false;
}
}
return true;
}
private int rB() { if (hNB()) return b[p++]; else return -1;}
private static boolean iPC(int c) { return 33 <= c && c <= 126;}
private void sU() { while(hNB() && !iPC(b[p])) p++;}
public boolean hN() { sU(); return hNB();}
public String next() {
if (!hN()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = rB();
while(iPC(b)) {
sb.appendCodePoint(b);
b = rB();
}
return sb.toString();
}
public char nextChar() {
return next().charAt(0);
}
public long nextLong() {
if (!hN()) throw new NoSuchElementException();
long n = 0;
boolean m = false;
int b = rB();
if (b=='-') {
m=true;
b=rB();
}
if (b<'0'||'9'<b) {
throw new NumberFormatException();
}
while(true){
if ('0'<=b&&b<='9') {
n *= 10;
n += b - '0';
}else if(b == -1||!iPC(b)){
return (m?-n:n);
}else{
throw new NumberFormatException();
}
b = rB();
}
}
public int nextInt() {
if (!hN()) throw new NoSuchElementException();
long n = 0;
boolean m = false;
int b = rB();
if (b == '-') {
m = true;
b = rB();
}
if (b<'0'||'9'<b) {
throw new NumberFormatException();
}
while(true){
if ('0'<=b&&b<='9') {
n *= 10;
n += b-'0';
}else if(b==-1||!iPC(b)){
return (int) (m?-n:n);
}else{
throw new NumberFormatException();
}
b = rB();
}
}
public int[] nextInts(int n) {
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongs(int n) {
long[] a = new long[n];
for(int i=0;i<n;i++) {
a[i] = nextLong();
}
return a;
}
public int[][] nextIntses(int n,int m){
int[][] a = new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j] = nextInt();
}
}
return a;
}
}
class Mathplus{
int mod = 1000000007;
long[] fac;
long[] revfac;
long[][] comb;
long[] pow;
long[] revpow;
boolean isBuild = false;
boolean isBuildc = false;
boolean isBuildp = false;
int mindex = -1;
int maxdex = -1;
int color(int[][] diff,int N) {
int[] val = new int[1<<N];
val[0] = 1;
for(int i=0;i<(1<<N);i++) {
for(int j=0;j<N;j++) {
if(contains(i,j)) {
if(val[bitremove(i,j)]==1) {
boolean b = true;
for(int k=0;k<N;k++) {
if(contains(i,k)&&diff[j][k]==1) {
b = false;
}
}
if(b)val[i] = 1;
}
break;
}
}
}
int[] dp = new int[1<<N];
Arrays.fill(dp,mod);;
dp[0] = 0;
for(int i=0;i<(1<<N);i++) {
for(int j=i;j>0;j=(j-1)&i) {
if(val[j]==1)dp[i]=Math.min(dp[i],dp[i^j]+1);
}
}
return dp[(1<<N)-1];
}
public DoubleTriplet Line(double x1,double y1,double x2,double y2) {
double a = y1-y2;
double b = x2-x1;
double c = x1*y2-x2*y1;
return new DoubleTriplet(a,b,c);
}
public double putx(DoubleTriplet T,double x) {
return -(T.a*x+T.c)/T.b;
}
public double puty(DoubleTriplet T,double y) {
return -(T.b*y+T.c)/T.a;
}
public double DistanceofPointandLine(DoublePair P,Triplet T) {
return Math.abs(P.a*T.a+P.b*T.b+T.c) / Math.sqrt(T.a*T.a+T.b*T.b);
}
public boolean cross(long ax, long ay, long bx, long by, long cx, long cy, long dx, long dy) {
long ta = (cx - dx) * (ay - cy) + (cy - dy) * (cx - ax);
long tb = (cx - dx) * (by - cy) + (cy - dy) * (cx - bx);
long tc = (ax - bx) * (cy - ay) + (ay - by) * (ax - cx);
long td = (ax - bx) * (dy - ay) + (ay - by) * (ax - dx);
return((tc>=0&&td<=0)||(tc<=0&&td>=0))&&((ta>=0&&tb<=0)||(ta<=0&&tb>=0));
}
public boolean dcross(double ax, double ay, double bx, double by, double cx, double cy, double dx, double dy) {
double ta = (cx - dx) * (ay - cy) + (cy - dy) * (cx - ax);
double tb = (cx - dx) * (by - cy) + (cy - dy) * (cx - bx);
double tc = (ax - bx) * (cy - ay) + (ay - by) * (ax - cx);
double td = (ax - bx) * (dy - ay) + (ay - by) * (ax - dx);
return((tc>=0&&td<=0)||(tc<=0&&td>=0))&&((ta>=0&&tb<=0)||(ta<=0&&tb>=0));
}
void buildFac(){
fac = new long[10000003];
revfac = new long[10000003];
fac[0] = 1;
for(int i=1;i<=10000002;i++){
fac[i] = (fac[i-1] * i)%mod;
}
revfac[10000002] = rev(fac[10000002])%mod;
for(int i=10000001;i>=0;i--) {
revfac[i] = (revfac[i+1] * (i+1))%mod;
}
isBuild = true;
}
public long[] buildrui(int[] a) {
int n = a.length;
long[] ans = new long[n];
ans[0] = a[0];
for(int i=1;i<n;i++) {
ans[i] = ans[i-1] + a[i];
}
return ans;
}
public long[][] buildrui(int[][] a) {
int n = a.length;
int m = a[0].length;
long[][] ans = new long[n][m];
for(int i=1;i<n;i++) {
for(int j=1;j<m;j++) {
ans[i][j] = a[i][j];
}
}
for(int i=1;i<n;i++) {
for(int j=1;j<m;j++) {
ans[i][j] += ans[i][j-1] + ans[i-1][j] - ans[i-1][j-1];
}
}
return ans;
}
long divroundup(long n,long d) {
if(n==0)return 0;
return (n-1)/d+1;
}
public long sigma(long i) {
return i*(i+1)/2;
}
public int digit(long i) {
int ans = 1;
while(i>=10) {
i /= 10;
ans++;
}
return ans;
}
public int popcount(int i) {
int ans = 0;
while(i>0) {
ans += i%2;
i /= 2;
}
return ans;
}
public boolean contains(int S,int i) {return (S>>i&1)==1;}
public int bitremove(int S,int i) {return S&(~(1<<i));}
public int bitadd(int S,int i) {return S|(1<<i);}
public boolean isSubSet(int S,int T) {return (S-T)==(S^T);}
public boolean isDisjoint(int S,int T) {return (S+T)==(S^T);}
public int isBigger(int[] d, int i) {
int ok = d.length;
int ng = -1;
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d[mid]>i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isSmaller(int[] d, int i) {
int ok = -1;
int ng = d.length;
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d[mid]<i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isBigger(long[] d, long i) {
int ok = d.length;
int ng = -1;
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d[mid]>i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isSmaller(long[] d, long i) {
int ok = -1;
int ng = d.length;
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d[mid]<i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isBigger(ArrayList<Long> d, long i) {
int ok = d.size();
int ng = -1;
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d.get(mid)>i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public int isSmaller(ArrayList<Long> d, long i) {
int ok = -1;
int ng = d.size();
while(Math.abs(ok-ng)>1) {
int mid = (ok+ng)/2;
if(d.get(mid)<i) {
ok = mid;
}else {
ng = mid;
}
}
return ok;
}
public HashSet<Integer> primetable(int m) {
HashSet<Integer> pt = new HashSet<Integer>();
for(int i=2;i<=m;i++) {
boolean b = true;
for(int d:pt) {
if(i%d==0) {
b = false;
break;
}
}
if(b) {
pt.add(i);
}
}
return pt;
}
public ArrayList<Integer> primetablearray(int m) {
ArrayList<Integer> al = new ArrayList<Integer>();
Queue<Integer> q = new ArrayDeque<Integer>();
for(int i=2;i<=m;i++) {
q.add(i);
}
boolean[] b = new boolean[m+1];
while(!q.isEmpty()) {
int e = q.poll();
if(!b[e]) {
al.add(e);
for(int j=1;e*j<=1000000;j++) {
b[e*j] = true;
}
}
}
return al;
}
public HashMap<Integer,Integer> hipPush(ArrayList<Integer> l){
HashMap<Integer,Integer> r = new HashMap<Integer,Integer>();
TreeSet<Integer> s = new TreeSet<Integer>();
for(int e:l)s.add(e);
int p = 0;
for(int e:s) {
r.put(e,p);
p++;
}
return r;
}
public TreeMap<Integer,Integer> thipPush(ArrayList<Integer> l){
TreeMap<Integer,Integer> r = new TreeMap<Integer,Integer>();
Collections.sort(l);
int b = -(mod+9393);
int p = 0;
for(int e:l) {
if(b!=e) {
r.put(e,p);
p++;
}
b=e;
}
return r;
}
long max(long[] a){
long M = 0;
for(int i=0;i<a.length;i++){
if(M<a[i]){
M =a[i];
maxdex = i;
}
}
return M;
}
int max(int[] a){
int M = 0;
for(int i=0;i<a.length;i++){
if(M<a[i]){
M =a[i];
maxdex = i;
}
}
return M;
}
long min(long[] a){
long m = Long.MAX_VALUE;
for(int i=0;i<a.length;i++){
if(m>a[i]){
m =a[i];
mindex = i;
}
}
return m;
}
int min(int[] a){
int m = Integer.MAX_VALUE;
for(int i=0;i<a.length;i++){
if(m>a[i]){
m =a[i];
mindex = i;
}
}
return m;
}
long sum(long[] a){
long s = 0;
for(int i=0;i<a.length;i++)s += a[i];
return s;
}
long sum(int[] a){
long s = 0;
for(int i=0;i<a.length;i++)s += a[i];
return s;
}
long gcd(long a, long b){
a = Math.abs(a);
b = Math.abs(b);
if(a==0)return b;
if(b==0)return a;
if(a%b==0) return b;
else return gcd(b,a%b);
}
int igcd(int a, int b) {
if(a%b==0) return b;
else return igcd(b,a%b);
}
long lcm(long a, long b) {return a / gcd(a,b) * b;}
public long perm(int a,int num) {
if(!isBuild)buildFac();
return fac[a]*(rev(fac[a-num]))%mod;
}
void buildComb(int N) {
comb = new long[N+1][N+1];
comb[0][0] = 1;
for(int i=1;i<=N;i++) {
comb[i][0] = 1;
for(int j=1;j<N;j++) {
comb[i][j] = comb[i-1][j-1]+comb[i-1][j];
if(comb[i][j]>mod)comb[i][j]-=mod;
}
comb[i][i] = 1;
}
}
public long comb(int a,int num){
if(a-num<0)return 0;
if(num<0)return 0;
if(!isBuild)buildFac();
return fac[a] * ((revfac[num]*revfac[a-num])%mod)%mod;
}
long mulchoose(int n,int k) {
if(k==0) return 1;
return comb(n+k-1,k);
}
long rev(long l) {return pow(l,mod-2);}
void buildpow(int l,int i) {
pow = new long[i+1];
pow[0] = 1;
for(int j=1;j<=i;j++) {
pow[j] = pow[j-1]*l;
if(pow[j]>mod)pow[j] %= mod;
}
}
void buildrevpow(int l,int i) {
revpow = new long[i+1];
revpow[0] = 1;
for(int j=1;j<=i;j++) {
revpow[j] = revpow[j-1]*l;
if(revpow[j]>mod) revpow[j] %= mod;
}
}
long pow(long l, long i) {
if(i==0)return 1;
else{
if(i%2==0){
long val = pow(l,i/2);
return val * val % mod;
}
else return pow(l,i-1) * l % mod;
}
}
}
|
np
|
1242_C. Sum Balance
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
public class B {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// System.setIn(new FileInputStream("b.in"));
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String[] parts = bf.readLine().trim().split("[ ]+");
int N = Integer.parseInt(parts[0]);
int K = Integer.parseInt(parts[1]);
int[] nums = new int[N];
int idx = 0;
String line = bf.readLine();
for(int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if(c == ' ') idx++;
else {
int d = c - '0';
nums[idx] = 10 * nums[idx] + d;
}
}
int from = -1, to = -1;
HashMap<Integer, Integer> count = new HashMap<Integer, Integer>();
for(int i = 0; i < N; i++) {
Integer q = count.get(nums[i]);
if(q == null) count.put(nums[i], 1);
else count.put(nums[i], q + 1);
if(count.size() == K) {
to = i;
break;
}
}
if(count.size() < K) {
System.out.println("-1 -1");
return;
}
for(from = 0; from <= to; from++) {
Integer q = count.get(nums[from]);
if(q == 1) count.remove(nums[from]);
else count.put(nums[from], q - 1);
if(count.size() < K) break;
}
System.out.println((from + 1) + " " + (to + 1));
}
}
|
linear
|
224_B. Array
|
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.Arrays;
import java.util.StringTokenizer;
public class LookingForOrder {
static final int INF = (int)1e9;
static Point a[];
static Point o;
static int n;
static int dp[];
static PrintWriter out;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
o = new Point(sc.nextInt(), sc.nextInt());
n = sc.nextInt();
a = new Point[n];
for (int i = 0; i < n; i++)
a[i] = new Point(sc.nextInt(), sc.nextInt());
dp = new int[(1 << n) + 5];
Arrays.fill(dp, -1);
out.println(rec(0));
out.print(0 + " ");
path(0);
out.println();
out.flush();
out.close();
}
static void path(int msk) {
if (msk == (1 << n) - 1) return;
int optimal = rec(msk);
for (int i = 0; i < n; i++) {
if ((msk & (1 << i)) == 0) {
if (rec(msk | (1 << i)) + 2 * o.dist(a[i]) == optimal) {
out.print((i + 1) + " " + 0 + " ");
path(msk | (1 << i));
return;
}
for (int j = 0; j < n; j++)
if (rec(msk | (1 << i) | (1 << j)) + o.dist(a[i]) + a[i].dist(a[j]) + a[j].dist(o) == optimal) {
out.print((i + 1) + " " + (j + 1) + " " + 0 + " ");
path(msk | (1 << i) | (1 << j));
return;
}
break;
}
}
}
static int rec(int msk) {
if (msk == (1 << n) - 1) return 0;
if (dp[msk] != -1) return dp[msk];
int ans = INF;
for (int i = 0; i < n; i++) {
if ((msk & (1 << i)) == 0) {
ans = Math.min(ans, rec(msk | (1 << i)) + 2 * o.dist(a[i]));
for (int j = 0; j < n; j++) {
if (i == j) continue;
if ((msk & (1 << j)) == 0)
ans = Math.min(ans, rec(msk | (1 << i) | (1 << j)) + o.dist(a[i]) + a[i].dist(a[j]) + a[j].dist(o));
}
break;
}
}
return dp[msk] = ans;
}
static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int dist(Point p) {
return (x - p.x) * (x - p.x) + (y - p.y) * (y - p.y);
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(FileReader f) {
br = new BufferedReader(f);
}
public Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean Ready() throws IOException {
return br.ready();
}
public void waitForInput(long time) {
long ct = System.currentTimeMillis();
while(System.currentTimeMillis() - ct < time) {};
}
}
}
|
np
|
8_C. Looking for Order
|
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 Alex
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
int n;
boolean[][] adj;
long[] mem;
int start;
long cycles(int cur, int visited) {
if (cur == start && visited > 0) {
return Integer.bitCount(visited) >= 3 ? 1 : 0;
}
int index = visited * n + cur;
if (mem[index] != -1) return mem[index];
long res = 0;
int newvisited = visited | (1 << cur);
for (int nxt = 0; nxt < n; nxt++)
if (adj[cur][nxt]) {
if (nxt >= start && (nxt == start || ((visited >> nxt) & 1) == 0)) {
res += cycles(nxt, newvisited);
}
}
return mem[index] = res;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
int m = in.readInt();
mem = new long[n * (1 << n)];
adj = new boolean[n][n];
for (int i = 0; i < m; i++) {
int a = in.readInt() - 1, b = in.readInt() - 1;
adj[a][b] = true;
adj[b][a] = true;
}
long res = 0;
for (int start = 0; start < n; start++) {
Arrays.fill(mem, -1);
this.start = start;
res += cycles(start, 0) / 2;
}
out.printLine(res);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
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);
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Subtractions {
public static void main(String[] args) {
InputReader r = new InputReader(System.in);
int n = r.nextInt();
while (n-- > 0) {
int a = r.nextInt();
int b = r.nextInt();
int res = 0;
while (a > 0 && b > 0) {
if (a > b) {
int div = a / b;
a -= div * b;
res += div;
} else {
int div = b / a;
b -= div * a;
res += div;
}
}
System.out.println(res);
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 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());
}
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.util.*;
public class cf573 {
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
int n=0;
if(scan.hasNext())
n=scan.nextInt();
TreeSet<Integer> set=new TreeSet<>();
for(int i=0;i<n;i++){
if(scan.hasNext())
set.add(scan.nextInt());
}
int[] arr=new int[set.size()];
Iterator<Integer> it=set.iterator();
int j=0;
while(it.hasNext()){
arr[j++]=it.next();
}
int tot=1,flag;
for(int i=1;i<arr.length;i++){
flag=0;
for(int k=0;k<i;k++){
if(arr[i]%arr[k]==0){
flag=1;
break;
}
}
if(flag==0){
tot++;
}
}
System.out.println(tot);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class Codeforces {
static long MOD = 1_000_000_007L;
static void main2() throws Exception {
int n = ni();
int[] arr = nia(n);
Map<Integer, List<Pair<Integer, Integer>>> map = new HashMap<>();
for(int r = 0; r < n; r++) {
int sum = 0;
for(int l = r; l >= 0; l--) {
sum += arr[l];
if(!map.containsKey(sum)) map.put(sum, new ArrayList<Pair<Integer, Integer>>());
map.get(sum).add(new Pair<Integer, Integer>(l + 1, r + 1));
}
}
int bestSum = Integer.MIN_VALUE;
int bestSumCount = -1;
for(Map.Entry<Integer, List<Pair<Integer, Integer>>> entry : map.entrySet()) {
int count = 0;
int r = -1;
for(Pair<Integer, Integer> pair : entry.getValue()) {
if(r < pair.first) {
count++;
r = pair.second;
}
}
if(count > bestSumCount) {
bestSumCount = count;
bestSum = entry.getKey();
}
}
//got best sum
println(bestSumCount);
int r = -1;
for(Pair<Integer, Integer> pair : map.get(bestSum)) {
if(r < pair.first) {
println(pair.first + " " + pair.second);
r = pair.second;
}
}
}
// ____________________________________________________________________________
//| |
//| /$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$$$$$ /$$$$$$ |
//| |_ $$_/ /$$__ $$ /$$__ $$ | $$ /$$__ $$ /$$__ $$ |
//| | $$ | $$ \ $$ | $$ \__//$$$$$$ /$$ /$$| $$ \__/| $$ \__/ |
//| | $$ | $$ | $$ | $$$$$$|_ $$_/ | $$ | $$| $$$$ | $$$$ |
//| | $$ | $$ | $$ \____ $$ | $$ | $$ | $$| $$_/ | $$_/ |
//| | $$ | $$ | $$ /$$ \ $$ | $$ /$$| $$ | $$| $$ | $$ |
//| /$$$$$$| $$$$$$/ | $$$$$$/ | $$$$/| $$$$$$/| $$ | $$ |
//| |______/ \______/ \______/ \___/ \______/ |__/ |__/ |
//|____________________________________________________________________________|
private static byte[] scannerByteBuffer = new byte[1024]; // Buffer of Bytes
private static int scannerIndex;
private static InputStream scannerIn;
private static int scannerTotal;
private static BufferedWriter printerBW;
private static boolean DEBUG = false;
private static int next() throws IOException { // Scan method used to scan buf
if (scannerTotal < 0)
throw new InputMismatchException();
if (scannerIndex >= scannerTotal) {
scannerIndex = 0;
scannerTotal = scannerIn.read(scannerByteBuffer);
if (scannerTotal <= 0)
return -1;
}
return scannerByteBuffer[scannerIndex++];
}
static int ni() throws IOException {
int integer = 0;
int n = next();
while (isWhiteSpace(n)) // Removing startPointing whitespaces
n = next();
int neg = 1;
if (n == '-') { // If Negative Sign encounters
neg = -1;
n = next();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = next();
} else
throw new InputMismatchException();
}
return neg * integer;
}
static long nl() throws IOException {
long integer = 0;
int n = next();
while (isWhiteSpace(n)) // Removing startPointing whitespaces
n = next();
int neg = 1;
if (n == '-') { // If Negative Sign encounters
neg = -1;
n = next();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = next();
} else
throw new InputMismatchException();
}
return neg * integer;
}
static String line() throws IOException {
StringBuilder sb = new StringBuilder();
int n = next();
while (isWhiteSpace(n))
n = next();
while (!isNewLine(n)) {
sb.append((char) n);
n = next();
}
return sb.toString();
}
private static boolean isNewLine(int n) {
return n == '\n' || n == '\r' || n == -1;
}
private static boolean isWhiteSpace(int n) {
return n == ' ' || isNewLine(n) || n == '\t';
}
static int[] nia(int n) throws Exception {
if (n < 0)
throw new Exception("Array size should be non negative");
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = ni();
return array;
}
static int[][] n2dia(int r, int c) throws Exception {
if (r < 0 || c < 0)
throw new Exception("Array size should be non negative");
int[][] array = new int[r][c];
for (int i = 0; i < r; i++)
array[i] = nia(c);
return array;
}
static long[] nla(int n) throws Exception {
if (n < 0)
throw new Exception("Array size should be non negative");
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nl();
return array;
}
static float[] nfa(int n) throws Exception {
if (n < 0)
throw new Exception("Array size should be non negative");
float[] array = new float[n];
for (int i = 0; i < n; i++)
array[i] = nl();
return array;
}
static double[] nda(int n) throws Exception {
if (n < 0)
throw new Exception("Array size should be non negative");
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nl();
return array;
}
static <T> void print(T ... str) {
try {
for(T ele : str)
printerBW.append(ele.toString());
if (DEBUG)
flush();
} catch (IOException e) {
System.out.println(e.toString());
}
}
static <T> void println(T ... str) {
if(str.length == 0) {
print('\n');
return;
}
for(T ele : str)
print(ele, '\n');
}
static void flush() throws IOException {
printerBW.flush();
}
static void close() {
try {
printerBW.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
public static void main(String[] args) throws Exception {
long startPointTime = System.currentTimeMillis();
scannerIn = System.in;
printerBW = new BufferedWriter(new OutputStreamWriter(System.out));
if (args.length > 0 && args[0].equalsIgnoreCase("debug")
|| args.length > 1 && args[1].equalsIgnoreCase("debug"))
DEBUG = true;
main2();
long endTime = System.currentTimeMillis();
float totalProgramTime = endTime - startPointTime;
if (args.length > 0 && args[0].equalsIgnoreCase("time") || args.length > 1 && args[1].equalsIgnoreCase("time"))
print("Execution time is " + totalProgramTime + " (" + (totalProgramTime / 1000) + "s)");
close();
}
static class Pair <L, R> {
L first;
R second;
Pair(L first, R second) {
this.first = first;
this.second = second;
}
public boolean equals(Object p2) {
if (p2 instanceof Pair) {
return ((Pair) p2).first.equals(first) && ((Pair) p2).second.equals(second);
}
return false;
}
public String toString() {
return "(first=" + first.toString() + ",second=" + second.toString() + ")";
}
}
static class DisjointSet {
int[] arr;
int[] size;
DisjointSet(int n) {
arr = new int[n + 1];
size = new int[n + 1];
makeSet();
}
void makeSet() {
for (int i = 1; i < arr.length; i++) {
arr[i] = i;
size[i] = 1;
}
}
void union(int i, int j) {
if (i == j)
return;
if (i > j) {
i ^= j;
j ^= i;
i ^= j;
}
i = find(i);
j = find(j);
if (i == j)
return;
arr[j] = arr[i];
size[i] += size[j];
size[j] = size[i];
}
int find(int i) {
if (arr[i] != i) {
arr[i] = find(arr[i]);
size[i] = size[arr[i]];
}
return arr[i];
}
int getSize(int i) {
i = find(i);
return size[i];
}
public String toString() {
return Arrays.toString(arr);
}
}
static boolean isSqrt(double a) {
double sr = Math.sqrt(a);
return ((sr - Math.floor(sr)) == 0);
}
static long abs(long a) {
return Math.abs(a);
}
static int min(int ... arr) {
int min = Integer.MAX_VALUE;
for (int var : arr)
min = Math.min(min, var);
return min;
}
static long min(long ... arr) {
long min = Long.MAX_VALUE;
for (long var : arr)
min = Math.min(min, var);
return min;
}
static int max(int... arr) {
int max = Integer.MIN_VALUE;
for (int var : arr)
max = Math.max(max, var);
return max;
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
public class naloga1{
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out=new PrintWriter(System.out);
public static void main(String[] args) throws Exception{
StringTokenizer st=new StringTokenizer(in.readLine());
int n=Integer.parseInt(st.nextToken());
int r=Integer.parseInt(st.nextToken());
int[] x=new int[n];
st=new StringTokenizer(in.readLine());
for(int i=0;i < n;i++){
x[i]=Integer.parseInt(st.nextToken());
}
sim a=new sim(n,r);
for(int i:x) {
a.add(i);
}
for(double d:a.cy) {
out.print(d+" ");
}
out.println();
out.close();
}
}
class sim{
double[]cx;
int[]ccx;
double[]cy;
int count;
int n;
int r;
sim(int nn,int rr){
r=rr;
n=nn;
cx=new double[n];
ccx=new int[n];
cy=new double[n];
count=0;
}
void add(int x) {
double lowest=r;
for(int i=0;i<count;i++) {
if(Math.abs(ccx[i]-x)<=2*r) {
double dy=Math.sqrt(4*r*r-(ccx[i]-x)*(ccx[i]-x));
lowest=Math.max(lowest,cy[i]+dy);
}
}
ccx[count]=x;
cy[count]=lowest;
cx[count++]=x;
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{
static class FastScanner {
BufferedReader br;
StringTokenizer stok;
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
int ni() throws IOException {
return Integer.parseInt(next());
}
long nl() throws IOException {
return Long.parseLong(next());
}
double nd() throws IOException {
return Double.parseDouble(next());
}
char nc() throws IOException {
return (char) (br.read());
}
String nextLine() throws IOException {
return br.readLine();
}
int[] niArray(int n) throws IOException{
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
long[] nlArray(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
double[] ndArray(int n)throws IOException {
double a[] = new double[n];
for (int i = 0; i < n; i++)
a[i] = nd();
return a;
}
}
static long mod=Long.MAX_VALUE;
static PrintWriter out=new PrintWriter(System.out);
static FastScanner in = new FastScanner(System.in);
public static void main (String[] args) throws java.lang.Exception
{ int i,j;
long flag,flag1,flag2,temp,temp2,temp1,count,counter,l;
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
/*
if(hm.containsKey(z))
hm.put(z,hm.get(z)+1);
else
hm.put(z,1);
*/
ArrayList<Integer> arr=new ArrayList<Integer>();
HashSet<Integer> set=new HashSet<Integer>();
PriorityQueue<Integer> pq=new PriorityQueue<Integer>();
//for(i=1;i<200;i++)
//{
long k=in.nl();
temp=9;l=1;temp2=0;
while(true)
{ if(k<=temp2+temp*l)
{k-=temp2;break;}
else
{ temp2+=temp*l;
temp*=10;
l++;
}
}
long z=((k-1)/l);
//out.println(i+":- "+l+" "+((k-1)/l)+" "+(k%l==0?l:k%l));
long no=(long)Math.pow(10,(l-1))+z;
//out.println(no);
int index=(int)(k%l==0?l:k%l)-1;
String p=Long.toString(no);
//out.println(p+" "+index);
out.println(p.charAt(index));
//}
out.close();
}
static long gcd(long a,long b)
{ if(b==0)
return a;
return gcd(b,a%b);
}
static long exponent(long a,long n)
{ long ans=1;
while(n!=0)
{ if(n%2==0)
ans=(ans*a)%mod;
a=(a*a)%mod;
n=n>>1;
}
return ans;
}
static int binarySearch(int a[], int item, int low, int high)
{ if (high <= low)
return (item > a[low])? (low + 1): low;
int mid = (low + high)/2;
if(item == a[mid])
return mid+1;
if(item > a[mid])
return binarySearch(a, item, mid+1, high);
return binarySearch(a, item, low, mid-1);
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
/**
* User: serparamon
*/
public class Codeforces_2012_08_31_A {
public static void main(String[] args) throws IOException {
//Scanner in = new Scanner(System.in);
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(System.out);
in.nextToken();
int n = (int) in.nval;
int[] a = new int[n];
for (int i=0; i<n; i++) {
in.nextToken();
a[i] = (int) in.nval;
}
int[] b = Arrays.copyOf(a, n);
Arrays.sort(a);
int k = 0;
for (int i=0; i<n; i++) {
if (a[i] != b[i]) k++;
}
if (k==0 || k==2)
out.println("YES");
else
out.println("NO");
out.flush();
out.close();
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
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
*/
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);
DExplorerSpace solver = new DExplorerSpace();
solver.solve(1, in, out);
out.close();
}
static class DExplorerSpace {
static final int oo = 1000000000;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
int[][] right = new int[n][m - 1];
int[][] down = new int[n - 1][m];
for (int i = 0; i < n; i++) right[i] = in.readIntArray(m - 1);
for (int i = 0; i + 1 < n; i++) down[i] = in.readIntArray(m);
if (k % 2 == 1) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) out.print(-1 + " ");
out.println();
}
return;
}
int[][][] dp = new int[k / 2 + 1][n][m];
for (int r = 1; 2 * r <= k; r++) {
for (int i = 0; i < n; i++) Arrays.fill(dp[r][i], oo);
for (int i = 0; i < n; i++)
for (int j = 0; j < m - 1; j++) {
int cost = right[i][j];
dp[r][i][j] = Integer.min(dp[r][i][j], dp[r - 1][i][j + 1] + cost);
dp[r][i][j + 1] = Integer.min(dp[r][i][j + 1], dp[r - 1][i][j] + cost);
}
for (int i = 0; i + 1 < n; i++)
for (int j = 0; j < m; j++) {
int cost = down[i][j];
dp[r][i][j] = Integer.min(dp[r][i][j], dp[r - 1][i + 1][j] + cost);
dp[r][i + 1][j] = Integer.min(dp[r][i + 1][j], dp[r - 1][i][j] + cost);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.print(2 * dp[k / 2][i][j] + " ");
}
out.println();
}
}
}
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(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
writer.print('\n');
}
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[] 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 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 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);
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.util.Scanner;
public class D
{
public static void main(String[] args)
{
new D();
}
D()
{
Scanner in = new Scanner(System.in);
double a = in.nextDouble();
double v = in.nextDouble();
double l = in.nextDouble();
double d = in.nextDouble();
double w = in.nextDouble();
if (w>v) w=v;
double dx=(v*v-w*w)/(2*a);
double d0=(w*w)/(2*a);
double t=0;
if (d0>d) // doesn't make it to speed w before reaching d
{
if (d0>=l) // never gets to speed w
{
t=Math.sqrt(2*a*l)/a;
}
else
{
t=w/a;
if (d0+dx>=l) // never gets to speed v
{
t+=(-w+Math.sqrt(w*w+2*a*(l-d0)))/a;
}
else // makes it to speed v
{
t+=(v-w)/a;
t+=(l-(d0+dx))/v;
}
}
}
else // makes it to speed w before reachig d
{
t=w/a; // get up to speed w
// get time after reaching d
if (d+dx>l) // never makes it back to v after reaching d
{
t+=(-w+Math.sqrt(w*w+2*a*(l-d)))/a;
}
else // makes it to speed v after reaching d
{
t+=(v-w)/a;
t+=(l-(d+dx))/v;
}
// handle getting to d
if (d0+2*dx>d) // can't get to v before reaching d
{
double half=(d-d0)/2;
t+=2*(-w+Math.sqrt(w*w+2*a*half))/a;
}
else // can get to v before reaching d
{
t+=2*(v-w)/a;
t+=(d-2*dx-d0)/v;
}
}
System.out.printf("%.12f%n", t+1e-11);
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.util.*;
import java.math.*;
public class Solution{
private long [] sums;
private void solve(){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int [] arr = new int[n];
this.sums = new long[n];
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
sums[i] = arr[i] + (i == 0 ? 0 : sums[i - 1]);
}
long ans = 0;
for(int i = 1; i <= n && i <= m; i++){
ans = Math.max(ans, sum(0, i - 1) - k);
}
long [] dp = new long[n];
for(int i = 0; i < n; i++){
if(i + 1 >= m){
long cur = sum(i - m + 1, i) - k;
if(i - m >= 0){
cur += dp[i - m];
}
dp[i] = Math.max(dp[i], cur);
}
for(int j = 0; j <= m && i + j < n; j++){
ans = Math.max(ans, dp[i] + sum(i + 1, i + j) - k * (j > 0 ? 1 : 0));
}
}
System.out.println(ans);
}
private long sum(int l, int r){
if(l <= 0){
return sums[r];
}else{
return sums[r] - sums[l - 1];
}
}
public static void main(String [] args){
new Solution().solve();
}
}
|
quadratic
|
1197_D. Yet Another Subarray Problem
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main{
public void run(){
Locale.setDefault(Locale.US);
Scanner in = new Scanner(System.in);
int n = in.nextInt();
double a[][] = new double[n][n];
for(int i=0;i<n;i++) for(int j=0;j<n;j++) a[i][j] = in.nextDouble();
double f[] = new double[1<<n];
f[(1<<n)-1] = 1;
for(int mask = (1<<n)-1;mask > 0;mask--){
int k = Integer.bitCount(mask);
if (k == 1) continue;
for(int i=0;i<n;i++){
if ((mask & (1 << i)) > 0){
for(int j=0;j<n;j++){
if ((mask & (1 << j)) > 0){
f[mask&(~(1<<j))]+=f[mask]*a[i][j]/(k*(k-1)/2);
}
}
}
}
}
for(int i=0;i<n;i++)
System.out.print(f[1<<i]+" ");
}
public static void main(String args[]){
new Main().run();
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class R015A {
final double EPS = 1e-9;
boolean isEqual(double x, double y) {
return Math.abs(x-y) <= EPS * Math.max(Math.abs(x), Math.abs(y));
}
class Pair implements Comparable<Pair>{
double left;
double right;
Pair(double left, double right) {
this.left = left;
this.right = right;
}
public String toString() {
return "(" + left + "," + right + ")";
}
public int hashCode() {
return (int)(left * 17 + right * 31);
}
public boolean equals(Object o) {
if(!(o instanceof Pair)) return false;
Pair that = (Pair)o;
return isEqual(this.left, that.left) && isEqual(this.right, that.right);
}
public int compareTo(Pair that) {
if(this.left != that.left)
return (int)(this.left - that.left);
return (int)(this.right - that.right);
}
}
public R015A() {
}
private void process() {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int t = scanner.nextInt();
int[] x = new int[n];
int[] a = new int[n];
for(int i=0; i<n; i++) {
x[i] = scanner.nextInt();
a[i] = scanner.nextInt();
}
List<Pair> pairs = new ArrayList<Pair>();
for(int i=0; i<n; i++) {
double left = x[i] - a[i] / 2.0;
double right= x[i] + a[i] / 2.0;
pairs.add(new Pair(left, right));
}
Collections.sort(pairs);
Set<Pair> newPairs = new HashSet<Pair>();
newPairs.add(new Pair(pairs.get(0).left - t, pairs.get(0).left));
for(int i=0; i<pairs.size()-1; i++) {
if(pairs.get(i+1).left - pairs.get(i).right >= t) {
newPairs.add(new Pair(pairs.get(i).right, pairs.get(i).right + t));
newPairs.add(new Pair(pairs.get(i+1).left - t, pairs.get(i+1).left));
}
}
newPairs.add(new Pair(pairs.get(pairs.size()-1).right, pairs.get(pairs.size()-1).right + t));
System.out.println(newPairs.size());
}
public static void main(String[] args) {
new R015A().process();
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Task2 {
public static void main(String[] args) throws IOException {
new Task2().solve();
}
//ArrayList<Integer>[] g;
int mod = 1000000007;
PrintWriter out;
int n;
int m;
//int[][] a = new int[1000][1000];
//int cnt = 0;
long base = (1L << 63);
long P = 31;
int[][] a;
void solve() throws IOException {
//Reader in = new Reader("in.txt");
//out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
Reader in = new Reader();
PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
//BufferedReader br = new BufferedReader( new FileReader("in.txt") );
//BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
int n = in.nextInt();
double[][] a = new double[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
a[i][j] = in.nextDouble();
double[] dp = new double[1 << n];
dp[(1 << n) - 1] = 1;
for (int mask = (1 << n) -1; mask >= 0; mask--) {
int k = Integer.bitCount(mask);
double p = 1.0 / (k*(k-1)/2.0);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if ((mask & (1 << i)) != 0 && (mask & (1 << j)) != 0)
dp[(mask & ~(1 << j))] += p*dp[mask]*a[i][j];
}
for (int i = 0; i < n; i++)
out.print(dp[1 << i]+" ");
out.flush();
out.close();
}
long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a%b);
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (b < p.b)
return 1;
if (b > p.b)
return -1;
return 0;
}
// @Override
// public boolean equals(Object o) {
// Pair p = (Pair) o;
// return a == p.a && b == p.b;
// }
//
// @Override
// public int hashCode() {
// return Integer.valueOf(a).hashCode() + Integer.valueOf(b).hashCode();
// }
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.io.*;
import java.util.StringTokenizer;
/**
* CodeForces Round 5D. Follow Traffic Rules
* Created by Darren on 14-9-14.
*/
public class Main {
Reader in = new Reader(System.in);
PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
new Main().run();
}
int a, v;
int l, d, w;
void run() throws IOException {
a = in.nextInt();
v = in.nextInt();
l = in.nextInt();
d = in.nextInt();
w = in.nextInt();
double totalTime = 0.0;
if (v >= w) {
if (w*w >= 2*a*d) {
double x = Math.sqrt(2*a*d);
totalTime = x / a;
if ((v*v-x*x) >= 2*a*(l-d))
totalTime += (-2*x+Math.sqrt(4*x*x+8*a*(l-d))) / (2*a);
else
totalTime += (v-x)/(1.0*a) + (l-d-(v*v-x*x)/(2.0*a))/v;
} else {
// totalTime = (-2*w+Math.sqrt(4*w*w+8*a*(l-d))) / (2*a);
if (2*v*v-w*w <= 2*a*d) {
totalTime = v / (1.0*a) + (v-w) / (1.0*a) + (d-(2*v*v-w*w)/(2.0*a)) / v;
} else {
double x = Math.sqrt((2*a*d+w*w)/2.0);
totalTime = x / a + (x-w) / a;
}
if ((v*v-w*w) >= 2*a*(l-d))
totalTime += (-2*w+Math.sqrt(4*w*w+8*a*(l-d))) / (2*a);
else
totalTime += (v-w)/(1.0*a) + (l-d-(v*v-w*w)/(2.0*a))/v;
}
} else {
if (v*v >= 2*a*l)
totalTime = Math.sqrt(l*2.0/a);
else
totalTime = v / (1.0*a) + (l-v*v/(2.0*a)) / v;
}
out.printf("%.10f", totalTime);
out.flush();
}
void solve() throws IOException {
}
static class Reader {
BufferedReader reader;
StringTokenizer tokenizer;
public Reader(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/** get next word */
String nextToken() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer( reader.readLine() );
}
return tokenizer.nextToken();
}
String readLine() throws IOException {
return reader.readLine();
}
char nextChar() throws IOException {
return (char)reader.read();
}
int nextInt() throws IOException {
return Integer.parseInt( nextToken() );
}
long nextLong() throws IOException {
return Long.parseLong( nextToken() );
}
double nextDouble() throws IOException {
return Double.parseDouble( nextToken() );
}
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
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);
}
int nextInt() {
try {
in.nextToken();
return Integer.parseInt(in.sval);
} catch (IOException e) {
throw new Error();
}
}
String next() {
try {
in.nextToken();
return in.sval;
} catch (IOException e) {
throw new Error();
}
}
}
static class Value implements Comparable <Value> {
int x;
int pos;
Value(int x, int pos) {
this.x = x;
this.pos = pos;
}
public int compareTo(Value second) {
if (this.x == second.x) {
return this.pos - second.pos;
} else {
return this.x - second.x;
}
}
}
void solve() {
int n = in.nextInt();
Value ar[] = new Value[n];
for (int i = 0; i < n; i++) {
ar[i] = new Value(in.nextInt(), i);
}
Arrays.sort(ar);
int cnt = 0;
//LinkedList <Integer> gavno = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
if (ar[i].pos != i && ar[ar[i].pos].x != ar[i].x) {
cnt++;
//gavno.add(i);
}
}
if (cnt > 2) {
out.println("NO");
} else {
out.println("YES");
}
}
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
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.util.*;
public class b {
static int n,k,A;
static int[] l,p;
static double [][][] memo;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
A = in.nextInt();
memo = new double[n+1][n+1][1<<n];
l = new int[n];
p = new int[n];
for(int i=0; i<n; i++) {
l[i] = in.nextInt();
p[i] = in.nextInt();
}
System.out.printf("%.10f%n",go(0,k));
}
static double go(int pos, int left) {
if(pos==n) {
for(int i=0; i<=n; i++)
for(int j=0; j<=n; j++)
Arrays.fill(memo[i][j],-1);
return go2(0,n/2+1,0);
}
double best = go(pos+1,left);
if(left == 0) return best;
if(p[pos] < 100) {
p[pos] += 10;
best = Math.max(best, go(pos,left-1));
p[pos] -= 10;
}
return best;
}
static double go2(int pos, int needed, int mask) {
if(needed == 0) return 1.0;
if(pos == n) {
int tot = 0;
for(int i=0; i<n; i++)
if((mask&(1<<i))!=0)
tot += l[n-i-1];
return (A)/(A+tot+0.0);
}
if(memo[pos][needed][mask] != -1)
return memo[pos][needed][mask];
double a = (p[pos]/100.)*go2(pos+1,needed-1,mask*2);
double b = (1-(p[pos]/100.))*go2(pos+1,needed,mask*2+1);
return memo[pos][needed][mask] = a+b;
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class KeyboardPurchase {
static final int INF = 1000000000;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out, false);
int N = in.nextInt(), M = in.nextInt();
String str = in.next();
int[][] count = new int[M][M];
for (int i = 1; i < N; i++) {
char c1 = str.charAt(i - 1), c2 = str.charAt(i);
count[c1 - 'a'][c2 - 'a']++;
count[c2 - 'a'][c1 - 'a']++;
}
int[] dp = new int[(1 << M)];
Arrays.fill(dp, INF);
dp[0] = 0;
for (int mask = 1; mask < (1 << M); mask++) {
int slow = 0;
for (int i = 0; i < M; i++) {
if ((mask & (1 << i)) != 0) {
for (int j = 0; j < M; j++) {
if ((mask & (1 << j)) == 0) {
slow += count[i][j];
}
}
}
}
for (int i = 0; i < M; i++) {
if ((mask & (1 << i)) != 0) {
dp[mask] = Math.min(dp[mask], slow + dp[mask ^ (1 << i)]);
}
}
}
out.println(dp[(1 << M) - 1]);
out.close();
System.exit(0);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author hheng
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] chores = new int[n];
for (int i=0; i<n; i++) chores[i] = in.nextInt();
Arrays.sort(chores);
out.println(chores[b]-chores[b-1]);
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.io.IOException;
import java.util.Scanner;
public class TC
{
static long N;
static int k;
static long WHOLESUM;
static long SUM( long k )
{
long res=k*( k+1 )/2;
return res-1;
}
static long returnPipes( int mid )
{
long not=SUM( mid-1 );
long totpipes=WHOLESUM-not;
int number=k-mid+1;
long res=totpipes-number+1;
return res;
}
static long binarySearch( int lo, int hi )
{
int res=Integer.MAX_VALUE;
int val=0;
while( lo <= hi )
{
int mid=( lo+hi )/2;
long cnt=returnPipes( mid );
val=k-mid+1;;
if( cnt < N )
{
hi=mid-1;
continue;
}
else
{
res=Math.min( val, res );
lo=mid+1;
}
}
if( res==Integer.MAX_VALUE )
return -1;
else
return res;
}
public static void main( String[] args ) throws IOException
{
Scanner s=new Scanner( System.in );
N=s.nextLong();
k=s.nextInt();
WHOLESUM=SUM( k );
if( N<=1 )
System.out.println(0 );
else
System.out.println( binarySearch( 2, k ) );
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class C_Edu_Round_23 {
public static long MOD = 1000000007;
static long[][][][] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
long n = in.nextLong();
long s = in.nextLong();
if (s == 0) {
out.println(n);
} else {
String N = "" + n;
dp = new long[N.length()][163][2][2];
long re = 0;
for (int i = 1; i < 163 && i <= n; i++) {
long tmp = s + i;
if (tmp <= n) {
String S = "" + tmp;
while(S.length() < N.length()){
S = '0' + S;
}
for (long[][][] a : dp) {
for (long[][] b : a) {
for (long[] c : b) {
Arrays.fill(c, -1);
}
}
}
re += cal(0, i, 0, 0, N, S);
}
}
out.println(re);
}
out.close();
}
public static long cal(int index, int left, int lessThanN, int largerThanS, String n, String s) {
if (index == n.length()) {
if (left == 0) {
return 1;
}
return 0;
}
if (dp[index][left][lessThanN][largerThanS] != -1) {
return dp[index][left][lessThanN][largerThanS];
}
int x = n.charAt(index) - '0';
int y = s.charAt(index) - '0';
long re = 0;
for (int i = 0; i < 10 && i <= left; i++) {
if (i <= x || lessThanN == 1) {
if (i >= y || largerThanS == 1) {
re += cal(index + 1, left - i, i < x ? 1 : lessThanN, i > y ? 1 : largerThanS, n, s);
}
}
}
return dp[index][left][lessThanN][largerThanS] = re;
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
//package round429;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
// 203530
public class C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
for(int i = 0;i < n;i++){
int v = a[i];
for(int j = 2;j*j <= v;j++){
while(v % (j*j) == 0){
v /= j*j;
}
}
a[i] = v;
}
Arrays.sort(a);
int[] f = new int[n];
int p = 0;
for(int i= 0;i < n;i++){
if(i > 0 && a[i] != a[i-1]){
p++;
}
f[p]++;
}
f = Arrays.copyOf(f, p+1);
int mod = 1000000007;
int[][] fif = enumFIF(1000, mod);
long[] res = countSameNeighborsSequence(f, fif, mod);
long ans = res[0];
for(int v : f){
ans = ans * fif[0][v] % mod;
}
out.println(ans);
}
public static int[][] enumFIF(int n, int mod) {
int[] f = new int[n + 1];
int[] invf = new int[n + 1];
f[0] = 1;
for (int i = 1; i <= n; i++) {
f[i] = (int) ((long) f[i - 1] * i % mod);
}
long a = f[n];
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
invf[n] = (int) (p < 0 ? p + mod : p);
for (int i = n - 1; i >= 0; i--) {
invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod);
}
return new int[][] { f, invf };
}
public static long[] countSameNeighborsSequence(int[] a, int[][] fif, int mod)
{
int all = 0;
for(int v : a)all += v;
int len = 0;
long[] dp = new long[all+1];
dp[0] = 1;
for(int v : a){
long[][] pre = new long[all+1][v+1];
for(int j = 0;j <= all;j++)pre[j][0] = dp[j];
for(int j = 0;j < v;j++){
for(int k = 0;k <= all;k++){
for(int L = j;L >= 0;L--){
if(pre[k][L] == 0)continue;
int ca = 2*(j-L);
int ab = len+j+1-k-ca-L;
if(ab < 0)continue;
if(k-1 >= 0){
pre[k-1][L] += pre[k][L]*k; // aca
pre[k-1][L] %= mod;
}
if(L+1 <= v){
pre[k][L+1] += pre[k][L]*(ca+L);
pre[k][L+1] %= mod;
}
pre[k][L] = pre[k][L]*ab%mod;
}
}
}
Arrays.fill(dp, 0);
for(int k = 0;k <= all;k++){
for(int L = 0;L <= v && k+L <= all;L++){
dp[k+L] += pre[k][L];
}
}
for(int k = 0;k <= all;k++){
dp[k] %= mod;
}
// for(int k = 0;k <= all;k++){
// dp[k] = dp[k] % mod * fif[1][v] % mod;
// }
len += v;
}
long fifs = 1;
for(int v : a)fifs = fifs * fif[1][v] % mod;
for(int k = 0;k <= all;k++)dp[k] = dp[k] * fifs % mod;
return dp;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new C().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
cubic
|
840_C. On the Bench
|
CODEFORCES
|
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
public class Main implements Runnable {
/**
* @param args
*/
public static void main(String[] args) {
new Thread(new Main()).start();
}
public void run() {
Locale.setDefault(Locale.US);
try {
run1();
} catch (IOException e) {
throw new RuntimeException();
}
}
int nextInt(StreamTokenizer st) throws IOException {
st.nextToken();
return (int) st.nval;
}
private List<Integer> kmp(String x, String a) {
String s = a + "$" + x;
int[] oppa = new int[s.length()];
oppa[0] = 0;
int tmp = 0;
List<Integer> res = new ArrayList<Integer>();
for (int i = 1; i < s.length(); i++) {
while (tmp != 0 && s.charAt(tmp) != s.charAt(i)) {
// System.out.println(i + " " + tmp);
tmp = oppa[tmp - 1];
}
if (s.charAt(tmp) == s.charAt(i))
tmp++;
oppa[i] = tmp;
if (tmp == a.length()) {
res.add(i - a.length() - a.length());
}
}
return res;
}
double nextDouble(StreamTokenizer st) throws IOException {
st.nextToken();
return st.nval;
}
String nextLine(StreamTokenizer st) throws IOException {
st.nextToken();
return st.sval;
}
public void run1() throws IOException {
Scanner sc = new Scanner(new InputStreamReader(System.in));
// Scanner sc = new Scanner(new FileReader("input.txt"));
int n = sc.nextInt();
int m = sc.nextInt();
boolean[][] arr = new boolean[n][n];
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
arr[a - 1][b - 1] = true;
arr[b - 1][a - 1] = true;
}
long[][] res = new long[n][1 << n];
for (int mask = 1; mask < (1 << n); mask++) {
int min = -1;
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
if (min == -1) {
min = i;
if (mask == (1 << min))
res[min][mask] = 1;
}
for (int j = min + 1; j < n; j++)
if ((mask & (1 << j)) == 0 && arr[i][j]) {
res[j][mask | (1 << j)] += res[i][mask];
}
}
}
}
long r = 0;
for (int mask = 1; mask < (1 << n); mask++)
if (Integer.bitCount(mask) != 2)
for (int j = 0; j < n; j++) {
int i = 0;
while ((mask & (1 << i)) == 0)
i++;
if (arr[i][j])
r += res[j][mask];
}
System.out.println(r / 2);
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static double[] dp;
static double[][] P;
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int n = r.nextInt();
double[][] g = new double[n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
g[i][j] = r.nextDouble();
dp = new double[1 << n];
P = new double[1 << n][n];
for(int mask = 0; mask < 1 << n; mask++){
for(int d = 0; d < n; d++)if((mask & (1 << d)) == 0)
for(int i = 0; i < n; i++)if((mask & (1 << i)) == 0){
if(i == d)continue;
P[mask][d] += g[i][d];
}
}
for(int i = 0; i < n; i++){
Arrays.fill(dp, -1);
double res = go(i, 0, g, n, n);
System.out.println(res);
}
}
private static double go(int a, int v, double[][] g, int cnt, int n) {
if(dp[v] != -1)return dp[v];
if(cnt == 1){
return 1;
}else{
double ret = 0;
for(int d = 0; d < n; d++)if((v & (1 << d)) == 0 && d != a){
double current = P[v][d] * go(a, v | 1 << d, g, cnt-1, n);
ret += current;
}
return dp[v] = ret/(cnt * (cnt-1) /2);
}
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import static java.lang.Math.*;
import static java.util.Arrays.* ;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class D
{
int [][] adjList ;
int dfs(int u , int p )
{
int size = 1 ;
for(int v : adjList[u])
if(v != p )
{
int curr = dfs(v, u) ;
size += curr ;
}
return size ;
}
void main() throws Exception
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt() ;
int [] a = new int [n] ;
boolean [] vis = new boolean[n] ;
int cnt = 0 ;
for(int i = 0 ;i < n ; i++)
a[i] = sc.nextInt() ;
sort(a);
for(int i = 0 ;i < n ; i ++)
{
if(!vis[i])
{
for(int j= i ; j < n ; j++)
if(a[j] % a[i] == 0)
vis[j] = true ;
cnt ++ ;
}
}
out.println(cnt);
out.flush();
out.close();
}
class SegmentTree
{
int [] sTree ;
int [] lazy ;
int N ;
SegmentTree(int n)
{
N = 1 << (32 - Integer.numberOfLeadingZeros(n - 1)) ;
sTree = new int [N << 1] ;
lazy= new int [N << 1] ;
}
void push(int node , int b , int e , int mid)
{
sTree[node << 1] += (mid - b + 1) * lazy[node] ;
sTree[node << 1 | 1] += (e - mid) * lazy[node] ;
lazy[node << 1] += lazy[node] ;
lazy[node << 1 | 1] += lazy[node] ;
lazy[node] = 0 ;
}
void updateRange(int node , int b , int e , int i , int j , int val)
{
if(i > e || j < b)return;
if(i <= b && e <= j)
{
sTree[node] += (e - b + 1) * val ;
lazy[node] += val ;
return;
}
int mid = b + e >> 1 ;
push(node , b , e , mid) ;
updateRange(node << 1 , b , mid , i , j , val);
updateRange(node << 1 | 1 , mid + 1 , e , i , j , val);
sTree[node] = sTree[node << 1] + sTree[node << 1 | 1] ;
}
int query(int node , int b , int e , int i , int j)
{
if(i > e || j < b)
return 0 ;
if(i <= b && e <= j)
return sTree[node] ;
int mid = b + e >> 1 ;
push(node , b , e , mid);
return query(node << 1 , b , mid , i , j) + query(node << 1 | 1 , mid + 1 , e , i , j) ;
}
}
class Compressor
{
TreeSet<Integer> set = new TreeSet<>() ;
TreeMap<Integer ,Integer> map = new TreeMap<>() ;
void add(int x)
{
set.add(x) ;
}
void fix()
{
for(int x : set)
map.put(x , map.size() + 1) ;
}
int get(int x)
{
return map.get(x) ;
}
}
class Scanner
{
BufferedReader br ;
StringTokenizer st ;
Scanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(in)) ;
}
String next() throws Exception
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine()) ;
return st.nextToken() ;
}
int nextInt() throws Exception
{
return Integer.parseInt(next()) ;
}
long nextLong() throws Exception
{
return Long.parseLong(next()) ;
}
double nextDouble() throws Exception
{
return Double.parseDouble(next()) ;
}
}
public static void main (String [] args) throws Exception {(new D()).main();}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.Scanner;
public class prob1177b {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
long k,c,n,d;
c=1;
d=9;
n=1;
k= sc.nextLong();
while(k>(c*d)) {
k-=(c*d);
n*=10;
d*=10;
c++;
}
n+=(k-1)/c;
char[] num = String.valueOf(n).toCharArray();
System.out.println(num[(int)((k-1)%c)]);
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author madis
*/
public class Pjar {
static int a[][];
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter("output.txt");
int N = in.nextInt();
int M = in.nextInt();
a = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
a[i][j] = Integer.MAX_VALUE;
}
}
int k = in.nextInt();
in.nextLine();
for (int i = 0; i < k; i++) {
int x = in.nextInt();
int y = in.nextInt();
a[x - 1][y - 1] = 1;
burn(x - 1, y - 1);
}
int max = Integer.MIN_VALUE;
int x = 0;
int y = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if(a[i][j]>max){
max = a[i][j];
x = i+1;
y = j+1;
}
}
}
out.printf("%d %d",x,y);
out.close();
in.close();
}
static void burn(int i, int j) {
for(int k = 0;k<a.length;k++){
for(int l=0;l<a[k].length;l++){
if(a[k][l]>Math.abs(k-i) + Math.abs(l-j)){
a[k][l]=Math.abs(k-i) + Math.abs(l-j);
}
}
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
public class MyClass {
static class Pair implements Comparable<Pair>{
int x,y;
Pair(int x,int y){
this.x=x; this.y=y;
}
public int compareTo(Pair p){
return Integer.compare(this.y,p.y);
}
}
public static void main(String args[]) {
Scanner in =new Scanner(System.in);
HashMap<Long,ArrayList<Pair>> hm=new HashMap<Long,ArrayList<Pair>>();
int n=in.nextInt();
int a[]=new int[n];
long sum[]=new long[n];
long s=0;
for(int i=0;i<n;i++){ a[i]=in.nextInt(); s+=a[i]; sum[i]=s; }
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
long x=sum[j]-sum[i]+a[i];
ArrayList<Pair> temp=new ArrayList<Pair>();
if(hm.containsKey(x)) { temp=hm.get(x); }
temp.add(new Pair(i+1,j+1));
hm.put(x,temp);
}
}
ArrayList<Pair> ans=new ArrayList<Pair>();
for(Map.Entry em:hm.entrySet()){
ArrayList<Pair> array=hm.get(em.getKey());
Collections.sort(array);
int prev=0;
ArrayList<Pair> temp=new ArrayList<Pair>();
for(int i=0;i<array.size();i++){
if(array.get(i).x>prev){ temp.add(new Pair(array.get(i).x,array.get(i).y)); prev=array.get(i).y; }
}
// System.out.println(temp.size());
if(temp.size()>ans.size()){
ans=(ArrayList<Pair>)temp.clone();
}
}
long g=-5;
System.out.println(ans.size());
for(int i=0;i<ans.size();i++){
System.out.println(ans.get(i).x+" "+ans.get(i).y);
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class D {
static long l, r;
static long[][][][][] dp;
public static void main(String[] args) throws IOException {
InputReader in = new InputReader();
l = in.nextLong();
r = in.nextLong();
dp = new long[65][2][2][2][2];
for(int i = 0 ; i < 65;i++)
for(int j = 0 ; j < 2;j++)
for(int k = 0 ; k < 2;k++)
for(int a = 0 ; a<2;a++)
dp[i][j][k][a][0]=dp[i][j][k][a][1]=-1;
System.out.println(go(63, 0, 0, 0, 0));
}
public static long go(int i, int a1, int a2, int b1, int b2) {
if(i==-1)return 0;
if(dp[i][a1][a2][b1][b2]!=-1)
return dp[i][a1][a2][b1][b2];
int f1 = 3, f2 = 3;
int bl = (int) ((l >> i)) & 1, br = (int) ((r >> i) & 1);
if (a2 == 0 && br==0)
f1 &= 1;
if(a1 == 0 && bl==1)
f1 &= 2;
if (b2 == 0 && br==0)
f2 &= 1;
if(b1 == 0 && bl==1)
f2 &= 2;
long res = 0;
for(int x = 0 ; x<2;x++){
for(int y = 0 ; y<2;y++){
if(((f1>>x)&1) == 1 &&((f2>>y)&1) == 1){
res = Math.max(res, (((long)(x^y))<<i)+go(i-1,x>bl||a1==1?1:0,x<br||a2==1?1:0,y>bl||b1==1?1:0,y<br||b2==1?1:0));
}
}
}
return dp[i][a1][a2][b1][b2]=res;
}
static class InputReader {
BufferedReader in;
StringTokenizer st;
public InputReader() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(in.readLine());
}
public String next() throws IOException {
while (!st.hasMoreElements())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
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.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Zakhar Voit
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, Scanner in, PrintWriter out) {
out.println(solve(in.nextLong(), in.nextLong()));
/*for (long l = 1; l < 500; l++) {
for (long r = l; r < 500; r++) {
if (badSolve(l, r) != solve(l, r)) {
out.println(l + " " + r);
return;
}
}
}
out.println("OK");*/
}
long solve(long l, long r) {
if (l == r)
return 0;
long ans = l ^ (l + 1);
for (int i = 0; i < 62; i++) {
l |= (1l << i);
if (l + 1 <= r)
ans = (1l << (i + 2l)) - 1;
}
return ans;
}
}
class Scanner {
BufferedReader in;
StringTokenizer tok;
public Scanner(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
tok = new StringTokenizer("");
}
public String nextToken() {
if (!tok.hasMoreTokens()) {
try {
String newLine = in.readLine();
if (newLine == null)
throw new InputMismatchException();
tok = new StringTokenizer(newLine);
} catch (IOException e) {
throw new InputMismatchException();
}
return nextToken();
}
return tok.nextToken();
}
public long nextLong() {
return Long.parseLong(nextToken());
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Reader in = new Reader();
int n = in.nextInt();
int[] a = in.na(n);
HashMap<Long, ArrayList<Pair>> v = new HashMap<>();
for(int i = 0; i<n; i++) {
long s = 0;
for(int j = i; j<n; j++) {
s+=a[j];
Pair p = new Pair(i+1, j+1);
if(v.containsKey(s)) {
v.get(s).add(p);
}else {
ArrayList<Pair> xd = new ArrayList<>();
xd.add(p);
v.put(s,xd);
}
}
}
ArrayList<Pair> ans = new ArrayList<>();
for(Entry<Long,ArrayList<Pair>> e : v.entrySet()) {
ArrayList<Pair> pairs = e.getValue();
Collections.sort(pairs);
Stack<Pair> st = new Stack<>();
for(int i = 0; i<pairs.size(); i++) {
Pair cur = pairs.get(i);
if(st.isEmpty()||st.peek().r<cur.l) {
st.push(cur);
}else if(st.peek().r>cur.r) {
st.pop();
st.push(cur);
}
if(st.size()>ans.size()) ans = new ArrayList<>(st);
}
}
System.out.println(ans.size());
for(Pair p : ans)
System.out.println(p.l +" "+p.r);
}
static class Pair implements Comparable<Pair>{
int l,r;
public Pair(int l, int r) {
this.l = l;
this.r = r;
}
@Override
public int compareTo(Pair o) {
return this.l - o.l;
}
}
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public String[] nS(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = next();
return a;
}
public int nextInt() {
if (st == null || !st.hasMoreTokens())
try {
readLine();
} catch (Exception e) {
}
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
if (st == null || !st.hasMoreTokens())
try {
readLine();
} catch (Exception e) {
}
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
if (st == null || !st.hasMoreTokens())
try {
readLine();
} catch (Exception e) {
}
return Long.parseLong(st.nextToken());
}
public String next() {
if (st == null || !st.hasMoreTokens())
try {
readLine();
} catch (Exception e) {
}
return st.nextToken();
}
public static void readLine() {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
}
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] wide = new int[n], sta = new int[n];
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
wide[i] = sc.nextInt();
hm.put(wide[i], i + 1);
}
Util.sort(wide);
sc.nextLine();
String s = sc.nextLine();
int tp = 0, pos = 0;
StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
int t;
if (s.charAt(i) == '0') {
t = wide[pos++];
sta[tp++] = t;
} else t = sta[--tp];
out.append(hm.get(t) + " ");
}
System.out.println(out.toString());
sc.close();
}
public static class Util {
public static <T extends Comparable<T> > void merge_sort(T[] a) {
Object[] aux = new Object[a.length];
merge_sort0(a, aux, 0, a.length);
}
public static <T extends Comparable<T> > void merge_sort(T[] a, int l, int r) {
Object[] aux = new Object[a.length];
merge_sort0(a, aux, l, r);
}
@SuppressWarnings("unchecked")
private static <T extends Comparable<T> > void merge_sort0(T[] a, Object[] temp, int l, int r) {
if (l + 1 == r) return;
int mid = (l + r) >> 1;
merge_sort0(a, temp, l, mid);
merge_sort0(a, temp, mid, r);
int x = l, y = mid, c = l;
while (x < mid || y < r) {
if (y == r || (x < mid && a[x].compareTo(a[y]) <= 0)) temp[c++] = a[x++];
else temp[c++] = a[y++];
}
for (int i = l; i < r; i++) a[i] = (T)temp[i];
}
static final Random RAN = new Random();
public static <T extends Comparable<T> > void quick_sort(T[] a) {
quick_sort0(a, 0, a.length);
}
public static <T extends Comparable<T> > void quick_sort(T[] a, int l, int r) {
quick_sort0(a, l, r);
}
private static <T extends Comparable<T> > void quick_sort0(T[] a, int l, int r) {
if (l + 1 >= r) return;
int p = l + RAN.nextInt(r - l);
T t = a[p]; a[p] = a[l]; a[l] = t;
int x = l, y = r - 1;
while (x < y) {
while (x < y && a[y].compareTo(t) > 0) --y;
while (x < y && a[x].compareTo(t) < 0) ++x;
if (x < y) {
T b = a[x]; a[x] = a[y]; a[y] = b;
++x; --y;
}
}
quick_sort0(a, l, y + 1);
quick_sort0(a, x, r);
}
static final int BOUND = 8;
public static void bucket_sort(int[] a) {
bucket_sort(a, 0, a.length);
}
public static void bucket_sort(int[] a, int l, int r) {
int[] cnt = new int[1 << BOUND], b = new int[r - l + 1];
int y = 0;
for (int i = l; i < r; i++) ++cnt[a[i] & (1 << BOUND) - 1];
while (y < Integer.SIZE) {
for (int i = 1; i < 1 << BOUND; i++) cnt[i] += cnt[i - 1];
for (int i = r - 1; i >= l; i--) b[--cnt[a[i] >> y & (1 << BOUND) - 1]] = a[i];
y += BOUND;
Arrays.fill(cnt, 0);
for (int i = l; i < r; i++) {
a[i] = b[i - l];
++cnt[a[i] >> y & (1 << BOUND) - 1];
}
}
}
public static void bucket_sort(long[] a) {
bucket_sort(a, 0, a.length);
}
public static void bucket_sort(long[] a, int l, int r) {
int[] cnt = new int[1 << BOUND];
long[] b = new long[r - l + 1];
int y = 0;
while (y < Long.SIZE) {
Arrays.fill(cnt, 0);
for (int i = l; i < r; i++) ++cnt[(int) (a[i] >> y & (1 << BOUND) - 1)];
for (int i = 1; i < 1 << BOUND; i++) cnt[i] += cnt[i - 1];
for (int i = r - 1; i >= l; i--) b[--cnt[(int) (a[i] >> y & (1 << BOUND) - 1)]] = a[i];
for (int i = l; i < r; i++) a[i] = b[i - l];
y += BOUND;
}
}
public static void sort(int[] a) {
if (a.length <= 1 << BOUND) {
Integer[] b = new Integer[a.length];
for (int i = 0; i < a.length; i++) b[i] = a[i];
quick_sort(b);
for (int i = 0; i < a.length; i++) a[i] = b[i];
} else bucket_sort(a);
}
public static void sort(long[] a) {
if (a.length <= 1 << BOUND) {
Long[] b = new Long[a.length];
for (int i = 0; i < a.length; i++) b[i] = a[i];
quick_sort(b);
for (int i = 0; i < a.length; i++) a[i] = b[i];
} else bucket_sort(a);
}
public static <T extends Comparable<T> > void sort(T[] a) {
quick_sort(a);
}
public static void shuffle(int[] a) {
Random ran = new Random();
for (int i = 0; i < a.length; i++) {
int p = ran.nextInt(i + 1);
int q = a[p]; a[p] = a[i]; a[i] = q;
}
}
public static void shuffle(long[] a) {
Random ran = new Random();
for (int i = 0; i < a.length; i++) {
int p = ran.nextInt(i + 1);
long q = a[p]; a[p] = a[i]; a[i] = q;
}
}
public static <T> void shuffle(T[] a) {
Random ran = new Random();
for (int i = 0; i < a.length; i++) {
int p = ran.nextInt(i + 1);
T q = a[p]; a[p] = a[i]; a[i] = q;
}
}
}
}
|
nlogn
|
982_B. Bus of Characters
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
private static void solve(InputReader in, OutputWriter out) {
int n = in.nextInt();
if (n < 6) {
out.println(-1);
} else {
int m = (n - 2);
for (int i = 2; i <= m; i++) {
out.println("1 " + i);
}
out.println(m + " " + (m + 1));
out.println(m + " " + (m + 2));
}
for (int i = 2; i <= n; i++) {
out.println("1 " + i);
}
}
private static void shuffleArray(int[] array) {
int index;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
if (index != i) {
array[index] ^= array[i];
array[i] ^= array[index];
array[index] ^= array[i];
}
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
solve(in, out);
in.close();
out.close();
}
private static class InputReader {
private BufferedReader br;
private StringTokenizer st;
InputReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
st = null;
}
String nextLine() {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String line = nextLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
byte nextByte() {
return Byte.parseByte(next());
}
short nextShort() {
return Short.parseShort(next());
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class OutputWriter {
BufferedWriter bw;
OutputWriter(OutputStream os) {
bw = new BufferedWriter(new OutputStreamWriter(os));
}
void print(int i) {
print(Integer.toString(i));
}
void println(int i) {
println(Integer.toString(i));
}
void print(long l) {
print(Long.toString(l));
}
void println(long l) {
println(Long.toString(l));
}
void print(double d) {
print(Double.toString(d));
}
void println(double d) {
println(Double.toString(d));
}
void print(boolean b) {
print(Boolean.toString(b));
}
void println(boolean b) {
println(Boolean.toString(b));
}
void print(char c) {
try {
bw.write(c);
} catch (IOException e) {
e.printStackTrace();
}
}
void println(char c) {
println(Character.toString(c));
}
void print(String s) {
try {
bw.write(s);
} catch (IOException e) {
e.printStackTrace();
}
}
void println(String s) {
print(s);
print('\n');
}
void close() {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
linear
|
959_C. Mahmoud and Ehab and the wrong algorithm
|
CODEFORCES
|
//package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static class Task {
public class Maxflow {
class Edge {
int t, rev;
long cap, f;
public Edge(int t, int rev, long cap) {
this.t = t;
this.rev = rev;
this.cap = cap;
}
}
public Maxflow(int n) {
graph = new List[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
}
List<Edge>[] graph;
void addEdge(int s, int t, long cap) {
graph[s].add(new Edge(t, graph[t].size(), cap));
graph[t].add(new Edge(s, graph[s].size() - 1, 0));
// System.err.println(s + " " + t + " " + cap);
}
boolean dinicBFS(int src, int dest, int[] dist) {
Arrays.fill(dist, -1);
dist[src] = 0;
int[] Q = new int[graph.length];
int sizeQ = 0;
Q[sizeQ++] = src;
for (int i = 0; i < sizeQ; i++) {
int u = Q[i];
for (Edge e: graph[u]) {
if (dist[e.t] < 0 && e.f < e.cap) {
dist[e.t] = dist[u] + 1;
Q[sizeQ++] = e.t;
}
}
}
return dist[dest] >= 0;
}
long dinicDFS(int[] ptr, int[] dist, int dest, int u, long f) {
if (u == dest) return f;
for (;ptr[u] < graph[u].size(); ++ptr[u]) {
Edge e = graph[u].get(ptr[u]);
if (dist[e.t] == dist[u] + 1 && e.f < e.cap) {
long df = dinicDFS(ptr, dist, dest, e.t, Math.min(f, e.cap - e.f));
if (df > 0) {
e.f += df;
graph[e.t].get(e.rev).f -= df;
return df;
}
}
}
return 0;
}
long maxFLow(int src, int dest) {
long flow = 0;
int[] dist = new int[graph.length];
while (dinicBFS(src, dest, dist)) {
int[] ptr = new int[graph.length];
while (true) {
long df = dinicDFS(ptr, dist, dest, src, Long.MAX_VALUE);
if (df == 0) break;
flow += df;
}
}
return flow;
}
}
public class MinCostFlowBF {
List<Edge>[] graph;
class Edge {
int to, f, cap, cost, rev;
Edge(int v, int cap, int cost, int rev) {
this.to = v;
this.cap = cap;
this.cost = cost;
this.rev = rev;
}
}
public MinCostFlowBF(int n) {
graph = new List[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<Edge>();
}
public void addEdge(int s, int t, int cap, int cost) {
graph[s].add(new Edge(t, cap, cost, graph[t].size()));
graph[t].add(new Edge(s, 0, -cost, graph[s].size() - 1));
}
void bellmanFord(int s, int[] dist, int[] prevnode, int[] prevedge, int[] curflow) {
int n = graph.length;
Arrays.fill(dist, 0, n, Integer.MAX_VALUE);
dist[s] = 0;
curflow[s] = Integer.MAX_VALUE;
boolean[] inqueue = new boolean[n];
int[] q = new int[n];
int qt = 0;
q[qt++] = s;
for (int qh = 0; (qh - qt) % n != 0; qh++) {
int u = q[qh % n];
inqueue[u] = false;
for (int i = 0; i < graph[u].size(); i++) {
Edge e = graph[u].get(i);
if (e.f >= e.cap)
continue;
int v = e.to;
int ndist = dist[u] + e.cost;
if (dist[v] > ndist) {
dist[v] = ndist;
prevnode[v] = u;
prevedge[v] = i;
curflow[v] = Math.min(curflow[u], e.cap - e.f);
if (!inqueue[v]) {
inqueue[v] = true;
q[qt++ % n] = v;
}
}
}
}
}
public int[] minCostFlow(int s, int t, int maxf) {
int n = graph.length;
int[] dist = new int[n];
int[] curflow = new int[n];
int[] prevedge = new int[n];
int[] prevnode = new int[n];
int flow = 0;
int flowCost = 0;
while (flow < maxf) {
bellmanFord(s, dist, prevnode, prevedge, curflow);
if (dist[t] == Integer.MAX_VALUE)
break;
int df = Math.min(curflow[t], maxf - flow);
flow += df;
for (int v = t; v != s; v = prevnode[v]) {
Edge e = graph[prevnode[v]].get(prevedge[v]);
e.f += df;
graph[v].get(e.rev).f -= df;
flowCost += df * e.cost;
}
}
return new int[]{flow, flowCost};
}
}
public void solve(Scanner sc, PrintWriter pw) throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int[] pos = new int[n];
for (int i = 0; i < k; i++) {
pos[sc.nextInt() - 1]++;
}
int T = 100;
MinCostFlowBF mf = new MinCostFlowBF((T + 1) * n + 2);
for (int i = 0; i < n; i++) {
if (pos[i] > 0)
mf.addEdge(0, i + 1, pos[i], 0);
}
for (int i = 0; i < T; i++) {
for (int j = 0; j < n; j++) {
mf.addEdge(1 + i * n + j, 1 + (i + 1) * n + j, k, 0);
}
}
for (int i = 0; i <= T; i++) {
for (int j = 1; j <= k; j++) {
mf.addEdge(1 + i * n, (T + 1) * n + 1, 1, c * i);
}
}
for (int i = 0; i < m; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
for (int j = 0; j < T; j++) {
int cost = 0;
for (int l = 1; l <= k; l++) {
mf.addEdge(1 + j * n + a, 1 + (j + 1) * n + b, 1, l * l * d - cost);
mf.addEdge(1 + j * n + b, 1 + (j + 1) * n + a, 1, l * l * d - cost);
cost = l * l * d;
}
}
}
int[] flowAndCost = mf.minCostFlow(0, (T + 1) * n + 1, k);
System.err.println(flowAndCost[0]);
pw.println(flowAndCost[1]);
}
}
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("input"));
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
// PrintWriter pw = new PrintWriter(new FileOutputStream("output"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);
System.err.println("Time used: " + (TIME_END - TIME_START) + ".");
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
cubic
|
1187_G. Gang Up
|
CODEFORCES
|
import java.util.*;
public class a{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next();
int max = 0;
for(int i=0; i<str.length(); i++) {
for(int j=i+1; j<=str.length(); j++) {
String first = str.substring(i,j);
for(int k=i+1; k<=str.length()-first.length(); k++) {
if(str.substring(k,k+first.length()).equals(first))
max = Math.max(max,first.length());
}
}
}
System.out.println(max);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main {
StreamTokenizer in;
//BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws IOException {
new Main().run();
}
int ni() throws IOException {
in.nextToken(); return (int)in.nval;
}
void run() throws IOException {
//in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt")));
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new OutputStreamWriter(System.out));
//out = new PrintWriter(new FileWriter("output.txt"));
int cprime = 0;
int[] prime = new int[1000];
for(int i = 2; i < 1001; i++) {
boolean f = false;
for(int j = 2; j*j <= i; j++)
if(i % j == 0) {
f = true; break;
}
if(!f) prime[cprime++] = i;
}
int n = ni(), k = ni();
int last = 0;
int count = 0;
for(int i = 0; i < cprime && prime[i] <= n; i++) {
for(int j = 0; j < cprime - 1; j++)
if(prime[j] + prime[j + 1] + 1 == prime[i]) {
count++; break;
}
else if(prime[j] + prime[j + 1] + 1 > prime[i]) break;
}
if(count >= k) out.print("YES");
else out.print("NO");
out.flush();
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
public class paintNumbers {
public static int minIndex(List<Integer> list) {
int min = list.get(0);
int minIndex = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) < min) {
min = list.get(i);
minIndex = i;
}
}
return minIndex;
}
public static void main(String[] args) throws IOException {
FastScanner sc = new FastScanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
list.add(sc.nextInt());
}
int count = 0;
while (list.size() > 0) {
count++;
int temp = list.get(minIndex(list));
// pw.println("min = " + temp);
for (int j = 0; j < list.size(); j++) {
if (list.get(j) % temp == 0) {
// pw.println("j = " + list.get(j));
// pw.println("min = " + temp);
list.remove(j);
j--;
}
}
// for (int i = 0; i < list.size(); i++) {
// pw.println(list.get(i) + " ");
// }
}
pw.println(count);
pw.close();
}
static class FastScanner {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastScanner(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n){
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextSortedIntArray(int n){
int array[]=nextIntArray(n);
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for(int i = 0; i < n; i++){
pq.add(array[i]);
}
int[] out = new int[n];
for(int i = 0; i < n; i++){
out[i] = pq.poll();
}
return out;
}
public int[] nextSumIntArray(int n){
int[] array=new int[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public ArrayList<Integer>[] nextGraph(int n, int m){
ArrayList<Integer>[] adj = new ArrayList[n];
for(int i = 0; i < n; i++){
adj[i] = new ArrayList<Integer>();
}
for(int i = 0; i < m; i++){
int u = nextInt(); int v = nextInt();
u--; v--;
adj[u].add(v); adj[v].add(u);
}
return adj;
}
public ArrayList<Integer>[] nextTree(int n){
return nextGraph(n, n-1);
}
public long[] nextLongArray(int n){
long[] array=new long[n];
for(int i=0;i<n;++i)array[i]=nextLong();
return array;
}
public long[] nextSumLongArray(int n){
long[] array=new long[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextSortedLongArray(int n){
long array[]=nextLongArray(n);
Arrays.sort(array);
return array;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.prefs.BackingStoreException;
public class answertillD {
static ArrayList<Integer>[] adjlist;
static int[][] adjmatrix;
static int[][] adjmatrix2;
static boolean[] vis;
static boolean[] intialvis;
static boolean[] vis2;
static int[] counter;
static int V, E;
static Stack<Integer> st;
static ArrayList<Integer> arrylist;
static boolean flag;
static int[] dx = new int[] { 1, -1, 0, 0 };
static int[] dy = new int[] { 0, 0, 1, -1 };
static int[] Arr;
static PrintWriter pw;
public static long gcd(long u, long v) {
if (u == 0)
return v;
return gcd(v % u, u);
}
public static int dfs(int u) {
vis[u] = true;
int a = 0;
for (int v : adjlist[u])
if (!vis[v])
a += dfs(v);
return 1 + a;
}
public static void dfs(int u, int num) {
vis2[u] = true;
counter[u] = num;
for (int v : adjlist[u])
if (!vis2[v])
dfs(v, num);
}
static long diff=Long.MAX_VALUE;
static boolean check(long num, long k) {
int n=(num+"").length()-1;
long m=1;
long sum=0;int i=1;
while(n-->0)
{
sum+=9*m*(i++) ;
m*=10;
}
sum+=(num-m)*i+1;
if(sum<=k)
diff=Math.min(diff, k-sum);
return sum<=k;
}
static long bin(long k) {
long left = 1;
long right = k+1;
long mid;
long ans = 1;
while (left <= right) {
mid = (left + right) / 2;
if (check(mid, k)) {
ans = mid;
left = mid + 1;
} else
right = mid - 1;
}
return ans;
}
public static long power(long x, int i) {
long r = 1;
while (i-- > 0) {
if (r > 1e18 / x)
return (long) (1e18 + 5);
r = r * x;
}
return r;
}
static int m;
static int calculate(int[] Arrs, int[] Arre, int index, boolean left, boolean targetleft) {
int ans = 0;
int n = m + 2;
if (left) {
ans = Arre[index - 1];
if ((index != E + 1))
ans += (targetleft) ? Arre[index - 1] : n - Arre[index - 1] - 1;
} else {
ans = n - Arrs[index - 1] - 1;
if ((index != E + 1))
ans += ((targetleft) ? Arrs[index - 1] : n - Arrs[index - 1] - 1);
}
return ans;
}
static int min = Integer.MAX_VALUE;
static void backtrack(int[] Arrs, int[] Arre, int soFarMin, int index, boolean left) {
if (index == E) {
min = Math.min(min, soFarMin - 1);
return;
}
int newmin1 = calculate(Arrs, Arre, index, left, left);
int newmin2 = calculate(Arrs, Arre, index, left, !left);
backtrack(Arrs, Arre, soFarMin + newmin1 + 1, index - 1, left);
backtrack(Arrs, Arre, soFarMin + newmin2 + 1, index - 1, !left);
}
public static String add(String str1,String str2){
Stack<String>st=new Stack<String>();
int n=str1.length();
int m=str2.length();
int max=Math.max(n, m);
int sum=0,carry=0;
for(int i=0;i<max;i++){
int num1=0,num2=0;
if(n>=i)
num1 = Integer.parseInt(str1.charAt(n-i) + "");
if(m>=i)
num2 = Integer.parseInt(str2.charAt(m-i) + "");
int z = num1 + num2 + carry;
if (z >= 10) {
sum = z / 10;
carry = z % 10;
} else {
sum = z;
carry=0;
}
st.add(sum+"");
}
StringBuilder sb=new StringBuilder();
while(!st.isEmpty()){
sb.append(st.pop());
}
return sb+"";
}
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
long k=sc.nextLong();
long bi=bin(k);
String str=bi+"";
System.out.println(str.charAt((int) diff));
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.BufferedInputStream;
import java.util.Scanner;
/**
* Created by jizhe on 2016/1/29.
*/
public class LCMChallenge {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
long N = in.nextLong();
if( N == 1 || N == 2 )
{
System.out.printf("%d\n", N);
return;
}
if( (N&1) == 1 )
{
long lcm = N*(N-1)*(N-2);
System.out.printf("%d\n", lcm);
}
else
{
if( N == 4 )
{
System.out.printf("12\n");
}
else
{
long lcm;
if( N%3 == 0 )
{
lcm = (N-1)*(N-2)*(N-3);
}
else
{
lcm = N*(N-1)*(N-3);
}
System.out.printf("%d\n", lcm);
}
}
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.awt.Point;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Start {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
public static void main(String[] args) {
new Start().run();
// Sworn to fight and die
}
public static void mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int levtIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (levtIndex < rightIndex) {
if (rightIndex - levtIndex <= MAGIC_VALUE) {
insertionSort(a, levtIndex, rightIndex);
} else {
int middleIndex = (levtIndex + rightIndex) / 2;
mergeSort(a, levtIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, levtIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int levtIndex, int middleIndex,
int rightIndex) {
int length1 = middleIndex - levtIndex + 1;
int length2 = rightIndex - middleIndex;
int[] levtArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, levtIndex, levtArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = levtIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = levtArray[i++];
} else {
a[k] = levtArray[i] <= rightArray[j] ? levtArray[i++]
: rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int levtIndex, int rightIndex) {
for (int i = levtIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= levtIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
class LOL implements Comparable<LOL> {
int x;
int y;
int num;
public LOL(int x, int y,int num) {
this.x = x;
this.y = y;
this.num = num;
}
@Override
public int compareTo(LOL o) {
return x - o.x; // ---->
// return o.x - x; // <----
// return o.y-y;
}
}
public void solve() throws IOException {
int n = readInt();
int m = readInt();
int k = readInt();
int [] a = new int [n];
for (int i = 0; i < n; i++){
a[i] = readInt();
}
mergeSort(a);
if (k>=m){
out.print(0);
return;
}
int ans = 0;
k--;
for (int i = n-1; i >=0; i--){
ans += a[i];
if (ans + k >= m){
out.print(n-i);
return;
}
else {
k--;
}
}
out.print(-1);
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Solve{
public static void main(String[] args) throws Exception{
Scanner sc=new Scanner(System.in);
PrintWriter out =new PrintWriter(System.out);
int size=(int)1e7+1;
int[] pr=new int[size];
for(int i=0;i<size;i++){
pr[i]=i;
}
for(int i=2;i*i<size;i++){
int val=i*i;
for(int j=val;j<=size;j+=val){
pr[j]=j/val;
}
}
int t=sc.nextInt();
int[] dp=new int[size];
Arrays.fill(dp,-1);
while(t-->0){
int n=sc.nextInt();
int k=sc.nextInt();
int[] ar=new int[n];
for(int i=0;i<n;i++){
int a=sc.nextInt();
ar[i]=pr[a];
}
int[] ans=new int[k+1];
int[] ind=new int[k+1];
for(int i=0;i<n;i++){
for(int h=k;h>=0;h--){
if(dp[ar[i]]>=ind[h]){
ans[h]++;
ind[h]=i;
}
if(h>0 && (ans[h-1]<ans[h] ||(ans[h-1]==ans[h] && ind[h-1]>ind[h])))
{
ans[h]=ans[h-1];
ind[h]=ind[h-1];
}
}
dp[ar[i]]=i;
}
out.println(ans[k]+1);
for(int i=0;i<n;i++)dp[ar[i]]=-1;
}
out.close();
}
}
|
cubic
|
1497E2
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.util.Map.Entry;
public class Codeforces {
static int n;
static double max;
static int[] pre;
public static void findIntensity(int l){
for(int i = 0, j = i + l; j < n + 1; i++, j++){
double res = (pre[j] - pre[i]) / (double) l;
max = Math.max(max, res);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] heat = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++){
heat[i] = Integer.parseInt(st.nextToken());
}
max = 0;
pre = new int[n + 1];
pre[0] = 0;
for(int i = 0; i < n; i++){
pre[i + 1] = pre[i] + heat[i];
}
for(int i = k; i <= n; i++){
findIntensity(i);
}
System.out.println(max);
}
}
|
quadratic
|
1003_C. Intense Heat
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ProblemD {
static int N;
static boolean[][] graph;
public static void main(String[] args) throws IOException {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String[] data = s.readLine().split(" ");
int n = Integer.valueOf(data[0]);
N = n;
int m = Integer.valueOf(data[1]);
graph = new boolean[n][n];
for (int i = 0 ; i < m ; i++) {
String[] line = s.readLine().split(" ");
int a = Integer.valueOf(line[0])-1;
int b = Integer.valueOf(line[1])-1;
graph[a][b] = true;
graph[b][a] = true;
}
long ans = 0;
for (int i = 0 ; i < n ; i++) {
ans += doit(i);
}
ans /= 2;
out.println(ans);
out.flush();
}
static long doit(int n) {
long[][] dp = new long[1<<n][n];
for (int i = 0 ; i < n ; i++) {
if (graph[i][n]) {
dp[1<<i][i] = 1;
}
}
for (int i = 0 ; i < (1<<n) ; i++) {
for (int j = 0 ; j < n ; j++) {
if (dp[i][j] >= 1) {
for (int k = 0 ; k < n ; k++) {
if (graph[j][k] && (i & (1<<k)) == 0) {
dp[i|1<<k][k] += dp[i][j];
}
}
}
}
}
long ret = 0;
for (int i = 0 ; i < (1<<n) ; i++) {
if (Integer.bitCount(i) >= 2) {
for (int j = 0 ; j < n ; j++) {
if (graph[j][n]) {
ret += dp[i][j];
}
}
}
}
return ret;
}
static void generateLarge() {
System.out.println("19 171");
for (int i = 1 ; i <= 19 ; i++) {
for (int j = i+1 ; j <= 19 ; j++) {
System.out.println(i + " " + j);
}
}
}
public static void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
/**
* @author Egor Kulikov (kulikov@devexperts.com)
*/
public class Order implements Runnable {
private Scanner in = new Scanner(System.in);
private PrintWriter out = new PrintWriter(System.out);
private int xs, ys, n;
private int[] x, y;
public static void main(String[] args) {
new Thread(new Order()).start();
}
private void read() {
xs = in.nextInt();
ys = in.nextInt();
n = in.nextInt();
x = new int[n];
y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
}
private void solve() {
int[] res = new int[1 << n];
int[] last = new int[1 << n];
Arrays.fill(res, Integer.MAX_VALUE);
int[] ds = new int[n];
for (int i = 0; i < n; i++) {
ds[i] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys);
}
int[][] d = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
d[i][j] = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
}
res[0] = 0;
for (int i = 1; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
if (((i >> j) & 1) != 0) {
if (res[i - (1 << j)] + 2 * ds[j] < res[i]) {
res[i] = res[i - (1 << j)] + 2 * ds[j];
last[i] = i - (1 << j);
}
for (int k = j + 1; k < n; k++) {
if (((i >> k) & 1) != 0) {
if (res[i - (1 << j) - (1 << k)] + ds[j] + ds[k] + d[j][k] < res[i]) {
res[i] = res[i - (1 << j) - (1 << k)] + ds[j] + ds[k] + d[j][k];
last[i] = i - (1 << j) - (1 << k);
}
}
}
break;
}
}
}
int cur = (1 << n) - 1;
out.println(res[cur]);
while (cur != 0) {
out.print("0 ");
int dif = cur - last[cur];
for (int i = 0; i < n && dif != 0; i++) {
if (((dif >> i) & 1) != 0) {
out.print((i + 1) + " ");
dif -= (1 << i);
}
}
cur = last[cur];
}
out.println("0");
}
private void write() {
}
public void run() {
read();
solve();
write();
out.close();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class SolA {
static Scanner in;
static PrintWriter out;
public static void main(String[] args) {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
new SolA().run();
in.close();
out.close();
}
private void run() {
int n = in.nextInt();
int[] a = new int[n];
int sum = 0;
for(int i = 0; i < n; i++) {
a[i] = in.nextInt();
sum+=a[i];
}
Arrays.sort(a);
int cs = 0;
int kol = 0;
for(int i = n - 1; i>=0; i--) {
cs+=a[i];
kol++;
if (cs > sum - cs) {
break;
}
}
out.print(kol);
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Practice {
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
String s=sc.nextLine();
//System.out.println(s);
char c[]=s.toCharArray();
ArrayList a =new ArrayList();
for(int i=0;i<c.length;i++)
{
//System.out.println(c[i]);
a.add(c[i]);
}
int x=Collections.frequency(a,'0' );
int y=Collections.frequency(a,'1');
//System.out.println(x+ " "+y );
if(y==0 || y==1)
{
System.out.println(s);
}
else
{
if(y>=2)
{
String s1="1";
for(int i=0;i<x;i++)
{
s1=s1+"0";
}
System.out.println(s1);
}
}
}
}
|
linear
|
976_A. Minimum Binary Number
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class G_PlaylistForPolycarp {
static final int mod = 1000000007;
static int dp[][];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] dat = br.readLine().split(" ");
int n = Integer.parseInt(dat[0]);
int T = Integer.parseInt(dat[1]);
int[] st = new int[n];
byte[] sg = new byte[n];
dp = new int[1 << (n + 1)][4];
for (int j = 0; j < 1 << (n + 1); j++) {
for (int k = 0; k < 4; k++) {
dp[j][k] = -1;
}
}
for (int i = 0; i < n; i++) {
dat = br.readLine().split(" ");
st[i] = Integer.parseInt(dat[0]);
sg[i] = Byte.parseByte(dat[1]);
}
short visited = 0;
int count = recur(0, visited, st, sg, T, 0);
bw.write(count + "\n");
bw.close();
}
private static int recur(int time, short visited, int[] st, byte[] sg, int T, int last) {
int count = 0;
if (dp[visited][last] != -1) {
return dp[visited][last];
}
for (int i = 0; i < st.length; i++) {
if ((visited & (1 << i)) == 0 && sg[i] != last) {
if (time + st[i] == T) {
count += 1;
} else if (time + st[i] < T) {
short visitedc = (short) (visited | (1 << i));
count += recur(time + st[i], visitedc, st, sg, T, sg[i]);
if (count > mod) {
count = count % mod;
}
}
}
}
return dp[visited][last] = count % mod;
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class problemA {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int[] hs = new int[n];
for(int i = 0; i < n; i++){
hs[i] = sc.nextInt();
}
Arrays.sort(hs);
System.out.println(hs[b]-hs[b-1]);
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class C113A{
static BufferedReader br;
public static void main(String args[])throws Exception{
br=new BufferedReader(new InputStreamReader(System.in));
int nm[]=toIntArray();
int n=nm[0];
int k=nm[1];
Pai p[]=new Pai[n];
for(int i=0;i<n;i++){
nm=toIntArray();
p[i]=new Pai(nm[0],nm[1]);
}
Arrays.sort(p);
int count=0;
for(int i=0;i<n;i++){
if(p[k-1].first==p[i].first && p[k-1].second==p[i].second){
count++;
}
}
System.out.println(count);
}
/****************************************************************/
public static int[] toIntArray()throws Exception{
String str[]=br.readLine().split(" ");
int k[]=new int[str.length];
for(int i=0;i<str.length;i++){
k[i]=Integer.parseInt(str[i]);
}
return k;
}
public static int toInt()throws Exception{
return Integer.parseInt(br.readLine());
}
public static long[] toLongArray()throws Exception{
String str[]=br.readLine().split(" ");
long k[]=new long[str.length];
for(int i=0;i<str.length;i++){
k[i]=Long.parseLong(str[i]);
}
return k;
}
public static long toLong()throws Exception{
return Long.parseLong(br.readLine());
}
public static double[] toDoubleArray()throws Exception{
String str[]=br.readLine().split(" ");
double k[]=new double[str.length];
for(int i=0;i<str.length;i++){
k[i]=Double.parseDouble(str[i]);
}
return k;
}
public static double toDouble()throws Exception{
return Double.parseDouble(br.readLine());
}
public static String toStr()throws Exception{
return br.readLine();
}
public static String[] toStrArray()throws Exception{
String str[]=br.readLine().split(" ");
return str;
}
/****************************************************************/
}
class Pai implements Comparable<Pai> {
int first;
int second;
public Pai(int f, int s) {
first = f;
second = s;
}
public int compareTo(Pai p) {
int ret = 0;
if (first < p.first) {
ret = 1;
} else if (first > p.first) {
ret = -1;
} else {
if(second<p.second){
ret=-1;
}
else if(second>p.second){
ret=1;
}
else ret=0;
}
return ret;
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.StringTokenizer;
public class A {
public static void main(String[] args) {
InputScanner scanner = new InputScanner();
try {
long l = scanner.nextLong();
long r = scanner.nextLong();
if ((r - l) < 2) {
System.out.println("-1");
return;
}
if (l % 2 == 0) {
long a = l;
long b = l + 1;
long c = l + 2;
System.out.println(a + " " + b + " " + c);
} else if (r%2==0){
long a = r;
long b = r-1;
long c = r-2;
System.out.println(c + " " + b + " " + a);
} else {
l++;
if ((r - l) < 2) {
System.out.println("-1");
return;
}
long a = l;
long b = l + 1;
long c = l + 2;
System.out.println(a + " " + b + " " + c);
}
} catch (IOException e) {
}
}
static class InputScanner {
BufferedReader br;
StringTokenizer st;
public InputScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException {
if (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() throws IOException {
String next = next();
next.length();
return Integer.parseInt(next);
}
public long nextLong() throws IOException {
String next = next();
next.length();
return Long.parseLong(next);
}
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.util.Arrays.*;
public class A {
private static final int mod = (int)1e9+9;
final IOFast io = new IOFast();
long k;
long rec(long n, long m, long cur) {
long pow = 1;
long margin = 10;
long p = 1000;
for(int i = 0; i < p; i++) pow = pow * 2 % mod;
while(true) {
if(n + 1 >= (m / (k - 1) * k + m % (k - 1)) || m < k) { return (m + cur) % mod; }
long q = (p + margin) * k;
if(n - q + 1 < ((m - q) / (k - 1) * k + (m - q) % (k - 1)) && m >= q) {
n -= p * k;
m -= p * k;
cur = cur * pow % mod;
cur += (pow - 1) * 2 * k % mod;
cur %= mod;
continue;
}
n -= k;
m -= k;
cur += k;
cur = cur * 2 % mod;
// System.err.println(cur);
}
}
public void run() throws IOException {
long n = io.nextLong();
long m = io.nextLong();
k = io.nextLong();
// io.out.println(rec(n, m, 0));
// if(true) return;
long low = -1, high = m / k + 1;
while(high - low > 1) {
long mid = (low + high) / 2;
long u = mid * k;
if(m < u) { high = mid; continue; }
long val = u;
val += (m - u) / (k - 1) * k;
if((m - u) % (k - 1) == 0) val -= 1;
else val += (m - u) % (k - 1);
if(val > n) {
low = mid;
}
else {
high = mid;
}
// System.err.println(mid + " " + (u + (m - u - k) / (k - 1) * k + k - 1 + (m - u) % (k - 1)) + " " + n);
}
long pow = powmod(2, high, mod);
long score = m - high * k;
score = (score + (pow - 1) * 2 * k) % mod;
io.out.println(score);
}
static long powmod(long n, long r, int m) {
long res = 1;
for(; r != 0; r >>>= 1, n = n * n % m) {
if((r&1) == 1) {
res = res * n;
if(res >= m) {
res %= m;
}
}
}
return res;
}
void main() throws IOException {
// IOFast.setFileIO("rle-size.in", "rle-size.out");
try {
run();
}
catch (EndOfFileRuntimeException e) { }
io.out.flush();
}
public static void main(String[] args) throws IOException {
new A().main();
}
static class EndOfFileRuntimeException extends RuntimeException {
private static final long serialVersionUID = -8565341110209207657L; }
static
public class IOFast {
private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private PrintWriter out = new PrintWriter(System.out);
void setFileIO(String ins, String outs) throws IOException {
in = new BufferedReader(new FileReader(ins));
out = new PrintWriter(new FileWriter(outs));
}
// private static final int BUFFER_SIZE = 50 * 200000;
private static int pos, readLen;
private static final char[] buffer = new char[1024 * 8];
private static final char[] str = new char[500000*8*2];
private static boolean[] isDigit = new boolean[256];
private static boolean[] isSpace = new boolean[256];
private static boolean[] isLineSep = new boolean[256];
static {
for(int i = 0; i < 10; i++) { isDigit['0' + i] = true; }
isDigit['-'] = true;
isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
isLineSep['\r'] = isLineSep['\n'] = true;
}
public int read() throws IOException {
if(pos >= readLen) {
pos = 0;
readLen = in.read(buffer);
if(readLen <= 0) { throw new EndOfFileRuntimeException(); }
}
return buffer[pos++];
}
public int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
public long nextLong() throws IOException {
return Long.parseLong(nextString());
}
public char nextChar() throws IOException {
while(true) {
final int c = read();
if(!isSpace[c]) { return (char)c; }
}
}
int reads(char[] cs, int len, boolean[] accept) throws IOException {
try {
while(true) {
final int c = read();
if(accept[c]) { break; }
str[len++] = (char)c;
}
}
catch(EndOfFileRuntimeException e) { ; }
return len;
}
public char[] nextLine() throws IOException {
int len = 0;
str[len++] = nextChar();
len = reads(str, len, isLineSep);
try {
if(str[len-1] == '\r') { len--; read(); }
}
catch(EndOfFileRuntimeException e) { ; }
return Arrays.copyOf(str, len);
}
public String nextString() throws IOException {
return new String(next());
}
public char[] next() throws IOException {
int len = 0;
str[len++] = nextChar();
len = reads(str, len, isSpace);
return Arrays.copyOf(str, len);
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextString());
}
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
public class B {
public static void main(String[] args) throws IOException {
Reader scan = new Reader();
int t = scan.nextInt();
for(int tt = 0;tt<t;tt++) {
int n = scan.nextInt();
int arr[] = new int[n];
for(int i = 0;i<n;i++) arr[i] = scan.nextInt();
List<Integer> list = new ArrayList<>();
int j = -1;
StringBuilder s = new StringBuilder();
for(int i = 0;i<n;i++) {
if(list.isEmpty() || arr[i]==1) { //add
list.add(arr[i]);
j++;
}
else if(arr[i] == list.get(j)+1) { //replace
list.set(j, arr[i]);
}
else {
for(int k = j;k>=0;k--) {
if(arr[i] == list.get(k)+1) {//replace
list.set(k, arr[i]);
break;
}
else {//delete
list.remove(k);
j--;
}
}
}
s.delete(0, s.length());
for(Integer p:list) {
s.append(p+".");
}
s.deleteCharAt(s.length()-1);
System.out.println(s.toString());
}
}
scan.close();
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import java.util.*;
/**
*
* @author kamranmaharov
*/
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
String[] line = in.readLine().split(" ");
int n = Integer.parseInt(line[0]);
int r = Integer.parseInt(line[1]);
line = in.readLine().split(" ");
int[] x = new int[n+1];
double[] y = new double[n+1];
for (int i=1; i<=n; ++i) {
x[i] = Integer.parseInt(line[i-1]);
double maxy = -1.0;
for (int j=1; j<i; ++j) {
double x2 = x[i];
double x1 = x[j];
double y1 = y[j];
double a = 1;
double b = -2 * y1;
double c = x1 * x1 + x2 * x2 - 2 * x1 * x2 + y1 * y1 - 4.0 * r * r;
double D = b * b - 4 * a * c;
//System.out.println(i + " " + j + " " + D);
if (D >= 0) {
double y2 = (-b + Math.sqrt(D)) / (2 * a);
maxy = Math.max(maxy, y2);
}
}
if (maxy < 0) {
maxy = r;
}
y[i] = maxy;
if (i>1) {System.out.print(" ");}
System.out.printf("%.13f", y[i]);
}
System.out.println();
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] info = s.split(" ");
long n = Long.parseLong(info[0]);
long k = Long.parseLong(info[1]);
sc.close();
long maximum = k * (k - 1) / 2 + 1;
if (n == 1)
System.out.println(0);
else if (n > maximum)
System.out.println(-1);
else {
long left = 0, right = k - 1;
while (left + 1 < right) {
long mid = (right + left) / 2;
if (mid * (k - 1 + k - mid) / 2 + 1 >= n)
right = mid;
else
left = mid;
}
System.out.println(right);
}
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.util.*;
public class A
{
public static int palin(String str)
{
int flag=0;
int l=str.length();
for(int i=0;i<l/2;i++)
{
if(str.charAt(i)!=str.charAt(l-i-1))
{
flag=1;
break;
}
}
if(flag==1)
return 0;
else
return 1;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
HashSet<Character> hs=new HashSet<>();
for(int i=0;i<str.length();i++)
{
hs.add(str.charAt(i));
}
if(hs.size()==1)
System.out.println(0);
else if(palin(str)==0)
System.out.println(str.length());
else
System.out.println(str.length()-1);
}
}
|
linear
|
981_A. Antipalindrome
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args)throws java.lang.Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int max = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i+1; j < s.length(); j++) {
if(s.substring(i+1).contains(s.substring(i,j)))
max = Math.max(max, j-i);
}}
System.out.println(max);
}
}
|
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.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
String[] response = {"even", "odd"};
int n = in.nextInt();
int[] arr = in.nextIntArray(0, n);
int swaps = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) swaps = (swaps + 1) % 2;
}
}
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int l = in.nextInt(), r = in.nextInt(), combinaisons = ((r - l) * (r - l + 1)) / 2;
if (combinaisons % 2 == 1) {
swaps ^= 1;
}
out.println(response[swaps]);
}
}
}
static class InputReader {
private StringTokenizer tokenizer;
private BufferedReader reader;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
private void fillTokenizer() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public String next() {
fillTokenizer();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray(int offset, int length) {
int[] arr = new int[offset + length];
for (int i = offset; i < offset + length; i++) {
arr[i] = nextInt();
}
return arr;
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.Random;
import java.util.StringTokenizer;
/**
* @author Polyarniy Nickolay
*/
public class ProblemD {
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tok;
private final String DELIMETER = " ";
private final boolean ENABLE_MULTITEST = false;
private final boolean DEBUG = true;
private final String FILENAME = null;//if FILENAME = null, then works with console
public void run() throws Exception {
initInputOutput();
do {
init();
solve();
} while (hasMoreTokens() && ENABLE_MULTITEST);
finish();
}
private void init() throws Exception {
}
private void solve() throws Exception {
String a = Long.toBinaryString(nextLong());
String b = Long.toBinaryString(nextLong());
while (a.length() < 64) {
a = "0" + a;
}
while (b.length() < 64) {
b = "0" + b;
}
// out.println(a);
// out.println(b);
char[] res = new char[a.length()];
int cur = 0;
while (cur < a.length() && a.charAt(cur) == b.charAt(cur)) {
res[cur] = '0';
cur++;
}
while (cur < res.length) {
res[cur] = '1';
cur++;
}
out.println(Long.valueOf(new String(res), 2));
}
public static void main(String[] args) throws Exception {
ProblemD solution = new ProblemD();
solution.run();
}
private void initInputOutput() throws Exception {
if (FILENAME == null) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
private void shuffleArray(Object[] arr) {
Random r = new Random();
for (int i = 0; i < arr.length; ++i) {
Object tmp = arr[i];
int j = r.nextInt(arr.length);
arr[i] = arr[j];
arr[j] = tmp;
}
}
private void shuffleArray(int[] arr) {
Random r = new Random();
for (int i = 0; i < arr.length; ++i) {
int tmp = arr[i];
int j = r.nextInt(arr.length);
arr[i] = arr[j];
arr[j] = tmp;
}
}
private int[] nextArrayInt(int n) throws Exception {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private String nextWord() throws Exception {
if (updateTokenizer()) {
return null;
} else {
return tok.nextToken();
}
}
private boolean hasMoreTokens() throws Exception {
return !updateTokenizer();
}
private boolean updateTokenizer() throws Exception {
while (tok == null || !tok.hasMoreTokens()) {
String nextLine = in.readLine();
if (nextLine == null || nextLine.isEmpty()) {
return true;
}
tok = new StringTokenizer(nextLine, DELIMETER);
}
return false;
}
private int nextInt() throws Exception {
return Integer.parseInt(nextWord());
}
private long nextLong() throws Exception {
return Long.parseLong(nextWord());
}
private void finish() throws Exception {
in.close();
out.close();
}
private void print(String s) {
if (DEBUG) {
System.out.print(s);
}
}
private void println(String s) {
if (DEBUG) {
System.out.println(s);
}
}
private void println() {
if (DEBUG) {
System.out.println();
}
}
private long[] getFirstSimpleNums(int n) {
boolean[] notPr = new boolean[n];
int res = n;
notPr[0] = true;
res--;
notPr[1] = true;
res--;
for (int i = 2; i < n; ++i) {
if (!notPr[i]) {
for (int j = i + i; j < n; j += i) {
if (!notPr[j]) {
notPr[j] = true;
res--;
}
}
}
}
long[] resA = new long[res];
int next = 0;
for (int i = 0; i < n; i++) {
if (!notPr[i]) {
resA[next] = i;
next++;
}
}
return resA;
}
private static class Pair {
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
public static final Comparator<Pair> comparator = new Comparator<Pair>() {
@Override
public int compare(Pair pair1, Pair pair2) {
return (pair1.a - pair2.a) != 0 ? (pair1.a - pair2.a) : (pair1.b - pair2.b);
}
};
@Override
public String toString() {
return "{" + a + "|" + b + '}';
}
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
/*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000L * 1000L * 1000L + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "Yes";
private static final String no = "No";
int n;
int[] arr;
class Segment {
int start;
int end;
public Segment(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public String toString() {
return start + " " + end;
}
}
Map<Integer, List<Segment>> hm = new HashMap<>();
void solve() throws IOException {
n = nextInt();
arr = nextIntArr(n);
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
if (!hm.containsKey(sum)) {
hm.put(sum, new ArrayList<>());
}
hm.get(sum).add(new Segment(i, j));
}
}
int max = -1;
int idx = -1;
for (Map.Entry<Integer, List<Segment>> entry : hm.entrySet()) {
int key = entry.getKey();
List<Segment> values = entry.getValue();
Collections.sort(values, new Comparator<Segment>() {
@Override
public int compare(Segment o1, Segment o2) {
return Integer.compare(o1.end, o2.end);
}
});
int cnt = findSeg(values).size();
if (cnt > max) {
max = cnt;
idx = key;
}
}
List<Segment> res = findSeg(hm.get(idx));
outln(res.size());
for (int i = 0; i < res.size(); i++) {
outln((1 + res.get(i).start) + " " + (1 + res.get(i).end));
}
}
List<Segment> findSeg(List<Segment> input) {
List<Segment> res = new ArrayList<>();
int bound = -1;
for (int i = 0; i < input.size(); i++) {
if (input.get(i).start > bound) {
res.add(input.get(i));
bound = input.get(i).end;
}
}
return res;
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
private void formatPrint(double val) {
outln(String.format("%.9f%n", val));
}
public CFA() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class AA {
static class O implements Comparable<O> {
int problems;
int penalty;
public O(int p, int pp) {
problems = p;
penalty = pp;
}
public int compareTo(O arg0) {
if (problems == arg0.problems) {
return penalty - arg0.penalty;
}
return -(problems - arg0.problems);
}
}
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String s = r.readLine();
String[] sp = s.split("[ ]+");
int n = new Integer(sp[0]), k = new Integer(sp[1]) - 1;
O[] arr = new O[n];
for (int i = 0; i < arr.length; i++) {
s = r.readLine();
sp = s.split("[ ]+");
arr[i] = new O(new Integer(sp[0]), new Integer(sp[1]));
}
Arrays.sort(arr);
int res = 1;
int i = k + 1;
while (i < arr.length && arr[i].problems == arr[k].problems
&& arr[i].penalty == arr[k].penalty) {
i++;
res++;
}
i = k - 1;
while (i >= 0 && arr[i].problems == arr[k].problems
&& arr[i].penalty == arr[k].penalty) {
i--;
res++;
}
System.out.println(res);
}
}
|
nlogn
|
166_A. Rank List
|
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
|
// Working program using Reader Class
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main2
{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main(String[] args) throws IOException
{
Reader z = new Reader();
long n=z.nextLong(), k=z.nextLong(), x;
x=9L+8L*(k+n);
x=(long) Math.sqrt(x);
x=(x-3)/2;
System.out.println(n-x);
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class A {
int INF = 1 << 28;
void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
long[] chores = new long[n];
for(int i=0;i<n;i++) chores[i] = sc.nextLong();
sort(chores);
System.out.println(chores[b]-chores[b-1]);
}
public static void main(String[] args) {
new A().run();
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class EdA {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
public static void main(String[] omkar) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
int[][]cnt = new int[m][m];
String s = sc.next();
for(int j =0;j<n-1;j++){
if (s.charAt(j) != s.charAt(j+1)){
cnt[s.charAt(j)-'a'][s.charAt(j+1)-'a']++;
cnt[s.charAt(j+1)-'a'][s.charAt(j)-'a']++;
}
}
int[] st = new int[m+1];
for(int j = 0;j<=m;j++){
st[j] = (1<<j);
}
int[][] arr = new int[m][1<<m];
for(int j = 0;j<m;j++){
for(int k = 1;k<(1<<m);k++){
int z = Integer.lowestOneBit(k);
int count = 0;
while(z!=0 && z%2==0){
z/=2;
count++;
}
arr[j][k] = arr[j][k^(Integer.lowestOneBit(k))] + cnt[j][count];
}
}
int[] dp = new int[1<<m];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for(int j = 1;j<st[m];j++){
for(int k = 0;k<m;k++){
int y = st[k];
if ((y&j) != 0){
int sum = 2*arr[k][j] - arr[k][(1<<m)-1];
// for(int t = 0;t<m;t++){
// if (t!= k){
// if ((st[t]&j) != 0)
// sum+=cnt[t][k];
// else
// sum-=cnt[t][k];
// }
// }
dp[j] = Math.min(dp[j], dp[y^j]+sum*Integer.bitCount(j));
}
}
}
out.println(dp[(1<<m)-1]);
out.close();
}
public static void sort(int[] array){
ArrayList<Integer> copy = new ArrayList<Integer>();
for (int i : array)
copy.add(i);
Collections.sort(copy);
for(int i = 0;i<array.length;i++)
array[i] = copy.get(i);
}
static String[] readArrayString(int n){
String[] array = new String[n];
for(int j =0 ;j<n;j++)
array[j] = sc.next();
return array;
}
static int[] readArrayInt(int n){
int[] array = new int[n];
for(int j = 0;j<n;j++)
array[j] = sc.nextInt();
return array;
}
static int[] readArrayInt1(int n){
int[] array = new int[n+1];
for(int j = 1;j<=n;j++){
array[j] = sc.nextInt();
}
return array;
}
static long[] readArrayLong(int n){
long[] array = new long[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextLong();
return array;
}
static double[] readArrayDouble(int n){
double[] array = new double[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextDouble();
return array;
}
static int minIndex(int[] array){
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(long[] array){
long minValue = Long.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(double[] array){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static long power(long x, long y){
if (y == 0)
return 1;
if (y%2 == 1)
return (x*power(x, y-1))%mod;
return power((x*x)%mod, y/2)%mod;
}
static void verdict(boolean a){
out.println(a ? "YES" : "NO");
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int in = sc.nextInt();
if(
in%4==0||
in%7==0||
in%44==0||
in%47==0||
in%74==0||
in%77==0||
in%444==0||
in%447==0||
in%474==0||
in%477==0||
in%744==0||
in%747==0||
in%774==0||
in%777==0
)
System.out.println("YES");
else System.out.println("NO");
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++)
arr[i] = in.nextInt();
for(int i = n-1; i > 0; i--)
arr[i] -= arr[i-1];
arr[0] = 0;
Arrays.sort(arr);
long sum = 0;
for(int i = n-k; i >= 0; i--)
sum += arr[i];
System.out.println(sum);
}
}
|
nlogn
|
1197_C. Array Splitting
|
CODEFORCES
|
import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
double a = sc.nextDouble();
double v = sc.nextDouble();
double l = sc.nextDouble();
double d = sc.nextDouble();
double w = sc.nextDouble();
double res = calc(a, v, l, d, w);
out.printf("%.10f\n", res);
}
double calc(double a, double v, double l, double d, double w) {
if (v <= w) return getTime(a, 0, l, v);
// 距離 d までに速度 w に達しない場合
if ((w * w) >= d * 2 * a) return getTime(a, 0, l, v);
// それ以外は、d は速度wで通過
double ans = 0;
double[] r1 = getReach(a, 0, v);
double[] r2 = getReach(a, w, v);
// d までに最高速度 v に達する場合
if (r1[1] + r2[1] <= d) {
ans += r1[0];
ans += r2[0];
ans += (d - r1[1] - r2[1]) / v;
} else {
// d までに最高速度に達しない場合
double t0 = sqrt((2 * a * d + w * w) / (2 * a * a));
ans += t0 + (a * t0 - w) / a;
}
ans += getTime(a, w, l - d, v);
return ans;
}
/**
* s から v に達するまでの時間と、その間の走行距離
*/
double[] getReach(double a, double s, double v) {
double t = (v - s) / a;
double dist = t * (v + s) / 2.0;
return new double[]{t, dist};
}
/**
* 初速 s、加速a、 最高速度 v で距離 l を走るのにかかる時間
*/
double getTime(double a, double s, double l, double v) {
double t = (-s + sqrt(s * s + 2 * a * l)) / a;
double t_ = (v - s) / a;
if (t < t_) return t;
double p = l - (s + v) * t_ / 2;
return t_ + (p / v);
}
public static void main(String[] args) throws Exception {
Class<?> here = new Object(){}.getClass().getEnclosingClass();
try {
String packageName = here.getPackage().getName();
packageName = "src/" + packageName.replaceAll("\\.", "/") + "/";
System.setIn(new FileInputStream(packageName + "input.txt"));
// System.setOut(new PrintStream(new FileOutputStream(packageName + "output.txt")));
} catch (FileNotFoundException e) {
} catch (NullPointerException e) {
}
Object o = Class.forName(here.getName()).newInstance();
o.getClass().getMethod("run").invoke(o);
}
static void tr(Object... os) {
System.err.println(deepToString(os));
}
MyScanner sc = null;
PrintWriter out = null;
public void run() throws Exception {
sc = new MyScanner(System.in);
out = new PrintWriter(System.out);
for (;sc.hasNext();) {
solve();
out.flush();
}
out.close();
}
void print(int[] a) {
out.print(a[0]);
for (int i = 1; i < a.length; i++) out.print(" " + a[i]);
out.println();
}
class MyScanner {
String line;
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public void eat() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
line = reader.readLine();
if (line == null) {
tokenizer = null;
return;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public String next() {
eat();
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasNext() {
eat();
return (tokenizer != null && tokenizer.hasMoreElements());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.Writer;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author palayutm
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
String[] a = new String[n];
String[] b = new String[n];
for (int i = 0; i < n; i++) {
a[i] = in.next();
}
for (int i = 0; i < n; i++) {
b[i] = in.next();
}
int ans = 0;
for (int i = 1; i < 5; i++) {
int a1 = 0, b1 = 0, c1 = 0;
for (int j = 0; j < n; j++) {
if (a[j].length() == i) {
if (a[j].charAt(i - 1) == 'M') {
a1++;
} else if (a[j].charAt(i - 1) == 'S') {
b1++;
} else {
c1++;
}
}
}
for (int j = 0; j < n; j++) {
if (b[j].length() == i) {
if (b[j].charAt(i - 1) == 'M') {
a1--;
} else if (b[j].charAt(i - 1) == 'S') {
b1--;
} else {
c1--;
}
}
}
if (a1 > 0) ans += a1;
if (b1 > 0) ans += b1;
if (c1 > 0) ans += c1;
}
out.println(ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0;
private int ptrbuf = 0;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int readByte() {
if (lenbuf == -1) throw new UnknownError();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = stream.read(inbuf);
} catch (IOException e) {
throw new UnknownError();
}
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;
}
public String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
static class OutputWriter extends PrintWriter {
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(Writer out) {
super(out);
}
public void close() {
super.close();
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.util.Scanner;
public class ProblemC {
public static void main(String[] args) {
ProblemC problem = new ProblemC();
problem.solve();
}
private void solve() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
int ret = n;
int toth = 0;
int tott = 0;
for (int j = 0; j < n; j++) {
if (s.charAt(j) == 'H') {
toth++;
} else {
tott++;
}
}
for (int j = 0; j < n; j++) {
int cnth = 0;
for (int k = 0; k < toth; k++) {
int pos = (j + k) % n;
if (s.charAt(pos) == 'H') {
cnth++;
}
}
int makeh = toth - cnth;
ret = Math.min(ret, makeh);
}
System.out.println(ret);
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Main2 {
static List<List<Integer>> getLayers(int[] numbers, int a, int b) {
boolean[] used = new boolean[numbers.length];
HashSet<Integer> hs = new HashSet<Integer>();
for (int i = 0; i < numbers.length; i++) {
hs.add(numbers[i]);
}
HashMap<Integer, Integer> numberToIndex = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
numberToIndex.put(numbers[i], i);
}
List<List<Integer>> ans = new ArrayList<List<Integer>>();
for (int i = 0; i < numbers.length; i++) {
if (!used[i]) {
List<Integer> ansRow = new ArrayList<Integer>();
LinkedList<Integer> current = new LinkedList<Integer>();
current.add(numbers[i]);
while (!current.isEmpty()) {
int c = current.removeFirst();
used[numberToIndex.get(c)] = true;
boolean found = false;
if (hs.contains(a - c)) {
found = true;
if (a - c != c)
current.add(a - c);
}
if (hs.contains(b - c)) {
found = true;
if (b - c != c)
current.add(b - c);
}
if (found || ansRow.size() > 0)
ansRow.add(c);
hs.remove(c);
}
ans.add(ansRow);
}
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = sc.nextInt();
}
HashSet<Integer> hs = new HashSet<Integer>();
for (int i = 0; i < numbers.length; i++) {
hs.add(numbers[i]);
}
int[] belongs = new int[n];
for (int i = 0; i < belongs.length; i++) {
belongs[i] = -1;
}
HashMap<Integer, Integer> numberToIndex = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
numberToIndex.put(numbers[i], i);
}
boolean possible = true;
List<List<Integer>> layers = getLayers(numbers, a, b);
for (List<Integer> layer : layers) {
if (layer.size() == 0) {
System.out.println("NO");
return;
}
int starting = -1;
for (int j = 0; j < layer.size(); j++) {
int cur = layer.get(j);
int nei = 0;
if (hs.contains(a - cur)) {
nei++;
}
if (hs.contains(b - cur)) {
nei++;
}
if (nei == 1 || (a == b && nei == 2)) {
starting = j;
}
}
if (starting == -1)
throw new Error();
int c = layer.get(starting);
HashSet<Integer> layerset = new HashSet<Integer>(layer);
while (true) {
if (layerset.contains(c) && layerset.contains(a - c)) {
belongs[numberToIndex.get(c)] = 0;
belongs[numberToIndex.get(a - c)] = 0;
layerset.remove(c);
layerset.remove(a - c);
c = b - (a - c);
} else if (layerset.contains(c) && layerset.contains(b - c)) {
belongs[numberToIndex.get(c)] = 1;
belongs[numberToIndex.get(b - c)] = 1;
layerset.remove(c);
layerset.remove(b - c);
c = a - (b - c);
} else {
break;
}
}
}
printResult(belongs);
}
static void printResult(int[] belongs) {
boolean ok = true;
for (int i = 0; i < belongs.length; i++) {
if (belongs[i] < 0)
ok = false;
}
if (ok) {
System.out.println("YES");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < belongs.length; i++) {
sb.append(belongs[i]);
if (i != belongs.length - 1)
sb.append(" ");
}
System.out.println(sb.toString());
} else {
System.out.println("NO");
}
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
// Main Code at the Bottom
import java.util.*;
import java.io.*;
public class Main{
//Fast IO class
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUDGE") != null;
//env=true;
if(!env) {
try {
br=new BufferedReader(new FileReader("src\\input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long MOD=(long)1e9+7;
//debug
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
//Global variables and functions
static int code(int x,int y) {
return 505*x+y;
}
static class pair{
int x,y;
pair(int a,int b){
this.x=a;
this.y=b;
}
public boolean equals(Object obj) {
if(obj == null || obj.getClass()!= this.getClass()) return false;
pair p = (pair) obj;
return (this.x==p.x && this.y==p.y);
}
public int hashCode() {
return Objects.hash(x,y);
}
}
static int hor[][],ver[][];
static int moves[][]= {{-1,0},{1,0},{0,-1},{0,1}};
static int n,m;
static int dp[][][];
static int solve(int x,int y,int k) {
if(k==0) {
return 0;
}
if(dp[x][y][k]!=0) return dp[x][y][k];
int min=(int)MOD;
for(int mo[]: moves) {
int X=x+mo[0],Y=y+mo[1];
if(X<0 || X>=n || Y<0 || Y>=m) continue;
int val=0;
if(mo[0]==1) val=ver[x][y];
else if(mo[0]==-1) val=ver[x-1][y];
else if(mo[1]==1) val=hor[x][y];
else val=hor[x][y-1];
min=Math.min(min, 2*val+solve(X,Y,k-2));
}
return dp[x][y][k]=min;
}
//Main function(The main code starts from here)
public static void main (String[] args) throws java.lang.Exception {
int test=1;
//test=sc.nextInt();
while(test-->0) {
n=sc.nextInt();m=sc.nextInt();
int k=sc.nextInt();
if(k%2!=0) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) out.print(-1+" ");
out.println();
}
continue;
}
hor=new int[n][m-1];
ver=new int[n-1][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m-1;j++) {
hor[i][j]=sc.nextInt();
}
}
for(int i=0;i<n-1;i++) {
for(int j=0;j<m;j++) {
ver[i][j]=sc.nextInt();
}
}
dp=new int[n][m][k+1];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
out.print(solve(i,j,k)+" ");
}
out.println();
}
}
out.flush();
out.close();
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class RationalResistance {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
long a = Long.parseLong(st.nextToken());
long b = Long.parseLong(st.nextToken());
System.out.println(f(a,b));
}
public static long f(long a, long b)
{
if (a == 1 || b == 1)
return a+b-1;
if (a > b)
return f(a%b,b) + a/b;
else
return f(a,b%a) + b/a;
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.Scanner;
public class A235 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long n = scan.nextInt();
BigInteger res = null;
if (n >= 3) {
if (n % 2 != 0) {
res = BigInteger.valueOf(n * (n - 1) * (n - 2));
} else if (n % 3 == 0) {
res = BigInteger.valueOf((n - 1) * (n - 2) * (n - 3));
} else {
res = BigInteger.valueOf(n * (n - 1) * (n - 3));
}
} else {
res = BigInteger.valueOf(n);
}
System.out.println(res);
}
}
|
constant
|
235_A. LCM Challenge
|
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 ilyakor
*/
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);
TaskE1 solver = new TaskE1();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++) {
solver.solve(i, in, out);
}
out.close();
}
static class TaskE1 {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] d = new int[2][1 << n];
int[] buf = new int[1 << n];
int[][] a = new int[m][n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
a[j][i] = in.nextInt();
}
}
for (int i = 0; i < m; ++i) {
int[] prev = d[i % 2], nx = d[(i + 1) % 2];
for (int shift = 0; shift < n; ++shift) {
int[] b = new int[n];
for (int j = 0; j < n; ++j) {
b[j] = a[i][(j + shift) % n];
}
System.arraycopy(prev, 0, buf, 0, prev.length);
for (int mask = 0; mask < (1 << n); ++mask) {
int val0 = buf[mask];
for (int j = 0; j < n; ++j) {
if ((mask >> j) % 2 == 0) {
int val = val0 + b[j];
int nm = mask ^ (1 << j);
if (val > buf[nm]) {
buf[nm] = val;
}
}
}
}
for (int mask = 0; mask < (1 << n); ++mask) {
if (nx[mask] < buf[mask]) {
nx[mask] = buf[mask];
}
}
}
}
out.printLine(d[m % 2][(1 << n) - 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 print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0) {
return -1;
}
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public String nextToken() {
int c = readSkipSpace();
StringBuilder sb = new StringBuilder();
while (!isSpace(c)) {
sb.append((char) c);
c = read();
}
return sb.toString();
}
public String next() {
return nextToken();
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.Scanner;
public class ehsan
{
public static BigInteger f(BigInteger m,BigInteger n){
BigInteger s,l;
s=n.multiply(m.add(BigInteger.valueOf(1)));
l=m.multiply(m.add(BigInteger.valueOf(1)));
l=l.divide(BigInteger.valueOf(2));
s=s.subtract(l);
s=s.subtract(m);
return s;
}
public static BigInteger bs(BigInteger a,BigInteger b,BigInteger n,BigInteger d){
BigInteger c,e;
c=a.add(b);
c=c.divide(BigInteger.valueOf(2));
e=f(c,n);
if(e.equals(d))
return c.add(BigInteger.valueOf(1));
if(a.equals(b.add(BigInteger.valueOf(-1))))
return b.add(BigInteger.valueOf(1));
if(e.compareTo(d)>0)
return bs(a,c,n,d);
return bs(c,b,n,d);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
BigInteger bi1 = sc.nextBigInteger();
BigInteger bi2 = sc.nextBigInteger();
BigInteger i,n=bi2;
BigInteger i2=BigInteger.valueOf(1);
BigInteger sum=BigInteger.valueOf(0);
if(bi1.compareTo(bi2)<0){
System.out.println(0);
return;
}
if(bi1.compareTo(bi2)==0){
System.out.println(1);
return;
}
bi2=((n.multiply(n.add(BigInteger.valueOf(1)))).divide(BigInteger.valueOf(2))).subtract(n.subtract(BigInteger.valueOf(1)));
if(bi1.compareTo(bi2)>0)
System.out.println(-1);
else{
System.out.println(bs(BigInteger.valueOf(0),n.add(BigInteger.valueOf(-2)),n,bi1));
}
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CodeD
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String nextLine()
{
try
{
return br.readLine();
}
catch(Exception e)
{
throw(new RuntimeException());
}
}
public String next()
{
while(!st.hasMoreTokens())
{
String l = nextLine();
if(l == null)
return null;
st = new StringTokenizer(l);
}
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 int[] nextIntArray(int n)
{
int[] res = new int[n];
for(int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n)
{
long[] res = new long[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n)
{
double[] res = new double[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public void sortIntArray(int[] array)
{
Integer[] vals = new Integer[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array)
{
Long[] vals = new Long[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array)
{
Double[] vals = new Double[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
}
static final Scanner sc;
static final int n;
static final int[][] distancias;
static final int[] distancia;
static final int[] dp;
static final int[] dpNext;
static final int X;
static final int Y;
static
{
sc = new Scanner();
X = sc.nextInt();
Y = sc.nextInt();
n = sc.nextInt();
distancias = new int[n][n];
distancia = new int[n];
dp = new int[1 << n];
Arrays.fill(dp, -1);
dpNext = new int[1 << n];
}
static int dp(int mascara)
{
if(dp[mascara] != -1)
return dp[mascara];
int highest = -1;
for(int i = 0, tmp = mascara; tmp != 0; i++, tmp >>= 1)
{
if((tmp & 1) == 1)
highest = i;
}
if(highest == -1)
return 0;
int nextMsc = mascara ^ (1 << highest);
int costHighest = distancia[highest];
int best = (costHighest << 1) + dp(nextMsc);
int bestNext = nextMsc;
for(int i = 0, tmp = nextMsc, iC = 1; tmp != 0; i++, tmp >>= 1, iC <<= 1)
{
if((tmp & 1) == 1)
{
int msc = nextMsc ^ iC;
int possibleA = costHighest + distancias[highest][i] + distancia[i] + dp(msc);
if(possibleA < best)
{
best = possibleA;
bestNext = msc;
}
}
}
dpNext[mascara] = bestNext;
return dp[mascara] = best;
}
public static void main(String[] args)
{
int[][] objetos = new int[n][2];
for(int i = 0; i < n; i++)
{
objetos[i][0] = sc.nextInt();
objetos[i][1] = sc.nextInt();
distancia[i] = (X - objetos[i][0]) * (X - objetos[i][0]) + (Y - objetos[i][1]) * (Y - objetos[i][1]);
}
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
distancias[i][j] = (objetos[i][0] - objetos[j][0]) * (objetos[i][0] - objetos[j][0]) + (objetos[i][1] - objetos[j][1]) * (objetos[i][1] - objetos[j][1]);
int ans = dp((1 << n) - 1);
System.out.println(ans);
int current = (1 << n) - 1;
while(current != 0)
{
int next = dpNext[current];
int differents = next ^ current;
System.out.print("0 ");
for(int i = 0; i < n; i++)
if((differents & (1 << i)) != 0)
System.out.print((i + 1) + " ");
current = next;
}
System.out.println("0");
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class e {
public static class FastReader {
BufferedReader br;
StringTokenizer st;
//it reads the data about the specified point and divide the data about it ,it is quite fast
//than using direct
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception r) {
r.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());//converts string to integer
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception r) {
r.printStackTrace();
}
return str;
}
}
static ArrayList<String>list1=new ArrayList<String>();
static void combine(String instr, StringBuffer outstr, int index,int k)
{
if(outstr.length()==k)
{
list1.add(outstr.toString());return;
}
if(outstr.toString().length()==0)
outstr.append(instr.charAt(index));
for (int i = 0; i < instr.length(); i++)
{
outstr.append(instr.charAt(i));
combine(instr, outstr, i + 1,k);
outstr.deleteCharAt(outstr.length() - 1);
}
index++;
}
static ArrayList<ArrayList<Integer>>l=new ArrayList<>();
static void comb(int n,int k,int ind,ArrayList<Integer>list)
{
if(k==0)
{
l.add(new ArrayList<>(list));
return;
}
for(int i=ind;i<=n;i++)
{
list.add(i);
comb(n,k-1,ind+1,list);
list.remove(list.size()-1);
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader in=new FastReader();
HashMap<Integer,Integer>map=new HashMap<Integer,Integer>();
int n=in.nextInt();
int r=in.nextInt();
double theta=(double)360/(double)n;
double b=1-((double)2/(double)(1-Math.cos((double)2*Math.PI/(double)n)));
double x=Math.sqrt(1-b)-1;
double ans=(double)r/(double)x;
System.out.println(ans);
}
}
|
constant
|
1100_C. NN and the Optical Illusion
|
CODEFORCES
|
// discussed with rainboy
import java.io.*;
import java.util.*;
public class CF915E {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
int q = Integer.parseInt(br.readLine());
TreeMap<Integer, Integer> mp = new TreeMap<>();
int ans = 0;
while (q-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken()) - 1;
int r = Integer.parseInt(st.nextToken());
int t = Integer.parseInt(st.nextToken());
Map.Entry<Integer, Integer> e;
int l_, r_;
if (t == 1) {
if ((e = mp.floorEntry(l)) != null && (r_ = e.getValue()) >= l) {
l_ = e.getKey();
ans -= r_ - l_;
l = l_;
r = Math.max(r, r_);
}
while ((e = mp.higherEntry(l)) != null && (l_ = e.getKey()) <= r) {
r_ = e.getValue();
ans -= r_ - l_;
r = Math.max(r, r_);
mp.remove(l_);
}
ans += r - l;
mp.put(l, r);
} else {
r_ = l;
if ((e = mp.floorEntry(l)) != null && (r_ = e.getValue()) > l) {
l_ = e.getKey();
if (l_ < l)
mp.put(l_, l);
else
mp.remove(l_);
ans -= r_ - l;
}
while ((e = mp.higherEntry(l)) != null && (l_ = e.getKey()) < r) {
r_ = e.getValue();
mp.remove(l_);
ans -= r_ - l_;
}
if (r_ > r) {
mp.put(r, r_);
ans += r_ - r;
}
}
pw.println(n - ans);
}
pw.close();
}
}
|
nlogn
|
915_E. Physical Education Lessons
|
CODEFORCES
|
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class A23 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
Map<String, Boolean> map = new HashMap<String, Boolean>();
for (int i = s.length(); i >= 1; i--) {
map.clear();
for (int j = 0; j < s.length()-i+1; j++) {
String temp = s.substring(j, j+i);
if (map.containsKey(temp)) {
System.out.println(i);
return;
}
map.put(temp, true);
}
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.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) {
long l = in.nextLong();
long r = in.nextLong();
int max = (int) (r - l);
if (max >= 2) {
if ((l & 1) == 0) {
out.println(l + " " + (l + 1) + " " + (l + 2));
return;
} else {
if (max >= 3) {
out.println((l + 1) + " " + (l + 2) + " " + (l + 3));
return;
}
}
}
out.println(-1);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
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 long nextLong() {
return Long.parseLong(next());
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class DigitSequenceA {
public static void main(String[] args) throws IOException{
FastReader in = new FastReader();
double digit = in.nextDouble();
double temp = digit;
long[] seq = new long[13];
for(int i = 1; i<13; i++){
seq[i] = (9* (long)Math.pow(10,i-1)) * (i) +seq[i-1];
}
int power = 0;
for(int i = 0; i< 13; i++){
if(temp-seq[i] >0){
continue;
}
else{
power = i;
break;
}
}
long place = (long) Math.ceil(digit - seq[power-1]);
place = (long)Math.ceil(place/power);
if((digit - seq[power-1])%power>0){
place++;
}
long num = (long) (place + Math.pow(10,power-1)-1);
String num2 = Long.toString(num);
long end = seq[power-1] + place*power;
long answer = (long)(power-(end - digit));
//System.out.println("Digit is at the " + power + " power");
//System.out.println("Digit is at the " + place + " number of the sequence");
//System.out.println("Number is " + num);
//System.out.println("Digit is at the " + answer+ " in that number");
//System.out.println("Answer is " + num2.charAt((int)answer-1));
System.out.println(num2.charAt((int)answer-1));
}
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;
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class G1 {
public static void main(String[] args) throws Exception {
new G1().run();
}
int MOD = 1_000_000_007;
public void run() throws Exception {
FastScanner f = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = f.nextInt(), t = f.nextInt();
int[][] dp = new int[1 << n][3];
int[] tarr = new int[n];
int[] garr = new int[n];
for(int i = 0; i < n; i++) {
tarr[i] = f.nextInt();
garr[i] = f.nextInt()-1;
if(tarr[i] <= t) dp[1 << i][garr[i]] = 1;
}
int[] time = new int[1 << n];
for(int i = 0; i < dp.length; i++) {
for(int bi = 0; bi < n; bi++)
if((i & 1 << bi) != 0) time[i] += tarr[bi];
}
for(int i = 0; i < dp.length; i++) {
int j = time[i];
for(int k = 0; k < 3; k++) {
if(dp[i][k] == 0) continue;
for(int bi = 0; bi < n; bi++)
if(tarr[bi] + j <= t && (i & 1 << bi) == 0 && garr[bi] != k) {
dp[i | 1 << bi][garr[bi]] =
(dp[i | 1 << bi][garr[bi]] + dp[i][k]) % MOD;
}
}
}
long ans = 0;
for(int i = 0; i < dp.length; i++)
for(int j = 0; j < 3; j++)
if(time[i] == t) ans = (ans + dp[i][j]) % MOD;
out.println(ans);
out.flush();
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author sheep
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
boolean[][] map = new boolean[n][n];
int m = in.nextInt();
int[] us = new int[m];
int[] vs = new int[m];
for (int i = 0; i < m; ++i) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
map[u][v] = true;
us[i] = u;
vs[i] = v;
}
int ans = Integer.MAX_VALUE;
for (int center = 0; center < n; ++center) {
int fixed = 0;
for (int i = 0; i < n; ++i) {
if (!map[center][i]) {
++fixed;
}
if (!map[i][center] && i != center) {
++fixed;
}
}
MaxFlow flow = new MaxFlow(n * 2 + 2, n * 2, n * 2 + 1);
for (int i = 0; i < n; ++i) {
if (i == center) continue;
flow.insert(n * 2, i, 1);
flow.insert(i + n, n * 2 + 1, 1);
}
for (int i = 0; i < m; ++i) {
if (us[i] == center || vs[i] == center) {
continue;
}
flow.insert(us[i], vs[i] + n, 1);
++fixed;
}
ans = Math.min(ans, fixed + (n - 1) - 2 * flow.maxFlow());
}
out.println(ans);
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new UnknownError();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
class MaxFlow
{
public class Edge
{
public int u,v,c;
public Edge next,r;
public Edge(int u,int v,int c)
{
this.u = u;
this.v = v;
this.c = c;
next = r = null;
}
}
public Edge vertex[];
public int height[], nheight[];
public int s, t, n;
public void init(int n,int s,int t)
{
height = new int[n+1];
nheight = new int[n+1];
vertex = new Edge[n+1];
this.s = s;
this.t = t;
this.n = n;
}
public MaxFlow(int n,int s,int t)
{
init(n,s,t);
}
public void insert(int u,int v,int c)
{
Edge e = new Edge(u,v,c);
Edge r = new Edge(v,u,0);
e.r = r;
r.r = e;
e.next = vertex[u];
vertex[u] = e;
r.next = vertex[v];
vertex[v] = r;
}
public int augPath(int u,int push)
{
if (u == t) return push;
int flow = push, minheight = n-1;
for (Edge e = vertex[u]; e != null; e = e.next)
if (e.c != 0)
{
if (height[e.v] + 1 == height[e.u])
{
int delta = flow < e.c ? flow : e.c;
if (delta > 0)
delta = augPath(e.v,delta);
e.c -= delta;
e.r.c += delta;
flow -= delta;
if (0 == flow || height[s] >= n) return push - flow;
}
minheight = Math.min(minheight, height[e.v]);
}
if (push == flow)
{
--nheight[height[u]];
if (0 == nheight[height[u]]) height[s] = n;
height[u] = ++minheight;
++nheight[height[u]];
}
return push - flow;
}
public int maxFlow()
{
Arrays.fill(height, 0);
Arrays.fill(nheight, 0);
nheight[0] = n;
int flow = 0;
while (height[s] < n)
flow += augPath(s,Integer.MAX_VALUE);
return flow;
}
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Math.min;
import static java.lang.System.exit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class F {
static void solve() throws Exception {
int n = scanInt();
long l[] = new long[n];
for (int i = 0; i < n; i++) {
l[i] = scanLong();
}
long e1 = 0, e2 = 0, ans = 0;
boolean water = false;
String types = scanString();
for (int i = 0; i < n; i++) {
long li = l[i], cur;
switch (types.charAt(i)) {
case 'G':
cur = min(e1, li);
e1 -= cur;
li -= cur;
e2 += 2 * cur;
ans += 2 * cur;
e2 += li;
ans += 3 * li;
break;
case 'W':
water = true;
e1 += li;
ans += 2 * li;
break;
case 'L':
cur = min(e1, li);
e1 -= cur;
li -= cur;
ans += 2 * cur;
cur = min(e2, li);
e2 -= cur;
li -= cur;
ans += 3 * cur;
ans += (water ? 4 : 6) * li;
break;
default:
throw new AssertionError();
}
}
out.print(ans);
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static String scanString() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
}
|
linear
|
1091_F. New Year and the Mallard Expedition
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Hexadecimaltheorem {
public static void main(String[] args) {
BufferedReader buf = new BufferedReader(
new InputStreamReader(System.in));
int x;
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(0);
arr.add(1);
try {
while ((x = Integer.parseInt(buf.readLine())) != -1) {
if (x == 1) {
System.out.println(arr.get(0) + " " + arr.get(0) + " "
+ arr.get(1));
} else if (x == 0) {
System.out.println(arr.get(0) + " " + arr.get(0) + " "
+ arr.get(0));
} else {
int i = 1;
while (x > arr.get(arr.size() - 1)) {
arr.add(arr.get(i) + arr.get(i - 1));
i++;
}
System.out.println(arr.get(0) + " " + arr.get(i - 2) + " "
+ arr.get(i - 1));
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.