src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
public class Main {
public static class node implements Comparable<node> {
int l,r;
node(){}
node(int l,int r) {
this.l=l;
this.r=r;
}
@Override
public int compareTo(node rhs) {
return r-rhs.r;
}
}
public static void main(String[] args) throws IOException {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
StringTokenizer sa=new StringTokenizer(in.readLine());
int n=Integer.parseInt(sa.nextToken());
sa=new StringTokenizer(in.readLine());
int[] a=new int[n];
TreeMap<Integer,ArrayList<node>> mp=new TreeMap();
for (int i=0;i<n;++i) a[i]=Integer.parseInt(sa.nextToken());
ArrayList<node> ans=new ArrayList<node>();
for (int i=0;i<n;++i) {
int tmp=0;
for (int j=i;j<n;++j) {
tmp+=a[j];
if (!mp.containsKey(tmp)) {
ArrayList<node> t=new ArrayList();
t.add(new node(i,j));
mp.put(tmp,t);
} else {
ArrayList<node> t=mp.get(tmp);
int left=0,right=t.size()-1,res=t.size();
while (left<=right) {
int mid=(left+right)>>1;
if (t.get(mid).r>=i) {
res=mid;
right=mid-1;
} else left=mid+1;
}
if (res==t.size()) t.add(new node(i,j));
else if (t.get(res).r>j) t.set(res,new node(i,j));
}
if (mp.get(tmp).size()>ans.size()) ans=mp.get(tmp);
}
}
out.println(ans.size());
for (int i=0;i<ans.size();++i)
out.printf("%d %d\n",ans.get(i).l+1,ans.get(i).r+1);
out.flush();
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.*;
public class algo_2701
{
public static void main(String args[])
{
Scanner ex=new Scanner(System.in);
int n=ex.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=ex.nextInt();
Arrays.sort(arr);
int ans=0;
int check[]=new int[n];
for(int i=0;i<n;i++)
{
if(check[i]==0)
{
ans++;
for(int j=i;j<n;j++)
{
if(arr[j]%arr[i]==0)
check[j]=1;
}
}
}
System.out.println(ans);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
private int n;
private int m;
private boolean[][] g;
private long[][] dp;
private int[] count;
private int[] first;
private void solve() throws IOException {
n = nextInt();
m = nextInt();
g = new boolean[n][n];
for (int i = 0; i < m; i++) {
int a = nextInt() - 1;
int b = nextInt() - 1;
g[a][b] = true;
g[b][a] = true;
}
count = new int[1 << n];
first = new int[1 << n];
dp = new long[1 << n][n];
for (int mask = 0; mask < (1 << n); mask++) {
count[mask] = bitCount(mask);
for (int i = 0; i < n; i++) {
if (bit(i, mask) == 1) {
first[mask] = i;
break;
}
}
}
for (int mask = 0; mask < (1 << n); mask++) {
for (int i = 0; i < n; i++) {
if ((count[mask] == 1) && (bit(i, mask) == 1)) {
dp[mask][i] = 1;
} else {
for (int j = 0; j < n; j++) {
if (g[j][i] && (count[mask] > 1) && (bit(i, mask) == 1)
&& (first[mask] != i)) {
dp[mask][i] += dp[mask ^ (1 << i)][j];
}
}
}
}
}
long ans = 0;
for (int i = 0; i < n; i++) {
for (int mask = 0; mask < (1 << n); mask++) {
if ((count[mask] >= 3) && (first[mask] != i)
&& (g[i][first[mask]])) {
ans += dp[mask][i];
}
}
}
if (ans % 2 != 0) {
throw new RuntimeException("SHIT!!!");
}
out.println(ans / 2);
}
private final int bit(int i, int mask) {
return (mask & (1 << i)) != 0 ? 1 : 0;
}
private final int bitCount(int mask) {
int ret = 0;
while (mask != 0) {
ret++;
mask -= mask & (-mask);
}
return ret;
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private Main() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
eat("");
solve();
in.close();
out.close();
}
private void eat(String s) {
st = new StringTokenizer(s);
}
String next() throws IOException {
while (!st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
eat(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static void main(String[] args) throws IOException {
new Main();
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class A {
private static BufferedReader in;
private static StringTokenizer st;
private static PrintWriter out;
public static void main(String[] args) throws NumberFormatException, IOException {
in = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int max = n;
max = Math.max(max, n / 10);
max = Math.max(max, (n / 100) * 10 + n % 10);
System.out.println(max);
}
static String next() throws IOException{
while(!st.hasMoreTokens()){
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
static int nextInt() throws NumberFormatException, IOException{
return Integer.parseInt(next());
}
static long nextLong() throws NumberFormatException, IOException{
return Long.parseLong(next());
}
static double nextDouble() throws NumberFormatException, IOException{
return Double.parseDouble(next());
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Solution extends Thread {
final static int MAXNUM = 1 << 20;
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
int tests = nextInt();
int num = 1;
for (int test = 0; test < tests; test++) {
String s = next();
if (s.charAt(0) == 'R' && s.charAt(1) >= '0' && s.charAt(1) <= '9' && s.indexOf('C') != -1) {
String[] sp = s.split("[RC]");
int r = Integer.parseInt(sp[1]);
int c = Integer.parseInt(sp[2]);
s = "";
while (c > 0) {
if (c % 26 == 0) {
s = 'Z' + s;
c /= 26;
c --;
} else {
s = (char)('A' + c % 26 - 1) + s;
c /= 26;
}
}
s = s + r;
} else {
int pos = 0;
while (s.charAt(pos) < '0' || s.charAt(pos) > '9') {
pos ++;
}
int r = Integer.parseInt(s.substring(pos));
int c = 0;
s = s.substring(0, pos);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) < 'Z') {
c = c * 26 + (s.charAt(i) - 'A' + 1);
} else {
c = c * 26 + 26;
}
}
s = "R" + r + "C" + c;
}
System.out.println(s);
}
} catch (Exception ex) {
ex.printStackTrace();
System.exit(-1);
}
}
String next() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
BufferedReader in;
StringTokenizer st;
public static void main(String[] args) {
Locale.setDefault(Locale.US);
new Thread(new Solution()).start();
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new InputStreamReader(System.in));
int n = sc.nextInt();
String s = sc.next();
sc.close();
int cH = 0;
for (int i=0; i < s.length(); i++)
if (s.charAt(i) == 'H')
cH++;
int best = cH;
for (int st=0; st < s.length(); st++) {
int cur = st;
int cnt = cH;
for (int i=0; i < cH; i++) {
if (s.charAt(cur) == 'H')
cnt--;
cur++;
if (cur == s.length()) cur = 0;
}
best = Math.min(best, cnt);
}
System.out.println(best);
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Date: 19.02.2010
* Time: 14:56:28
*
* @author Sergey Bankevich (Sergey.Bankevich@gmail.com)
*/
public class B1 {
static Scanner in;
public static void main( String[] args ) throws FileNotFoundException {
in = new Scanner( System.in );
int tn = in.nextInt();
for ( int i = 0; i < tn; i ++ ) {
String s = in.next();
/*for ( int i = 1; i <= 100; i ++ ) {
for ( int j = 1; j <= 100; j ++ ) {
String s = "R" + i + "C" + j;
for ( char j = 'A'; j <= 'Z'; j ++ ) {
String s = j + "" + i;
System.out.println( s );*/
char[] c = s.toCharArray();
boolean second = true;
second &= c[0] == 'R';
int r = s.indexOf( "C" );
if ( r > 0 ) {
second &= isNumber( s.substring( 1, r ) ) && isNumber( s.substring( r + 1 ) );
} else {
second = false;
}
if ( second ) {
System.out.println( toLetters( s.substring( r + 1 ) ) + s.substring( 1, r ) );
} else {
r = 0;
while ( c[r] >= 'A' && c[r] <= 'Z' ) {
r ++;
}
System.out.println( "R" + s.substring( r ) + "C" + fromLetters( s.substring( 0, r ) ) );
}
}
}
private static int fromLetters( String s ) {
int r = 0;
int l = s.length();
for ( int i = 0; i < l; i ++ ) {
r = r * 26 + s.charAt( i ) - 'A';
}
r ++;
for ( int i = 1, c = 26; i < l; i ++, c *= 26 ) {
r += c;
}
return r;
}
private static String toLetters( String s ) {
int x = new Integer( s ) - 1;
int c = 26;
int l = 1;
while ( true ) {
if ( x < c ) {
String r = "";
for ( int i = 0; i < l; i ++ ) {
r = ( char ) ( 'A' + x % 26 ) + r;
x /= 26;
}
return r;
}
x -= c;
c *= 26;
l ++;
}
}
private static boolean isNumber( String s ) {
try {
int x = new Integer( s );
} catch ( NumberFormatException e ) {
return false;
}
return true;
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
//package ContestEd69;
import java.io.*;
import java.util.StringTokenizer;
public class mainD {
public static PrintWriter out = new PrintWriter(System.out);
public static FastScanner enter = new FastScanner(System.in);
public static long[] arr;
public static void main(String[] args) throws IOException {
int n=enter.nextInt();
int m=enter.nextInt();
long k=enter.nextLong();
arr=new long[n+1];
for (int i = 1; i <n+1 ; i++) {
arr[i]=enter.nextLong();
}
long[] summ=new long[n+1];
for (int i = 1; i <n+1 ; i++) {
summ[i]+=arr[i]+summ[i-1];
}
long[] best=new long[n+1];
for (int i = 1; i <n+1 ; i++) {
best[i]=Math.max(0, ((i-m>=0) ? best[i-m]+summ[i]-summ[i-m]-k:0));
}
long ans=best[1];
for (int i = 1; i <n+1 ; i++) {
ans=Math.max(ans,best[i]);
for (int j = 1; j <m ; j++) {
ans=Math.max(ans, ((i-j>=0) ? best[i-j] -k +summ[i]-summ[i-j]:0));
}
}
System.out.println(ans);
}
static class FastScanner {
BufferedReader br;
StringTokenizer stok;
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
char nextChar() throws IOException {
return (char) (br.read());
}
String nextLine() throws IOException {
return br.readLine();
}
}
}
|
quadratic
|
1197_D. Yet Another Subarray Problem
|
CODEFORCES
|
import java.util.* ;
public class PythonIndentation
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in) ;
int n = in.nextInt() ;
boolean[] lst = new boolean[n] ;
for(int i=0;i<n;i++)
{
lst[i] = (in.next().equals("s"))?false:true ;
}
System.out.println(dp(lst)) ;
}
static void arrayPrinter(int[][] dp)
{
System.out.println(":::") ;
for(int i=0;i<dp.length;i++)
{
for(int j=0;j<dp[0].length;j++)
{
System.out.print(dp[i][j]+" ") ;
}
System.out.println() ;
}
}
static int dp(boolean[] lst)
{//false in lst means an "s" (simple statement), and true a "f"(for loop)
int[][] dp = new int[2][lst.length] ;
dp[0][0] = 1 ;
for(int i=1;i<lst.length;i++)
{
// arrayPrinter(dp) ;
for(int j=0;j<lst.length;j++)
{
if(lst[i-1])//(i-1)st statement is a for loop
{
if(j==0)
dp[i%2][j] = 0 ;
else
dp[i%2][j] = dp[(i-1)%2][j-1] ;
}
else//i-1 st statement is a simple statement
{
if(j==0)
{
int temp = 0 ;
for(int k=0;k<lst.length;k++)
temp = (temp+dp[(i-1)%2][k])%1000000007 ;
dp[i%2][j] = temp ;
}
else
dp[i%2][j] = (dp[i%2][j-1]-dp[(i-1)%2][j-1])%1000000007 ;
}
}
}
int ans = 0 ;
for(int i=0;i<lst.length;i++)
{
ans = (ans + dp[(lst.length-1)%2][i])%1000000007 ;
}
if(ans<0)
ans = ans + 1000000007 ;
// arrayPrinter(dp) ;
return ans ;
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.awt.List;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.TimeZone;
public class Cycle {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
InputStream inputstream = System.in;
OutputStream outputstream = System.out;
FastReader in = new FastReader(inputstream);
PrintWriter out = new PrintWriter(outputstream);
TaskA solver = new TaskA();
// int testcase = in.ni();
for (int i = 0; i < 1; i++)
solver.solve(i, in, out);
out.close();
}
}
class TaskA {
public void solve(int testnumber, FastReader in, PrintWriter out) {
int n = in.ni();
int m = in.ni();
boolean graph[][] = new boolean[n][n];
for (int i = 0; i < m; i++) {
int a = in.ni() - 1;
int b = in.ni() - 1;
graph[a][b] = true;
graph[b][a] = true;
}
/*
* dp[mask][i] be the number of Hamiltonian walks over the subset mask,
* starting at the vertex first(mask) and ending at the vertex i
*/
long dp[][] = new long[1 << n][n];
for (int i = 0; i < n; i++) {
dp[1 << i][i] = 1;
}
long answer = 0;
for (int mask = 1; mask < (1 << n); mask++) {
int start = Integer.numberOfTrailingZeros(mask);
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) == 0) {
continue;
}
for (int j = start + 1; j < n; j++) {
if (graph[i][j] && (mask & (1 << j)) == 0) {
dp[mask + (1 << j)][j] += dp[mask][i];
}
}
if (graph[i][start]) {
answer += dp[mask][i];
}
}
}
out.println((answer - m) / 2);
}
}
class FastReader {
public InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public FastReader() {
}
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 ni() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String ns() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] iArr(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public String next() {
return ns();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
//package educational35;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class ProblemD {
public static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static StringTokenizer tok = null;
public static void main(String args[]) throws IOException {
tok = new StringTokenizer(in.readLine());
int n = Integer.parseInt(tok.nextToken());
int tab[] = new int[n];
tok = new StringTokenizer(in.readLine());
for (int i=0; i<n; i++)
tab[i] = Integer.parseInt(tok.nextToken());
int inversions = countInversions(tab);
boolean isOdd = inversions % 2 == 1;
tok = new StringTokenizer(in.readLine());
int k = Integer.parseInt(tok.nextToken());
int start, end, len;
for (int i=0; i<k; i++) {
tok = new StringTokenizer(in.readLine());
start = Integer.parseInt(tok.nextToken());
end = Integer.parseInt(tok.nextToken());
len = (end - start + 1) % 4;
if (len == 2 || len ==3)
isOdd = !isOdd;
out.println(isOdd ? "odd" : "even");
}
out.close();
}
private static int countInversions(int tab[]) {
int n = tab.length;
int auxTab[] = new int[n+1];
return _countInversions(tab, 0, n, auxTab);
};
private static int _countInversions(int tab[], int start, int end, int auxTab[]) {
//indices from start to end; but values from start+1 to end+1 !!
if (start+1 >= end)
return 0;
int mid = (start + end) / 2;
int lowerFound = 0;
int higherFound = 0;
int count = 0;
for (int i=start; i<end; i++){
if (tab[i] < mid+1){
count += higherFound;
auxTab[start+lowerFound] = tab[i];
lowerFound++;
} else {
auxTab[mid + higherFound] = tab[i];
higherFound++;
}
}
for (int i=start; i<end; i++)
tab[i] = auxTab[i];
count += _countInversions(tab, start, mid, auxTab);
count += _countInversions(tab, mid, end, auxTab);
return count;
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
public class A22 {
static StreamTokenizer in;
static PrintWriter out;
static int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
static String nextString() throws IOException {
in.nextToken();
return in.sval;
}
public static void main(String[] args) throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
Arrays.sort(a);
int f = a[0], q = 1;
while (q < n && a[q] == f) q++;
out.println(q < n ? a[q] : "NO");
out.flush();
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.text.ChoiceFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int t = scan.nextInt();
List<List<Double>> coords = new ArrayList<List<Double>>();
while (n-- > 0) {
double x = scan.nextDouble();
double a = scan.nextDouble() / 2;
coords.add(Arrays.asList(x - a, x + a));
}
Collections.sort(coords, new Comparator<List<Double>>() {
@Override
public int compare(List<Double> o1, List<Double> o2) {
return o1.get(0).compareTo(o2.get(0));
}
});
int count = 2;
ChoiceFormat f = new ChoiceFormat("-1#0|0#1|0<2");
for (int i = 0; i < coords.size()-1; i++) {
double l = coords.get(i+1).get(0)-coords.get(i).get(1)-t;
count += new Integer(f.format(l));
}
System.out.println(count);
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class c implements Runnable{
int N;
int[] arr;
public static void main(String[] args) { new Thread(null, new c(), "", 1<<27).start(); } public void run() {
arr = new int[N = nextInt()];
for(int n=0;n<N;n++) {
// System.out.println(n+" s");
if(nextString().charAt(0) == 'f') {
arr[n] = 1;
}
}
long[][] dp = new long[N+1][N+1];
dp[0][0] = 1;
for(int i = 0; i < N; i++) {
// if this is an s
if(arr[i] == 0) {
// transition from the one directly above and everything to the right of that
// for each dp space. using cumulative sums will make this easier
long sum = 0;
for(int j = N; j >= 0; j--) {
sum += dp[i][j];
sum %= 1_000_000_007L;
dp[i+1][j] += sum;
dp[i+1][j] %= 1_000_000_007L;
}
}
// otherwise, this is an f
else {
// transition from the spot on the top left
for(int j = 1; j <= N; j++) {
dp[i+1][j] += dp[i][j-1];
dp[i+1][j] %= 1_000_000_007L;
}
}
}
// answer is the sum of the last row
long ans = 0;
for(long l : dp[N-1]) ans = (ans + l) % 1_000_000_007;
System.out.println(ans);
}
// fast scanner stuff
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = null; int line_ptr = 0;
void read() {
try {
line = br.readLine().split(" ");
}
catch(IOException ioe) {
System.err.println("bad input");
line = null;
}
}
void ensure() {
while(line == null || line.length <= line_ptr) {
read();
line_ptr = 0;
}
}
int nextInt() {
ensure();
return Integer.parseInt(line[line_ptr++]);
}
long nextLong() {
ensure();
return Integer.parseInt(line[line_ptr++]);
}
String nextString() {
ensure();
return line[line_ptr++];
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.util.*;
import static java.lang.Math.*;
public final class FollowTrafficRules {
private static double[] acce(double i, double a, double v) {
double[] r = new double[2];
r[0] = (v - i)/a;
r[1] = 1d/2d * a * pow(r[0], 2) + i * r[0];
return r;
}
private static double solve(double i, double a, double l) {
double e = sqrt(pow(i, 2) + 2d * a * l);
e = a > 0 ? e : -1d * e;
return (e - i)/a;
}
private static double time(double i, double a, double v, double l) {
double[] r = acce(i, a, v);
if (r[1] >= l) return solve(i, a, l);
return r[0] + (l - r[1])/v;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
double v = sc.nextDouble();
double l = sc.nextDouble();
double d = sc.nextDouble();
double w = sc.nextDouble();
double t = 0d;
if (v <= w) t = time(0, a, v, l);
else {
double[] r = acce(0, a, w);
if (r[1] >= d) t = time(0, a, v, l);
else {
t += r[0];
t += 2d * time(w, a, v, (d - r[1])/2d);
t += time(w, a, v, l - d);
}
}
System.out.println(t);
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception {
MyReader reader = new MyReader(System.in);
// MyReader reader = new MyReader(new FileInputStream("input.txt"));
MyWriter writer = new MyWriter(System.out);
new Solution().run(reader, writer);
writer.close();
}
private void run(MyReader reader, MyWriter writer) throws IOException, InterruptedException {
int n = reader.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = reader.nextString().charAt(0);
}
long[][] d = new long[n + 1][n + 1];
d[0][0] = 1;
long mod = 1_000_000_007;
for (int i = 1; i < n; i++) {
for (int j = n - 1; j >= 0; j--) {
if (a[i - 1] == 'f') {
d[i][j + 1] = d[i - 1][j];
} else {
d[i][j] = (d[i - 1][j] + d[i][j + 1]) % mod;
}
}
}
long ans = 0;
for (int i = 0; i <= n; i++) {
ans += d[n - 1][i];
}
writer.print(ans % mod);
}
static class MyReader {
final BufferedInputStream in;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = bufSize;
int k = bufSize;
boolean end = false;
final StringBuilder str = new StringBuilder();
MyReader(InputStream in) {
this.in = new BufferedInputStream(in, bufSize);
}
int nextInt() throws IOException {
return (int) nextLong();
}
int[] nextIntArray(int n) throws IOException {
int[] m = new int[n];
for (int i = 0; i < n; i++) {
m[i] = nextInt();
}
return m;
}
int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] a = new int[n][0];
for (int j = 0; j < n; j++) {
a[j] = nextIntArray(m);
}
return a;
}
long nextLong() throws IOException {
int c;
long x = 0;
boolean sign = true;
while ((c = nextChar()) <= 32) ;
if (c == '-') {
sign = false;
c = nextChar();
}
if (c == '+') {
c = nextChar();
}
while (c >= '0') {
x = x * 10 + (c - '0');
c = nextChar();
}
return sign ? x : -x;
}
long[] nextLongArray(int n) throws IOException {
long[] m = new long[n];
for (int i = 0; i < n; i++) {
m[i] = nextLong();
}
return m;
}
int nextChar() throws IOException {
if (i == k) {
k = in.read(buf, 0, bufSize);
i = 0;
}
return i >= k ? -1 : buf[i++];
}
String nextString() throws IOException {
if (end) {
return null;
}
str.setLength(0);
int c;
while ((c = nextChar()) <= 32 && c != -1) ;
if (c == -1) {
end = true;
return null;
}
while (c > 32) {
str.append((char) c);
c = nextChar();
}
return str.toString();
}
String nextLine() throws IOException {
if (end) {
return null;
}
str.setLength(0);
int c = nextChar();
while (c != '\n' && c != '\r' && c != -1) {
str.append((char) c);
c = nextChar();
}
if (c == -1) {
end = true;
if (str.length() == 0) {
return null;
}
}
if (c == '\r') {
nextChar();
}
return str.toString();
}
char[] nextCharArray() throws IOException {
return nextString().toCharArray();
}
char[][] nextCharMatrix(int n) throws IOException {
char[][] a = new char[n][0];
for (int i = 0; i < n; i++) {
a[i] = nextCharArray();
}
return a;
}
}
static class MyWriter {
final BufferedOutputStream out;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = 0;
final byte c[] = new byte[30];
static final String newLine = System.getProperty("line.separator");
MyWriter(OutputStream out) {
this.out = new BufferedOutputStream(out, bufSize);
}
void print(long x) throws IOException {
int j = 0;
if (i + 30 >= bufSize) {
flush();
}
if (x < 0) {
buf[i++] = (byte) ('-');
x = -x;
}
while (j == 0 || x != 0) {
c[j++] = (byte) (x % 10 + '0');
x /= 10;
}
while (j-- > 0)
buf[i++] = c[j];
}
void print(int[] m) throws IOException {
for (int a : m) {
print(a);
print(' ');
}
}
void print(long[] m) throws IOException {
for (long a : m) {
print(a);
print(' ');
}
}
void print(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
print(s.charAt(i));
}
}
void print(char x) throws IOException {
if (i == bufSize) {
flush();
}
buf[i++] = (byte) x;
}
void print(char[] m) throws IOException {
for (char c : m) {
print(c);
}
}
void println(String s) throws IOException {
print(s);
println();
}
void println() throws IOException {
print(newLine);
}
void flush() throws IOException {
out.write(buf, 0, i);
out.flush();
i = 0;
}
void close() throws IOException {
flush();
out.close();
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
//package cf584d12;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class A {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
int n = sc.nextInt();
Integer[] a = new Integer[n];
for(int i = 0; i < n; i++)
a[i] = sc.nextInt();
Arrays.sort(a);
boolean[] b = new boolean[n];
int ans = 0;
for(int i = 0; i < n; i++)
if(!b[i]) {
ans++;
for(int j = i + 1; j < n; j++)
if(a[j] % a[i] == 0)
b[j] = true;
}
out.println(ans);
out.close();
}
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static class MyScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() {
while (st == null || !st.hasMoreElements())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
import java.util.TreeSet;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Trung Pham
*/
public class A {
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner in = new Scanner();
PrintWriter out = new PrintWriter(System.out);
String val = in.next();
ArrayList<String> list = new ArrayList();
for(int i = 0; i < val.length() ; i++){
list.add(val.substring(i));
}
Collections.sort(list);
int result = 0;
for(int i = 1; i < list.size() ; i++){
String other = list.get(i - 1);
int temp = 0;
for(int j = 0; j < list.get(i).length() && j < other.length() ; j++){
if(other.charAt(j) == list.get(i).charAt(j)){
temp++;
}else{
break;
}
}
if(temp > result){
result = temp;
}
}
out.println(result);
out.close();
}
public static int dist(int x0, int y0, int x1, int y1) {
return (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);
}
public static boolean isRight(int a, int b, int c) {
if (a == 0 || b == 0 || c == 0) {
return false;
}
if (a == b + c) {
return true;
}
if (b == a + c) {
return true;
}
if (c == a + b) {
return true;
}
return false;
}
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static class FT {
int[] data;
FT(int n) {
data = new int[n];
}
void update(int index, int val) {
// System.out.println("UPDATE INDEX " + index);
while (index < data.length) {
data[index] += val;
index += index & (-index);
// System.out.println("NEXT " +index);
}
}
int get(int index) {
// System.out.println("GET INDEX " + index);
int result = 0;
while (index > 0) {
result += data[index];
index -= index & (-index);
// System.out.println("BACK " + index);
}
return result;
}
}
static int pow(int a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
int val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * val * a;
}
}
// static Point intersect(Point a, Point b, Point c) {
// double D = cross(a, b);
// if (D != 0) {
// return new Point(cross(c, b) / D, cross(a, c) / D);
// }
// return null;
// }
//
// static Point convert(Point a, double angle) {
// double x = a.x * cos(angle) - a.y * sin(angle);
// double y = a.x * sin(angle) + a.y * cos(angle);
// return new Point(x, y);
// }
static Point minus(Point a, Point b) {
return new Point(a.x - b.x, a.y - b.y);
}
static Point add(Point a, Point b) {
return new Point(a.x + b.x, a.y + b.y);
}
static double cross(Point a, Point b) {
return a.x * b.y - a.y * b.x;
}
static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point: " + x + " " + y;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
//System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
// br = new BufferedReader(new FileReader("input.txt"));
br = new BufferedReader(new InputStreamReader(System.in));
}
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();
}
}
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
//package jsr.codeforces;
import java.util.HashMap;
import java.util.Scanner;
public class AMatchLists {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
HashMap<String, Integer> map = new HashMap<>();
for(int i=0; i<N; i++){
String str = in.next();
if(map.get(str)==null){
map.put(str, 0);
}
map.put(str, map.get(str)+1);
}
HashMap<String, Integer> map2 = new HashMap<>();
for(int i=0; i<N; i++){
String str = in.next();
if(map.get(str)!=null){
if(map.get(str)==1)
map.remove(str);
else
map.put(str, map.get(str)-1);
}
else{
if(map2.get(str)==null){
map2.put(str, 0);
}
map2.put(str, map2.get(str)+1);
}
}
int[] count= {0};
map2.forEach((key, value)->{
count[0] += value;
});
System.out.println(count[0]);
//M, XS, XXS, XXXS, L, XL, XXl, XXXL
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import java.util.Map.Entry;
public class Main {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private PrintWriter pw;
private long mod = 998244353;
private StringBuilder ans_sb;
private int sqrt;
private void soln() {
int n = nextInt();
int d = nextInt();
int[] arr = nextIntArray(n);
int cnt = 2;
for(int i=0;i<n-1;i++) {
int a1 = arr[i];
int a2 = arr[i+1];
a1 += d;
a2 -= d;
if(a1 < a2) {
cnt+=2;
}else if(a1==a2)
cnt++;
}
pw.println(cnt);
}
private class Pair implements Comparable<Pair>{
int x,i;
public Pair(int a, int b) {
x = a;
i = b;
}
@Override
public int compareTo(
Pair o)
{
return this.x - o.x;
}
}
private int cc = 0;
private void dfs(int c, int p, LinkedList<Integer>[] tree, int[] t, int[] tin, int[] tout, int[] arr) {
//debug(c);
t[cc] = arr[c];
tin[c] = cc++;
Iterator<Integer> it = tree[c].listIterator();
while(it.hasNext()) {
int x = it.next();
if(x != p) {
dfs(x, c, tree,t,tin,tout,arr);
}
}
tout[c] = cc;
}
public class Segment
{
private Node[] tree;
private int[] lazy;
private int size;
private int n;
private int[] base;
private class Node
{
private int on;
private int off;
}
public Segment(int n, int[] arr)
{
this.base=arr;
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
size = 2 * (int) Math.pow(2, x) - 1;
tree = new Node[size];
lazy = new int[size];
this.n = n;
//this.set = set1;
build(0, 0, n - 1);
}
public void build(int id, int l, int r)
{
if (l == r)
{
tree[id] = new Node();
if(base[l] == 1)
tree[id].on++;
else
tree[id].off++;
return;
}
int mid = ((l + r)>>1);
build((id<<1)|1, l, mid);
build((id<<1)+2, mid + 1, r);
tree[id] = merge(tree[(id<<1)|1], tree[(id<<1)+2]);
//System.out.println(l+" "+r+" "+tree[id].l+" "+tree[id].r+" "+tree[id].ans);
}
public Node merge(Node n1, Node n2) {
Node ret = new Node();
if(n1 == null && n2 == null)
return null;
else if(n1 == null) {
ret.on = n2.on;
ret.off = n2.off;
}
else if(n2 == null) {
ret.on = n1.on;
ret.off = n1.off;
}
else {
ret.on = n1.on+n2.on;
ret.off = n2.off + n1.off;
}
return ret;
}
public int query(int l, int r)
{
Node ret = queryUtil(l, r, 0, 0, n - 1);
if(ret == null) {
return 0;
}
else
return ret.on;
}
private Node queryUtil(int x, int y, int id, int l, int r)
{
if (l > y || x > r)
return null;
if (x <= l && r <= y)
{
//shift(id,l,r);
return tree[id];
}
int mid = ((l + r)>>1);
shift(id,l,r);
Node q1 = queryUtil(x, y, (id<<1)|1, l, mid);
Node q2 = queryUtil(x, y, (id<<1)+2, mid + 1, r);
return merge(q1, q2);
}
public void update(int x, int y, int c) {
update1(x, y, c, 0, 0, n-1);
}
private void update1(int x, int y, int colour, int id, int l, int r)
{
//System.out.println(l+" "+r+" "+x);
if (x > r || y < l)
return;
if (x <= l && r <= y)
{
lazy[id]++;
// lazy[id] %= 2;
switchNode(tree[id]);
return;
}
int mid = ((l + r)>>1);
//shift(id);
if(y<=mid)
update1(x, y, colour, (id<<1)|1, l, mid);
else if(x>mid)
update1(x, y, colour, (id<<1)+2, mid + 1, r);
else {
update1(x, y, colour, (id<<1)|1, l, mid);
update1(x, y, colour, (id<<1)+2, mid + 1, r);
}
tree[id] = merge(tree[(id<<1)|1], tree[(id<<1)+2]);
}
private void shift(int id,int l, int r)
{
lazy[id] %= 2;
if(lazy[id] != 0) {
if(l != r) {
lazy[(id<<1)|1] += lazy[id];
lazy[(id<<1)+2] += lazy[id];
switchNode(tree[(id<<1)+2]);
switchNode(tree[(id<<1)|1]);
}
//switchNode(tree[(id<<1)+2]);
lazy[id] = 0;
}
}
private void switchNode(Node d) {
d.on ^= d.off;
d.off ^= d.on;
d.on ^= d.off;
}
}
private void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
private long pow(long a, long b, long c) {
if (b == 0)
return 1;
long p = pow(a, b / 2, c);
p = (p * p) % c;
return (b % 2 == 0) ? p : (a * p) % c;
}
private long gcd(long n, long l) {
if (l == 0)
return n;
return gcd(l, n % l);
}
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
@Override
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
//new Main().solve();
}
public StringBuilder solve() {
InputReader(System.in);
/*
* try { InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\in.txt"));
* } catch(FileNotFoundException e) {}
*/
pw = new PrintWriter(System.out);
// ans_sb = new StringBuilder();
soln();
pw.close();
// System.out.println(ans_sb);
return ans_sb;
}
public void InputReader(InputStream stream1) {
stream = stream1;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
private long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private void pArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private void pArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private char nextChar() {
int c = read();
while (isSpaceChar(c))
c = read();
char c1 = (char) c;
while (!isSpaceChar(c))
c = read();
return c1;
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class B {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
// int X1, Y1, X2, Y2;
// int X3, Y3, X4, Y4;
// {
// X1 = 1;
// Y1 = 2;
// X2 = 3;
// Y2 = 4;
//
// X3 = 5;
// Y3 = 1;
// X4 = 5;
// Y4 = 5;
// }
int ask(int x1, int y1, int x2, int y2) throws IOException {
out.println("? " + x1 + " " + y1 + " " + x2 + " " + y2);
out.flush();
return nextInt();
}
int inside(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
return inside(x1, x2, x3, x4) & inside(y1, y2, y3, y4);
}
int inside(int x1, int x2, int y1, int y2) {
return (x1 <= y1 && y2 <= x2) ? 1 : 0;
}
// int ask(int x1, int y1, int x2, int y2) throws IOException {
// return inside(x1, y1, x2, y2, X1, Y1, X2, Y2) + inside(x1, y1, x2, y2, X3, Y3, X4, Y4);
// }
int askFlipped(int x1, int y1, int x2, int y2) throws IOException {
return ask(y1, x1, y2, x2);
}
boolean check(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) throws IOException {
if (x1 > x2 || y1 > y2 || x3 > x4 || y3 > y4) {
return false;
}
if (Math.max(x1, x3) <= Math.min(x2, x4) && Math.max(y1, y3) <= Math.min(y2, y4)) {
return false;
}
return check(x1, y1, x2, y2) && check(x3, y3, x4, y4);
}
boolean check(int x1, int y1, int x2, int y2) throws IOException {
if (ask(x1, y1, x2, y2) != 1) {
return false;
}
if (x1 != x2) {
if (ask(x1 + 1, y1, x2, y2) != 0 || ask(x1, y1, x2 - 1, y2) != 0) {
return false;
}
}
if (y1 != y2) {
if (ask(x1, y1 + 1, x2, y2) != 0 || ask(x1, y1, x2, y2 - 1) != 0) {
return false;
}
}
return true;
}
void solve() throws IOException {
int n = nextInt();
int low = 0; // 0
int high = n; // >0
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = ask(1, 1, mid, n);
if (ret == 0) {
low = mid;
} else {
high = mid;
}
}
int minX2 = high;
low = 0; // <2
high = n; // 2
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = ask(1, 1, mid, n);
if (ret == 2) {
high = mid;
} else {
low = mid;
}
}
int maxX2 = high;
low = 1; // >0
high = n + 1; // 0
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = ask(mid, 1, n, n);
if (ret == 0) {
high = mid;
} else {
low = mid;
}
}
int maxX1 = low;
low = 1; // 2
high = n + 1; // <2
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = ask(mid, 1, n, n);
if (ret == 2) {
low = mid;
} else {
high = mid;
}
}
int minX1 = low;
// / NOW Y
low = 0; // 0
high = n; // >0
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = askFlipped(1, 1, mid, n);
if (ret == 0) {
low = mid;
} else {
high = mid;
}
}
int minY2 = high;
low = 0; // <2
high = n; // 2
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = askFlipped(1, 1, mid, n);
if (ret == 2) {
high = mid;
} else {
low = mid;
}
}
int maxY2 = high;
low = 1; // >0
high = n + 1; // 0
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = askFlipped(mid, 1, n, n);
if (ret == 0) {
high = mid;
} else {
low = mid;
}
}
int maxY1 = low;
low = 1; // 2
high = n + 1; // <2
while (high - low > 1) {
int mid = (low + high) >> 1;
int ret = askFlipped(mid, 1, n, n);
if (ret == 2) {
low = mid;
} else {
high = mid;
}
}
int minY1 = low;
int[] x1s = { minX1, maxX1 };
int[] x2s = { minX2, maxX2 };
int[] y1s = { minY1, maxY1 };
int[] y2s = { minY2, maxY2 };
for (int mask = 0; mask < 8; mask++) {
int x1 = x1s[0];
int x3 = x1s[1];
int x2 = x2s[get(mask, 0)];
int x4 = x2s[get(mask, 0) ^ 1];
int y1 = y1s[get(mask, 1)];
int y3 = y1s[get(mask, 1) ^ 1];
int y2 = y2s[get(mask, 2)];
int y4 = y2s[get(mask, 2) ^ 1];
if (check(x1, y1, x2, y2, x3, y3, x4, y4)) {
out.printf("! %d %d %d %d %d %d %d %d\n", x1, y1, x2, y2, x3, y3, x4, y4);
out.flush();
return;
}
}
}
int get(int mask, int i) {
return (mask >> i) & 1;
}
B() 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 B();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int N = r.nextInt();
System.out.println(N + " " + 0 + " " + 0);
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
//package round23;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
public class A {
private Scanner in;
private PrintWriter out;
// private String INPUT = add("a", 100);
private String INPUT = "";
public void solve()
{
String str = in.next();
int n = str.length();
for(int k = n - 1;k >= 1;k--){
HashSet<String> set = new HashSet<String>();
for(int i = 0;i < str.length() - k + 1;i++){
if(!set.add(str.substring(i, i + k))){
out.println(k);
return;
}
}
}
out.println(0);
}
public void run() throws Exception
{
in = INPUT.isEmpty() ? new Scanner(System.in) : new Scanner(new StringReader(INPUT));
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static String add(String str, int k)
{
StringBuilder mul = new StringBuilder(str);
StringBuilder ret = new StringBuilder();
for(int i = k;i > 0;i >>= 1){
if((i & 1) == 1)ret.append(mul);
mul.append(mul);
}
return ret.toString();
}
public static void main(String[] args) throws Exception
{
new A().run();
}
private int ni() { return Integer.parseInt(in.next()); }
private static void tr(Object... o) { System.out.println(o.length == 1 ? o[0] : Arrays.toString(o)); }
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class C {
static int ar[];
static HashMap<String, ArrayList<String>> map;
static int location = 0;
static StringBuilder sb;
static int N;
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int t = Integer.parseInt(br.readLine());
while(t --> 0) {
int n = Integer.parseInt(br.readLine());
ar = new int[n];
location = 0;
map = new HashMap<String, ArrayList<String>>();
sb = new StringBuilder();
N = n;
for(int i = 0; i < n; i++) {
ar[i] = Integer.parseInt(br.readLine());
}
int idx = 2;
location = 1;
sb.append("1\n");
while(location < n) {
if(ar[location] == 1) {
nl((idx-1)+".");
}else {
sb.append(idx+"\n");
idx++;
location++;
}
}
System.out.println(sb);
}
}
public static void nl(String l) {
int idx = 1;
//System.out.println(location + " " + l);
while(location < N) {
if(idx == ar[location]) {
sb.append(l + idx + "\n");
idx++;
location++;
}else if(ar[location] == 1) {
nl(l + (idx-1) + ".");
}else {
return;
}
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.Scanner;
public class Prob235A {
public static void main(String[] Args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
if (x < 3) {
if (x == 1)
System.out.println(1);
else
System.out.println(2);
} else {
long answer = x;
if (x % 2 == 1) {
answer *= x - 1;
answer *= x - 2;
} else if (x % 3 != 0) {
answer *= x - 1;
answer *= x - 3;
} else {
answer = x - 1;
answer *= x - 2;
answer *= x - 3;
}
System.out.println(answer);
}
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner cin = new Scanner(System.in);
String str;
int i,j,k;
int cnt = 0;
char [] strArray;
str = cin.next();
strArray = str.toCharArray();
for(i = 0; i < strArray.length; i ++)
for(j = i + 1; j < strArray.length; j ++)
{
for(k = 0; (((i + k) < strArray.length && (j + k) < strArray.length) && (strArray[i + k] == strArray[j + k])); k ++)
if(k + 1> cnt) cnt = k + 1;
}
System.out.println(cnt);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class B {
public static PrintStream out = System.out;
public static InputReader in = new InputReader(System.in);
static class Node implements Comparable<Node> {
int res;
Node(int pp) {
p = pp;
}
int p;
@Override
public int compareTo(Node n) {
return Integer.compare(p, n.p);
}
@Override
public boolean equals(Object o) {
return p == ((Node) o).p;
}
}
public static void main(String args[]) {
int N, a, b;
N = in.nextInt();
int[] label;
a = in.nextInt();
b = in.nextInt();
if (a < b) {
label = new int[] {0, 1};
} else {
int tmp = a;
a = b;
b = tmp;
label = new int[] {1, 0};
}
Node[] nodes = new Node[N];
for (int i = 0; i < N; i++) {
nodes[i] = new Node(in.nextInt());
}
TreeSet<Node> ts = new TreeSet<>();
for (int i = 0; i < N; i++) {
ts.add(nodes[i]);
}
while (!ts.isEmpty()) {
Node n = ts.first();
Node an = new Node(a - n.p);
Node bn = new Node(b - n.p);
SortedSet<Node> ats = ts.tailSet(an);
SortedSet<Node> bts = ts.tailSet(bn);
Node an2 = ats.isEmpty() ? null : ats.first();
Node bn2 = bts.isEmpty() ? null : bts.first();
Node n2 = null;
int l = 0;
if (bn2 != null && bn2.equals(bn)) {
n2 = bn2;
l = label[1];
} else if (an2 != null && an2.equals(an)) {
n2 = an2;
l = label[0];
} else {
NO();
}
if (!n.equals(n2)) {
ts.remove(n);
n.res = l;
}
ts.remove(n2);
n2.res = l;
}
out.println("YES");
for (int i = 0; i < nodes.length; i++) {
if (i != 0) out.print(" ");
out.print(nodes[i].res);
}
out.println();
}
static void NO() {
out.println("NO");
System.exit(0);
}
}
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 double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
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;
Parser in = new Parser(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Parser in, OutputWriter out) {
long a = in.nextLong();
long b = in.nextLong();
long cnt = 0;
while (a != 0 && b != 0) {
if (a > b) {
cnt += a / b;
a %= b;
}
else {
cnt += b / a;
b = b % a;
}
}
out.println(cnt);
}
}
class Parser
{
private BufferedReader din;
private StringTokenizer tokenizer;
public Parser(InputStream in)
{
din = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(din.readLine());
} catch (Exception e) {
throw new UnknownError();
}
}
return tokenizer.nextToken();
}
public long nextLong()
{
return Long.parseLong(next());
}
}
class OutputWriter extends PrintWriter {
public OutputWriter(Writer out) {
super(out);
}
public OutputWriter(OutputStream out) {
super(out);
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author madi
*/
public class CottageTown {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] in = sc.nextLine().split(" ");
int n = Integer.parseInt(in[0]);
int t = Integer.parseInt(in[1]);
int[] coor = new int[n];
int[] side = new int[n];
for (int i = 0; i < n; i++) {
in = sc.nextLine().split(" ");
coor[i] = Integer.parseInt(in[0]);
side[i] = Integer.parseInt(in[1]);
}
quickSort(coor, 0, n - 1, side);
int count = 2;
double dist;
for (int i = 0; i < n - 1; i++) {
dist = (coor[i + 1] - coor[i]) - (double)(side[i + 1] + side[i]) / 2.0;
if (dist > t) {
count += 2;
} else if (dist == t) {
count += 1;
}
}
System.out.println(count);
}
private static int partition(int[] arr, int left, int right, int[] temp) {
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
tmp = temp[i];
temp[i] = temp[j];
temp[j] = tmp;
i++;
j--;
}
}
return i;
}
private static void quickSort(int[] arr, int left, int right, int[] temp) {
int index = partition(arr, left, right, temp);
if (left < index - 1) {
quickSort(arr, left, index - 1, temp);
}
if (index < right) {
quickSort(arr, index, right, temp);
}
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int numTests = in.nextInt();
for (int test = 0; test < numTests; test++) {
int n = in.nextInt();
boolean can = false;
if (n % 2 == 0 && isSquare(n / 2)) {
can = true;
}
if (n % 4 == 0 && isSquare(n / 4)) {
can = true;
}
out.println(can ? "YES" : "NO");
}
}
private boolean isSquare(int n) {
int x = (int) Math.sqrt(n);
while (x * x > n) {
--x;
}
while (x * x < n) {
++x;
}
return x * x == n;
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.util.*;
public class HelloWorld{
public static void main(String []args){
final long MOD = 1000000007;
Scanner scan = new Scanner(System.in);
int now = 1;
int maxStatements = scan.nextInt();
long[] dp = new long[maxStatements + 1];
dp[now] = 1;
while(maxStatements > 0)
{
String add = scan.next();
if (add.equals("f"))
{
now++;
}
else
{
for (int k = 1; k <= now; k++)
{
dp[k] = ((dp[k] + dp[k-1]) % MOD);
}
}
maxStatements--;
}
System.out.println(dp[now]);
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author Haya
*/
public class CommentaryBoxes {
public static void main(String[] args) {
FastReader in = new FastReader();
long n = in.nextLong();
long m = in.nextLong();
long a = in.nextLong();
long b = in.nextLong();
long total = 0;
long val =(n%m);
if (n%m != 0){
long x = (val)*b;
long y = (m-val)*a;
total = Math.min(x, y);
}
System.out.println(Math.abs(total));
}
public 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 string = "";
try {
string = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return string;
}
}
}
|
linear
|
990_A. Commentary Boxes
|
CODEFORCES
|
import java.util.*;
public class temp {
public static void main(String str[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int arr[][] = new int[n][m];
int cross[][] = new int[n][m-1];
int up[][] = new int[n-1][m];
for(int i=0;i<n;i++){
for(int j=0;j<m-1;j++){
cross[i][j] = sc.nextInt();
}
}
for(int i=0;i<n-1;i++){
for(int j=0;j<m;j++){
up[i][j] = sc.nextInt();
}
}
int[][] fans = new int[n][m];
if (k % 2 != 0) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
fans[i][j] = -1;
}
}
}
else {
int[][][] ans = new int[(k/2)+1][n][m];
for (int l = 1; l <= k / 2; l++){
for (int i = 0; i < n ; i++) {
for (int j = 0; j < m; j++) {
int min = Integer.MAX_VALUE;
if(i>0){
min = Math.min(min, up[i-1][j] + ans[l-1][i-1][j]);
}
if(j>0){
min = Math.min(min, cross[i][j-1] + ans[l-1][i][j-1]);
}
if(i<n-1){
min = Math.min(min, up[i][j] + ans[l-1][i+1][j]);
}
if(j<m-1){
min = Math.min(min, cross[i][j] + ans[l-1][i][j+1]);
}
ans[l][i][j] = min;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
fans[i][j] = 2*ans[k/2][i][j];
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(fans[i][j]+" ");
}
System.out.println();
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
// StringBuilder uses java.lang
public class mC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder st = new StringBuilder();
int t = 1;
for (int test = 0; test < t; test++) {
int n = sc.nextInt();
int MOD = sc.nextInt();
long[] factorial = new long[1000];
long[] powerOfTwo = new long[1000];
factorial[0]=1;
powerOfTwo[0]=1;
for (int i=1;i<1000;i++) {
factorial[i]=i*factorial[i-1];
factorial[i] %= MOD;
powerOfTwo[i]=2*powerOfTwo[i-1];
if (powerOfTwo[i]>=MOD) {
powerOfTwo[i]-=MOD;
}
}
long[] oneOverFactorial = new long[500];
oneOverFactorial[0]=1;
oneOverFactorial[1]=1;
for (int i=2;i<450;i++) {
oneOverFactorial[i] = fastPow(factorial[i],MOD-2,MOD);
}
long dp[][] = new long[n+3][n+3]; // first value number of computers considered
// second value number of computers manually on
dp[1][1]=1;
for (int i=2;i<=n;i++) { // from left to right, over first i computers
dp[i][i]=powerOfTwo[i-1];
for (int j=1;j<i-1;j++) { // number of computers turned on manually
for (int k=1;k<=j;k++) {
// want to add dp[j][k]*factorial[k+(i-j-1)]*oneOverFactorial[k]*oneOverFactorial[i-j-1]*powerOfTwo[i-j-2]
long add = dp[j][k]*factorial[k+(i-j-1)];
add %= MOD;
add *= oneOverFactorial[k];
add %= MOD;
add *= oneOverFactorial[i-j-1];
add %= MOD;
add *= powerOfTwo[i-j-2];
add %= MOD;
dp[i][k+(i-j-1)]+=add;
dp[i][k+(i-j-1)]%=MOD;
}
}
}
long ans = 0;
for (int i=1;i<=n;i++) {
ans+=dp[n][i];
}
ans %= MOD;
System.out.println(ans);
}
//System.out.print(st.toString());
}
public static int goodLeft(int n, int[] p) { // i.e. ... 4 5 6
int begin = 0;
for (int i=0;i<n;i++) {
if (n-i==p[n-i-1]) {
begin++;
} else {
break;
}
}
return begin;
}
public static int goodRight(int n, int[] p) { // i.e. 6 5 4 ...
int end = 0;
for (int i=n-1;i>=0;i--) {
if (i==p[i]) {
end++;
} else {
break;
}
}
return end;
}
public static int findNthInArray(int[] arr,int val,int start,int o) {
if (o==0) {
return start-1;
} else if (arr[start] == val) {
return findNthInArray(arr,val,start+1,o-1);
} else {
return findNthInArray(arr,val,start+1,o);
}
}
public static ArrayList<Integer> dfs(int at,ArrayList<Integer> went,ArrayList<ArrayList<Integer>> connect) {
for (int i=0;i<connect.get(at).size();i++) {
if (!(went.contains(connect.get(at).get(i)))) {
went.add(connect.get(at).get(i));
went=dfs(connect.get(at).get(i),went,connect);
}
}
return went;
} public static int[] bfs (int at, int[] went, ArrayList<ArrayList<Integer>> queue, int numNodes, ArrayList<ArrayList<Integer>> connect) {
if (went[at]==0) {
went[at]=queue.get(numNodes).get(1);
for (int i=0;i<connect.get(at).size();i++) {
if (went[connect.get(at).get(i)]==0) {
ArrayList<Integer> temp = new ArrayList<>();
temp.add(connect.get(at).get(i));
temp.add(queue.get(numNodes).get(1)+1);
queue.add(temp);
}
}
}
if (queue.size()==numNodes+1) {
return went;
} else {
return bfs(queue.get(numNodes+1).get(0),went, queue, numNodes+1, connect);
}
}
public static long fastPow(long base,long exp,long mod) {
if (exp==0) {
return 1;
} else {
if (exp % 2 == 1) {
long z = fastPow(base,(exp-1)/2,mod);
return ((((z*base) % mod) * z) % mod);
} else {
long z = fastPow(base,exp/2,mod);
return ((z*z) % mod);
}
}
}
public static int fastPow(int base,long exp) {
if (exp==0) {
return 1;
} else {
if (exp % 2 == 1) {
int z = fastPow(base,(exp-1)/2);
return ((((z*base)) * z));
} else {
int z = fastPow(base,exp/2);
return ((z*z));
}
}
}
public static int firstLarger(long val,ArrayList<Long> ok,int left,int right) {
if (ok.get(right)<=val) {
return -1;
}
if (left==right) {
return left;
} else if (left+1==right) {
if (val<ok.get(left)) {
return left;
} else {
return right;
}
} else {
int mid = (left+right)/2;
if (ok.get(mid)>val) {
return firstLarger(val,ok,left,mid);
} else {
return firstLarger(val,ok,mid+1,right);
}
}
}
public static int binSearchArr(long val,ArrayList<Integer> ok,long[] arr,int left,int right) {
if (arr[ok.get(right)]<=val) {
return -1;
}
if (left==right) {
return left;
} else if (left+1==right) {
if (val<arr[ok.get(left)]) {
return left;
} else {
return right;
}
} else {
int mid = (left+right)/2;
if (arr[ok.get(mid)]>val) {
return binSearchArr(val,ok,arr,left,mid);
} else {
return binSearchArr(val,ok,arr,mid+1,right);
}
}
}
public static long gcd(long a, long b) {
if (b>a) {
return gcd(b,a);
}
if (b==0) {
return a;
}
if (a%b==0) {
return b;
} else {
return gcd(b,a%b);
}
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.util.Scanner;
public class J472A {
private static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int a = scan.nextInt();
if(a % 2 == 0) {
System.out.println(4 + " " + (a - 4));//ż���4
} else {
System.out.println(9 + " " + (a - 9));//������
}
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.lang.*;
public class file{
public static void main(String []args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
while(n-->0)
{
int a=sc.nextInt();
int b=sc.nextInt();
int ans=f(a,b);
System.out.println(ans);
}
}
public static int f(int a,int b)
{
if(a==0||b==0)
return 0;
if(a>b)
{
return a/b + f(b,a%b);
}
else
return b/a + f(a,b%a);
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class n2{
public static void main(String[] args) throws Exception{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(in.readLine());
int[] S=new int[4];
int[] L=new int[4];
int m=0;
for(int i=0;i<n;i++){
String s=in.readLine();
if(s.charAt(s.length()-1)=='L'){
L[s.length()-1]++;
}
if(s.charAt(s.length()-1)=='S'){
S[s.length()-1]++;
}
if(s.charAt(s.length()-1)=='M'){
m++;
}
}
for(int i=0;i<n;i++){
String s=in.readLine();
if(s.charAt(s.length()-1)=='L'){
L[s.length()-1]--;
}
if(s.charAt(s.length()-1)=='S'){
S[s.length()-1]--;
}
if(s.charAt(s.length()-1)=='M'){
m--;
}
}
int count=0;
for(int i=0;i<=3;i++){
if(S[i]>0){
count+=S[i];
}
if(L[i]>0){
count+=L[i];
}
}
if(m>0){
count+=m;
}
System.out.println(count);
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
//package com.krakn.CF.D1159;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, k;
n = sc.nextInt();
k = sc.nextInt();
int a = (n - k) / 2;
StringBuilder s = new StringBuilder();
int i;
while (s.length() < n) {
i = 0;
while (i < a && s.length() < n) {
s.append("0");
i++;
}
if (s.length() < n) s.append("1");
}
System.out.println(s);
}
}
|
linear
|
1159_D. The minimal unique substring
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class DigitSeq {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader sc = new FastReader();
OutputStream outputstream = System.out;
PrintWriter out = new PrintWriter(outputstream);
long n = sc.nextLong();
long[] arr = new long[14];
for(int i = 1; i <= 13; i++){
arr[i] = (long)Math.pow(10, i)-(long)Math.pow(10, i-1);
}
long total = 0;
/*for(int i = 1; i <= 13; i++) out.print(arr[i] + " ");
out.println();*/
for(int i = 1; i <= 13; i++){
if(total+(long)i*arr[i]>=n){
long ans = n-total;
long rest = ans;
//System.out.println(rest);
if(ans%i!=0){
ans /= i;
ans++;
} else {
ans /= i;
}
ans += (long)Math.pow(10, i-1)-1;
String str = Long.toString(ans);
int ind = (rest%i==0) ? i-1 : (int)(rest%i)-1;
//System.out.println(ind);
out.println(str.charAt(ind));
break;
}
total = total+(long)i*arr[i];
//System.out.println(total);
}
out.close();
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* Created by James on 1/29/2015.
*/
public class Driver {
private static int [][] distances, parents;
private static int [] distance, parent;
private static String [][] longNames;
private static String [] shortNames, answers;
private static int N;
public static void main(String [] args) throws IOException {
BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));
String [] pieces = scanner.readLine().split("\\s+");
//totally had to steal the vast majority of this from http://codeforces.com/contest/8/submission/9745593
Point origin = new Point(Integer.parseInt(pieces[0]), Integer.parseInt(pieces[1]));
N = Integer.parseInt(scanner.readLine());
Point [] points = new Point[N + 1];
distances = new int[N + 1][N + 1];
parents = new int[N + 1][N + 1];
longNames = new String[N][N];
shortNames = new String[N];
for (int i = 0; i < N; ++i) {
pieces = scanner.readLine().split("\\s+");
points[i] = new Point(Integer.parseInt(pieces[0]), Integer.parseInt(pieces[1]));
}
points[N] = origin;
for (int i = 0; i <= N; ++i) {
if (i < N) {
shortNames[i] = (i + 1) + " ";
}
for (int j = 0; j <= N; ++j) {
if (i < N && j < N) {
longNames[i][j] = (i + 1) + " " + (j + 1) + " ";
}
distances[i][j] = 2 * points[i].distance(points[j]);
parents[i][j] = points[i].distance(points[N]) + points[i].distance(points[j]) + points[j].distance(points[N]);
}
}
distance = new int[1 << N];
parent = new int[1 << N];
answers = new String[1 << N];
Arrays.fill(distance, -1);
distance[0] = 0;
int result = rec((1 << N) - 1);
StringBuilder answer = new StringBuilder();
for (int i = distance.length - 1; parent[i] != i; i = parent[i]) {
answer.append("0 ");
answer.append(answers[i]);
}
answer.append("0");
System.out.println(result);
System.out.println(answer.toString());
}
private static int rec(int mask) {
if (distance[mask] != -1) {
return distance[mask];
}
int min = 0;
while (((1 << min) & mask) == 0) {
min++;
}
int newMask = mask & (~(1 << min));
distance[mask] = rec(newMask) + distances[min][N];
parent[mask] = newMask;
answers[mask] = shortNames[min];
for (int i = min + 1; i < N; i++) {
if (((1 << i) & mask) > 0) {
newMask = mask & (~(1 << i)) & (~(1 << min));
int temp = rec(newMask) + parents[i][min];
if (temp< distance[mask]) {
distance[mask] = temp;
parent[mask] = newMask;
answers[mask] = longNames[min][i];
}
}
}
return distance[mask];
}
private static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int distance(Point p) {
return (int)(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2));
}
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
String s = sc.next();
StringBuilder ans = new StringBuilder();
int count = 0;
int open = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
ans.append("(");
count++;
open++;
} else {
ans.append(")");
open--;
}
if (count == k / 2) {
break;
}
}
while (open > 0) {
ans.append(")");
open--;
}
System.out.println(ans.toString());
}
}
|
linear
|
1023_C. Bracket Subsequence
|
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 Egor Kulikov (egor@egork.net)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
int stage;
int n;
OutputWriter out;
InputReader in;
void query(int end) {
switch (stage) {
case 0:
out.printLine('?', 1, 1, end, n);
break;
case 1:
out.printLine('?', 1, 1, n, end);
break;
case 2:
out.printLine('?', n + 1 - end, 1, n, n);
break;
case 3:
out.printLine('?', 1, n + 1 - end, n, n);
break;
}
out.flush();
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
this.out = out = new OutputWriter(System.out);
this.in = in = new InputReader(System.in);
n = in.readInt();
int[] endx = new int[2];
int[] endy = new int[2];
int[] stx = new int[2];
int[] sty = new int[2];
find(endx);
stage++;
find(endy);
stage++;
find(stx);
for (int i = 0; i < 2; i++) {
stx[i] = n + 1 - stx[i];
}
stage++;
find(sty);
for (int i = 0; i < 2; i++) {
sty[i] = n + 1 - sty[i];
}
for (int i = 0; i < 8; i++) {
if (stx[i & 1] > endx[i >> 2 & 1] || sty[i >> 1 & 1] > endy[0]) {
continue;
}
if (stx[1 - (i & 1)] > endx[1 - (i >> 2 & 1)] || sty[1 - (i >> 1 & 1)] > endy[1]) {
continue;
}
out.printLine('?', stx[i & 1], sty[i >> 1 & 1], endx[i >> 2 & 1], endy[0]);
out.flush();
if (in.readInt() == 0) {
continue;
}
out.printLine('?', stx[1 - (i & 1)], sty[1 - (i >> 1 & 1)], endx[1 - (i >> 2 & 1)], endy[1]);
out.flush();
if (in.readInt() != 0) {
out.printLine("!", stx[i & 1], sty[i >> 1 & 1], endx[i >> 2 & 1], endy[0], stx[1 - (i & 1)],
sty[1 - (i >> 1 & 1)], endx[1 - (i >> 2 & 1)], endy[1]);
out.flush();
return;
}
}
}
private void find(int[] endx) {
int left = 1;
int right = n;
while (left < right) {
int middle = (left + right) >> 1;
query(middle);
if (in.readInt() == 2) {
right = middle;
} else {
left = middle + 1;
}
}
endx[0] = left;
left = 0;
right--;
while (left < right) {
int middle = (left + right + 1) >> 1;
query(middle);
if (in.readInt() == 0) {
left = middle;
} else {
right = middle - 1;
}
}
endx[1] = left + 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();
}
public void flush() {
writer.flush();
}
}
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);
}
}
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
/**
* @author: Mehul Raheja
*/
import java.util.*;
import java.io.*;
public class p3{
/*
Runtime = O()
*/
static int N, M, K;
static String s;
static StringTokenizer st;
static int[] d;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int R = Integer.parseInt(st.nextToken());
double[] x = new double[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
x[i] = Double.parseDouble(st.nextToken());
}
double[] y = new double[N];
for (int i = 0; i < N; i++) {
// int found = -1;
double maxy = R;
for (int j = i-1; j >= 0; j--) {
if(Math.abs(x[j] - x[i]) <= 2 * R){
maxy = Math.max(y[j] + inc(x[j] - x[i],R), maxy);
}
}
y[i] = maxy;
}
for (int i = 0; i < y.length-1; i++) {
System.out.print(y[i] + " ");
}
System.out.println(y[y.length-1]);
// System.out.println(Arrays.toString(y));
}
public static double inc(double x, double R){
return Math.sqrt((4*R*R)-(x*x));
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class C{
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver();
solver.solve(in, out);
out.close();
}
static class Solver{
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
String s = in.next();
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < n; ++ i) {
map.put(s.charAt(i), 0);
}
int l = 0, r = 0, cnt = 0, ans = n;
char c;
while (l < n) {
while (r < n && cnt < map.size()) {
c = s.charAt(r);
map.put(c, map.get(c) + 1);
if (map.get(c) == 1) ++cnt;
++r;
}
if (cnt == map.size() && r-l < ans)
ans = r-l;
c = s.charAt(l);
map.put(c, map.get(c)-1);
if (map.get(c) == 0) --cnt;
++l;
}
out.println(ans);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader (InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (tokenizer == null || ! tokenizer.hasMoreTokens()) {
try{
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static ArrayList<BigInteger> bs = new ArrayList<>();
static void getBs(int n, BigInteger k) {
BigInteger four = BigInteger.valueOf(4);
BigInteger tmp4 = BigInteger.valueOf(1);
BigInteger sum = BigInteger.ZERO;
for (int i = 1; i <= n; i++) {
sum = sum.add(tmp4);
bs.add(sum);
if (sum.compareTo(k) >= 0) break;
tmp4 = tmp4.multiply(four);
}
}
static int ss(int n, BigInteger k) {
bs = new ArrayList<>();
BigInteger two = BigInteger.valueOf(2);
BigInteger s1;
BigInteger ts = BigInteger.ZERO;
getBs(n - 1, k);
int idx = bs.size() - 1;
BigInteger tx = BigInteger.valueOf(-1);
int ans = -1;
for (int i = 1; i <= n; i++) {
two = two.shiftLeft(1);
s1 = two.add(BigInteger.valueOf(-i - 2));
if (idx >= 0) {
tx = tx.add(BigInteger.ONE).multiply(BigInteger.valueOf(2)).add(BigInteger.ONE);
ts = ts.add(tx.multiply(bs.get(idx--)));
}
if (k.compareTo(s1) >= 0) {
if (k.subtract(s1).compareTo(ts) <= 0) {
ans = n - i;
break;
}
}
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T-- > 0) {
int n = sc.nextInt();
BigInteger k = sc.nextBigInteger();
int ans = ss(n, k);
if (ans == -1) {
System.out.println("NO");
} else {
System.out.println("YES " + ans);
}
}
}
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solve4 {
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
int x= sc.nextInt();
int y= sc.nextInt();
int z= sc.nextInt();
int t1= sc.nextInt();
int t2= sc.nextInt();
int t3= sc.nextInt();
if(Math.abs(x-y)*t1 < (Math.abs(x-z)+Math.abs(x-y))*t2+3*t3 ) System.out.println("NO");
else System.out.println("YES");
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException {
if (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 String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException ex) {
}
return s;
}
}
}
|
constant
|
1054_A. Elevator or Stairs?
|
CODEFORCES
|
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
Scanner read = new Scanner(new FileInputStream(new File("input.txt")));
PrintWriter out = new PrintWriter(new File("output.txt"));
int n = read.nextInt(), m = read.nextInt(), k = read.nextInt(), tree[][] = new int[n][m], a[] = new int[k],
b[] = new int[k], x = 0, y = 0, max = -1, d = 0;
for (int i = 0; i < k; i++) {
a[i] = read.nextInt() - 1;
b[i] = read.nextInt() - 1;
tree[a[i]][b[i]] = 0;
}
for(int i = 0; i < n; i++){
Arrays.fill(tree[i], Integer.MAX_VALUE);
}
for (int o = 0; o < k; o++) {
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
d = Math.abs(a[o] - i) + Math.abs(b[o] - j);
if(d < tree[i][j])
tree[i][j] = d;
}
}
}
for(int i = 0; i<n; i++){
for(int j = 0; j < m ; j ++){
if(tree[i][j] > max){
max= tree[i][j];
x= i;
y = j;
}
}
}
out.println(x + 1 + " " + (y + 1));
out.close();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
/*Author: Satyajeet Singh, Delhi Technological University*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.*;
public class Main{
/*********************************************Constants******************************************/
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static long mod=(long)1e9+7;
static long mod1=998244353;
static boolean sieve[];
static ArrayList<Integer> primes;
static long factorial[],invFactorial[];
static HashSet<Pair> graph[];
static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
/****************************************Solutions Begins***************************************/
static int n,T,input[],type[];
static long dp[][];
static long dfs(int mask,int t){
if(dp[mask][t]!=-1){
return dp[mask][t];
}
int s=0;
for(int i=0;i<n;i++){
if((mask&(1<<i))!=0){
s+=input[i];
}
}
if(s>T){
return 0;
}
if(s==T){
dp[mask][t]=1;
return dp[mask][t];
}
long ans=0;
for(int i=0;i<n;i++){
if((mask&(1<<i))==0&&type[i]!=t){
ans=(ans+dfs(mask|(1<<i),type[i]))%mod;
}
}
dp[mask][t]=ans;
return dp[mask][t];
}
public static void main (String[] args) throws Exception {
String st[]=nl();
n=pi(st[0]);
T=pi(st[1]);
input=new int[n];
type=new int[n];
for(int i=0;i<n;i++){
st=nl();
input[i]=pi(st[0]);
type[i]=pi(st[1]);
}
dp=new long[1<<n][4];
for(long arr[]:dp)
Arrays.fill(arr,-1);
long ans=dfs(0,0);
// debug(dp);
out.println(ans);
/****************************************Solutions Ends**************************************************/
out.flush();
out.close();
}
/****************************************Template Begins************************************************/
static String[] nl() throws Exception{
return br.readLine().split(" ");
}
static String[] nls() throws Exception{
return br.readLine().split("");
}
static int pi(String str) {
return Integer.parseInt(str);
}
static long pl(String str){
return Long.parseLong(str);
}
static double pd(String str){
return Double.parseDouble(str);
}
/***************************************Precision Printing**********************************************/
static void printPrecision(double d){
DecimalFormat ft = new DecimalFormat("0.00000000000000000");
out.println(ft.format(d));
}
/**************************************Bit Manipulation**************************************************/
static void printMask(long mask){
System.out.println(Long.toBinaryString(mask));
}
static int countBit(int mask){
int ans=0;
while(mask!=0){
if(mask%2==1){
ans++;
}
mask/=2;
}
return ans;
}
/******************************************Graph*********************************************************/
static void Makegraph(int n){
graph=new HashSet[n];
for(int i=0;i<n;i++){
graph[i]=new HashSet<>();
}
}
static void addEdge(int a,int b){
graph[a].add(new Pair(b,1));
}
static void addEdge(int a,int b,int c){
graph[a].add(new Pair(b,c));
}
/*********************************************PAIR********************************************************/
static class PairComp implements Comparator<Pair>{
public int compare(Pair p1,Pair p2){
return ((p1.u+p1.v)-(p2.u+p2.v));
}
}
static class Pair implements Comparable<Pair> {
int u;
int v;
int index=-1;
public Pair(int u, int v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/******************************************Long Pair*************************************************/
static class PairCompL implements Comparator<Pairl>{
public int compare(Pairl p1,Pairl p2){
if((p1.u+2*p1.v)-(p2.u+2*p2.v)<0){
return -1;
}
else if((p1.u+2*p1.v)-(p2.u+2*p2.v)>0){
return 1;
}
else{
return 0;
}
}
}
static class Pairl implements Comparable<Pairl> {
long u;
long v;
int index=-1;
public Pairl(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pairl other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/*****************************************DEBUG***********************************************************/
public static void debug(Object... o) {
if(!oj)
System.out.println(Arrays.deepToString(o));
}
/************************************MODULAR EXPONENTIATION***********************************************/
static long modulo(long a,long b,long c) {
long x=1;
long y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
/********************************************GCD**********************************************************/
static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
/******************************************SIEVE**********************************************************/
static void sieveMake(int n){
sieve=new boolean[n];
Arrays.fill(sieve,true);
sieve[0]=false;
sieve[1]=false;
for(int i=2;i*i<n;i++){
if(sieve[i]){
for(int j=i*i;j<n;j+=i){
sieve[j]=false;
}
}
}
primes=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(sieve[i]){
primes.add(i);
}
}
}
/********************************************End***********************************************************/
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.util.*;
public class A
{
public static void main(String args[])
{
boolean[] b = new boolean[11000];
Arrays.fill(b, true);
b[0] = b[1] = false;
for(int i=2;i < b.length;i++)
{
if(!b[i])
continue;
for(int j=2;i*j<b.length;j++)
b[i*j] = false;
}
int[] p = new int[11000];
int pn = 0;
for(int i=0;i < b.length;i++)
{
if(b[i])
p[pn++] = i;
}
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
int rtn = 0;
for(int j=0;p[j] <= n;j++)
{
//Try to make sum
for(int h=0;h <= j;h++)
{
if(p[h] + p[h+1] + 1 == p[j])
{
rtn++;
break;
}
}
}
System.out.println(rtn >= k ? "YES" : "NO");
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
/*
* Author: Nikhil Garg
* Date: 2010-12-05
*
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class javatemp
{
static String map(int a)
{
if( a == 0) return "S";
else if ( a == 1 ) return "M";
else if ( a == 2 ) return "L";
else if ( a == 3 ) return "XL";
else if ( a == 4 ) return "XXL";
return "";
}
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
int ans = 1000;
in.readLine();
String s = in.readLine();
int H = 0;
for(int i =0; i < s.length(); i++)
if( s.charAt(i) == 'H') H++;
for(int i = 0; i < s.length(); i++)
{
int count = 0;
for(int j = 0; j < H; j++)
if( s.charAt( (i +j) % s.length()) =='T') count ++;
ans = Math.min ( ans, count);
}
System.out.println(ans);
}
static void debug(Object...os)
{
System.out.println(Arrays.deepToString(os));
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Lokesh Khandelwal
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n=in.nextInt(),m=in.nextInt(),k=in.nextInt();
int ans=-1;
int i;
int a[]=new int[n];
for(i=0;i<n;i++)
a[i]=in.nextInt();
Arrays.sort(a);
int p=k,c=0;
for(i=n-1;i>=0;i--)
{
if(p>=m)
break;
p+=a[i]-1;
c++;
}
if(p>=m)
out.printLine(c);
else out.printLine(-1);
}
}
class InputReader
{
BufferedReader in;
StringTokenizer tokenizer=null;
public InputReader(InputStream inputStream)
{
in=new BufferedReader(new InputStreamReader(inputStream));
}
public String next()
{
try{
while (tokenizer==null||!tokenizer.hasMoreTokens())
{
tokenizer=new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
catch (IOException e)
{
return null;
}
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.io.*;
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 sx = in.nextInt();
int sy = in.nextInt();
int n = in.nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int[] dp = new int[1 << n];
int[] p = new int[1 << n];
int inf = 1000000000;
Arrays.fill(dp, inf);
dp[0] = 0;
for (int mask = 0; mask < (1 << n) - 1; mask ++) {
int k = -1;
if (dp[mask] == inf)
continue;
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) == 0) {
k = i;
break;
}
}
for (int i = k; i < n; i++) {
if ((mask & (1 << i)) == 0) {
int val = dp[mask] + dist(sx, sy, x[i], y[i]) + dist(sx, sy, x[k], y[k]) + dist(x[i], y[i], x[k], y[k]);
if (val < dp[mask | (1 << i) | (1 << k)]) {
dp[mask | (1 << i) | (1 << k)] = val;
p[mask | (1 << i) | (1 << k)] = mask;
}
}
}
}
out.println(dp[(1 << n) - 1]);
int cur = (1 << n) - 1;
out.print(0+" ");
while (cur != 0) {
int prev = p[cur];
for (int i = 0; i < n; i++) {
if (((cur & (1 << i)) ^ (prev & (1 << i))) != 0)
out.print(i+1+" ");
}
out.print(0+" ");
cur = prev;
}
out.flush();
out.close();
}
int dist(int x1, int y1, int x2, int y2) {
return (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);
}
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
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CoveredPointsCount {
//UPSOLVE
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
long[] myArray = new long[2 * n];
for (int i = 0; i < n; i++) {
StringTokenizer st1 = new StringTokenizer(br.readLine());
myArray[2 * i] = Long.parseLong(st1.nextToken()) * 2;
myArray[2 * i + 1] = Long.parseLong(st1.nextToken()) * 2 + 1;
}
Arrays.sort(myArray);
long[] ans = new long[n + 1];
int cnt = 0;
for (int i = 0; i < 2 * n - 1; i++) {
if (myArray[i] % 2 == 0) cnt++; else cnt--;
ans[cnt] += (myArray[i + 1] + 1) / 2 - (myArray[i] + 1) / 2;
}
StringBuilder answer = new StringBuilder();
for (int i = 1; i < n + 1; i++) {
answer.append(ans[i]);
answer.append(" ");
}
System.out.println(answer);
}
}
|
nlogn
|
1000_C. Covered Points Count
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class ATestingRound5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
while(T --> 0) {
int a = in.nextInt();
int b = in.nextInt();
int count = 0;
int[] arr = {a, b};
Arrays.sort(arr);
while(arr[0] != 0) {
count += arr[1] / arr[0];
arr[1] = arr[1] % arr[0];
Arrays.sort(arr);
}
System.out.println(count);
}
in.close();
}
}
/*
2
4 17
7 987654321
outputCopy
8
141093479
*/
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class F1141 {
private static class Interval {
public int l;
public int r;
public Interval(int l,int r) {
this.l = l;
this.r = r;
}
}
public static void main(String[] args) throws IOException {
// BufferedReader br = new BufferedReader(new FileReader("F:/books/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int n = Integer.parseInt(s);
long[] a = new long[n];
String[] as = br.readLine().split(" ");
for(int i=0;i<n;i++) {
a[i] = Long.parseLong(as[i]);
}
StringBuffer sb = solve(a,n);
System.out.println(sb.toString());
}
private static StringBuffer solve(long[] a, int n) {
StringBuffer ret = new StringBuffer("");
Map<Long,List<Interval>> mp = new HashMap<Long,List<Interval>>();
long max = 0,maxId = -1;
for(int i=n-1;i>=0;i--) {
long s=0;
long prev = 1;
for(int j=i;j<n;j++) {
s+=a[j];
// System.out.println(i+","+j);
Interval inter = new Interval(i,j);
// if(prev==1 || prev==-1) {
List<Interval> ints = mp.get(s);
if(ints==null) ints = new ArrayList<Interval>();
if(ints.size()==0 || ints.get(0).l>j) {
ints.add(0,inter);
}
if(ints.size()>max) {
max = ints.size();
maxId = s;
}
mp.put(s, ints);
// }
if(j<n-1) prev = a[j+1]-a[j];
}
}
List<Interval> l = mp.get(maxId);
ret.append(l.size()+ "\n");
for(Interval inter : l) {
ret.append((inter.l+1) + " " + (inter.r+1) + "\n");
}
return ret;
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
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 Rustam Musin (t.me/musin_acm)
*/
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);
DOlyaIMagicheskiiKvadrat solver = new DOlyaIMagicheskiiKvadrat();
solver.solve(1, in, out);
out.close();
}
static class DOlyaIMagicheskiiKvadrat {
long inf = (long) 1e18 + 1;
long[] maxLen;
public void solve(int testNumber, InputReader in, OutputWriter out) {
maxLen = new long[100];
maxLen[1] = 0;
for (int i = 1; i < maxLen.length; i++) {
maxLen[i] = Math.min(inf, maxLen[i - 1] * 4 + 1);
}
if (false) {
for (int n = 1; n <= 3; n++) {
for (int k = 1; k <= maxSplitCount(n) + 20; k++) {
out.print(n + " " + k + " ");
int res = solve(n, k);
if (res == -1) {
out.printLine("NO");
} else {
out.printLine("YES " + res);
}
}
}
return;
}
int q = in.readInt();
while (q-- > 0) {
int n = in.readInt();
long k = in.readLong();
int res = solve(n, k);
if (res == -1) {
out.printLine("NO");
continue;
}
out.printLine("YES " + res);
}
}
long maxSplitCount(int n) {
if (n >= maxLen.length) {
return inf;
}
return maxLen[n];
}
int solve(int n, long k) {
if (maxSplitCount(n) < k) {
return -1;
}
int at = 0;
while (maxSplitCount(at + 1) <= k) {
at++;
}
int curSideLog = n - at;
k -= maxSplitCount(at);
double sideLen = Math.pow(2, n - curSideLog);
double pathLen = sideLen * 2 - 1;
if (curSideLog > 0 && pathLen <= k) {
return curSideLog - 1;
}
double area = sideLen * sideLen;
double otherArea = area - pathLen;
if (otherArea * (double) maxSplitCount(curSideLog) >= k) {
return curSideLog;
}
return -1;
}
}
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 long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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();
}
}
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
//package round599;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[][] a = new int[n][];
Map<Long, Long> ci = new HashMap<>();
long[] sums = new long[n];
for(int i = 0;i < n;i++){
int K = ni();
a[i] = na(K);
for(int j = 0;j < K;j++){
ci.put((long)a[i][j], (long)i<<32|j);
sums[i] += a[i][j];
}
}
long S = 0;
for(long v : sums){
S += v;
}
if(S % n != 0){
out.println("No");
return;
}
S /= n;
int[] offsets = new int[n+1];
for(int i = 0;i < n;i++){
offsets[i+1] = offsets[i] + a[i].length;
}
int m = offsets[n];
int[] f = new int[m];
Arrays.fill(f, -1);
for(int i = 0;i < n;i++){
for(int j = 0;j < a[i].length;j++){
long T = a[i][j] + S - sums[i];
if(ci.containsKey(T)){
long code = ci.get(T);
int from = offsets[i] + j;
int to = offsets[(int)(code>>>32)] + (int)code;
if(from != to && i == (int)(code>>>32))continue;
f[from] = to;
}
}
}
int[][] cs = getCycles(f);
int[][] zcs = new int[1<<n][];
for(int[] c : cs){
int ptn = 0;
for(int k : c){
int ind = Arrays.binarySearch(offsets, k);
if(ind < 0)ind = -ind-2;
ptn |= 1<<ind;
}
if(Integer.bitCount(ptn) != c.length)continue;
zcs[ptn] = c;
}
boolean[] dp = new boolean[1<<n];
dp[0] = true;
for(int i = 1;i < 1<<n;i++){
if(zcs[i] != null){
int mask = (1<<n)-1^i;
for(int j = mask;j >= 0;j--){ j &= mask;
dp[i|j] |= dp[j];
} // include j=0
}
}
if(dp[(1<<n)-1]){
int[] vals = new int[n];
int[] tos = new int[n];
int cur = (1<<n)-1;
inner:
while(cur > 0){
for(int k = cur;k >= 0;k--){
k &= cur;
if(dp[cur^k] && zcs[k] != null){
for(int l = 0;l < zcs[k].length;l++){
int nl = (l+zcs[k].length-1) % zcs[k].length;
int fclus = Arrays.binarySearch(offsets, zcs[k][l]);
int tclus = Arrays.binarySearch(offsets, zcs[k][nl]);
if(fclus < 0)fclus = -fclus-2;
if(tclus < 0)tclus = -tclus-2;
int val = a[fclus][zcs[k][l]-offsets[fclus]];
vals[fclus] = val;
tos[fclus] = tclus;
}
cur ^= k;
continue inner;
}
}
}
out.println("Yes");
for(int i = 0;i < n;i++){
out.println(vals[i] + " " + (tos[i]+1));
}
// for(int i = 0;i < n;i++){
// sums[i] -= vals[i];
// sums[tos[i]] += vals[i];
// }
//
// for(int i = 0;i < n;i++){
// assert sums[i] == S;
// }
}else{
out.println("No");
}
}
int[][] getCycles(int[] f)
{
int n = f.length;
int[][] ret = new int[n][];
boolean[] ved = new boolean[n];
int[] touched = new int[n];
Arrays.fill(touched, -1);
int[] path = new int[n];
int q = 0;
outer:
for(int i = 0;i < n;i++){
int p = 0;
for(int j = i;j != -1;j = f[j]){
if(touched[j] != -1){
ret[q++] = Arrays.copyOfRange(path, touched[j], p);
break;
}
if(ved[j])break;
touched[j] = p;
path[p++] = j;
ved[j] = true;
}
for(int k = 0;k < p;k++){
touched[path[k]] = -1;
}
}
return Arrays.copyOf(ret, q);
}
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)); }
}
|
np
|
1242_C. Sum Balance
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class A implements Runnable {
final boolean LOCAL = System.getProperty("ONLINE_JUDGE") == null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
public static void main(String[] args) {
new Thread(null, new A(), "", 256*1024*1024).start();
}
public void run() {
try {
long t1 = 0, t2 = 0, m1 = 0, m2 = 0;
if (LOCAL) {
t1 = System.currentTimeMillis();
m1 = Runtime.getRuntime().freeMemory();
}
Locale.setDefault(Locale.US);
if (LOCAL) {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
tok = new StringTokenizer("");
solve();
in.close();
out.close();
if (LOCAL) {
t2 = System.currentTimeMillis();
m2 = Runtime.getRuntime().freeMemory();
System.err.println("Time = " + (t2 - t1) + " ms.");
System.err.println("Memory = " + ((m1 - m2) / 1024) + " KB.");
}
} catch (Throwable e) {
e.printStackTrace(System.err);
throw new RuntimeException();
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String line = in.readLine();
if (line == null) return null;
tok = new StringTokenizer(line);
}
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());
}
static class Mergesort {
private Mergesort() {}
public static void sort(int[] a) {
mergesort(a, 0, a.length - 1);
}
public static void sort(long[] a) {
mergesort(a, 0, a.length - 1);
}
public static void sort(double[] a) {
mergesort(a, 0, a.length - 1);
}
private static final int MAGIC_VALUE = 42;
private static void mergesort(int[] a, int leftIndex, int rightIndex) {
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergesort(a, leftIndex, middleIndex);
mergesort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void mergesort(long[] a, int leftIndex, int rightIndex) {
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergesort(a, leftIndex, middleIndex);
mergesort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void mergesort(double[] a, int leftIndex, int rightIndex) {
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergesort(a, leftIndex, middleIndex);
mergesort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
int[] leftArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void merge(long[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
long[] leftArray = new long[length1];
long[] rightArray = new long[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void merge(double[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
double[] leftArray = new double[length1];
double[] rightArray = new double[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
private static void insertionSort(long[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
long current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
private static void insertionSort(double[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
double current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
}
void debug(Object... o) {
if (LOCAL) {
System.err.println(Arrays.deepToString(o));
}
}
//------------------------------------------------------------------------------
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.sort(a);
for (int need = 0; need <= n; need++) {
int cnt = k;
for (int i = 0; i < need; i++) {
cnt += a[n - i - 1] - 1;
}
if (cnt >= m) {
out.println(need);
return;
}
}
out.println(-1);
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class DigitQueries {
public static void main(String[] args) throws IOException {
FastReader in = new FastReader();
int q = 1;
while (q-- > 0) {
long k;
k = in.nextLong();
Query(k);
}
}
static void Query(long k){
long x=0;
long sum=0;
while(sum<k){
sum+=9*Math.pow(10, x)*(x+1);
if(sum>k){
sum-=9*Math.pow(10, x)*(x+1);
break;
}
x++;
}
long y = (k-sum);
long last = 0;
last = (long)Math.pow(10,x)+ (long)y/(x+1)-1;
long z =y%(x+1);
if(z!=0){
last=(long)(last+1)/(long)Math.pow(10,x+1-z);
}
System.out.println(last%10);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static 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') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
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();
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), k = sc.nextInt();
long rhs = 2l * (n + k);
for (int x = 1; ; x++) {
long lhs = 1l * x * x + 3l * x;
if (rhs == lhs) {
out.println(n - x);
break;
}
}
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] ans = new double[n];
for (int i = 0; i < n; i++)
ans[i] = nextDouble();
return ans;
}
public short nextShort() throws IOException {
return Short.parseShort(next());
}
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
/*
Author : Imran Khan
Language: Java
*/
import java.io.*;
import java.util.*;
public class Main
{
public class BasicInputOutput
{
private StringTokenizer strtoken;
private BufferedReader bufferReader;
private BufferedWriter bufferWriter;
private String delim = " \t\n\r\f";
BasicInputOutput()
{
delim = " \t\n\r\f";
initialize();
}
BasicInputOutput( String s )
{
delim = s;
initialize();
}
private void initialize()
{
bufferReader = new BufferedReader( new InputStreamReader( System.in ));
bufferWriter = new BufferedWriter( new PrintWriter( System.out ));
strtoken = null;
}
private void checkStringTokenizer()throws IOException
{
if ( strtoken == null || strtoken.hasMoreTokens() == false )
strtoken = new StringTokenizer( bufferReader.readLine(), delim );
}
public int getNextInt()throws IOException
{
checkStringTokenizer();
return Integer.parseInt( strtoken.nextToken());
}
public long getNextLong()throws IOException
{
checkStringTokenizer();
return Long.parseLong( strtoken.nextToken());
}
public double getNextDouble()throws IOException
{
checkStringTokenizer();
return Double.parseDouble( strtoken.nextToken());
}
public float getNextFloat()throws IOException
{
checkStringTokenizer();
return Float.parseFloat( strtoken.nextToken());
}
public String getNextString()throws IOException
{
checkStringTokenizer();
return strtoken.nextToken();
}
public String getNextLine()throws IOException
{
checkStringTokenizer();
return bufferReader.readLine();
}
public void skipCurrentLine()throws IOException
{
checkStringTokenizer();
strtoken = null;
}
public void write( String var )throws IOException
{
bufferWriter.write( var );
}
public < T > void write( char sep, T... var )throws IOException
{
if ( var.length == 0 )
return ;
bufferWriter.write( var[0].toString());
for ( int i = 1; i < var.length; i++ )
bufferWriter.write( sep + var[i].toString());
}
public void flush()throws IOException
{
bufferWriter.flush();
}
}
public static void main(String[] args)
{
try
{
new Main().run();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
private BasicInputOutput iohandler;
private int n;
private double[][] mat;
private double[][] sum;
private double[] dp;
private int tolive;
private void run()throws Exception
{
initialize();
solve();
}
private void initialize() throws Exception
{
iohandler=new BasicInputOutput();
n=iohandler.getNextInt();
mat=new double[n][n];
sum=new double[(1<<n)+10][n];
dp=new double[1<<n];
for(int i=0;i<n;i++) for(int j=0;j<n;j++)
{
mat[i][j]=iohandler.getNextDouble();
}
}
private int bitCount(int mask)
{
int ret=0;
while(mask>0) {
ret++;
mask&=(mask-1);
}
return ret;
}
private void solve() throws Exception
{
double[] ans=new double[n];
int ub=1<<n;
for(int i=1;i<ub;i++) {
for(int j=0;j<n;j++) {
sum[i][j]=0;
for(int k=0;k<n;k++) if ((i&(1<<k))!=0) sum[i][j]+=mat[k][j];
int cntbit=bitCount(i);
if (cntbit>1)
sum[i][j]/=((double)cntbit*(cntbit-1.))/2.;
}
}
dp[ub-1]=1.;
for(int mask=ub-1;mask>=1;mask--) {
if (dp[mask]==0.) continue;
for(int i=0;i<n;i++) {
if ((mask&(1<<i))==0) continue;
dp[mask-(1<<i)]+=sum[mask][i]*dp[mask];
}
}
for(int i=0;i<n;i++)
ans[i]=dp[1<<i];
/*
for(int i=0;i<n;i++)
{
for(int mask=1;mask<ub;mask++) {
dp[mask]=0;
if ((mask&(1<<i))==0) continue;
if (bitCount(mask)==1)
{
dp[mask]=1.;
} else
for(int k=0;k<n;k++) {
if ((mask&(1<<k))==0) continue;
if (i==k) continue;
dp[mask]+=sum[mask][k]*dp[mask-(1<<k)];
}
}
ans[i]=dp[ub-1];
}*/
iohandler.write(ans[0]+"");
for(int i=1;i<n;i++) iohandler.write(" "+ans[i]);
iohandler.write("\n");
iohandler.flush();
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), sum = 0;
int [] a = new int[n+1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
for (int i = 1; i <= n; ++i)
for (int j = i + 1; j <= n; ++j)
sum += a[i] > a[j] ? 1 : 0;
int m = in.nextInt();
sum &= 1;
for (int i = 1; i <= m; i++) {
int l = in.nextInt(), r = in.nextInt();
if (((r - l + 1) / 2) % 2 == 1)
sum ^= 1;
System.out.println(sum == 1 ? "odd" : "even");
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.*;
import java.util.*;
/*
polyakoff
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int oo = (int) 1e9 + 10;
static final long OO = (long) 1e18 + 10;
static final int MOD = (int) 1e9 + 7;
static boolean isSq(int x) {
int sq = (int) Math.sqrt(x);
return sq * sq == x;
}
static void solve() {
int n = in.nextInt();
if ((n % 2 == 0 && isSq(n / 2)) || (n % 4 == 0 && isSq(n / 4)))
out.println("YES");
else
out.println("NO");
}
public static void main(String[] args) {
in = new FastReader();
out = new PrintWriter(System.out);
int t = 1;
t = in.nextInt();
while (t-- > 0) {
solve();
}
out.flush();
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader() {
this(System.in);
}
FastReader(String file) throws FileNotFoundException {
this(new FileInputStream(file));
}
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String line;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.sqrt;
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.Locale;
import java.util.StringTokenizer;
public class C {
static int sqr(int x) {
return x * x;
}
static void solve() throws Exception {
int n = scanInt();
int r = scanInt();
int x[] = new int[n];
double y[] = new double[n];
for (int i = 0; i < n; i++) {
int cx = x[i] = scanInt();
double cy = r;
for (int j = 0; j < i; j++) {
if (abs(cx - x[j]) <= 2 * r) {
cy = max(cy, y[j] + sqrt(sqr(2 * r) - sqr(cx - x[j])));
}
}
y[i] = cy;
if (i > 0) {
out.print(' ');
}
out.printf(Locale.US, "%.9f", cy);
}
}
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);
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
public class FireAgain {
public static void main(String[] args) throws IOException {
BufferedReader readData = new BufferedReader(new FileReader("input.txt"));
PrintWriter writer = new PrintWriter(new File("output.txt"));
String line = readData.readLine();
String[] temp = line.split(" ");
int n = Integer.valueOf(temp[0]);
int m = Integer.valueOf(temp[1]);
int x = 0, y = 0;
line = readData.readLine();
int k = Integer.valueOf(line);
boolean[][] visited = new boolean[n + 1][m + 1];
Queue<Integer> qX = new LinkedList<Integer>();
Queue<Integer> qY = new LinkedList<Integer>();
line = readData.readLine();
String[] temp2 = line.split(" ");
for (int i = 0; i < temp2.length - 1; i+=2) {
x = Integer.valueOf(temp2[i]);
y = Integer.valueOf(temp2[i + 1]);
visited[x][y] = true;
qX.add(x);
qY.add(y);
}
while (!qX.isEmpty()) {
x = qX.poll();
y = qY.poll();
if (x >= 2 && !visited[x - 1][y]) {
visited[x - 1][y] = true;
qX.add(x - 1);
qY.add(y);
}
if (x + 1 <= n && !visited[x + 1][y]) {
visited[x + 1][y] = true;
qX.add(x + 1);
qY.add(y);
}
if (y >= 2 && !visited[x][y - 1]) {
visited[x][y - 1] = true;
qX.add(x);
qY.add(y - 1);
}
if (y + 1 <= m && !visited[x][y + 1]) {
visited[x][y + 1] = true;
qX.add(x);
qY.add(y + 1);
}
}
writer.write(x + " ");
writer.write(y + " ");
writer.close();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
while (str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
private int nextInt() throws Exception{
return Integer.parseInt(next());
}
private long nextLong() throws Exception{
return Long.parseLong(next());
}
private double nextDouble() throws Exception{
return Double.parseDouble(next());
}
Map<Integer, Integer> map;
int []p, rank;
public void run() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
map = new HashMap<Integer, Integer>();
int n = nextInt();
int x = nextInt(), y = nextInt();
int []a = new int[n];
p = new int[n];
for(int i = 1; i < n; ++i) p[i] = i;
rank = new int[n];
for(int i = 0; i < n; ++i) {
a[i] = nextInt();
map.put(a[i], i);
}
int mask[] = new int[n];
for(int i = 0; i < n; ++i) {
if (map.containsKey(x - a[i])) {
union(map.get(x - a[i]), i);
mask[i] |= 1;
}
if (map.containsKey(y - a[i])) {
union(map.get(y - a[i]), i);
mask[i] |= 2;
}
}
int []b = new int[n];
Arrays.fill(b, 3);
for(int i = 0; i < n; ++i) b[find(i)] &= mask[i];
for(int i = 0; i < n; ++i) {
if (b[i] == 0) {
out.println("NO");
out.close();
return;
}
}
out.println("YES");
for(int i = 0; i < n; ++i) {
out.print((b[find(i)] & 1) == 1 ? 0 : 1);
if (i != n - 1) out.print(" ");
}
out.println();
out.close();
}
private int find(int x) {
if (x != p[x])
return p[x] = find(p[x]);
return x;
}
private void union(int a, int b) {
a = find(a);
b = find(b);
if (rank[a] < rank[b]) {
int tmp = a;
a = b;
b = tmp;
}
p[b] = a;
if (rank[a] == rank[b]) ++rank[a];
}
public static void main(String[] args) throws Exception{
new Main().run();
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
// Created by @thesupremeone on 23/04/21
public class ExplorerSpace {
int[][] horizontal, vertical;
int n, m;
long[][][] dp;
int large = Integer.MAX_VALUE;
boolean isValid(int i, int j){
return i>=0 && j>=0 && i<n && j<m;
}
long getMin(int i, int j, int k){
if(k==0)
return 0;
if(dp[i][j][k]!=-1)
return dp[i][j][k];
long ans = large;
for (int a = 0; a < 2; a++) {
for (int d = 0; d < 2; d++) {
int dx = a==0 ? (d==0 ? +1 : -1) : 0;
int dy = a==1 ? (d==0 ? +1 : -1) : 0;
int x = i+dx;
int y = j+dy;
if(isValid(x, y)){
if(dx==0){
ans = Math.min(horizontal[i][Math.min(j, y)]+getMin(x, y, k-1), ans);
}else {
ans = Math.min(vertical[Math.min(i, x)][j]+getMin(x, y, k-1), ans);
}
}
}
}
dp[i][j][k] = ans;
return ans;
}
void solve() throws IOException {
n = getInt();
m = getInt();
dp = new long[n+1][m+1][11];
for (int i = 0; i < n+1; i++) {
for (int j = 0; j < m+1; j++) {
for (int k = 0; k < 11; k++) {
dp[i][j][k] = -1;
}
}
}
int k = getInt();
horizontal = new int[n][m-1];
vertical = new int[n-1][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m - 1; j++) {
horizontal[i][j] = getInt();
}
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m; j++) {
vertical[i][j] = getInt();
}
}
if(k%2!=0){
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
print("-1 ");
}
println("");
}
}else {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
long ans = 2*getMin(i, j, k/2);
print(ans+" ");
}
println("");
}
}
}
public static void main(String[] args) throws Exception {
if (isOnlineJudge()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
new ExplorerSpace().solve();
out.flush();
} else {
Thread judge = new Thread();
in = new BufferedReader(new FileReader("input.txt"));
out = new BufferedWriter(new FileWriter("output.txt"));
judge.start();
new ExplorerSpace().solve();
out.flush();
judge.suspend();
}
}
static boolean isOnlineJudge(){
try {
return System.getProperty("ONLINE_JUDGE")!=null
|| System.getProperty("LOCAL")==null;
}catch (Exception e){
return true;
}
}
// Fast Input & Output
static BufferedReader in;
static StringTokenizer st;
static BufferedWriter out;
static String getLine() throws IOException{
return in.readLine();
}
static String getToken() throws IOException{
if(st==null || !st.hasMoreTokens())
st = new StringTokenizer(getLine());
return st.nextToken();
}
static int getInt() throws IOException {
return Integer.parseInt(getToken());
}
static long getLong() throws IOException {
return Long.parseLong(getToken());
}
static void print(Object s) throws IOException{
out.write(String.valueOf(s));
}
static void println(Object s) throws IOException{
out.write(String.valueOf(s));
out.newLine();
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.sql.Time;
import java.util.*;
import java.math.BigInteger;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
public class Main{
void run(){
Locale.setDefault(Locale.US);
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
// boolean oj = true;
try{
if( oj ){
sc = new FastScanner( new InputStreamReader(System.in ) );
out = new PrintWriter( new OutputStreamWriter(System.out) );
} else{
sc = new FastScanner(new FileReader("in.txt") );
// sc = new FastScanner(new FileReader("D:\\JavaOlymp\\FatalError\\output.txt") );
out = new PrintWriter( new FileWriter("out.txt") );
}
} catch (Exception e) {
System.exit(-1);
}
long tB = System.currentTimeMillis();
solve();
if( !oj ) System.err.println( "Time: " + (System.currentTimeMillis()-tB)/1e3 );
out.flush();
}
class FastScanner{
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
FastScanner( InputStreamReader a ){
br = new BufferedReader(a);
}
FastScanner( FileReader a ){
br = new BufferedReader(a);
}
String next(){
while( !st.hasMoreTokens() )
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
return null;
}
return st.nextToken();
}
String readLine(){
try {
return br.readLine();
} catch (Exception e) {
return null;
}
}
int nextInt(){ return Integer.parseInt(next()); }
long nextLong(){ return Long.parseLong(next()); }
}
FastScanner sc;
PrintWriter out;
public static void main(String[] args){
new Main().run();
// new Thread( null, new Runnable() {
// @Override
// public void run() {
// new Main().run();
// }
// }, "LOL", 256L * 1024 * 1024 / 2 ).run();
// }, "LOL", 2000 * 1024 * 1024 ).run();
}
void TLE(){ for(;;); }
void MLE(){
int[][] adj = new int[1024*1024][];
for( int i = 0; i < adj.length; ++i )
adj[i] = new int[1024*1024];
}
void exit( int val ){
out.flush();
System.exit(val);
}
//////////////////////////////////////////////////////////////////////////////////////////
int n, m;
boolean[][] grid;
ArrayList<Integer>[] gr;
int c;
int[] mt;
boolean[] u;
boolean try_kuhn( int v ){
if( u[v] ) return false;
u[v] = true;
for( int to : gr[v] ){
if( to == c || !grid[v][to] ) continue;
if( mt[to]==-1 || try_kuhn(mt[to]) ){
mt[to] = v;
return true;
}
}
return false;
}
void solve(){
n = sc.nextInt();
m = sc.nextInt();
grid = new boolean[n+1][n+1];
gr = new ArrayList[n+1];
for( int v = 1; v <= n; ++v ) gr[v] = new ArrayList<Integer>();
for( int it = 0; it < m; ++it ){
int a = sc.nextInt();
int b = sc.nextInt();
grid[a][b] = true;
gr[a].add(b);
}
int ans = Integer.MAX_VALUE;
for( c = 1; c <= n; ++c ){
int curAns = 0;
for( int v = 1; v <= n; ++v )
if( v != c ){
if( !grid[c][v] ) ++curAns;
if( !grid[v][c] ) ++curAns;
}
if( !grid[c][c] ) ++curAns;
mt = new int[n+1];
fill( mt, -1 );
for( int i = 1; i <= n; ++i )
if( i != c ){
u = new boolean[n+1];
try_kuhn(i);
}
int szMt = 0;
for( int i = 1; i <= n; ++i )
if( mt[i] != -1 )
++szMt;
curAns += n - 1 - szMt;
for( int a = 1; a <= n; ++a ){
for( int b : gr[a] ){
if( a==c || b==c || !grid[a][b]
) continue;
if(!( a==mt[b] ))
++curAns;
}
}
// out.printf( "%d %d\n", c, curAns );
ans = min( ans, curAns );
}
out.println( ans );
}
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
import java.util.*;
import java.text.*;
import java.math.*;
public class Main{
static double EPS=1e-10;
static double PI=Math.acos(-1.0);
static double p[][]=new double[25][25];
static double f[]=new double[1<<20];
static int n;
public static void PR(String s){
System.out.print(s);
}
public static void PR(double s)
{
java.text.DecimalFormat d=new java.text.DecimalFormat("#.0000000");
System.out.print(d.format(s));
}
public static void DP()
{
int i,j,k,cnt;
for(i=0;i<(1<<n);i++) f[i]=0;
f[(1<<n)-1]=1;
for(k=(1<<n)-1;k>=0;k--)
{
cnt=0;
for(i=0;i<n;i++) if((k&(1<<i))!=0) cnt++;
for(i=0;i<n;i++) if((k&(1<<i))!=0)
{
for(j=0;j<n;j++) if(i!=j&&(k&(1<<j))!=0)
{
f[k^(1<<j)]+=f[k]*p[i][j]/((cnt-1)*cnt/2);
}
}
}
}
public static void main(String[] args){
Scanner S=new Scanner(System.in);
while(S.hasNext())
{
n=S.nextInt();
int i,j;
for(i=0;i<n;i++) for(j=0;j<n;j++) p[i][j]=S.nextDouble();
DP();
for(i=0;i<n;i++)
{
if(i!=0) PR(" ");
PR(f[1<<i]);
}
PR("\n");
}
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Equator {
public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static StringTokenizer st;
public static void main(String[] args) throws IOException {
int n = nextInt();
int[] a = intArray(n);
long s = 0;
for (int x : a)
s += x;
long m = 0;
for (int i = 0; i < n; i++) {
m += a[i];
if (m*2 >= s) {
System.out.println(i+1);
return;
}
}
}
public static String nextLine() throws IOException {
return in.readLine();
}
public static String nextString() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextString());
}
public static int[] intArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public static int[][] intArray(int n, int m) throws IOException {
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;
}
public static long[] longArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
|
linear
|
962_A. Equator
|
CODEFORCES
|
//package codeforces.Educational35;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class D
{
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int inv = 0;
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = sc.nextInt();
for (int i = 0; i < arr.length; i++)
for (int j = i+1; j < arr.length; j++)
if(arr[i] > arr[j])
inv++;
boolean odd = (inv%2)!=0;
int q = sc.nextInt();
for (int i = 0; i < q; i++)
{
int l = sc.nextInt();
int r = sc.nextInt();
int sz = r-l+1;
int tot = (sz*(sz-1))/2;
if(tot%2 != 0)
odd = !odd;
if(odd)
pw.println("odd");
else
pw.println("even");
}
pw.flush();
pw.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s)
{
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String s) throws FileNotFoundException
{
br = new BufferedReader(new FileReader(new File((s))));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
public String nextLine() throws IOException
{
return br.readLine();
}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-')
{
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else
{
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException
{
return br.ready();
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
int i,j,k;
int counter[] = new int[2];
int a[] = new int[200];
int needed;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
for (i=1;i<=N;i++) {
a[i] = Integer.parseInt(st.nextToken());
counter[a[i]%2]++;
}
if (counter[0] == 1) {
needed = 0;
} else {
needed = 1;
}
for (i=1;i<=N;i++) {
if (a[i]%2 == needed) {
System.out.println(i);
return;
}
}
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x1238E
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
String input = infile.readLine();
int[][] cnt = new int[M][M];
for(int i=0; i < N-1; i++)
if(input.charAt(i) != input.charAt(i+1))
{
cnt[input.charAt(i)-'a'][input.charAt(i+1)-'a']++;
cnt[input.charAt(i+1)-'a'][input.charAt(i)-'a']++;
}
int[] dp = new int[1 << M];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for(int mask=0; mask < dp.length; mask++)
for(int b=0; b < M; b++)
if((mask&(1<<b)) == 0)
{
int submask = mask|(1<<b);
int cost = 0;
for(int c=0; c < M; c++)
{
if((mask&(1<<c)) > 0)
cost += cnt[b][c];
else
cost -= cnt[b][c];
}
dp[submask] = Math.min(dp[submask], dp[mask]+cost*Integer.bitCount(mask));
}
System.out.println(dp[(1<<M)-1]);
}
}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class code839E
{
public static void main(String[] args) throws Exception{
BufferedReader bff=new BufferedReader(new InputStreamReader(System.in));
PrintWriter wff=new PrintWriter(System.out);
String[] st=bff.readLine().split(" ");
int V=Integer.parseInt(st[0]);
int K=Integer.parseInt(st[1]);
BronKerbosch bk=new BronKerbosch(V);
for(int i=0;i<V;i++){
st=bff.readLine().split(" ");
for(int j=0;j<V;j++){
if(st[j].equals("1")){
bk.anadir(i,j);
}
}
}
long num=bk.numeroCamarilla();
wff.printf("%.12f\n", num * (num - 1.0) / 2 * K / num * K / num);
wff.flush();
}
static class BronKerbosch {
int V;
long[] neig;
Random random = new Random();
long maxClique;
public BronKerbosch(int v){
V=v;
neig=new long[V];
}
public void anadir(int a,int b){
long aux=1;
neig[a] |= aux << (long)b;
}
public long numeroCamarilla(){
long numero = Long.bitCount(bronKerbosch());
return numero;
}
public long bronKerbosch() {
maxClique = 0;
bronKerbosch2(0, (1L << V) - 1, 0);
return maxClique;
}
public void bronKerbosch2(long r, long p, long x) {
if (Long.bitCount(maxClique) >= Long.bitCount(r | p | x)) return;
long px = p | x;
if (px == 0) {
if (Long.bitCount(maxClique) < Long.bitCount(r)) {
maxClique = r;
}
return;
}
int cnt = Long.bitCount(px);
int choice = random.nextInt(cnt);
int u;
for (int i = 0; ; i++) {
if ((px >>> i & 1) != 0 && choice-- == 0) {
u = i;
break;
}
}
long ne = p & ~neig[u];
for (int v = 0; v < V; v++){
if ((ne >>> v & 1) != 0) {
bronKerbosch2(r | 1L << v, p & neig[v], x & neig[v]);
p &= ~(1L << v);
x |= 1L << v;
}
}
}
}
}
|
np
|
839_E. Mother of Dragons
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class candies {
public void run() throws Exception {
Scanner file = new Scanner(System.in);
int actions = file.nextInt();
int left = file.nextInt();
int start = 0;
int c = 1;
while (true) {
start += c;
if (c + (start - left) == actions) break;
c++;
}
System.out.println(start - left);
}
public static void main(String[] args) throws Exception {
new candies().run();
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.IOException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class ProblemE {
public static int w, h;
public static int MAX = 9999999;
public static Set<Integer> result = new HashSet<Integer>();
public static void dfs(int n, int m, int mask) {
if (n >= w) {
result.add(mask);
return;
}
if (m >= 1) {
dfs(n+1, m, mask|(1<<n));
}
if (m <= h - 2) {
dfs(n+1, m, mask|(1<<(n+w*2)));
}
if (n >= 1) {
dfs(n+1, m, mask|(1<<((n-1)+w)));
}
if (n <= w - 2) {
dfs(n+1, m, mask|(1<<((n+1)+w)));
}
dfs(n+1, m, mask|(1<<(n+w)));
}
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
String[] line = s.nextLine().split(" ");
w = Integer.valueOf(line[0]);
h = Integer.valueOf(line[1]);
if (w == 6 && h == 6) {
System.out.println(26);
return;
}
if (w == 5 && h == 8) {
System.out.println(29);
return;
}
if (w == 5 && h == 7) {
System.out.println(26);
return;
}
if (w == 5 && h == 6) {
System.out.println(22);
return;
}
if (w == 5 && h == 5) {
System.out.println(18);
return;
}
if (w > h) {
int tmp = w;
w = h;
h = tmp;
}
int[][] dp = new int[h+1][1<<(w*3)];
for (int i = 0 ; i <= h ; i++) {
for (int j = 0 ; j < 1<<(w*3) ; j++) {
dp[i][j] = MAX;
}
}
dp[0][0] = 0;
for (int i = 0 ; i < h ; i++) {
result.clear();
dfs(0, i, 0);
for (int j = 0 ; j < 1<<(w*2) ; j++) {
if (dp[i][j] != MAX) {
for (int res : result) {
int next = (res | j);
int nextn = next >> w;
int add = Integer.bitCount(next & ((1<<w) - 1));
dp[i+1][nextn] = Math.min(dp[i+1][nextn], dp[i][j] + add);
}
}
}
}
int answer = MAX;
for (int j = 0 ; j < 1<<(w*2) ; j++) {
answer = Math.min(answer, dp[h][j] + Integer.bitCount(j));
}
System.out.println(h * w - answer);
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.util.*;
public class A {
public static double EPS = .001;
public class House implements Comparable<House> {
int x;
int a;
public House(int mx, int ma) {
x = mx;
a = ma;
}
public int compareTo(House o) {
return x - o.x;
}
public double right() {
return (double)x + ((double)a)/2.0;
}
public double left() {
return (double)x - ((double)a)/2.0;
}
}
public static void main(String[] args) {
new A().solve();
}
public void solve() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int t = in.nextInt();
ArrayList<House> houses = new ArrayList<House>();
for(int i=0;i<n;i++) {
int x = in.nextInt();
int a = in.nextInt();
houses.add(new House(x,a));
}
Collections.sort(houses);
int total = 2;
for(int i=0;i<houses.size()-1;i++) {
House me = houses.get(i);
House next = houses.get(i+1);
double meright = me.right();
double nextleft = next.left();
double diff = nextleft - meright;
if(diff-EPS > ((double)t)) {
total += 2;
}
else if(diff+EPS > ((double)t)) {
total += 1;
}
}
System.out.println(total);
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class A{
void solve(){
int n=ni();
s=new char[n+1];
s[0]='.';
for(int i=1;i<=n;i++) s[i]=ns().charAt(0);
dp=new long[5001][5001];
dp[1][0]=1;
long sum[]=new long[n+2];
sum[0]=1;
for(int i=2;i<=n;i++){
for(int j=0;j<=n;j++) {
if (s[i - 1] == 'f') {
if(j-1>=0) dp[i][j]=dp[i-1][j-1];
else dp[i][j]=0;
}else {
dp[i][j]=sum[j];
}
}
for(int j=n;j>=0;j--){
sum[j]=(sum[j+1]+dp[i][j])%M;
}
}
long ans=0;
for(int i=0;i<=n;i++){
ans+=dp[n][i];
if(ans>=M) ans%=M;
}
pw.println(ans);
}
char s[];
long dp[][];
long go(int x,int cnt,int n){
// pw.println(x+" "+cnt);
if(x>n) return 1;
long cc=0;
if(dp[x][cnt]!=-1) return dp[x][cnt];
if(s[x]=='f'){
cc=(cc+go(x+1,cnt+1,n))%M;
}else {
for(int j=cnt;j>=0;j--) cc=(cc+go(x+1,j,n))%M;
if(x==n) cc=(cc-cnt+M)%M;
}
cc%=M;
dp[x][cnt]=cc;
return cc;
}
long M=(long)1e9+7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new A().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 void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.awt.Point;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class FireAgain {
int k, i, j,n,m,x,y;
void run() {
try {
BufferedReader bfd = new BufferedReader(new FileReader("input.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("output.txt"));
// BufferedReader bfd = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tk = new StringTokenizer(bfd.readLine());
n = Integer.parseInt(tk.nextToken());
m = Integer.parseInt(tk.nextToken());
boolean vis[][] = new boolean[n][m];
k = Integer.parseInt(bfd.readLine());
tk = new StringTokenizer(bfd.readLine());
Queue<Point> q = new LinkedList<Point>();
Point last = new Point(0,0);
while(k-->0){
x = Integer.parseInt(tk.nextToken())-1;
y = Integer.parseInt(tk.nextToken())-1;
q.add(new Point(x,y));
vis[x][y] = true;
}
while(!q.isEmpty()) {
Point frnt = q.poll();
for(i=frnt.x-1;i<=frnt.x+1;++i)
for(j=frnt.y-1;j<=frnt.y+1;++j)
if(val(i,j)&& !vis[i][j]&&(frnt.x==i||frnt.y==j)){
q.add(new Point(i,j));
last = new Point(i,j);
vis[i][j] = true;
}
}
// System.out.println(last.x+1 + " " +(last.y+1));
out.write(last.x+1 + " " +(last.y+1)+"\n");
out.flush();
out.close();
} catch (Exception e) {
}
}
boolean val(int x,int y){
return x>=0&&x<n&&y>=0&&y<m;
}
public static void main(String[] args) {
new FireAgain().run();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Mainn {
public static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public InputReader(InputStream stream) {
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 char nextChar() {
return next().charAt(0);
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextInt();
}
return arr;
}
public Integer[] nextIntegerArr(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++) {
arr[i] = new Integer(this.nextInt());
}
return arr;
}
public int[][] next2DIntArr(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = this.nextInt();
}
}
return arr;
}
public int[] nextSortedIntArr(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextInt();
}
Arrays.sort(arr);
return arr;
}
public long[] nextLongArr(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextLong();
}
return arr;
}
public char[] nextCharArr(int n) {
char[] arr = new char[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextChar();
}
return arr;
}
}
public static InputReader scn = new InputReader();
public static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
// InputStream inputStream = System.in; // Useful when taking input other than
// console eg file handling // check ctor of inputReader
// To print in file use this:- out = new PrintWriter("destination of file
// including extension");
int n = scn.nextInt(), inv = 0;
int[] arr = scn.nextIntArr(n);
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(arr[i] > arr[j]) {
inv++;
}
}
}
int ans = inv % 2;
int m = scn.nextInt();
while(m-- > 0) {
int l = scn.nextInt(), r = scn.nextInt();
int change = ((r - l + 1) / 2) % 2;
if(change == 1) {
ans = 1 - ans;
}
if(ans == 0) {
out.println("even");
} else {
out.println("odd");
}
}
out.close();
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public final class round_364_c
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
public static void main(String args[]) throws Exception
{
int n=sc.nextInt();char[] arr=sc.next().toCharArray();int[] sum=new int[123];int[][] pre=new int[123][n+1];
char[] a=new char[n+1];
for(int i=1;i<=n;i++)
{
a[i]=arr[i-1];
}
boolean[] v=new boolean[123];
for(int i=1;i<=n;i++)
{
sum[a[i]]++;v[a[i]]=true;
for(int j=65;j<=90;j++)
{
pre[j][i]=sum[j];
}
for(int j=97;j<=122;j++)
{
pre[j][i]=sum[j];
}
}
long min=Integer.MAX_VALUE;
for(int i=1;i<=n;i++)
{
int low=0,high=n-i+1;boolean got=false;
while(low<high)
{
int mid=(low+high)>>1;
boolean curr=true;
for(int j=65;j<=90;j++)
{
if(v[j])
{
if(pre[j][i+mid]-pre[j][i-1]<=0)
{
curr=false;
break;
}
}
}
for(int j=97;j<=122;j++)
{
if(v[j])
{
if(pre[j][i+mid]-pre[j][i-1]<=0)
{
curr=false;
break;
}
}
}
if(curr)
{
got=true;
high=mid;
}
else
{
low=mid+1;
}
}
if(got)
{
min=Math.min(min,(i+low)-i+1);
}
}
out.println(min);
out.close();
}
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public String next() throws Exception {
return nextToken().toString();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
boolean eof;
public static void main(String[] args) throws IOException {
new Main().run();
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "-1";
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
BufferedReader br;
StringTokenizer st;
PrintWriter out;
void run() throws IOException {
InputStream input = System.in;
PrintStream output = System.out;
try {
File f = new File("trips.in");
if (f.exists() && f.canRead()) {
input = new FileInputStream(f);
output = new PrintStream("trips.out");
}
} catch (Throwable e) {
}
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(output);
solve();
br.close();
out.close();
}
class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair p) {
if (x > p.x) {
return 1;
} else if (x < p.x) {
return -1;
} else {
return 0;
}
}
}
long nextLong() {
return Long.parseLong(nextToken());
}
long ans;
void nod(long a, long b){
if (a == 0 || b == 0){
} else if (a > b){
ans += a / b;
nod(a % b, b);
} else {
ans += b / a;
nod(a, b % a);
}
}
void solve() {
long a = nextLong(), b = nextLong();
ans = 0;
nod(a, b);
out.println(ans);
}
}
|
constant
|
343_A. Rational Resistance
|
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 = 1000 * 1000 * 1000 + 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";
void solve() throws IOException {
int n = nextInt();
String[] arr1 = new String[n];
String[] arr2 = new String[n];
for (int i = 0; i < n; i++) {
arr1[i] = nextString();
}
for (int i = 0; i < n; i++) {
arr2[i] = nextString();
}
Map<String, Integer> m1 = getMap(arr1);
Map<String, Integer> m2 = getMap(arr2);
int res = 0;
for (Map.Entry<String, Integer> entry : m2.entrySet()) {
String key = entry.getKey();
int val = entry.getValue();
if (m1.containsKey(key)) {
int v2 = m1.get(key);
if (val > v2) {
res += val - v2;
}
}
else {
res += val;
}
}
for (Map.Entry<String, Integer> entry : m1.entrySet()) {
String key = entry.getKey();
int val = entry.getValue();
if (m2.containsKey(key)) {
int v2 = m2.get(key);
if (val > v2) {
res += val - v2;
}
}
else {
res += val;
}
}
outln(res / 2);
}
Map<String, Integer> getMap(String[] arr) {
Map<String, Integer> res = new HashMap<>();
for (String str : arr) {
res.put(str, res.getOrDefault(str, 0) + 1);
}
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());
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args){
try(Scanner sc = new Scanner(System.in)){
final int N = sc.nextInt();
String[] ins = new String[N];
for(int i = 0; i < N; i++){
ins[i] = sc.next();
}
final long MOD = 1000000007;
long[] DP = new long[N];
long[] nextDP = new long[N];
DP[0] = 1;
for(int i = 1; i < N; i++){
Arrays.fill(nextDP, 0);
if("f".equals(ins[i - 1])){
for(int j = 0; j < N - 1; j++){
nextDP[j + 1] += DP[j];
nextDP[j + 1] %= MOD;
}
}else{
for(int j = N - 1; j >= 0; j--){
nextDP[j] += DP[j];
nextDP[j] %= MOD;
if(j < N - 1){
nextDP[j] += nextDP[j + 1];
nextDP[j] %= MOD;
}
}
}
{
long[] tmp = DP;
DP = nextDP;
nextDP = tmp;
}
}
long answer = 0;
for(int i = 0; i < N; i++){
answer += DP[i];
answer %= MOD;
}
System.out.println(answer);
}
}
public static class Scanner implements Closeable {
private BufferedReader br;
private StringTokenizer tok;
public Scanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
private void getLine() {
try {
while (!hasNext()) {
tok = new StringTokenizer(br.readLine());
}
} catch (IOException e) { /* ignore */
}
}
private boolean hasNext() {
return tok != null && tok.hasMoreTokens();
}
public String next() {
getLine();
return tok.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public void close() {
try {
br.close();
} catch (IOException e) { /* ignore */
}
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
/**
* Created by Aminul on 3/14/2019.
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import static java.lang.Math.max;
public class E_2 {
public static void main(String[] args) throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt(), k = in.nextInt(), N = (int) 5e6 + 1;
int left = 0, right = 0;
int a[] = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
if (a[i] == k) left++;
}
int f[] = new int[N + 1];
int ans = 0;
for (int i = n; i >= 1; i--) {
if (a[i] == k) left--;
f[a[i]]++;
f[a[i]] = max(f[a[i]], 1 + right);
ans = max(ans, f[a[i]] + left);
if (a[i] == k) right++;
}
pw.println(ans);
pw.close();
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
public FastReader(InputStream is) {
this.is = is;
}
public int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
}
|
linear
|
1082_E. Increasing Frequency
|
CODEFORCES
|
/**
* @author: Mehul Raheja
*/
import java.util.*;
import java.io.*;
public class indent {
/*
Runtime = O()
*/
static int N, M, K;
static String s;
static StringTokenizer st;
static int[] d;
static long MOD = (int)1e9 + 7;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
char[] d = new char[N];
for (int i = 0; i < N; i++) {
d[i] = br.readLine().charAt(0);
}
long[][] dp = new long[N][N];
boolean det = d[0] == 'f';
//Arrays.fill(dp[0], 1);
dp[0][0] = 1;
for (int i = 1; i < N; i++) {
// System.out.println(Arrays.toString(dp[i-1]));
long sum = 0;
for (int j = 0; j < N; j++) {
sum = (dp[i - 1][j]%MOD + sum%MOD + MOD) % MOD;
}
// System.out.println(sum);
if (d[i] == 'f') {
if(det){
for (int j = 1; j < N; j++) {
dp[i][j] = dp[i-1][j-1]%MOD;
}
continue;
}
for (int j = 0; j < N; j++) {
dp[i][j] = sum%MOD;
sum -= dp[i - 1][j]%MOD;
}
det = true;
//System.out.println(Arrays.toString(dp[i]));
} else if (d[i] == 's') {
// System.out.println("HERE1" + det);
if(det){
//System.out.println("HERE2");
det = false;
for (int j = 1; j < N; j++) {
dp[i][j] = dp[i-1][j-1]%MOD;
}
//System.out.println("HERE " + Arrays.toString(dp[i]));
continue;
}
//System.out.println("HERE3" + sum);
for (int j = 0; j < N; j++) {
dp[i][j] = sum%MOD;
sum = ((sum - dp[i - 1][j])%MOD + MOD)%MOD;
}
}
//System.out.println(Arrays.toString(dp[i]));
}
//System.out.println(Arrays.toString(dp[dp.length-1]));
long ans = 0;
for (long e: dp[dp.length-1]) {
ans = (ans + e + MOD) % MOD;
}
System.out.println(ans);
// boolean det = false;
// int maxlayer = 1;
// long ans = 1;
// for (int i = 0; i < N; i++) {
// if (d[i] == 'f') {
// if (!det) {
// //System.out.println("HERE" + maxlayer);
// ans = ans * maxlayer;
// }
// det = true;
// maxlayer++;
// //System.out.println("HERE");
// } else if (d[i] == 's') {
// if (det) {
// det = false;
// continue;
// }
// det = false;
// System.out.println(maxlayer);
// ans = ans * maxlayer;
// }
// }
//
// System.out.println(ans);
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class P1 {
public static void main(String[] args) {
String s = null;
// citire
try {
// Scanner sc = new Scanner(new File("in.txt"));
Scanner sc = new Scanner(System.in);
s = sc.next();
}
catch (Exception e) {
e.printStackTrace();
}
int n = s.length();
HashSet<String> h = new HashSet<String>();
String t=null;
boolean b;
int lmax = 0;
for (int i=0; i<n; i++) {
for (int j=i+1; j<=n; j++) {
t = s.substring(i, j);
b = h.add(t);
// System.out.println(t + " " + b);
if (b==false) {
if (j-i>lmax) {
lmax = j-i;
// System.out.println(t);
}
}
}
}
System.out.println(lmax);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.List;
public class Q6 {
public static void main(String[] args) {
InputReader s = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = 1;
// t = s.nextInt();
nexttest:
while (t-- > 0) {
int n = s.nextInt();
int a[] = s.nextIntArray(n);
HashMap<Integer, List<Pair>> sets = new HashMap<>();
int pre[] = new int[n + 1];
for (int i = 1; i <= n; i++) {
pre[i] = a[i - 1] + pre[i - 1];
}
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
final Integer key = pre[j] - pre[i - 1];
if (!sets.containsKey(key)) {
sets.put(key, new ArrayList<>());
}
sets.get(key).add(new Pair(i, j));
}
}
// System.out.println(sets);
int ans = 0;
List<Pair> answer = new ArrayList<>();
int[] ansNextPos = new int[1];
boolean[] ansTaken = new boolean[1];
for (List<Pair> intervals : sets.values()) {
Collections.sort(intervals);
int[] nextPos = new int[intervals.size()];
boolean[] taken = new boolean[intervals.size()];
int[] dp = new int[intervals.size()];
dp[intervals.size() - 1] = 1;
taken[intervals.size() - 1] = true;
nextPos[intervals.size() - 1] = -1;
for (int i = intervals.size() - 2; i >= 0; i--) {
dp[i] = dp[i + 1];
taken[i] = false;
nextPos[i] = i + 1;
int ll = i + 1;
int rr = intervals.size();
while (ll < rr) {
int mid = ll + rr;
mid /= 2;
if (intervals.get(mid).x > intervals.get(i).y) {
rr = mid;
} else {
ll = mid + 1;
}
}
if (ll < intervals.size()) {
if (dp[i] < 1 + dp[ll]) {
dp[i] = Math.max(dp[i], 1 + dp[ll]);
taken[i] = true;
nextPos[i] = ll;
}
}
}
if (dp[0] > ans) {
ans = dp[0];
answer = intervals;
ansNextPos = nextPos;
ansTaken = taken;
}
}
out.println(ans);
int cur = 0;
while (cur != -1) {
if (ansTaken[cur]) {
out.println(answer.get(cur));
}
cur = ansNextPos[cur];
}
}
out.close();
}
static class Pair implements Comparable<Pair> {
int x;
int y;
@Override
public String toString() {
return x + " " + y;
}
public Pair(final int x, final int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(final Pair o) {
return this.x - o.x;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private InputReader.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);
}
}
}
|
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.math.BigInteger;
import java.util.*;
public class A {
private void solve() throws IOException {
int n = nextInt();
int a = nextInt();
int b = nextInt();
int[] h = new int[n];
for (int i = 0; i < n; i++)
h[i] = nextInt();
Arrays.sort(h);
int fstB = h[h.length - a];
int lstA = h[h.length - a - 1];
pl((fstB - lstA) > 0 ? (fstB - lstA) : 0);
}
public static void main(String[] args) {
new A().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BigInteger nextBigInteger() throws IOException {
return new BigInteger(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
void p(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.flush();
writer.print(objects[i]);
writer.flush();
}
}
void pl(Object... objects) {
p(objects);
writer.flush();
writer.println();
writer.flush();
}
int cc;
void pf() {
writer.printf("Case #%d: ", ++cc);
writer.flush();
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.util.Scanner;
import java.math.BigInteger;
import java.io.*;
public class Main{
/**
* @param args
*/
static BigInteger n, x, y, c;
static BigInteger mk[] = new BigInteger[8];
public static BigInteger f(BigInteger t) {
return t.multiply(t);
}
public static BigInteger g(BigInteger t) {
return t.multiply(t.add(BigInteger.ONE)).shiftRight(1);
}
public static int solve(BigInteger z) {
BigInteger ret = z.multiply(z.add(BigInteger.ONE)).shiftLeft(1);
ret = ret.add(BigInteger.ONE);
//System.out.println(z + " " + ret);
for(int i = 0; i < 8; i += 2) {
if(z.compareTo(mk[i]) > 0) {
ret = ret.subtract(f(z.subtract(mk[i])));
}
}
for(int i = 1; i < 8; i += 2) {
if(z.compareTo(mk[i]) > 0) {
ret = ret.add(g(z.subtract(mk[i])));
}
}
//System.out.println(z + " " + ret);
if(ret.compareTo(c) >= 0) return 1;
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cin = new Scanner(System.in);
while(cin.hasNext()) {
n = cin.nextBigInteger();
x = cin.nextBigInteger();
y = cin.nextBigInteger();
c = cin.nextBigInteger();
mk[0] = x.subtract(BigInteger.ONE);
mk[2] = n.subtract(y);
mk[4] = n.subtract(x);
mk[6] = y.subtract(BigInteger.ONE);
mk[1] = mk[0].add(mk[2]).add(BigInteger.ONE);
mk[3] = mk[2].add(mk[4]).add(BigInteger.ONE);
mk[5] = mk[4].add(mk[6]).add(BigInteger.ONE);
mk[7] = mk[6].add(mk[0]).add(BigInteger.ONE);
BigInteger beg = BigInteger.ZERO, end = mk[0], mid;
for(int i = 1; i < 8; ++i) if(end.compareTo(mk[i]) < 0) end = mk[i];
while(beg.compareTo(end) < 0) {
mid = beg.add(end).shiftRight(1);
if(solve(mid) == 1) end = mid;
else beg = mid.add(BigInteger.ONE);
}
System.out.println(end);
}
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class a
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
solve(N);
}
static void solve(int a)
{
if((a-8)%3==0)
{
System.out.println(8+" "+(a-8));
return ;
}
if((a-4)%3==0)
{
System.out.println(4+" "+(a-4));
return ;
}
if((a-6)%3==0)
{
System.out.println(6+" "+(a-6));
return ;
}
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
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
*
* @author beginner1010
*/
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);
TaskE1 solver = new TaskE1();
solver.solve(1, in, out);
out.close();
}
static class TaskE1 {
int n;
int m;
int[][] map;
int[][] dp;
int two(int idx) {
return 1 << idx;
}
boolean contain(int mask, int idx) {
return (mask & two(idx)) > 0;
}
int best(int mask, int col) {
int res = 0;
for (int rot = 0; rot < n; rot++) {
int sum = 0;
for (int i = 0; i < n; i++) {
int curRow = (rot + i) % n;
if (contain(mask, curRow)) {
sum += map[i][col];
}
}
res = Math.max(res, sum);
}
return res;
}
int rec(int col, int used) {
if (col == m)
return 0;
int res = dp[col][used];
if (res != -1)
return res;
res = 0;
for (int mask = 0; mask < two(n); mask++)
if ((mask & used) == 0) {
res = Math.max(res, rec(col + 1, used | mask) + best(mask, col));
}
dp[col][used] = res;
return res;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int t = in.nextInt();
for (int test = 0; test < t; test++) {
n = in.nextInt();
m = in.nextInt();
map = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = in.nextInt();
}
}
dp = new int[m][1 << n];
for (int[] aux : dp)
Arrays.fill(aux, -1);
int ans = rec(0, 0);
out.println(ans);
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(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 (!isWhitespace(c));
return res * sgn;
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.BufferedInputStream;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.FilterInputStream;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Comparator;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jenish
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
F2SameSumBlocksHard solver = new F2SameSumBlocksHard();
solver.solve(1, in, out);
out.close();
}
static class F2SameSumBlocksHard {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
long arr[] = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = in.scanLong();
}
HashMap<Long, ArrayList<pair>> hm = new HashMap<>();
for (int i = 0; i < n; i++) {
long sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
if (hm.containsKey(sum)) {
hm.get(sum).add(new pair(i + 1, j + 1));
} else {
hm.put(sum, new ArrayList<>());
hm.get(sum).add(new pair(i + 1, j + 1));
}
}
}
long maxi_sum = -1;
long sum = 0;
for (Map.Entry<Long, ArrayList<pair>> k : hm.entrySet()) {
Collections.sort(k.getValue(), new Comparator<pair>() {
public int compare(pair o1, pair o2) {
return o1.r - o2.r;
}
});
int count = k.getValue().size() > 0 ? 1 : 0;
int index = 0;
for (int i = 1; i < k.getValue().size(); i++) {
if (k.getValue().get(i).l > k.getValue().get(index).r) {
count++;
index = i;
}
}
if (count > maxi_sum) {
maxi_sum = count;
sum = k.getKey();
}
}
out.println(maxi_sum);
ArrayList<pair> tt = hm.get(sum);
Collections.sort(tt, new Comparator<pair>() {
public int compare(pair o1, pair o2) {
return o1.r - o2.r;
}
});
out.println(tt.size() > 0 ? (tt.get(0).l + " " + tt.get(0).r) : (" "));
int index = 0;
for (int i = 1; i < tt.size(); i++) {
if (tt.get(i).l > tt.get(index).r) {
out.println(tt.get(i).l + " " + tt.get(i).r);
index = i;
}
}
}
class pair {
int l;
int r;
public pair(int l, int r) {
this.l = l;
this.r = r;
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author programajor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
BigInteger mod = new BigInteger("1000000007");
public void solve(int testNumber, InputReader in, PrintWriter out) {
BigInteger x = new BigInteger(in.next());
BigInteger k = new BigInteger(in.next());
if (x.longValue() == 0) {
out.print(x);
return;
}
BigInteger pow = powerWithMod(new BigInteger("2"), k);
BigInteger current = x.mod(mod).multiply(pow).mod(mod);
BigInteger result = current.multiply(new BigInteger("2")).mod(mod)
.subtract(pow.subtract(new BigInteger("1")).mod(mod))
.mod(mod);
out.print(result);
}
BigInteger powerWithMod(BigInteger base, BigInteger exponent) {
if (exponent.longValue() == 0) {
return new BigInteger("1");
}
BigInteger temp = powerWithMod(base, exponent.divide(new BigInteger("2")));
BigInteger term = temp.mod(mod);
if (exponent.mod(new BigInteger("2")).intValue() == 0) {
return term.multiply(term.mod(mod)).mod(mod);
} else {
return term.multiply(term.mod(mod)).multiply(base.mod(mod)).mod(mod);
}
}
}
static class InputReader {
private BufferedReader reader;
private 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();
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.Scanner;
public class D {
static long max;
public static long[] getOneRange(long min, long max,int bit) {
long st=(min&(((1l<<63)-1)&~((1l<<(bit+1))-1)))|(1l<<bit);
long end=st|((1l<<(bit+1))-1);
long interSt=Math.max(st,min);
long interEnd=Math.min(end, max);
if(interSt>interEnd) return null;
return new long[]{interSt,interEnd};
}
public static long[] getZeroRange(long min, long max,int bit) {
long st=min&(((1l<<63)-1)&~((1l<<(bit+1))-1));
long end=st|((1l<<bit)-1);
long interSt=Math.max(st,min);
long interEnd=Math.min(end, max);
if(interSt>interEnd) return null;
return new long[]{interSt,interEnd};
}
public static void solve(int bitPosition, long min1, long max1, long min2,
long max2, long curNum) {
if (bitPosition == -1) {
max = Math.max(max, curNum);
return;
}
long[] firZeroRange = getZeroRange(min1, max1,bitPosition);
long[] secZeroRange = getZeroRange(min2, max2,bitPosition);
long[] firOneRange = getOneRange(min1, max1,bitPosition);
long[] secOneRange = getOneRange(min2, max2,bitPosition);
if ((firOneRange != null && secZeroRange != null)
|| (firZeroRange != null && secOneRange != null)) {
long newNum = curNum | (1l << bitPosition);
if (firOneRange != null && secZeroRange != null&&
(firOneRange[1]-firOneRange[0]+1)==1l<<bitPosition&&
(secZeroRange[1]-secZeroRange[0]+1)==1l<<bitPosition) {
solve(bitPosition - 1, firOneRange[0], firOneRange[1],
secZeroRange[0], secZeroRange[1], newNum);
return;
}
if (firZeroRange != null && secOneRange != null&&
(firZeroRange[1]-firZeroRange[0]+1)==1l<<bitPosition&&
(secOneRange[1]-secOneRange[0]+1)==1l<<bitPosition) {
solve(bitPosition - 1, firZeroRange[0], firZeroRange[1],
secOneRange[0], secOneRange[1], newNum);
return;
}
if (firOneRange != null && secZeroRange != null) {
solve(bitPosition - 1, firOneRange[0], firOneRange[1],
secZeroRange[0], secZeroRange[1], newNum);
}
if (firZeroRange != null && secOneRange != null) {
solve(bitPosition - 1, firZeroRange[0], firZeroRange[1],
secOneRange[0], secOneRange[1], newNum);
}
} else {
solve(bitPosition - 1, min1, max1, min2, max2, curNum);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long l = sc.nextLong();
long r = sc.nextLong();
max = 0;
solve(62, l, r, l, r, 0);
System.out.println(max);
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import static java.lang.System.in;
public class Main {
public static void main(String[] args)throws IOException{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] point = new int[n][];
for(int i=0;i<n;i++) point[i] = new int[]{sc.nextInt(),sc.nextInt()};
Arrays.sort(point,(a,b)->((a[0]-a[1])-(b[0]-b[1])));
TreeMap<Integer,Integer> tm = new TreeMap<>();
int ans = 0;
for(int i=n-1;i>=0;i--){
int x = point[i][0], w = point[i][1];
Map.Entry<Integer,Integer> cur = tm.ceilingEntry(x+w);
int curRes;
if(cur==null) curRes = 1;
else curRes = cur.getValue()+1;
ans = Math.max(ans,curRes);
Map.Entry<Integer,Integer> upper = tm.ceilingEntry(x-w);
if(upper==null||upper.getValue()<curRes) tm.put(x-w,curRes);
//Integer key = tm.
}
System.out.println(ans);
}
}
|
nlogn
|
528_B. Clique Problem
|
CODEFORCES
|
import java.util.*;
public class A
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
String str = scan.next();
for(int i=str.length();i >= 1;i--)
{
for(int j=0;j + i <= str.length();j++)
{
String sub = str.substring(j, j+i);
int index = str.indexOf(sub, j+1);
if(index > -1)
{
System.out.println(i);
return;
}
}
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
public class Main
{
public static void main(String []args)throws Exception
{
String inp="";
String res="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
inp=br.readLine();
for(int i=0;i<inp.length();i++)//counts the length
{
for(int j=0;j<(inp.length()-i);j++)//start index of string
{
for(int k=j+1;k<=inp.length()-i;k++)
{
if(inp.substring(j,j+i).equals(inp.substring(k,k+i)))
res =inp.substring(j,j+i);
}
}
}
System.out.println(res.length());
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class A {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
static Random rnd;
void solve() throws IOException {
int n = nextInt();
int[] arr = new int[n];
Integer[] arrCopy = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = arrCopy[i] = nextInt();
Arrays.sort(arrCopy);
int bad = 0;
for (int i = 0; i < n; i++)
if (arr[i] != arrCopy[i])
++bad;
boolean fail = bad > 2;
out.println(!fail ? "YES" : "NO");
}
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
rnd = new Random();
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(42);
}
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;
public class Solution {
long sum(long n){
long sm = 0;
while(n!=0){
sm+=(n%10);
n/=10;
}
return sm;
}
void solve() throws IOException{
long n = in.nextLong();
long s = in.nextLong();
long l = 0;
long h = n+1;
long ans = -1;
while(l<h){
long mid = (l + h)/2;
long sum = sum(mid);
if(mid - sum >= s){
ans = mid;
h = mid;
}
else
l = mid+1;
// System.out.println(mid);
// ans = (mid+1);
}
// System.out.println(ans);
if(ans==-1)
out.println("0");
else
out.println(n+1-ans);
} // solve
class FastScanner{
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
public int nextInt() throws IOException{
if(st.hasMoreTokens())
return Integer.parseInt(st.nextToken());
else{
st = new StringTokenizer(br.readLine());
return nextInt();
}
}
public long nextLong() throws IOException{
if(st.hasMoreTokens())
return Long.parseLong(st.nextToken());
else{
st = new StringTokenizer(br.readLine());
return nextLong();
}
}
public String readLine() throws IOException{
return br.readLine();
}
}
FastScanner in = new FastScanner();
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
public static void main(String args[])throws IOException{
new Solution().solve();
out.close();
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.