src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static long gcd(long a, long b)
{
return b==0? a:gcd(b, a%b);
}
public static long lcm(long a, long b, long c)
{
long d=a/gcd(a, b)*b;
return c/gcd(c, d)*d;
}
public static long max(long a, long b)
{
return a>b? a:b;
}
public static void main(String[] args)
{
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
long n=in.nextLong();
if(n<=2)
out.println(n);
else
out.println(max(lcm(n, n-1, n-2), max(lcm(n, n-1, n-3), lcm(n-1, n-2, n-3))));
out.close();
}
}
class InputReader
{
BufferedReader buf;
StringTokenizer tok;
InputReader()
{
buf = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext()
{
while(tok == null || !tok.hasMoreElements())
{
try
{
tok = new StringTokenizer(buf.readLine());
}
catch(Exception e)
{
return false;
}
}
return true;
}
String next()
{
if(hasNext())
return tok.nextToken();
return null;
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
BigInteger nextBigInteger()
{
return new BigInteger(next());
}
BigDecimal nextBigDecimal()
{
return new BigDecimal(next());
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.io.*;
import java.util.Scanner;
import java.util.TreeMap;
/**
*
* @author camoroh13
*/
public class Solution {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("/home/camoroh13/NetBeansProjects/JavaApplication1/src/input.txt"));
int n = sc.nextInt();
int t = sc.nextInt();
// int[][] h = new int[n][2];
TreeMap<Integer, Integer> h = new TreeMap<Integer, Integer>();
for (int i=0; i < n; i++) {
int key = sc.nextInt();
h.put(key, sc.nextInt());
}
int ans = 2;
Integer lastKey = h.firstKey();
Integer last = h.get(lastKey);
h.remove(lastKey);
for (int i=1; i < n; i++) {
int key = h.firstKey();
int val = h.get(key);
//System.out.println(Math.abs(key-val*1.0/2 - (lastKey + last*1.0/2)) + "-" + key + "-"+val);
if (Math.abs(key-val*1.0/2 - (lastKey + last*1.0/2)) == t) {
ans++;
} else if (Math.abs(key-val*1.0/2 - (lastKey + last*1.0/2)) > t) {
ans += 2;
}
lastKey = key;
last = val;
h.remove(lastKey);
}
System.out.println(ans);
sc.close();
}
}
|
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.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 ankur
*/
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 {
String[] str;
long mod = (long) 1e9 + 7;
long[][] dp;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
str = new String[n];
dp = new long[n + 2][n + 2];
for (int i = 0; i < dp.length; i++) {
Arrays.fill(dp[i], -1);
}
for (int i = 0; i < n; i++) {
str[i] = in.readString();
}
if (str[0].charAt(0) == 'f') {
out.print(solve(1, 1));
} else {
out.print(solve(1, 0));
}
}
long solve(int n, int horiz) {
if (horiz < 0)
return 0;
if (n >= str.length - 1) {
return 1;
}
if (dp[n][horiz] != -1) {
return dp[n][horiz];
}
if (str[n].charAt(0) == 'f') {
return dp[n][horiz] = solve(n + 1, horiz + 1);
} else {
long ans1 = solve(n, horiz - 1);
//System.out.println(ans1+" "+n+" egsvd"+horiz);
ans1 += solve(n + 1, horiz);
//System.out.println(ans1+" "+n+" "+horiz);
ans1 = ans1 % mod;
return dp[n][horiz] = ans1;
}
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
//*-*------clare------
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 = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A4 {
public BufferedReader input;
public PrintWriter output;
public StringTokenizer stoken = new StringTokenizer("");
public static void main(String[] args) throws IOException {
new A4();
}
A4() throws IOException {
input = new BufferedReader(new InputStreamReader(System.in));
output = new PrintWriter(System.out);
run();
input.close();
output.close();
}
private void run() throws IOException {
int n = Math.toIntExact(nextLong());
int m = Math.toIntExact(nextLong());
int[] coor = new int[n + 1];
int[] ss = new int[n + 1];
for (int i = 0; i < n; i++) {
coor[i] = Math.toIntExact(nextLong());
}
coor[n] = 1000000000;
Arrays.sort(coor);
for (int i = 0; i < m; i++) {
long x1 = nextLong();
long x2 = nextLong();
nextLong();
if (x1 == 1 && x2 >= coor[0]) {
int l = 0;
int r = n + 1;
while (r - l > 1) {
int mi = (r + l) / 2;
if (coor[mi] > x2) {
r = mi;
} else {
l = mi;
}
}
ss[l]++;
}
}
long[] ans = new long[n + 1];
ans[n] = ss[n] + n;
long min = ans[n];
for (int i = n - 1; i > -1; i--) {
ans[i] = ans[i + 1] - 1 + ss[i];
if (ans[i] < min) {
min = ans[i];
}
}
System.out.println(min);
}
private Long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextString());
}
private String nextString() throws IOException {
while (!stoken.hasMoreTokens()) {
String st = input.readLine();
stoken = new StringTokenizer(st);
}
return stoken.nextToken();
}
}
|
nlogn
|
1075_C. The Tower is Going Home
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class TwoSquares {
int INF = 1000;
void solve() {
int[][] s1 = new int[4][2];
for (int i = 0; i < 4; i++) {
s1[i][0] = in.nextInt();
s1[i][1] = in.nextInt();
}
int[][] s2 = new int[4][2];
for (int i = 0; i < 4; i++) {
s2[i][0] = in.nextInt();
s2[i][1] = in.nextInt();
}
if (ok(s1, s2)) {
out.println("Yes");
return;
}
rotate(s1);
rotate(s2);
if (ok(s2, s1)) {
out.println("Yes");
return;
}
out.println("No");
}
void rotate(int[][] s) {
for (int i = 0; i < 4; i++) {
int x = s[i][0], y = s[i][1];
s[i][0] = x - y;
s[i][1] = x + y;
}
}
boolean ok(int[][] s1, int[][] s2) {
int xmin = INF, xmax = -INF, ymin = INF, ymax = -INF;
for (int i = 0; i < 4; i++) {
xmin = Math.min(xmin, s1[i][0]);
xmax = Math.max(xmax, s1[i][0]);
ymin = Math.min(ymin, s1[i][1]);
ymax = Math.max(ymax, s1[i][1]);
}
for (int i = 0; i < 4; i++) {
if (s2[i][0] >= xmin && s2[i][0] <= xmax && s2[i][1] >= ymin && s2[i][1] <= ymax) return true;
}
int[] mid2 = new int[]{s2[0][0] + s2[2][0], s2[0][1] + s2[2][1]};
return mid2[0] >= xmin * 2 && mid2[0] <= xmax * 2 && mid2[1] >= ymin * 2 && mid2[1] <= ymax * 2;
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new TwoSquares().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
|
constant
|
994_C. Two Squares
|
CODEFORCES
|
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
// Write your code here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
char[] seq=new char[n];
for(int i=0;i<n;i++){
seq[i]=s.next().charAt(0);
}
long mod=(long)Math.pow(10,9)+7;
long[][] arr=new long[n][n];
arr[0][0]=1;
for(int i=1;i<n;i++){
if(seq[i-1]=='f'){
for(int j=1;j<n;j++){
arr[i][j]=arr[i-1][j-1];
}
}else{
long sum=0;
for(int j=n-1;j>=0;j--){
sum=(sum+arr[i-1][j])%mod;
arr[i][j]=sum;
}
}
}
long ans=0;
for(int i=0;i<n;i++){
ans=(ans+arr[n-1][i])%mod;
}
System.out.println(ans);
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.util.Scanner;
public class prob1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s = input.next();
int n = s.length();
int i = n-1;
CharSequence temp;
for(i = n-1; i > 0; i--)
for(int j = 0 ; j <= n-i; j++)
{
temp = s.subSequence(j, i+j);
if( s.substring(j+1, n).contains(temp) || s.substring(0, j+i-1).contains(temp))
{
System.out.println(i);
return;
}
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.text.*;
public class FollowTrafficRules
{
public Scanner in = new Scanner(System.in);
public PrintStream out = System.out;
public double len, d, w, vmax, a;
DecimalFormat fmt = new DecimalFormat("0.0000000000000000");
public void main()
{
a = in.nextDouble();
vmax = in.nextDouble();
len = in.nextDouble();
d = in.nextDouble();
w = in.nextDouble();
out.println(fmt.format(T()));
}//end public void main()
public double T()
{
double t, s;
double t1, s1;
t1 = vmax / a;
s1 = vmax*vmax/(2.0*a);
double t3, s3;
t3 = w/a;
s3 = w*w/(2.0*a);
if(w >= vmax)
{
if(s1 < len)
{
return t1 + (len - s1)/vmax;
}
else
{
return Math.sqrt(2.0*len/a);
}
}
else
{
//w < vmax
double t2, s2, v2;
t2 = Math.sqrt(2.0*d/a);
v2 = a*t2;
double tx, vx;
vx = Math.sqrt((2.0*a*d + w*w)/2.0);
tx = vx / a;
//vmax > w
//v2 > vx > w
if(v2 < w)
{
if(v2 > vmax)
{
//v2 > vmax > w
if(vmax > vx)
{
return tx + (vx - w)/a + T2(w);
}
else
{
double ty, sy;
ty = (vmax - w)/a;
sy = ty * (vmax + w)/2.0;
return t1 + ty + (d - s1 - sy)/vmax + T2(w);
}
}
else
{
//v2 < w, v2 <= vmax
return t2 + T2(v2);
}
}
else if(v2 > vmax) //v2 >= w, vmax > w
{
//v2 > vmax > w
if(vmax > vx)
{
return tx + (vx - w)/a + T2(w);
}
else
{
double ty, sy;
ty = (vmax - w)/a;
sy = ty * (vmax + w)/2.0;
return t1 + ty + (d - s1 - sy)/vmax + T2(w);
}
}
else //vmax >= v2 >= w
{
//out.println("Questionable.");
//return binary() + T2(w);
//return t3 + (d-s3)/w + T2(w);
return tx + (vx - w)/a + T2(w);
}
}
}
public double binary()
{
double low, high, t, s;
low = 0.0; high = vmax/a;
for(int c=0;c<50;++c)
{
t = (low+high)/2;
s = (a*t*t)/2 + ((a*t - w)/a)*(a*t + w)/2.0;
if(s > d) high = t;
else low = t;
}
t = (low+high)/2;
return t + (a*t - w)/a;
}
/*
public double T()
{
double t1, s1, tx, sx, vx, ty, vy, sz, tz;
t1 = vmax / a;
s1 = a*t1*t1 / 2.0;
vx = Math.sqrt((2.0*a*d + w*w)/2.0);
tx = vx / a;
if(s1 < d)
{
//reaches vmax
if(vx < vmax)
{
//stops at vx
return tx + (vx - w)/a + T2(w);
}
else //vx >= vmax
{
//stops at vmax
if(w > vmax)
{
return t1 + (d - s1)/vmax + T2(vmax);
}
else
{
tz = (vmax - w)/a;
sz = ((vmax + w)/2.0) * tz;
return t1 + (d-sz-s1)/vmax + tz + T2(w);
}
}
}
else //s1 >= d
{
//never reaches vmax
vy = Math.sqrt(2.0*d*a);
ty = vy / a;
if(vx < vy)
{
//stops at vx
return tx + (vx - w)/a + T2(w);
}
else //vx >= vy
{
if(w < vy)
{
return w/a + (d - w*w/(2.0*a))/w + T2(w);
}
else //w >= vy
{
//goes to vy, accelerate all the way
return ty + T2(vy);
}
}
}
}
*/
public double T2(double v0)
{
//v0 <= min(w, vmax)
double t1, s1;
t1 = (vmax - v0)/a;
s1 = ((vmax + v0)/2.0)*t1;
if(s1 < len-d)
{
//reaches vmax
return t1 + (len-d-s1)/vmax;
}
else //s1 >= len - d
{
//does not reach vmax
return (-v0 + Math.sqrt(v0*v0 + 2*a*(len-d)))/a;
}
}
public static void main(String[] args)
{
(new FollowTrafficRules()).main();
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class D {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
public void solve() {
int n = in.nextInt();
HashMap<Long, Integer> map = new HashMap();
BigInteger sum = BigInteger.ZERO;
BigInteger ans = BigInteger.valueOf(0);
for (int i = 0; i < n; i++) {
long x = in.nextLong();
ans = ans.add(BigInteger.valueOf(i * x));
if (map.containsKey(x + 1)) {
ans = ans.add(BigInteger.valueOf(map.get(x + 1)));
}
if (map.containsKey(x - 1)) {
ans = ans.subtract(BigInteger.valueOf(map.get(x - 1)));
}
if (map.containsKey(x)) {
map.put(x, map.get(x) + 1);
} else {
map.put(x, 1);
}
ans = ans.subtract(sum);
sum = sum.add(BigInteger.valueOf(x));
}
out.print(ans.toString());
}
public void run() {
try {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("segments.in"));
out = new PrintWriter(new File("segments.out"));
}
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] arg) {
new D().run();
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
//package round524;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class D {
InputStream is;
PrintWriter out;
String INPUT = "";
long I = 4000000000000000007L;
void solve()
{
// 1 5 13
outer:
for(int T = ni();T > 0;T--){
long n = nl(), K = nl();
long inf = 0;
long sup = 0;
for(int d = 1;d <= n;d++){
inf += pow(2,d)-1;
if(inf >= I)inf = I;
sup += pow(2,d)-1 + mul(pow(2,d+1)-3, (pow(4,n-d)-1)/3);
if(sup >= I)sup = I;
// tr(d, inf, sup);
if(inf <= K && K <= sup){
out.println("YES " + (n-d));
continue outer;
}
}
out.println("NO");
}
}
long mul(long a, long b)
{
if((double)a*b > I)return I;
return a*b;
}
long pow(int b, long d)
{
long v = 1;
for(int i = 1;i <= d;i++){
if((double)v*b > I)return I;
v = v * b;
}
return v;
}
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 D().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)); }
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long n = in.nextLong();
if (n == 1 || n == 2) {
System.out.println(n);
} else if (n % 2 == 0) {
if (n % 3 == 0)
System.out.println((n - 1) * (n - 2) * (n - 3));
else
System.out.println(n * (n - 1) * (n - 3));
} else {
System.out.println(n * (n - 1) * (n - 2));
}
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
// https://codeforces.com/contest/1185/submission/55800229 (rainboy)
import java.io.*;
import java.util.*;
public class CF1185G2 {
static final int MD = 1000000007;
static int[][] solve1(int[] aa, int t, int n) {
int[][] da = new int[t + 1][n + 1];
da[0][0] = 1;
for (int i = 0; i < n; i++) {
int a = aa[i];
for (int s = t - 1; s >= 0; s--)
for (int m = 0; m < n; m++) {
int x = da[s][m];
if (x != 0) {
int s_ = s + a;
if (s_ <= t)
da[s_][m + 1] = (da[s_][m + 1] + x) % MD;
}
}
}
return da;
}
static int[][][] solve2(int[] aa, int[] bb, int t, int na, int nb) {
int[][] da = solve1(aa, t, na);
int[][][] dab = new int[t + 1][na + 1][nb + 1];
for (int s = 0; s <= t; s++)
for (int ma = 0; ma <= na; ma++)
dab[s][ma][0] = da[s][ma];
for (int i = 0; i < nb; i++) {
int b = bb[i];
for (int s = t - 1; s >= 0; s--)
for (int ma = 0; ma <= na; ma++)
for (int mb = 0; mb < nb; mb++) {
int x = dab[s][ma][mb];
if (x != 0) {
int s_ = s + b;
if (s_ <= t)
dab[s_][ma][mb + 1] = (dab[s_][ma][mb + 1] + x) % MD;
}
}
}
return dab;
}
static int[][][] init(int n, int na, int nb, int nc) {
int[][][] dp = new int[na + 1][nb + 1][nc + 1];
int[][][][] dq = new int[na + 1][nb + 1][nc + 1][3];
for (int ma = 0; ma <= na; ma++)
for (int mb = 0; mb <= nb; mb++)
for (int mc = 0; mc <= nc; mc++)
if (ma == 0 && mb == 0 && mc == 0) {
dp[ma][mb][mc] = 1;
dq[ma][mb][mc][0] = dq[ma][mb][mc][1] = dq[ma][mb][mc][2] = 1;
} else {
int x0 = ma > 0 ? (int) ((long) dq[ma - 1][mb][mc][0] * ma % MD) : 0;
int x1 = mb > 0 ? (int) ((long) dq[ma][mb - 1][mc][1] * mb % MD) : 0;
int x2 = mc > 0 ? (int) ((long) dq[ma][mb][mc - 1][2] * mc % MD) : 0;
dp[ma][mb][mc] = (int) (((long) x0 + x1 + x2) % MD);
dq[ma][mb][mc][0] = (x1 + x2) % MD;
dq[ma][mb][mc][1] = (x2 + x0) % MD;
dq[ma][mb][mc][2] = (x0 + x1) % MD;
}
return dp;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int t = Integer.parseInt(st.nextToken());
int[] aa = new int[n];
int[] bb = new int[n];
int[] cc = new int[n];
int na = 0, nb = 0, nc = 0;
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int g = Integer.parseInt(st.nextToken());
if (g == 1)
aa[na++] = a;
else if (g == 2)
bb[nb++] = a;
else
cc[nc++] = a;
}
int[][][] dp = init(n, na, nb, nc);
int[][][] dab = solve2(aa, bb, t, na, nb);
int[][] dc = solve1(cc, t, nc);
int ans = 0;
for (int tab = 0; tab <= t; tab++) {
int tc = t - tab;
for (int ma = 0; ma <= na; ma++)
for (int mb = 0; mb <= nb; mb++) {
int xab = dab[tab][ma][mb];
if (xab == 0)
continue;
for (int mc = 0; mc <= nc; mc++) {
int xc = dc[tc][mc];
if (xc == 0)
continue;
ans = (int) ((ans + (long) xab * xc % MD * dp[ma][mb][mc]) % MD);
}
}
}
System.out.println(ans);
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.util.*;
/*Author LAVLESH*/
public class solution
{
static long gcd(long a,long b){
if(b==0) return a;
else
return gcd(b,a%b);
}
public static void main(String[]args){
Scanner in=new Scanner(System.in);
long n=in.nextLong();
long m1=0,m2=0;
if(n<3)m1=n;
else {
if((n&1)==1){
long lcm=n*(n-1)/gcd(n,n-1);
m1=lcm*(n-2)/gcd(lcm,n-2);
}
else{
long lcm=(n-1)*(n-2)/gcd(n-1,n-2);
m1=lcm*(n-3)/gcd(lcm,n-3);
lcm=n*(n-1)/gcd(n,n-1);
m2=lcm*(n-3)/gcd(lcm,n-3);
m1 = Math.max(m1,m2);
}
}
System.out.println(m1);
}}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class C {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
final int INF = Integer.MAX_VALUE / 2;
void solve() throws IOException {
int n = nextInt();
int m = nextInt();
if (n > m) {
int tmp = n;
n = m;
m = tmp;
}
// n < m !!!!
// n rows m columns
if (n == 1) {
out.print(m - (m + 2) / 3);
return;
}
int[][] dp = new int[n * m + 1][1 << (2 * n)];
for (int i = 0; i < dp.length; i++)
Arrays.fill(dp[i], INF);
dp[0][0] = 0;
for (int i = 0; i < dp.length - 1; i++) {
int maxNewMask = (1 << Math.min(2 * n, n * m - i)) - 1;
for (int mask = 0; mask < dp[i].length; mask++)
if (dp[i][mask] != INF) {
//System.err.println(i + " " + mask + " " + dp[i][mask]);
if ((mask & 1) == 1) // already covered, skip
dp[i + 1][mask >> 1] = Math.min(dp[i + 1][mask >> 1],
dp[i][mask]);
// place on this tile
int newMask = mask >> 1;
if (i % n != n - 1)
newMask |= 1;
newMask |= 1 << (n - 1);
newMask &= maxNewMask;
dp[i + 1][newMask] = Math.min(dp[i + 1][newMask],
dp[i][mask] + 1);
if (i % n != n - 1) {// place on next tile
newMask = mask >> 1;
newMask |= 1;
if (i % n != n - 2)
newMask |= 2;
newMask |= (1 << n);
newMask &= maxNewMask;
dp[i + 1][newMask] = Math.min(dp[i + 1][newMask],
dp[i][mask] + 1);
}
// place on lower tile
if (i + n < n * m) {
newMask = mask >> 1;
newMask |= 1 << (n - 1);
if (i % n != 0)
newMask |= 1 << (n - 2);
if (i % n != n - 1)
newMask |= 1 << n;
newMask |= 1 << (2 * n - 1);
newMask &= maxNewMask;
dp[i + 1][newMask] = Math.min(dp[i + 1][newMask],
dp[i][mask] + 1);
}
}
}
out.print(n * m - dp[n * m][0]);
}
void inp() 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 C().inp();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "0";
}
}
return st.nextToken();
}
String nextString() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "0";
}
}
return st.nextToken("\n");
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.util.List;
public class Main {
private static StringTokenizer st;
private static BufferedReader br;
public static long MOD = 1000000007;
public static long tenFive = 100000;
public static int INF = 100000;
public static void print(Object x) {
System.out.println(x + "");
}
public static void printArr(long[] x) {
StringBuilder s = new StringBuilder();
for (int i = 0; i < x.length; i++) {
s.append(x[i] + " ");
}
print(s);
}
public static void printArr(int[] x) {
StringBuilder s = new StringBuilder();
for (int i = 0; i < x.length; i++) {
s.append(x[i] + " ");
}
print(s);
}
public static String join(Collection<?> x, String space) {
if (x.size() == 0) return "";
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object elt : x) {
if (first) first = false;
else sb.append(space);
sb.append(elt);
}
return sb.toString();
}
public static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
st = new StringTokenizer(line.trim());
}
return st.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public static List<Integer> nextInts(int N) throws IOException {
List<Integer> ret = new ArrayList<Integer>();
for (int i = 0; i < N; i++) {
ret.add(nextInt());
}
return ret;
}
public static void solve(int a, int b, List<Integer> orig) {
boolean swap = false;
if (a > b) {
swap = true;
int tmp = a;
a = b;
b = tmp;
}
List<Integer> nums = new ArrayList<Integer>(orig);
Collections.sort(nums);
Collections.reverse(nums);
Set<Integer> all = new HashSet<Integer>(nums);
Set<Integer> done = new HashSet<Integer>();
Set<Integer> inB = new HashSet<Integer>();
for (int x : nums) {
if (done.contains(x)) continue;
if (all.contains(a - x) && !done.contains(a - x)) {
done.add(x);
done.add(a - x);
//print(x + " " + (a - x));
} else if (all.contains(b - x) && !done.contains(b - x)) {
done.add(x);
done.add(b - x);
inB.add(x);
inB.add(b - x);
} else {
print("NO");
return;
}
}
print("YES");
List<Integer> out = new ArrayList<Integer>();
for (int x : orig) {
if (inB.contains(x) ^ swap) out.add(1);
else out.add(0);
}
print(join(out, " "));
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
int n = nextInt();
int a = nextInt();
int b = nextInt();
List<Integer> nums = nextInts(n);
solve(a, b, nums);
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.util.Scanner;
public class HammingDistancesSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine(), b = sc.nextLine();
long sum = 0;
int frequency[][] = new int[200010][2];
for (int i = 1; i <= b.length(); i++) {
for (int j = 0; j < 2; j++)
frequency[i][j] = frequency[i - 1][j];
frequency[i][Character.getNumericValue((b.charAt(i - 1)))]++;
}
for (int i = 0; i < a.length(); i++) {
int c = Character.getNumericValue(a.charAt(i));
for (int j = 0; j < 2; j++) {
int flippingTerm = Math.abs(c - j);
int endOfWindowValue = frequency[b.length() - a.length() + i + 1][j];
int startOfWindowOffset = frequency[i][j];
sum += flippingTerm * (endOfWindowValue - startOfWindowOffset);
}
}
System.out.println(sum);
sc.close();
}
}
|
linear
|
608_B. Hamming Distance Sum
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.InputMismatchException;
public class R111_D2_A {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
// BufferedReader in = new BufferedReader(new
// InputStreamReader(System.in));
int n = in.readInt();
int[] inp = new int[n];
for (int i = 0; i < inp.length; i++) {
inp[i] = in.readInt();
}
Arrays.sort(inp);
int sum1 = 0;
int res = 0;
for (int i = inp.length - 1; i >= 0; i--) {
sum1 += inp[i];
res++;
int sum2 = 0;
for (int j = 0; j < i; j++) {
sum2 += inp[j];
}
if (sum1 > sum2) {
break;
}
}
System.out.println(res);
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1000];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Built using CHelper plug-in Actual solution is at the top
*/
public class Practice {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
String[] arr1 = new String[n];
String[] arr2 = new String[n];
for (int i = 0; i < n; i++) {
arr1[i] = in.next();
}
for (int i = 0; i < n; i++) {
arr2[i] = in.next();
}
int ans = 0;
boolean arr[]=new boolean[n];
boolean found=false;
for (int i = 0; i < arr1.length; i++) {
for(int j=0;j<arr1.length;j++){
found=false;
if(arr1[i].equals(arr2[j]) && !arr[j]){
found=true;
arr[j]=true;
break;
}
}
if(!found){
ans++;
}
}
out.println(ans);
}
}
public static boolean checkPrime(int n, int p) {
for (int i = 2; i <= Math.sqrt(n) && i <= p; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void mergeArrays(int[] arr1, int[] arr2, int n1,
int n2, int[] arr3) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j]) {
arr3[k++] = arr1[i++];
} else {
arr3[k++] = arr2[j++];
}
}
while (i < n1) {
arr3[k++] = arr1[i++];
}
while (j < n2) {
arr3[k++] = arr2[j++];
}
}
public long GCD(long a, long b) {
if (b == 0) {
return a;
}
return GCD(b, a % b);
}
public static long nCr(int n, int r) {
return n * (n - 1) / 2;
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
quadratic
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastReader in, PrintWriter out) {
Debug debug = new Debug(out);
int n = in.nextInt();
TaskC.Circle[] c = new TaskC.Circle[n];
double rr = in.nextInt();
for (int i = 0; i < n; ++i) {
c[i] = new TaskC.Circle();
c[i].x = in.nextInt();
}
ArrayList<TaskC.Circle> done = new ArrayList<>();
for (int i = 0; i < n; ++i) {
TaskC.Circle cur = c[i];
double ans = Double.MIN_VALUE;
for (int j = 0; j < done.size(); ++j) {
TaskC.Circle dd = done.get(j);
if (Double.compare(2 * rr, Math.abs(dd.x - cur.x)) < 0) continue;
double temp = Math.sqrt(4 * rr * rr - (cur.x - dd.x) * (cur.x - dd.x)) + dd.y;
ans = Math.max(ans, temp);
}
if (ans == Double.MIN_VALUE)
ans = rr;
cur.y = ans;
done.add(cur);
}
for (TaskC.Circle cc : done) {
out.printf("%.12f ", cc.y);
}
}
static class Circle implements Comparable<TaskC.Circle> {
double x;
double y;
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (o.getClass() != this.getClass()) return false;
TaskC.Circle c = (TaskC.Circle) o;
return Double.compare(x, c.x) == 0 && Double.compare(y, c.y) == 0;
}
public int compareTo(TaskC.Circle o) {
if (Double.compare(o.x, x) != 0) {
return Double.compare(x, o.x);
}
return Double.compare(y, o.y);
}
}
}
static class Debug {
PrintWriter out;
boolean oj;
long timeBegin;
Runtime runtime;
public Debug(PrintWriter out) {
oj = System.getProperty("ONLINE_JUDGE") != null;
this.out = out;
this.timeBegin = System.currentTimeMillis();
this.runtime = Runtime.getRuntime();
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int size = Integer.parseInt(keyboard.nextLine());
int[] arr = new int[size];
int i = 0;
while( size != 0 )
{
arr[i] = keyboard.nextInt();
size--;
i++;
}
if( arr.length == 1 )
{
System.out.println("NO");
}
else
{
Arrays.sort(arr);
boolean val = false;
int ans = 0;
for ( i = 0; i< arr.length-1 ; i++ )
{
if( arr[i] != arr[i+1] )
{
val = true;
ans = arr[i+1];
System.out.println(ans);
i = arr.length;
}
else if( i == arr.length-2 ) //val == false
{
System.out.println("NO");
}
}
}
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main implements Runnable {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new Main(),"Main",1<<26).start();
}
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = sc.nextInt();
long d = sc.nextLong();
long a[] = new long[n];
for(int i = 0; i < n; ++i)
a[i] = sc.nextLong();
int ans = 0;
for(int i = 1; i < n; ++i) {
if(a[i] - a[i - 1] > 2 * d)
ans += 2;
else if(a[i] - a[i - 1] == 2 * d)
ans++;
}
ans += 2;
w.print(ans);
w.close();
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
/*
* DA-IICT
* Author: Jugal Kalal
*/
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.DecimalFormat;
public class Practice{
static long MOD=(long)Math.pow(10,9)+7;
public static void main(String args[]) {
new Thread(null, new Runnable() {
public void run() {
try{
solve();
w.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
static InputReader in;
static PrintWriter w;
static void solve(){
in = new InputReader(System.in);
w = new PrintWriter(System.out);
long n=in.nextLong();
long s=in.nextLong();
long low=1,high=n,ans=-1;
while(low<=high){
long mid=(low+high)/2;
if(check(mid,s)){
ans=mid;
high=mid-1;
}else{
low=mid+1;
}
}
if(ans==-1){
w.println(0);
}else
w.println(n-ans+1);
}
static boolean check(long n,long s){
long temp=n;
long sum=0;
while(temp>0){
sum+=temp%10;
temp=temp/10;
}
if(n-sum>=s){
return true;
}
return false;
}
static int adj[][];
// static ArrayList<Integer> adj[]; //Adjacency Lists
static int V; // No. of vertices
// Constructor
static void Graph(int v){
V = v;
adj=new int[v][v];
// adj = new ArrayList[v];
// for (int i=0; i<v; ++i){
// adj[i] = new ArrayList();
// }
}
// Function to add an edge into the graph
static void addEdge(int u,int v,int w){
// adj[u].add(v);
// adj[v].add(u);
adj[u][v]=w;
}
// static void bfs(int s,int n){
// boolean visited[]=new boolean[n];
// LinkedList<Integer> queue=new LinkedList<Integer>();
// queue.add(s);
// visited[s]=true;
// while(!queue.isEmpty()){
// int num=queue.pop();
//// System.out.println(ans.toString());
// for(int i=0;i<adj[num].size();i++){
// if(!visited[adj[num].get(i)]){
// visited[adj[num].get(i)]=true;
// queue.add(adj[num].get(i));
// }
// }
// }
// }
static long gcd(long a,long b){
if(a==0){
return b;
}
return gcd(b%a,a);
}
static long power(long base, long exponent, long modulus){
long result = 1L;
while (exponent > 0) {
if (exponent % 2L == 1L)
result = (result * base) % modulus;
exponent = exponent >> 1;
base = (base * base) % modulus;
}
return result;
}
static HashMap<Long,Long> primeFactors(long n){
HashMap<Long,Long> ans=new HashMap<Long,Long>();
// Print the number of 2s that divide n
while (n%2L==0L)
{
if(ans.containsKey(2L)){
ans.put(2L,ans.get(2L)+1L);
}else{
ans.put(2L,1L);
}
n /= 2L;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (long i = 3; i <= Math.sqrt(n); i+= 2L)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
if(ans.containsKey(i)){
ans.put(i,ans.get(i)+1L);
}else{
ans.put(i,1L);
}
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
ans.put(n,1L);
return ans;
}
////for marking all prime numbers greater than 1 and less than equal to N
static void sieve(int N) {
boolean isPrime[]=new boolean[N+1];
isPrime[0] = true;
isPrime[1] = true;
for(int i = 2; i * i <= N; ++i) {
if(isPrime[i] == false) {//Mark all the multiples of i as composite numbers
for(int j = i * i; j <= N ;j += i)
isPrime[j] = true;
}
}
}
// //if str2 (pattern) is subsequence of str1 (Text) or not
// static boolean function(String str1,String str2){
// str2 = str2.replace("", ".*"); //returns .*a.*n.*n.*a.
// return (str1.matches(str2)); // returns true
// }
static int Arr[];
static long size[];
//modified initialize function:
static void initialize(int N){
Arr=new int[N];
size=new long[N];
for(int i = 0;i<N;i++){
Arr[ i ] = i ;
size[ i ] = 1;
}
}
static boolean find(int A,int B){
if( root(A)==root(B) ) //if A and B have same root,means they are connected.
return true;
else
return false;
}
// modified root function.
static void weighted_union(int A,int B,int n){
int root_A = root(A);
int root_B = root(B);
if(size[root_A] < size[root_B ]){
Arr[ root_A ] = Arr[root_B];
size[root_B] += size[root_A];
}
else{
Arr[ root_B ] = Arr[root_A];
size[root_A] += size[root_B];
}
}
static int root (int i){
while(Arr[ i ] != i){
Arr[ i ] = Arr[ Arr[ i ] ] ;
i = Arr[ i ];
}
return i;
}
static boolean isPrime(long n) {
if(n < 2L) return false;
if(n == 2L || n == 3L) return true;
if(n%2L == 0 || n%3L == 0) return false;
long sqrtN = (long)Math.sqrt(n)+1L;
for(long i = 6L; i <= sqrtN; i += 6L) {
if(n%(i-1) == 0 || n%(i+1) == 0) return false;
}
return true;
}
// static HashMap<Integer,Integer> level;;
// static HashMap<Integer,Integer> parent;
static int maxlevel=0;
// static boolean T[][][];
// static void subsetSum(int input[], int total, int count) {
// T = new boolean[input.length + 1][total + 1][count+1];
// for (int i = 0; i <= input.length; i++) {
// T[i][0][0] = true;
// for(int j = 1; j<=count; j++){
// T[i][0][j] = false;
// }
// }
// int sum[]=new int[input.length+1];
// for(int i=1;i<=input.length;i++){
// sum[i]=sum[i-1]+input[i-1];
// }
// for (int i = 1; i <= input.length; i++) {
// for (int j = 1; j <= (int)Math.min(total,sum[i]); j++) {
// for (int k = 1; k <= (int)Math.min(i,count); k++){
// if (j >= input[i - 1]) {//Exclude and Include
// T[i][j][k] = T[i - 1][j][k] || T[i - 1][j - input[i - 1]][k-1];
// } else {
// T[i][j][k] = T[i-1][j][k];
// }
// }
// }
// }
// }
// static <K,V extends Comparable<? super V>>
// SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
// SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
// new Comparator<Map.Entry<K,V>>() {
// @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
// int res = e2.getValue().compareTo(e1.getValue());
// return res != 0 ? res : 1;
// }
// }
// );
// sortedEntries.addAll(map.entrySet());
// return sortedEntries;
// }
//minimum prime factor of all the numbers less than n
static int minPrime[];
static void minimumPrime(int n){
minPrime=new int[n+1];
minPrime[1]=1;
for (int i = 2; i * i <= n; ++i) {
if (minPrime[i] == 0) { //If i is prime
for (int j = i * i; j <= n; j += i) {
if (minPrime[j] == 0) {
minPrime[j] = i;
}
}
}
}
for (int i = 2; i <= n; ++i) {
if (minPrime[i] == 0) {
minPrime[i] = i;
}
}
}
static long modInverse(long A, long M)
{
long x=extendedEuclid(A,M)[0];
return (x%M+M)%M; //x may be negative
}
static long[] extendedEuclid(long A, long B) {
if(B == 0) {
long d = A;
long x = 1;
long y = 0;
return new long[]{x,y,d};
}
else {
long arr[]=extendedEuclid(B, A%B);
long temp = arr[0];
arr[0] = arr[1];
arr[1] = temp - (A/B)*arr[1];
return arr;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public 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);
}
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
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 static void main(String[] args) {
// InputStream inputStream = System.in; // Useful when taking input other than
// console eg file handling // check ctor of inputReader
InputReader scn = new InputReader();
int n = scn.nextInt(), r = scn.nextInt();
double[] y = new double[n];
int[] x = new int[n];
boolean[] mark = new boolean[n];
for(int i = 0; i < n; i++) {
x[i] = scn.nextInt();
}
for(int i = 0; i < n; i++) {
double yc = r;
for(int j = 0; j < n; j++) {
if(i == j || !mark[j]) {
continue;
}
if(x[i] + r < x[j] - r || x[i] - r > x[j] + r) {
continue;
}
yc = Math.max(yc, y[j] + Math.sqrt(Math.abs(Math.pow(x[i] - x[j], 2) - 4 * r * r)));
}
y[i] = yc;
mark[i] = true;
}
for(int i = 0; i < n; i++) {
System.out.print(y[i] + " ");
}
System.out.println();
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
/*
Author: Anthony Ngene
Created: 05/10/2020 - 14:12
*/
import java.io.*;
import java.util.*;
public class F {
// checks: 1. edge cases 2. overflow 3. possible errors (e.g 1/0, arr[out]) 4. time/space complexity
void solver() throws IOException {
int n = in.intNext();
int[] arr = in.nextIntArray(n);
HashMap<Integer, Deque<Tuple>> subSum = new HashMap<>();
Integer best = null;
for (int i = 0; i < n; i++) {
int total = 0;
for (int j = i; j < n; j++) {
total += arr[j];
if (!subSum.containsKey(total)) subSum.put(total, new ArrayDeque<>());
Deque<Tuple> rs = subSum.get(total);
if (rs.size() > 0 && rs.peekLast().b > j) rs.pollLast();
if (rs.size() == 0 || rs.peekLast().b < i)
rs.add(new Tuple(i, j));
if (best == null || rs.size() > subSum.get(best).size())
best = total;
}
}
Deque<Tuple> bestList = subSum.get(best);
out.println(bestList.size());
for (Tuple aa: bestList)
out.pp(aa.a + 1, aa.b + 1);
}
// Generated Code Below:
private static final FastWriter out = new FastWriter();
private static FastScanner in;
static ArrayList<Integer>[] adj;
private static long e97 = (long)1e9 + 7;
public static void main(String[] args) throws IOException {
in = new FastScanner();
new F().solver();
out.close();
}
static class FastWriter {
private static final int IO_BUFFERS = 128 * 1024;
private final StringBuilder out;
public FastWriter() { out = new StringBuilder(IO_BUFFERS); }
public FastWriter p(Object object) { out.append(object); return this; }
public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; }
public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(int[] args) { for (int ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(long[] args) { for (long ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(char[] args) { for (char ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public void println(long[] arr) { for(long e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(int[] arr) { for(int e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(char[] arr) { for(char e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(double[] arr) { for(double e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(boolean[] arr) { for(boolean e: arr) out.append(e).append(" "); out.append("\n"); }
public <T>void println(T[] arr) { for(T e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(long[][] arr) { for (long[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(int[][] arr) { for (int[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(char[][] arr) { for (char[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(double[][] arr) { for (double[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public <T>void println(T[][] arr) { for (T[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public FastWriter println(Object object) { out.append(object).append("\n"); return this; }
public void toFile(String fileName) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(out.toString());
writer.close();
}
public void close() throws IOException { System.out.print(out); }
}
static class FastScanner {
private InputStream sin = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
public FastScanner(){}
public FastScanner(String filename) throws FileNotFoundException {
File file = new File(filename);
sin = new FileInputStream(file);
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = sin.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long longNext() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while(true){
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
}else if(b == -1 || !isPrintableChar(b) || b == ':'){
return minus ? -n : n;
}else{
throw new NumberFormatException();
}
b = readByte();
}
}
public int intNext() {
long nl = longNext();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double doubleNext() { return Double.parseDouble(next());}
public long[] nextLongArray(final int n){
final long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = longNext();
return a;
}
public int[] nextIntArray(final int n){
final int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = intNext();
return a;
}
public double[] nextDoubleArray(final int n){
final double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = doubleNext();
return a;
}
public ArrayList<Integer>[] getAdj(int n) {
ArrayList<Integer>[] adj = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();
return adj;
}
public ArrayList<Integer>[] adjacencyList(int nodes, int edges) throws IOException {
return adjacencyList(nodes, edges, false);
}
public ArrayList<Integer>[] adjacencyList(int nodes, int edges, boolean isDirected) throws IOException {
adj = getAdj(nodes);
for (int i = 0; i < edges; i++) {
int a = intNext(), b = intNext();
adj[a].add(b);
if (!isDirected) adj[b].add(a);
}
return adj;
}
}
static class u {
public static int upperBound(long[] array, long obj) {
int l = 0, r = array.length - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj < array[c]) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int upperBound(ArrayList<Long> array, long obj) {
int l = 0, r = array.size() - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj < array.get(c)) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int lowerBound(long[] array, long obj) {
int l = 0, r = array.length - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj <= array[c]) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int lowerBound(ArrayList<Long> array, long obj) {
int l = 0, r = array.size() - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj <= array.get(c)) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
static <T> T[][] deepCopy(T[][] matrix) { return Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone()); }
static int[][] deepCopy(int[][] matrix) { return Arrays.stream(matrix).map(int[]::clone).toArray($ -> matrix.clone()); }
static long[][] deepCopy(long[][] matrix) { return Arrays.stream(matrix).map(long[]::clone).toArray($ -> matrix.clone()); }
private static void sort(int[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
private static void sort(long[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
private static <T>void rSort(T[] arr) { Arrays.sort(arr, Collections.reverseOrder()); }
private static void customSort(int[][] arr) {
Arrays.sort(arr, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a[0] == b[0]) return Integer.compare(a[1], b[1]);
return Integer.compare(a[0], b[0]);
}
});
}
public static int[] swap(int[] arr, int left, int right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
return arr;
}
public static char[] swap(char[] arr, int left, int right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
return arr;
}
public static int[] reverse(int[] arr, int left, int right) {
while (left < right) {
int temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return arr;
}
public static boolean findNextPermutation(int[] data) {
if (data.length <= 1) return false;
int last = data.length - 2;
while (last >= 0) {
if (data[last] < data[last + 1]) break;
last--;
}
if (last < 0) return false;
int nextGreater = data.length - 1;
for (int i = data.length - 1; i > last; i--) {
if (data[i] > data[last]) {
nextGreater = i;
break;
}
}
data = swap(data, nextGreater, last);
data = reverse(data, last + 1, data.length - 1);
return true;
}
public static int biSearch(int[] dt, int target){
int left=0, right=dt.length-1;
int mid=-1;
while(left<=right){
mid = (right+left)/2;
if(dt[mid] == target) return mid;
if(dt[mid] < target) left=mid+1;
else right=mid-1;
}
return -1;
}
public static int biSearchMax(long[] dt, long target){
int left=-1, right=dt.length;
int mid=-1;
while((right-left)>1){
mid = left + (right-left)/2;
if(dt[mid] <= target) left=mid;
else right=mid;
}
return left;
}
public static int biSearchMaxAL(ArrayList<Integer> dt, long target){
int left=-1, right=dt.size();
int mid=-1;
while((right-left)>1){
mid = left + (right-left)/2;
if(dt.get(mid) <= target) left=mid;
else right=mid;
}
return left;
}
private static <T>void fill(T[][] ob, T res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(boolean[][] ob,boolean res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(int[][] ob, int res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(long[][] ob, long res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(char[][] ob, char res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(double[][] ob, double res){for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(int[][][] ob,int res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static void fill(long[][][] ob,long res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static <T>void fill(T[][][] ob,T res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static void fill_parent(int[] ob){ for(int i=0; i<ob.length; i++) ob[i]=i; }
private static boolean same3(long a, long b, long c){
if(a!=b) return false;
if(b!=c) return false;
if(c!=a) return false;
return true;
}
private static boolean dif3(long a, long b, long c){
if(a==b) return false;
if(b==c) return false;
if(c==a) return false;
return true;
}
private static double hypotenuse(double a, double b){
return Math.sqrt(a*a+b*b);
}
private static long factorial(int n) {
long ans=1;
for(long i=n; i>0; i--){ ans*=i; }
return ans;
}
private static long facMod(int n, long mod) {
long ans=1;
for(long i=n; i>0; i--) ans = (ans * i) % mod;
return ans;
}
private static long lcm(long m, long n){
long ans = m/gcd(m,n);
ans *= n;
return ans;
}
private static long gcd(long m, long n) {
if(m < n) return gcd(n, m);
if(n == 0) return m;
return gcd(n, m % n);
}
private static boolean isPrime(long a){
if(a==1) return false;
for(int i=2; i<=Math.sqrt(a); i++){ if(a%i == 0) return false; }
return true;
}
static long modInverse(long a, long mod) {
/* Fermat's little theorem: a^(MOD-1) => 1
Therefore (divide both sides by a): a^(MOD-2) => a^(-1) */
return binpowMod(a, mod - 2, mod);
}
static long binpowMod(long a, long b, long mod) {
long res = 1;
while (b > 0) {
if (b % 2 == 1) res = (res * a) % mod;
a = (a * a) % mod;
b /= 2;
}
return res;
}
private static int getDigit2(long num){
long cf = 1; int d=0;
while(num >= cf){ d++; cf = 1<<d; }
return d;
}
private static int getDigit10(long num){
long cf = 1; int d=0;
while(num >= cf){ d++; cf*=10; }
return d;
}
private static boolean isInArea(int y, int x, int h, int w){
if(y<0) return false;
if(x<0) return false;
if(y>=h) return false;
if(x>=w) return false;
return true;
}
private static ArrayList<Integer> generatePrimes(int n) {
int[] lp = new int[n + 1];
ArrayList<Integer> pr = new ArrayList<>();
for (int i = 2; i <= n; ++i) {
if (lp[i] == 0) {
lp[i] = i;
pr.add(i);
}
for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n; ++j) {
lp[i * pr.get(j)] = pr.get(j);
}
}
return pr;
}
static long nPrMod(int n, int r, long MOD) {
long res = 1;
for (int i = (n - r + 1); i <= n; i++) {
res = (res * i) % MOD;
}
return res;
}
static long nCr(int n, int r) {
if (r > (n - r))
r = n - r;
long ans = 1;
for (int i = 1; i <= r; i++) {
ans *= n;
ans /= i;
n--;
}
return ans;
}
static long nCrMod(int n, int r, long MOD) {
long rFactorial = nPrMod(r, r, MOD);
long first = nPrMod(n, r, MOD);
long second = binpowMod(rFactorial, MOD-2, MOD);
return (first * second) % MOD;
}
static void printBitRepr(int n) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < 32; i++) {
int mask = (1 << i);
res.append((mask & n) == 0 ? "0" : "1");
}
out.println(res);
}
static String bitString(int n) {return Integer.toBinaryString(n);}
static int setKthBitToOne(int n, int k) { return (n | (1 << k)); } // zero indexed
static int setKthBitToZero(int n, int k) { return (n & ~(1 << k)); }
static int invertKthBit(int n, int k) { return (n ^ (1 << k)); }
static boolean isPowerOfTwo(int n) { return (n & (n - 1)) == 0; }
static HashMap<Character, Integer> counts(String word) {
HashMap<Character, Integer> counts = new HashMap<>();
for (int i = 0; i < word.length(); i++) counts.merge(word.charAt(i), 1, Integer::sum);
return counts;
}
static HashMap<Integer, Integer> counts(int[] arr) {
HashMap<Integer, Integer> counts = new HashMap<>();
for (int value : arr) counts.merge(value, 1, Integer::sum);
return counts;
}
static HashMap<Long, Integer> counts(long[] arr) {
HashMap<Long, Integer> counts = new HashMap<>();
for (long l : arr) counts.merge(l, 1, Integer::sum);
return counts;
}
static HashMap<Character, Integer> counts(char[] arr) {
HashMap<Character, Integer> counts = new HashMap<>();
for (char c : arr) counts.merge(c, 1, Integer::sum);
return counts;
}
static long hash(int x, int y) {
return x* 1_000_000_000L +y;
}
static final Random random = new Random();
static void sort(int[] a) {
int n = a.length;// shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void sort(long[] arr) {
shuffleArray(arr);
Arrays.sort(arr);
}
static void shuffleArray(long[] arr) {
int n = arr.length;
for(int i=0; i<n; ++i){
long tmp = arr[i];
int randomPos = i + random.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
}
static class Tuple implements Comparable<Tuple> {
int a;
int b;
int c;
public Tuple(int a, int b) {
this.a = a;
this.b = b;
this.c = 0;
}
public Tuple(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public int getA() { return a; }
public int getB() { return b; }
public int getC() { return c; }
public int compareTo(Tuple other) {
if (this.a == other.a) {
if (this.b == other.b) return Long.compare(this.c, other.c);
return Long.compare(this.b, other.b);
}
return Long.compare(this.a, other.a);
}
@Override
public int hashCode() { return Arrays.deepHashCode(new Integer[]{a, b, c}); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Tuple)) return false;
Tuple pairo = (Tuple) o;
return (this.a == pairo.a && this.b == pairo.b && this.c == pairo.c);
}
@Override
public String toString() { return String.format("(%d %d %d) ", this.a, this.b, this.c); }
}
private static int abs(int a){ return (a>=0) ? a: -a; }
private static int min(int... ins){ int min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static int max(int... ins){ int max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static int sum(int... ins){ int total = 0; for (int v : ins) { total += v; } return total; }
private static long abs(long a){ return (a>=0) ? a: -a; }
private static long min(long... ins){ long min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static long max(long... ins){ long max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static long sum(long... ins){ long total = 0; for (long v : ins) { total += v; } return total; }
private static double abs(double a){ return (a>=0) ? a: -a; }
private static double min(double... ins){ double min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static double max(double... ins){ double max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static double sum(double... ins){ double total = 0; for (double v : ins) { total += v; } return total; }
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
// package CF1141;
import java.io.*;
import java.util.*;
public class CF1141F1 {
static FastReader s;
static PrintWriter out;
static String INPUT = "7\n" +
"4 1 2 2 1 5 3\n";
public static void main(String[] args) {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
s = new FastReader(oj);
int n = s.nextInt();
int[] arr = s.nextIntArray(n);
int[] sum = new int[n];
sum[0] = arr[0];
for (int i = 1; i < n; i++) {
sum[i] = sum[i - 1] + arr[i];
}
// int max = Integer.MIN_VALUE;
HashMap<Integer, ArrayList<pair>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if(i == 0) {
ArrayList<pair> list = map.getOrDefault(sum[j], new ArrayList<>());
list.add(new pair(i, j));
map.put(sum[j], list);
} else {
ArrayList<pair> list = map.getOrDefault(sum[j] - sum[i - 1], new ArrayList<>());
list.add(new pair(i, j));
map.put(sum[j] - sum[i - 1], list);
}
}
}
ArrayList<Integer> keys = new ArrayList<>(map.keySet());
ArrayList<pair> ans = null;
for (int curr : keys) {
ArrayList<pair> list = map.get(curr);
Collections.sort(list);
ArrayList<pair> smallAns = new ArrayList<>();
smallAns.add(list.get(0));
for (int k = 1; k < list.size(); k++) {
if(list.get(k).start > smallAns.get(smallAns.size() - 1).finish) {
smallAns.add(list.get(k));
}
}
if(ans == null) {
ans = smallAns;
} else {
if(ans.size() < smallAns.size()) {
ans = smallAns;
}
}
}
// out.println(ans.size() + "\n" + ans);
//
// out.println(map);
//
// out.println(Arrays.toString(sum));
StringBuilder ans1 = new StringBuilder();
ans1.append(ans.size() + "\n");
for (pair p : ans) {
ans1.append((p.start + 1) + " " + (p.finish + 1));
ans1.append("\n");
}
out.println(ans1);
if (!oj) {
System.out.println(Arrays.deepToString(new Object[]{System.currentTimeMillis() - time + " ms"}));
}
out.flush();
}
private static class pair implements Comparable<pair>{
int start;
int finish;
public pair(int start, int finish) {
this.start = start;
this.finish = finish;
}
@Override
public int compareTo(pair o) {
return Integer.compare(this.finish, o.finish);
}
@Override
public String toString() {
return this.start + " " + this.finish;
}
}
private static class Matrix {
static long[][] I;
static long mod = 1000000007;
public static long[][] exp(long[][] M, long n) {
if (n <= 0) {
I = new long[M.length][M.length];
for (int i = 0; i < M.length; i++) {
I[i][i] = 1L;
}
return I;
}
if (n == 1) return M;
long[][] res = exp(M, n / 2);
res = mult(res, res);
if (n % 2 == 0) return res;
return mult(res, M);
}
public static long[][] mult(long[][] p, long[][] q) {
long[][] r = new long[p.length][q[0].length];
for (int i = 0; i < p.length; i++)
for (int j = 0; j < q[0].length; j++)
for (int k = 0; k < q.length; k++) {
r[i][j] += p[i][k] * q[k][j];
r[i][j] %= mod;
}
return r;
}
}
private static class Maths {
static ArrayList<Long> printDivisors(long n) {
// Note that this loop runs till square root
ArrayList<Long> list = new ArrayList<>();
for (long i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
if (n / i == i) {
list.add(i);
} else {
list.add(i);
list.add(n / i);
}
}
}
return list;
}
// GCD - Using Euclid theorem.
private static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
// Extended euclidean algorithm
// Used to solve equations of the form ax + by = gcd(a,b)
// return array [d, a, b] such that d = gcd(p, q), ap + bq = d
static long[] extendedEuclidean(long p, long q) {
if (q == 0)
return new long[]{p, 1, 0};
long[] vals = extendedEuclidean(q, p % q);
long d = vals[0];
long a = vals[2];
long b = vals[1] - (p / q) * vals[2];
return new long[]{d, a, b};
}
// X ^ y mod p
static long power(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
// Returns modulo inverse of a
// with respect to m using extended
// Euclid Algorithm. Refer below post for details:
// https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
static long inv(long a, long m) {
long m0 = m, t, q;
long x0 = 0, x1 = 1;
if (m == 1)
return 0;
// Apply extended Euclid Algorithm
while (a > 1) {
q = a / m;
t = m;
m = a % m;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
// Make x1 positive
if (x1 < 0)
x1 += m0;
return x1;
}
// k is size of num[] and rem[].
// Returns the smallest number
// x such that:
// x % num[0] = rem[0],
// x % num[1] = rem[1],
// ..................
// x % num[k-2] = rem[k-1]
// Assumption: Numbers in num[] are pairwise
// coprime (gcd for every pair is 1)
static long findMinX(long num[], long rem[], long k) {
int prod = 1;
for (int i = 0; i < k; i++)
prod *= num[i];
int result = 0;
for (int i = 0; i < k; i++) {
long pp = prod / num[i];
result += rem[i] * inv(pp, num[i]) * pp;
}
return result % prod;
}
}
private static class BS {
// Binary search
private static int binarySearch(int[] arr, int ele) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == ele) {
return mid;
} else if (ele < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
// First occurence using binary search
private static int binarySearchFirstOccurence(int[] arr, int ele) {
int low = 0;
int high = arr.length - 1;
int ans = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == ele) {
ans = mid;
high = mid - 1;
} else if (ele < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
// Last occurenece using binary search
private static int binarySearchLastOccurence(int[] arr, int ele) {
int low = 0;
int high = arr.length - 1;
int ans = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == ele) {
ans = mid;
low = mid + 1;
} else if (ele < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
}
private static class arrays {
// Merge sort
static void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
static void sort(int arr[], int l, int r) {
if (l < r) {
int m = (l + r) / 2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
static void sort(int[] arr) {
sort(arr, 0, arr.length - 1);
}
}
private static class UnionFindDisjointSet {
int[] parent;
int[] size;
int n;
int size1;
public UnionFindDisjointSet(int n) {
this.n = n;
this.parent = new int[n];
this.size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
for (int i = 0; i < n; i++) {
size[i] = 1;
}
this.size1 = n;
}
private int numDisjointSets() {
System.out.println(size1);
return size1;
}
private boolean find(int a, int b) {
int rootA = root(a);
int rootB = root(b);
if (rootA == rootB) {
return true;
}
return false;
}
private int root(int b) {
if (parent[b] != b) {
return parent[b] = root(parent[b]);
}
return b;
}
private void union(int a, int b) {
int rootA = root(a);
int rootB = root(b);
if (rootA == rootB) {
return;
}
if (size[rootA] < size[rootB]) {
parent[rootA] = parent[rootB];
size[rootB] += size[rootA];
} else {
parent[rootB] = parent[rootA];
size[rootA] += size[rootB];
}
size1--;
System.out.println(Arrays.toString(parent));
}
}
private static class SegTree {
int[] st;
int[] arr;
public SegTree(int[] arr) {
this.arr = arr;
int size = (int) Math.ceil(Math.log(arr.length) / Math.log(2));
st = new int[(int) ((2 * Math.pow(2, size)) - 1)];
buildSegmentTree(1, 0, arr.length - 1);
}
//**********JUST CALL THE CONSTRUCTOR, THIS FUNCTION WILL BE CALLED AUTOMATICALLY******
private void buildSegmentTree(int index, int L, int R) {
if (L == R) {
st[index] = arr[L];
return;
}
buildSegmentTree(index * 2, L, (L + R) / 2);
buildSegmentTree(index * 2 + 1, (L + R) / 2 + 1, R);
// Replace this line if you want to change the function of the Segment tree.
st[index] = Math.min(st[index * 2], st[index * 2 + 1]);
}
//***********We have to use this function **************
private int Query(int queL, int queR) {
return Query1(1, 0, arr.length - 1, queL, queR);
}
//This is a helper function.
//************* DO NOT USE THIS ****************
private int Query1(int index, int segL, int segR, int queL, int queR) {
if (queL > segR || queR < segL) {
return -1;
}
if (queL <= segL && queR >= segR) {
return st[index];
}
int ans1 = Query1(index * 2, segL, (segL + segR) / 2, queL, queR);
int ans2 = Query1(index * 2 + 1, (segL + segR) / 2 + 1, segR, queL, queR);
if (ans1 == -1) {
return ans2;
}
if (ans2 == -1) {
return ans1;
}
// Segment tree implemented for range minimum query. Change the below line to change the function.
return Math.min(ans1, ans2);
}
private void update(int idx, int val) {
update1(1, 0, arr.length - 1, idx, val);
}
private void update1(int node, int queL, int queR, int idx, int val) {
// idx - index to be updated in the array
// node - index to be updated in the seg tree
if (queL == queR) {
// Leaf node
arr[idx] += val;
st[node] += val;
} else {
int mid = (queL + queR) / 2;
if (queL <= idx && idx <= mid) {
// If idx is in the left child, recurse on the left child
update1(2 * node, queL, mid, idx, val);
} else {
// if idx is in the right child, recurse on the right child
update1(2 * node + 1, mid + 1, queR, idx, val);
}
// Internal node will have the min of both of its children
st[node] = Math.min(st[2 * node], st[2 * node + 1]);
}
}
}
private static class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(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);
}
int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nextLong() {
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();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
int[] uniq(int[] arr) {
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.Scanner;
public class LuckyDivision{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
int a = input.nextInt();
if(a%4 == 0) System.out.println("YES");
else if(a%7 == 0) System.out.println("YES");
else if(a%47 == 0) System.out.println("YES");
else if(a%74 == 0) System.out.println("YES");
else if(a%447 == 0) System.out.println("YES");
else if(a%474 == 0) System.out.println("YES");
else if(a%477 == 0) System.out.println("YES");
else if(a%747 == 0) System.out.println("YES");
else if(a%774 == 0) System.out.println("YES");
else System.out.println("NO");
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
public static void main(String[] args)throws Throwable {
MyScanner sc=new MyScanner();
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
String [] s={"M","L","S","XL","XS","XXL","XXS","XXXL","XXXS"};
int [] cnt=new int [9];
for(int i=0;i<n;i++){
String t=sc.next();
for(int j=0;j<9;j++)
if(t.equals(s[j]))
cnt[j]++;
}
for(int i=0;i<n;i++){
String t=sc.next();
for(int j=0;j<9;j++)
if(t.equals(s[j]))
cnt[j]--;
}
for(int i=0;i<9;i++)
cnt[i]=Math.abs(cnt[i]);
int ans=0;
for(int i=0;i<9;i++)
ans+=cnt[i];
pw.println(ans/2);
pw.flush();
pw.close();
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}}
return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
String nextLine(){String str = "";
try {str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Solution
{
static long n, x, y, c;
static boolean can (long len)
{
BigInteger blen = BigInteger.valueOf(len);
//BigInteger sum = blen.multiply(blen.add(BigInteger.ONE)).multiply(blen.shiftLeft(1).add(BigInteger.ONE)).divide(BigInteger.valueOf(6));
BigInteger sum = BigInteger.ONE;
sum = sum.add(blen.multiply(blen.add(BigInteger.ONE)).shiftLeft(1));
long a1 = Math.max(0, len - x);
sum = sum.subtract(BigInteger.valueOf(a1).multiply(BigInteger.valueOf(a1)));
long a2 = Math.max(0, len - y);
sum = sum.subtract(BigInteger.valueOf(a2).multiply(BigInteger.valueOf(a2)));
long a3 = Math.max(0, len - (n - 1 - x));
sum = sum.subtract(BigInteger.valueOf(a3).multiply(BigInteger.valueOf(a3)));
long a4 = Math.max(0, len - (n - 1 - y));
sum = sum.subtract(BigInteger.valueOf(a4).multiply(BigInteger.valueOf(a4)));
if (y - a1 + 1 < 0)
{
long b1 = Math.abs(y - a1 + 1);
sum = sum.add(BigInteger.valueOf(b1).multiply(BigInteger.valueOf(b1 + 1)).shiftRight(1));
}
if (y - a3 + 1 < 0)
{
long b1 = Math.abs(y - a3 + 1);
sum = sum.add(BigInteger.valueOf(b1).multiply(BigInteger.valueOf(b1 + 1)).shiftRight(1));
}
if (y + a1 - 1 >= n)
{
long b1 = y + a1 - n;
sum = sum.add(BigInteger.valueOf(b1).multiply(BigInteger.valueOf(b1 + 1)).shiftRight(1));
}
if (y + a3 - 1 >= n)
{
long b1 = y + a3 - n;
sum = sum.add(BigInteger.valueOf(b1).multiply(BigInteger.valueOf(b1 + 1)).shiftRight(1));
}
return sum.compareTo(BigInteger.valueOf(c)) >= 0;
}
public static void main (String argv[])
{
Scanner in = new Scanner(System.in);
n = in.nextLong();
x = in.nextLong();
y = in.nextLong();
c = in.nextLong();
x--; y--;
long lf = 0, rg = 2 * 1000 * 1000 * 1000 + 3;
while (lf != rg)
{
long mid = (lf + rg) >> 1;
if (can(mid))
rg = mid;
else
lf = mid + 1;
}
System.out.println(lf);
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
import java.util.Scanner;
public class A {
public static final boolean DEBUG = false;
Scanner sc;
public void debug(Object o) {
if (DEBUG) {
int ln = Thread.currentThread().getStackTrace()[2].getLineNumber();
String fn = Thread.currentThread().getStackTrace()[2].getFileName();
System.out.println("(" + fn + ":" + ln+ "): " + o);
}
}
public void pln(Object o) {
System.out.println(o);
}
public void run() {
sc = new Scanner(System.in);
long a = sc.nextLong();
long b = sc.nextLong();
long nr = 0;
if (a < b) {
long aux = a;
a = b;
b = aux;
}
while (a != 0 && b != 0) {
nr += a / b;
long c = a % b;
a = b;
b = c;
}
pln(nr);
return;
}
public static void main(String[] args) {
A t = new A();
t.run();
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
/**
* author: derrick20
* created: 3/19/21 11:57 PM
*/
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class E2_SquareFreeDivision2 {
static FastScanner sc = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
// generate();
int T = sc.nextInt();
int MAX = (int) 1e7;
int[] canonical = new int[MAX + 1];
canonical[1] = 1;
for (int factor = 2; factor <= MAX; factor++) {
if (canonical[factor] == 0) {
for (int mult = factor; mult <= MAX; mult += factor) {
int prev = canonical[mult / factor];
if (prev % factor == 0) {
canonical[mult] = prev / factor;
} else {
canonical[mult] = prev * factor;
}
}
}
}
// System.out.println(Arrays.toString(canonical));
int[] freq = new int[MAX + 1];
while (T-->0) {
int N = sc.nextInt();
int K = sc.nextInt();
int[] a = new int[N + 1];
for (int i = 1; i <= N; i++) {
a[i] = canonical[sc.nextInt()];
}
int[][] transition = new int[K + 1][N + 1];
// HashMap<Integer, Integer> freq = new HashMap<>();
for (int k = 0; k <= K; k++) {
int l = N + 1;
int duplicates = 0;
for (int r = N; r >= 1; r--) {
while (l - 1 >= 1) {
int nextDuplicates = duplicates;
if (freq[a[l - 1]] >= 1) {
nextDuplicates++;
}
if (nextDuplicates <= k) {
duplicates = nextDuplicates;
freq[a[l - 1]]++;
l--;
} else {
break;
}
}
transition[k][r] = l;
if (--freq[a[r]] >= 1) {
duplicates--;
}
}
}
int[][] dp = new int[K + 1][N + 1];
int oo = (int) 1e9;
for (int[] row : dp) {
Arrays.fill(row, oo);
}
for (int k = 0; k <= K; k++) {
dp[k][0] = 0;
}
for (int r = 1; r <= N; r++) {
for (int k = 0; k <= K; k++) {
for (int delta = 0; delta <= k; delta++) {
dp[k][r] = min(dp[k][r], dp[k - delta][transition[delta][r] - 1] + 1);
}
}
}
out.println(dp[K][N]);
}
out.close();
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
int nextInt() {
return (int) nextLong();
}
long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
double nextDouble() {
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
double cur = nextLong();
if (c != '.') {
return neg ? -cur : cur;
} else {
double frac = nextLong() / cnt;
return neg ? -cur - frac : cur + frac;
}
}
String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static void ASSERT(boolean assertion, String message) {
if (!assertion) throw new AssertionError(message);
}
static void ASSERT(boolean assertion) {
if (!assertion) throw new AssertionError();
}
}
|
cubic
|
1497E2
|
CODEFORCES
|
import java.io.*;
import java.text.*;
import java.math.*;
import java.util.*;
public class Main {
private StreamTokenizer in;
private BufferedWriter out;
public void solve() throws Exception {
int n = nextInt(), m = nextInt();
int[] ss = new int[n];
for (int i=0; i<m; i++)
{
int a = nextInt(), b = nextInt();
a--;b--;
ss[a]|=1<<b;
ss[b]|=1<<a;
}
long[][] res = new long[n][1<<n];
int[] cnt = new int[1<<n], first = new int[1<<n];
for (int i=0; i<n; i++)
{
res[i][1<<i] = 1;
first[1<<i] = i;
cnt[1<<i] = 1;
}
long ans = 0;
for (int mask = 0; mask<1<<n; mask++)
{
for (int last = first[mask]; last<n; last++)
{
if (res[last][mask]==0)
continue;
if (cnt[mask]>2)
{
if ((ss[last]&(1<<first[mask]))!=0)
ans+=res[last][mask];
}
int m2 = (~mask) & ss[last];
for (int next = first[mask]+1; next<n; next++)
{
if ((m2&(1<<next))==0) continue;
int mask2 = mask|1<<next;
res[next][mask2]+=res[last][mask];
cnt[mask2] = cnt[mask]+1;
first[mask2] = first[mask];
}
}
}
ans/=2;
out.write(ans+"\n");
}
public int nextInt() throws Exception
{
in.nextToken();
return (int)in.nval;
}
public void run() {
try {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new BufferedWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
new Main().run();
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Vector;
public class con67 {
public static void main(String[] args) throws IOException
{
// System.out.println(power(2,9,1000000007));
long x=l();
long k=l();
if(x!=0)
{
long f=x%1000000007;
long s=(f*power(2,k+1,1000000007))%1000000007;
//out.println(s);
long e= (power(2,k,1000000007)-1)%1000000007;
//out.println(e);
long ans=(s-e+1000000007)%1000000007;
out.println(ans);
}
else
{
out.println(0);
}
out.close();
}
static long power(long x, long y, long p)
{
// Initialize result
long res = 1;
// Update x if it is more
// than or equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply x
// with result
if((y & 1)==1)
res = (res * x) % p;
// y must be even now
// y = y / 2
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
static int i()
{
return in.readInt();
}
static long l()
{
return in.readLong();
}
static double d()
{
return in.readDouble();
}
static String s()
{
return in.readString();
}
static void Iarr( int[] array, int no )
{
for( int i=0 ; i<no ; i++ )
{
array[i] = i();
}
}
static void Larr( long[] array, int no )
{
for( int i=0 ; i<no ; i++ )
{
array[i] = l();
}
}
static void Darr( double[] array, int no )
{
for( int i=0 ; i<no ; i++ )
{
array[i] = d();
}
}
static void Sarr( String[] array, int no )
{
for( int i=0 ; i<no ; i++ )
{
array[i] = s();
}
}
private static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
private static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.Scanner;
public class d {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] arr = new int[N];
for(int n=0;n<N;n++){
arr[n] = in.nextInt();
}
Wavelet waveyMcWaveFace = new Wavelet(arr);
BigInteger bigSum = BigInteger.ZERO;
for(int n=0;n<N;n++){
// calculate the amount added for all j = n all at once
// it's a[j] - a[i]
// step one
// positive part
long amtPlus = arr[n] * (long)(waveyMcWaveFace.numValsBtwn(1, arr[n] - 2, 0, n)
+ waveyMcWaveFace.numValsBtwn(arr[n] + 2, 2147483647, 0, n));
// step two
// negative part
long amtMinus = waveyMcWaveFace.sumOfValsBtwn(1, arr[n] - 2, 0, n)
+ waveyMcWaveFace.sumOfValsBtwn(arr[n] + 2, 2147483647, 0, n);
// System.out.println(amtPlus+" "+amtMinus);
bigSum = bigSum.add(new BigInteger(""+(amtPlus - amtMinus)));
}
System.out.println(bigSum);
}
static class Wavelet{
int l = 2147483647, h = -2147483648;
int[] arr, ldex, hdex;
long[] sum;
Wavelet low = null, high = null;
Wavelet(int[] arr){
this.arr = arr;
for(int i : arr){
l = Math.min(l, i);
h = Math.max(h, i);
}
ldex = new int[arr.length + 1];
hdex = new int[arr.length + 1];
sum = new long[arr.length + 1];
int mid = l + (h - l) / 2;
for(int n = 0; n < arr.length; n++){
sum[n+1] = sum[n] + arr[n];
if(arr[n] > mid){
ldex[n+1] = ldex[n];
hdex[n+1] = hdex[n] + 1;
}
else{
ldex[n+1] = ldex[n] + 1;
hdex[n+1] = hdex[n];
}
}
if(l == h) return;
int[] larr = new int[ldex[arr.length]];
int[] harr = new int[hdex[arr.length]];
for(int n=0;n<arr.length;n++){
if(hdex[n] == hdex[n+1]){
larr[ldex[n]] = arr[n];
}
else{
harr[hdex[n]] = arr[n];
}
}
low = new Wavelet(larr);
high = new Wavelet(harr);
}
// range [ll, rr)
int kthLowest(int k, int ll, int rr){
if(l == h){
return arr[ll + k-1];
}
if(ldex[rr] - ldex[ll] >= k){
return low.kthLowest(k, ldex[ll], ldex[rr]);
}
return high.kthLowest(k - ldex[rr] + ldex[ll], hdex[ll], hdex[rr]);
}
// number of values in between [lo, hi] in range [ll, rr)
int numValsBtwn(int lo, int hi, int ll, int rr){
if(hi < lo) return 0;
if(lo <= l && h <= hi){
return rr - ll;
}
if(l == h) return 0;
if(hi < high.l){
return low.numValsBtwn(lo, hi, ldex[ll], ldex[rr]);
}
if(low.h < lo){
return high.numValsBtwn(lo, hi, hdex[ll], hdex[rr]);
}
return low.numValsBtwn(lo, hi, ldex[ll], ldex[rr])
+ high.numValsBtwn(lo, hi, hdex[ll], hdex[rr]);
}
// sum of values between [lo, hi] in range [ll, rr)
long sumOfValsBtwn(int lo, int hi, int ll, int rr){
if(lo <= l && h <= hi){
return sum[rr] - sum[ll];
}
if(l == h) return 0;
if(hi < high.l){
return low.sumOfValsBtwn(lo, hi, ldex[ll], ldex[rr]);
}
if(low.h < lo){
return high.sumOfValsBtwn(lo, hi, hdex[ll], hdex[rr]);
}
return low.sumOfValsBtwn(lo, hi, ldex[ll], ldex[rr])
+ high.sumOfValsBtwn(lo, hi, hdex[ll], hdex[rr]);
}
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
import java.util.Scanner;
public class RationalResistance {
static long n = 0;
static void R(long a, long b) {
n += a / b;
a %= b;
if (a == 0) {
return;
}
R(b, a);
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
long a = cin.nextLong();
long b = cin.nextLong();
cin.close();
R(a, b);
System.out.println(n);
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class main{
static int max = 5000+1;
static FastReader in = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int N = 18;
static int[][] mn1 = new int[N][N];
static int[][] mn2 = new int[N][N];
static int[][] dp = new int[1<<N][N];
static int n,m;
static void solve(){
n = in.nextInt(); m = in.nextInt();
int[][] a = new int[n][m];
for(int i=0;i<n;i++)for(int j=0;j<m;j++)a[i][j] = in.nextInt();
for(int i=0;i<n;i++){
Arrays.fill(mn1[i],Integer.MAX_VALUE);
Arrays.fill(mn2[i],Integer.MAX_VALUE);
}
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int k=0;k<m;k++){
mn1[i][j] = Math.min(mn1[i][j],Math.abs(a[i][k]-a[j][k]));
if(k<=m-2)
mn2[i][j] = Math.min(mn2[i][j],Math.abs(a[i][k]-a[j][k+1]));
}
int ans = 0;
for(int i=0;i<n;i++){
for(int x=0;x<1<<n;x++)Arrays.fill(dp[x],-1);
for(int j=0;j<n;j++)dp[1<<j][j] = 0;
dp[1<<i][i] = Integer.MAX_VALUE;
for(int j=0;j<n;j++)
ans = Math.max(ans,Math.min(mn2[j][i],calc((1 << n) - 1, j)));
}
out.println(ans);
}
static int calc(int mask, int v){
if (dp[mask][v] != -1)
return dp[mask][v];
dp[mask][v] = 0;
for(int u=0;u<n;u++) if (v != u && (((mask >> u) & 1)>0))
dp[mask][v] = Math.max(dp[mask][v], Math.min(mn1[u][v], calc(mask ^ (1 << v), u)));
return dp[mask][v];
}
public static void main(String[] args){
solve();
out.close();
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
int nextInt(){return Integer.parseInt(in.next());}
long nextLong(){return Long.parseLong(in.next());}
double nextDouble(){return Double.parseDouble(in.next());}
}
}
// |xvcxv|vcv[cvcvc|cxv||]vcvx:v|c|vxc|[|cvx:cxvx||||]
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Alex
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
int n;
ArrayList<Integer>[] adj;
long[] mem;
long cycles(int cur, int start, int visited) {
if (cur == start && visited > 0) {
return Integer.bitCount(visited) >= 3 ? 1 : 0;
}
int index = n * visited + cur;
if (mem[index] != -1) return mem[index];
long res = 0;
int newvisited = visited | (1 << cur);
for (int nxt : adj[cur]) {
if (nxt >= start && (nxt == start || ((visited >> nxt) & 1) == 0)) {
res += cycles(nxt, start, newvisited);
}
}
return mem[index] = res;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
int m = in.readInt();
adj = new ArrayList[n];
mem = new long[n * (1 << n)];
for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int a = in.readInt() - 1, b = in.readInt() - 1;
adj[a].add(b);
adj[b].add(a);
}
long res = 0;
for (int start = 0; start < n; start++) {
Arrays.fill(mem, -1);
res += cycles(start, start, 0) / 2;
}
out.printLine(res);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.*;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class D {
public static void main(String[] args) {
init();
int n = in.nextInt();
long total = 0L;
int arr[] = new int[n+5];
Map<Integer, Integer> freq = new HashMap<>();
Map<Integer, Integer> kiri = new HashMap<>();
for (int i = 1; i <= n; ++i){
arr[i] = in.nextInt();
if (freq.containsKey(arr[i])) {
freq.put(arr[i], freq.get(arr[i])+1);
} else {
freq.put(arr[i], 1);
kiri.put(arr[i], 0);
}
total += (long)arr[i];
}
BigInteger ans = BigInteger.valueOf(0L);
for (int i = 1; i <= n - 1; ++i) {
kiri.put(arr[i], kiri.get(arr[i])+1);
total -= arr[i];
int cnt_kanan = n - i;
long temp = total;
int cnt_sama = freq.get(arr[i]) - kiri.get(arr[i]);
temp -= (cnt_sama)*(long)arr[i];
cnt_kanan -= (cnt_sama);
if (freq.containsKey(arr[i]-1)) {
int cnt_kurang = freq.get(arr[i]-1) - kiri.get(arr[i]-1);
cnt_kanan -= cnt_kurang;
temp -= (long) cnt_kurang * (long)(arr[i]-1);
}
if (freq.containsKey(arr[i]+1)) {
int cnt_lebih = freq.get(arr[i]+1) - kiri.get(arr[i]+1);
cnt_kanan -= cnt_lebih;
temp -= (long)(cnt_lebih) * (long)(arr[i]+1);
}
temp -= (long)cnt_kanan * (long)arr[i];
ans = ans.add(BigInteger.valueOf(temp));
}
out.println(ans.toString());
out.close();
}
/* PrintWriter and BufferedReader Template from Codeforces */
public static MyScanner in;
public static PrintWriter out;
public static void init() {
in = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
TreeSet<Integer> set = new TreeSet<>();
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int x = in.nextInt();
set.add(x);
}
int ans = 0;
while (!set.isEmpty()) {
ans++;
int minimal = set.first();
int cur = minimal;
while (cur <= 100) {
set.remove(cur);
cur += minimal;
}
}
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;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
//package com.company;
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("Test.in"));
PrintWriter pw = new PrintWriter(System.out);
// PrintWriter pw = new PrintWriter(new FileOutputStream("Test.out"));
// PrintWriter pw = new PrintWriter(new FileOutputStream("Test.in"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
System.out.println("Memory increased:" + (usedMemoryAfter-usedMemoryBefore) / 1000000 );
System.out.println("Time used: " + (TIME_END - TIME_START) + ".");
}
public static class Task {
int mod = 1_000_000_007;
public long pow(long a, long b) {
if (b == 0) return 1L;
if (b % 2 == 0) return pow(a * a % mod, b >> 1);
return a * pow(a * a % mod, b >> 1) % mod;
}
public void solve(Scanner sc, PrintWriter pw) throws IOException {
long T = sc.nextLong();
long k = sc.nextLong();
if (T == 0) {
pw.println(0);
return;
}
long a1 = pow(2, k + 1);
long a2 = pow(2, k);
long s = a1 * (T % mod) % mod;
long t = ((1 - a2) + mod) % mod;
long y = (s + t) % mod;
pw.println((y + 5L * mod) % mod);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader s) throws FileNotFoundException {br = new BufferedReader(s);}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
//package codeforces;
import java.util.Scanner;
public class ex5 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String S [] = new String[3];
int m=0,s=0,p=0;
int temp=0;
for (int i = 0; i < S.length; i++) {
S[i]=scan.next();
if(S[i].indexOf('m')!=-1) m++;
if(S[i].indexOf('s')!=-1) s++;
if(S[i].indexOf('p')!=-1) p++;
}
int n1 = Integer.parseInt(S[0].substring(0,1));
int n2 = Integer.parseInt(S[1].substring(0,1));
int n3 = Integer.parseInt(S[2].substring(0,1));
int d3 = Math.abs(n1-n2);
int d4 = Math.abs(n1-n3);
int d5 = Math.abs(n2-n3);
if(m==3||s==3||p==3) {
if(d3==1&d5==1&d4==2||d3==1&d4==1&d5==2||d5==1&d4==1&d3==2)
System.out.println(0);
else
if(d3==0&d4==0) System.out.println(0);
else
if(d3<d5&d3<d4) {
if(d3==1||d3==2||d3==0) System.out.println(1);
else System.out.println(2);
}
else if (d5<d4&d5<d3){
if(d5==1||d5==2||d5==0) System.out.println(1);
else System.out.println(2);
}
else if(d4<d5&d4<d3) {
if(d4==1||d4==2||d4==0) System.out.println(1);
else System.out.println(2);
}
else if(d3==2&d5==2||d4==2&d5==2||d3==2&d4==2||d3==1&d5==1||d4==1&d5==1||d3==2&d4==1)
System.out.println(1);
else System.out.println(2);
}
if(m==2||s==2||p==2) {
char c1 = S[0].charAt(1);
char c2 = S[1].charAt(1);
char c3 = S[2].charAt(1);
if(c1==c2) {
if(n1==n2) System.out.println(1);
else if(d3==1||d3==2) System.out.println(1);
else System.out.println(2);
}
if(c1==c3) {
if(n1==n3) System.out.println(1);
else if(d4==1||d4==2) System.out.println(1);
else System.out.println(2);
}
if(c2==c3) {
if(n2==n3) System.out.println(1);
else if(d5==1||d5==2) System.out.println(1);
else System.out.println(2);
}
}
if(m==1&s==1&p==1) System.out.println(2);
}
}
|
constant
|
1191_B. Tokitsukaze and Mahjong
|
CODEFORCES
|
import java.util.*;
public class Beta17PA {
boolean[] isPrime = new boolean[1001];
int[] prime = new int[200];
public static void main(String[] args) {
// TODO Auto-generated method stub
new Beta17PA().solve();
}
public void solve() {
Scanner scan = new Scanner(System.in);
int n, k;
n = scan.nextInt();
k = scan.nextInt();
init();
int m = 0;
for(int i=2; i<=n; i++) {
if(check(i)) m ++;
}
if(m>=k) System.out.println("YES");
else System.out.println("NO");
}
private boolean check(int n) {
if(n<6||!isPrime[n]) return false;
int d = n-1;
for(int i=0; i<199&&prime[i]+prime[i+1]<=d; i++) {
if(prime[i]+prime[i+1]==d) return true;
}
return false;
}
private void init() {
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for(int i=2; i<1001; i++) {
if(!isPrime[i]) continue;
for(int j=i+i; j<1001; j+=i) {
isPrime[j] = false;
}
}
int count = 0;
for(int i=2; i<1001; i++) {
if(isPrime[i]) prime[count++] = i;
}
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
public class Village
{
static Scanner in = new Scanner( new BufferedReader( new InputStreamReader( System.in ) ) );
public static void main( String[] args )
{
int n = in.nextInt(), t = 2*in.nextInt(), h[][] = new int[n][2], ans = 2;
for( int i = 0; i < n; i++ )
{
h[i][0] = 2*in.nextInt();
h[i][1] = in.nextInt();
}
Arrays.sort( h, new Comp() );
for( int i = 1; i < n; i++ )
{
int d = (h[i][0]-h[i][1])-(h[i-1][0]+h[i-1][1]);
if( d>t ) ans += 2;
if( d==t ) ans++;
}
System.out.println( ans );
}
static class Comp implements Comparator<int[]>
{
public int compare( int[] a, int[] b ) { return a[0]-b[0]; }
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class P16E {
int n;
double [][]prob;
double []dp;
public P16E() {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
prob = new double [n][n];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
prob[i][j] = sc.nextDouble();
}
}
sc.close();
dp = new double[(1<<n)];
Arrays.fill(dp, -1);
for (int i = 0; i < n; i++) {
int a = 1 << i;
System.out.print(compute(a) + " ");
}
}
double compute (int mask){
if (mask == (1<<n) - 1){
return 1;
}
if (dp[mask] != -1){
return dp[mask];
}
double result = 0;
int c = 0;
for (int i = 0; i < n; i++) {
int a = 1 << i;
if ((a & mask) != 0) {
c++;
for (int j = 0; j < n; j++) {
int b = 1 << j;
if ((b & mask) == 0) {
result += (prob[i][j] * compute(mask | b));
}
}
}
}
int nC2 = (c + 1) * c / 2;
dp[mask] = result / nC2;
return dp[mask];
}
public static void main (String []args){
new P16E();
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
// Scanner scan = new Scanner(System.in);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
// int n = Integer.parseInt(bf.readLine());
StringTokenizer st = new StringTokenizer(bf.readLine());
// int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
long n = Long.parseLong(st.nextToken());
long k = Long.parseLong(st.nextToken());
int mod = 1000000007;
if(n == 0) {
out.println(0);
out.close(); System.exit(0);
}
n %= mod;
long ans = exp(2, (int)((k+1) % (mod-1)), mod);
ans = (1L*ans * n) % mod;
ans = ans + mod + 1 - exp(2, (int)((k) % (mod-1)), mod);
ans %= mod;
out.println(ans);
// int n = scan.nextInt();
out.close(); System.exit(0);
}
public static int exp(int base, int e, int mod) {
if(e == 0) return 1;
if(e == 1) return base;
int val = exp(base, e/2, mod);
int ans = (int)(1L*val*val % mod);
if(e % 2 == 1)
ans = (int)(1L*ans*base % mod);
return ans;
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.math.*;
import java.text.*;
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sca = new Scanner(System.in);
long k,n;
long ans;
long[] pw = new long[33];
pw[1]=4;
pw[0]=1;
for(int i=2;i<=31;i++)
pw[i]=pw[i-1]<<2;
int t;
t = sca.nextInt();
for(int cas=1;cas<=t;cas++) {
n = sca.nextLong();
k = sca.nextLong();
ans = n;
long last, path = 1;
for (int i = 0; ; i++) {
if ((pw[i + 1] - 1) / 3 > k) {
ans -= i;
last = k - (pw[i] - 1) / 3;
break;
}
path *= 2;
}
long sp = path * 2 - 1;
if (ans < 0 || (ans == 0 && last > 0)) {
System.out.println("NO");
continue;
}
BigInteger sq = BigInteger.valueOf(path).multiply(BigInteger.valueOf(path)).subtract(BigInteger.valueOf(sp));
if (ans == 1 && sq.compareTo(BigInteger.valueOf(last))==-1 && last < sp) {
System.out.println("NO");
continue;
} else if (ans == 1 && last >= sp) {
ans--;
}
System.out.println("YES "+ans);
}
}
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class C455C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
ArrayList<Integer> listCount = new ArrayList<Integer>();
listCount.add(1);
boolean justf = false;
int p = 1000000007;
long ans = 0;
for(int x=0; x<n; x++){
String next = sc.nextLine();
if(next.equals("f")){
if(justf){
listCount.add(0);
}
else{
for(int i=1; i<listCount.size(); i++){
int sum = (listCount.get(i-1) + listCount.get(i)) % p;
listCount.set(i, sum);
}
listCount.add(0);
}
justf = true;
}
else{ // "s"
if(justf){
justf = false;
}
else{
for(int i=1; i<listCount.size(); i++){
int sum = (listCount.get(i-1) + listCount.get(i)) % p;
listCount.set(i, sum);
}
}
}
//System.out.println(listCount);
}
for(int i=0; i<listCount.size(); i++){
ans += listCount.get(i);
}
System.out.print((ans % p));
}
}
/*
int n = Integer.parseInt(sc.nextLine());
String[] t = sc.nextLine().split(" ");
int[] list = new int[n];
for(int x=0; x<n; x++){
list[x] = Integer.parseInt(t[x]);
}
String[] dir = sc.nextLine().split(" ");
int a = Integer.parseInt(dir[0]);
int b = Integer.parseInt(dir[1]);
int c = Integer.parseInt(dir[2]);
int d = Integer.parseInt(dir[3]);
int e = Integer.parseInt(dir[4]);
int n = Integer.parseInt(sc.nextLine());
*/
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
static int n,r,x[];
static double ans[];
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = sc.nextInt();
r = sc.nextInt();
x = new int[n];
ans = new double[n];
for (int i=0;i<n;i++)
x[i] = sc.nextInt();
for (int i=0;i<n;i++)
{
ans[i] = r;
for (int j=0;j<i;j++)
{
if (Math.abs(x[i]-x[j])>2*r)
continue;
int deltaxsq = (x[i]-x[j])*(x[i]-x[j]);
int deltaysq = 4 * r * r - deltaxsq;
double deltay = Math.sqrt(deltaysq);
ans[i] = Math.max(ans[i], ans[j]+deltay);
}
pw.print(ans[i]+" ");
}
pw.flush();
pw.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class CF008C {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int x = s.nextInt();
int y = s.nextInt();
int n = s.nextInt();
int[] xx = new int[n+1];
int[] yy = new int[n+1];
for(int i = 0;i<n;i++){
xx[i] = s.nextInt();
yy[i] = s.nextInt();
}
// int[][] dp = new int[n][n];
// for(int i = 0;i<n;i++){
// Arrays.fill(dp[i],-1);
// }
xx[n] = x;
yy[n] = y;
int[][] dp = new int[n + 1][n + 1];
for (int i = 0; i <= n; i++)
for (int j = i + 1; j <= n; j++) {
int dx = xx[i] - xx[j];
int dy = yy[i] - yy[j];
dp[i][j] = dx * dx + dy * dy;
}
int[] aa = new int[1 << n];
int[] bb = new int[1 << n];
for (int k = 1; k < 1 << n; k++) {
int a = -1;
for (int b = 0; b < n; b++)
if ((k & 1 << b) > 0) {
a = b;
break;
}
int l = k ^ 1 << a;
int d = dp[a][n] + dp[a][n];
aa[k] = aa[l] + d;
bb[k] = l;
for (int b = a + 1; b < n; b++)
if ((k & 1 << b) > 0) {
l = k ^ 1 << a ^ 1 << b;
d = dp[a][n] + dp[b][n] + dp[a][b];
if (aa[l] + d < aa[k]) {
aa[k] = aa[l] + d;
bb[k] = l;
}
}
}
int k = (1 << n) - 1;
System.out.println(aa[k]);
StringBuilder sb = new StringBuilder();
sb.append(0);
while (k != 0) {
int l = bb[k];
int m = k ^ l;
for (int b = 0; b < n; b++)
if ((m & 1 << b) > 0)
sb.append(' ').append(b + 1);
sb.append(' ').append(0);
k = l;
}
System.out.println(sb);
}
// int[] distFromOrigin = new int[n];
//// HashMap<Integer,Boolean> map = new HashMap<>();
// for(int i=0;i<n;i++){
// distFromOrigin[i] = (int) (Math.pow((xCoord[i] - x),2) + Math.pow(yCoord[i] - y,2));
//// map.put(i,true);
// }
// System.out.println(0);
// long sum = 0;
// String str = "0 ";
//
// while(!map.isEmpty()){
// int first = 0;
// int second = Integer.MIN_VALUE;
// if(map.size() == 1){
// first = new ArrayList<Integer>(map.keySet()).get(0) + 1;
// int min = distFromOrigin[first - 1] + distFromOrigin[first - 1];
// sum += min;
// map.remove(first - 1);
// }else {
// int min = Integer.MAX_VALUE;
//
// for (int i = 0; i < n; i++) {
// for (int j = 0; j <= i; j++) {
// if (map.containsKey(i) && map.containsKey(j) && distFromOrigin[i] + distFromOrigin[j] + dp[i][j] < min) {
// min = distFromOrigin[i] + distFromOrigin[j] + dp[i][j];
// first = i + 1;
// if(i == j){
// second = Integer.MIN_VALUE;
// }else {
// second = j + 1;
// }
// }
// }
// }
// sum += min;
// map.remove(first - 1);
// if(second != Integer.MIN_VALUE){
// map.remove(second - 1);
// }
// }
// if(second == Integer.MIN_VALUE){
// str = str + first + " ";
// }else{
// if(map.size() == 0) {
// str = str + first + " " + second + " ";
// }else{
// str = str + first + " " + second + " 0 ";
// }
// }
//// System.out.print(first + " " + second + " ");
// }
// System.out.println(sum);
// System.out.println(str + "0");
// int[] ans = new int[(int)Math.pow(2,n)];
// Arrays.fill(ans,Integer.MAX_VALUE);
// for(int i = 0;i<Math.pow(2,n);i++){
// for(int j = 0;j<n;j++){
// //I can't figure out how to do that.
// }
// }
// System.out.print(sum);
// System.out.print(0);
private static int calculateDistanceBetweenIandJ(int[] xCoord, int[] yCoord, int i, int j) {
int length = (int) (Math.pow((xCoord[i] - xCoord[j]),2) + Math.pow(yCoord[i] - yCoord[j], 2));
return length;
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int mod = (int) 1e9 + 7;
public void solve(int testNumber, InputReader in, PrintWriter out) {
long x = in.readLong();
long k = in.readLong();
if (x == 0) {
out.println(0);
return;
}
long ans = (BigInteger.valueOf(MathUtil.pow(2, k + 1, mod)).multiply(BigInteger.valueOf(x))).mod(BigInteger.valueOf(mod)).longValue();
long sub = (mod + MathUtil.pow(2, k, mod) - 1) % mod;
out.println((mod + ans - sub) % mod);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public long 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 MathUtil {
public static long pow(long a, long b, long mod) {
long ans = 1;
while (b > 0) {
if (b % 2 == 1) ans = (ans * a) % mod;
a = (a * a) % mod;
b /= 2;
}
return ans;
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), k = sc.nextInt(), kol = 0, prev;
boolean ok;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(2);
prev = 2;
for(int i=3;i<=n;i+=2)
{
ok = true;
for(Integer x: al)
if (i%x == 0)
{
ok = false;
break;
}
if (ok)
{
for(Integer x: al)
if (ok)
{
prev = x;
ok = false;
} else
{
if (x + prev + 1 == i)
{
kol++;
break;
}
if (x + prev + 1 > i) break;
prev = x;
}
al.add(i);
}
}
if (kol >= k) System.out.print("YES"); else System.out.print("NO");
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
G1PleilistDlyaPolikarpaUproshennayaVersiya solver = new G1PleilistDlyaPolikarpaUproshennayaVersiya();
solver.solve(1, in, out);
out.close();
}
static class G1PleilistDlyaPolikarpaUproshennayaVersiya {
static final int MOD = (int) 1e9 + 7;
int n;
int t;
int[][] a = new int[15][2];
long[][] mem = new long[1 << 15][4];
public void solve(int testNumber, InputReader in, PrintWriter out) {
for (int i = 0; i < (1 << 15); i++) {
for (int h = 0; h < 4; h++) {
mem[i][h] = -1;
}
}
n = in.nextInt();
t = in.nextInt();
for (int i = 0; i < n; i++) {
a[i][0] = in.nextInt();
a[i][1] = in.nextInt();
}
out.println(doit(0, 0, 0));
}
private long doit(int mask, int genre, int sum) {
if (mem[mask][genre] != -1) {
return mem[mask][genre];
}
if (sum > t) {
mem[mask][genre] = 0;
return mem[mask][genre];
}
if (sum == t) {
mem[mask][genre] = 1;
return mem[mask][genre];
}
long ct = 0;
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) > 0 || genre == a[i][1]) {
continue;
}
ct = (ct + doit(mask | (1 << i), a[i][1], sum + a[i][0])) % MOD;
}
mem[mask][genre] = ct;
return mem[mask][genre];
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Solution implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
int fu(int[] a, int l) {
for (int i = l; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) return i;
}
return a.length;
}
void swap(int[] a, int q, int w) {
int t = a[q]; a[q] = a[w]; a[w] = t;
}
void solve() throws Exception {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
int q = fu(a, 0);
if (q == n) out.println("YES"); else {
int w = fu(a, q + 1);
if (w < n) {
boolean ans = false;
swap(a, q, w);
ans |= fu(a, 0) == n;
swap(a, q, w);
if (q < n - 1) {
swap(a, q + 1, w);
ans |= fu(a, 0) == n;
swap(a, q + 1, w);
}
if (w < n - 1) {
swap(a, q, w + 1);
ans |= fu(a, 0) == n;
swap(a, q, w + 1);
}
if (q < n - 1 && w < n - 1) {
swap(a, q + 1, w + 1);
ans |= fu(a, 0) == n;
swap(a, q + 1, w + 1);
}
if (ans) out.println("YES"); else out.println("NO");
} else {
int j = q + 1;
while (j < n && a[j] == a[q + 1]) j++;
j--;
swap(a, q, j);
if (fu(a, 0) == n) out.println("YES"); else {
swap(a, q, j);
q++;
j = q - 1;
while (j >= 0 && a[j] == a[q - 1]) j--;
j++;
swap(a, q, j);
if (fu(a, 0) == n) out.println("YES"); else out.println("NO");
}
}
}
}
public void run() {
try {
Locale.setDefault(Locale.UK);
in = new BufferedReader(new InputStreamReader(System.in));
// in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(System.out);
// out = new PrintWriter("output.txt");
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
out.close();
}
}
public static void main(String[] args) {
// new Thread(null, new Solution(), "1", 1 << 28).start();
(new Solution()).run();
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.util.*;
public class Main {
static Scanner cin = new Scanner(System.in);
private int xs, ys, n;
private int[] x, y;
public static void main(String[] args) throws Exception {
new Main().run();
}
class Item implements Comparable<Item> {
int w, h, idx;
Item(int w, int h, int idx) {
this.w = w;
this.h = h;
this.idx = idx;
}
@Override
public int compareTo(Item o) {
if (this.w == o.w) {
return this.h - o.h;
}
return this.w - o.w;
}
}
private void run() throws Exception {
xs = cin.nextInt();
ys = cin.nextInt();
n = cin.nextInt();
x = new int[n + 1];
y = new int[n + 1];
for (int i = 0; i < n; i++) {
x[i] = cin.nextInt();
y[i] = cin.nextInt();
}
int[] res = new int[1 << n];
Arrays.fill(res, Integer.MAX_VALUE);
int[] ds = new int[n];
for (int i = 0; i < n; i++) {
ds[i] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys);
}
int[][] d = new int[n + 1][n + 1];
int[] tr = new int[1 << n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
d[i][j] = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
}
}
//----------------------
res[0] = 0;
for (int i = 1; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
if (((i >> j) & 1) != 0) {
if (res[i - (1 << j)] + 2 * ds[j] < res[i]) {
res[i] = res[i - (1 << j)] + 2 * ds[j];
tr[i] = i - (1 << j);
}
for (int k = j + 1; k < n; k++) {
if (((i >> k) & 1) != 0) {
if (res[i - (1 << j) - (1 << k)] + ds[k] + ds[j] + d[k][j] < res[i]) {
res[i] = res[i - (1 << j) - (1 << k)] + ds[k] + ds[j] + d[k][j];
tr[i] = i - (1 << j) - (1 << k);
}
}
}
break;
}
}
}
System.out.println(res[(1 << n) - 1]);
int now = (1 << n) - 1;
while (now != 0) {
System.out.print("0 ");
int dif = now - tr[now];
for (int i = 0; i < n && dif != 0; i++) {
if (((dif >> i) & 1) != 0) {
System.out.print((i + 1) + " ");
dif -= (1 << i);
}
}
now=tr[now];
}
System.out.print("0");
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Arrays;
public class Main {
static Scanner in = new Scanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
long n = in.nextLong(), m = in.nextLong();
out.print(m / n + (m % n == 0 ? 0 : 1));
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
public String next() throws IOException {
if(!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());
}
}
}
|
constant
|
1036_A. Function Height
|
CODEFORCES
|
import java.util.Scanner;
public class p84a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println((n/2)*3);
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class j
{
public static void main(String aa[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int i=0,m=0,p=0,n=0,k=0,j=0;
String s,r;
s=b.readLine();
r=s;
n=Integer.parseInt(s);
s=s.substring(0,s.length()-2);
s+=r.charAt(r.length()-1);
r=r.substring(0,r.length()-1);
m=Integer.parseInt(s);
p=Integer.parseInt(r);
System.out.print((long)Math.max(Math.max(m,n),p));
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Set;
/**
* @author Egor Kulikov (egor@egork.net)
* Created on 14.03.2010
*/
public class TaskA implements Runnable {
private InputReader in;
private PrintWriter out;
public static void main(String[] args) {
new Thread(new TaskA()).start();
// new Template().run();
}
public TaskA() {
// String id = getClass().getName().toLowerCase();
// try {
// System.setIn(new FileInputStream(id + ".in"));
// System.setOut(new PrintStream(new FileOutputStream(id + ".out")));
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream(new FileOutputStream("output.txt")));
// } catch (FileNotFoundException e) {
// throw new RuntimeException();
// }
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
public void run() {
// int numTests = in.readInt();
// for (int testNumber = 0; testNumber < numTests; testNumber++) {
// out.print("Case " + (testNumber + 1) + ": ");
// }
String s = in.readString();
Set<String> m = new HashSet<String>();
int ans = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j <= s.length(); j++) {
if (m.contains(s.substring(i, j)))
ans = Math.max(ans, j - i);
else
m.add(s.substring(i, j));
}
}
out.print(ans);
out.close();
}
private static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1000];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
public class C{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
long mod=1000000007l;
int cases=sc.nextInt();
while(cases>0)
{
cases--;
Stack<Integer> stack=new Stack<>();
int n=sc.nextInt();
for(int j=0;j<n;j++)
{
int x=sc.nextInt();
if(x==1)
{
stack.add(1);
}
else
{
int p=stack.pop();
if(p==x-1)
{
stack.add(x);
}
else {
while (p != x-1) {
p = stack.pop();
}
stack.add(x);
}
}
StringBuilder f=new StringBuilder();
Stack<Integer> temp=new Stack<>();
while(stack.isEmpty()==false)
{
temp.add(stack.pop());
}
while(temp.isEmpty()==false)
{
int z=temp.pop();
f.append(z+".");
stack.add(z);
}
System.out.println(f.substring(0,f.length()-1));
}
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
if (n%2==0) {
System.out.println(4+" "+(n-4));
} else {
System.out.println(9+" "+(n-9));
}
in.close();
out.close();
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main{
public static void pri(ArrayList<Integer> list)
{
int len=list.size();
for(int i=0;i<len-1;++i)
System.out.print(list.get(i)+".");
System.out.println(list.get(len-1));
}
public static void main(String[] args) throws java.io.IOException {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;++i)
{
arr[i]=sc.nextInt();
}
ArrayList<Integer> cur=new ArrayList<>();
cur.add(1);
System.out.println(1);
for(int i=1;i<n;++i)
{
if(arr[i]==1)
{
cur.add(1);
pri(cur);
continue;
}
int len=cur.size();
while(cur.get(len-1)!=arr[i]-1)
{
cur.remove(len-1);
len--;
}
cur.set(len-1,arr[i]);
pri(cur);
continue;
}
}
}
}
// 1 0 1 1 0 0 1
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class D
{
static FastIO f;
static long ve[][], he[][];
public static void main(String args[]) throws IOException
{
f = new FastIO();
int n = f.ni(), m = f.ni(), k = f.ni(), i, j;
ve = new long[n-1][];
he = new long[n][];
long[][] ans = new long[n][m], pans = new long[n][m], temp;
for(i = 0; i < n; i++)
he[i] = f.nla(m-1);
for(i = 0; i < n-1; i++)
ve[i] = f.nla(m);
if(k%2 == 1)
{
for(i = 0; i < n; i++)
Arrays.fill(ans[i], -1L);
}
else
{
k /= 2;
while(k-->0)
{
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
ans[i][j] = Integer.MAX_VALUE;
if(i != 0)
ans[i][j] = Math.min(ans[i][j], pans[i-1][j] + 2*edge(i, j, i-1, j));
if(i != n-1)
ans[i][j] = Math.min(ans[i][j], pans[i+1][j] + 2*edge(i, j, i+1, j));
if(j != 0)
ans[i][j] = Math.min(ans[i][j], pans[i][j-1] + 2*edge(i, j, i, j-1));
if(j != m-1)
ans[i][j] = Math.min(ans[i][j], pans[i][j+1] + 2*edge(i, j, i, j+1));
}
}
// f.err(k + "\n");
// errorprint(ans, n, m);
temp = pans;
pans = ans;
ans = temp;
}
temp = pans;
pans = ans;
ans = temp;
}
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
f.out(ans[i][j] + " ");
}
f.out("\n");
}
f.flush();
}
public static void errorprint(long[][] p, int n, int m) throws IOException
{
int i, j;
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
f.err(p[i][j] + " ");
}
f.err("\n");
}
f.err("\n");
}
public static long edge(int i, int j, int x, int y)
{
if(i == x)
return he[i][Math.min(j, y)];
else
return ve[Math.min(i, x)][j];
}
public static class FastIO
{
BufferedReader br;
BufferedWriter bw, be;
StringTokenizer st;
public FastIO()
{
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
be = new BufferedWriter(new OutputStreamWriter(System.err));
st = new StringTokenizer("");
}
private void read() throws IOException
{
st = new StringTokenizer(br.readLine());
}
public String ns() throws IOException
{
while(!st.hasMoreTokens())
read();
return st.nextToken();
}
public int ni() throws IOException
{
return Integer.parseInt(ns());
}
public long nl() throws IOException
{
return Long.parseLong(ns());
}
public float nf() throws IOException
{
return Float.parseFloat(ns());
}
public double nd() throws IOException
{
return Double.parseDouble(ns());
}
public char nc() throws IOException
{
return ns().charAt(0);
}
public int[] nia(int n) throws IOException
{
int[] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = ni();
return a;
}
public long[] nla(int n) throws IOException
{
long[] a = new long[n];
for(int i = 0; i < n; i++)
a[i] = nl();
return a;
}
public char[] nca() throws IOException
{
return ns().toCharArray();
}
public void out(String s) throws IOException
{
bw.write(s);
}
public void flush() throws IOException
{
bw.flush();
be.flush();
}
public void err(String s) throws IOException
{
be.write(s);
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import javafx.util.Pair;
import java.io.*;
import java.util.*;
public class Beacon8 {
public static void main(String[] args) throws IOException {
// int[] arr = {1, 3, 7, 18};
// int bIndex = Arrays.binarySearch(arr, 4);
// System.out.println(bIndex);
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Map<Integer, Integer> beacons = new TreeMap<>();
for (int i = 0; i < n; i++) {
int index = scan.nextInt();
int power = scan.nextInt();
beacons.put(index, power);
}
int[] indicesArr = new int[n];
int arrInd = 0;
for (int index : beacons.keySet()) {
indicesArr[arrInd] = index;
arrInd++;
}
// Integer[] indicesArr = ((Integer[])beacons.keySet().toArray());
int[] nDestroys = new int[n];
for (int i = 0; i < n; i++) {
int bIndex = Arrays.binarySearch(indicesArr, indicesArr[i] - beacons.get(indicesArr[i]));
if (bIndex < 0)
bIndex = -(bIndex + 1);
nDestroys[i] = i - bIndex;
}
int[] totalBeacons = new int[n];
int maxBeacons = 1;
totalBeacons[0] = 1;
for (int i = 1; i < n; i++) {
if (nDestroys[i] == 0)
totalBeacons[i] = totalBeacons[i - 1] + 1;
else {
if ((i - nDestroys[i] - 1) >= 0)
totalBeacons[i] = totalBeacons[i - nDestroys[i] - 1] + 1;
else
totalBeacons[i] = 1;
}
// totalBeacons[i] = totalBeacons[i - nDestroys[i]] + 1;
//totalBeacons[i] = i - nDestroys[i] + totalBeacons[i - nDestroys[i]] + 1;
if(totalBeacons[i] > maxBeacons)
maxBeacons = totalBeacons[i];
}
// System.out.println("\ntotalBeacons array");
// for (int i = 0; i < n; i++) {
// System.out.print(totalBeacons[i] + " ");
// }
// if (maxBeacons == -1)
// System.out.println(n);
System.out.println(n - maxBeacons);
}
}
|
nlogn
|
608_C. Chain Reaction
|
CODEFORCES
|
import java.util.Scanner;
import java.util.Arrays;
public class P166A
{
public static void main(String[] args)
{
Scanner myScanner = new Scanner(System.in);
int n = myScanner.nextInt();
int k = myScanner.nextInt();
Team[] queue = new Team[n];
for (int i = 0; i < n; i++)
{
queue[i] = new Team(myScanner.nextInt(), myScanner.nextInt());
}
Arrays.sort(queue);
int counter = 0;
int i = 0;
int p = -1;
int t = -1;
for (; i < k; i++)
{
if (p == queue[i].problems && t == queue[i].penalty)
counter++;
else
{
p = queue[i].problems;
t = queue[i].penalty;
counter = 1;
}
}
for (; i < n; i++)
{
if (p == queue[i].problems && t == queue[i].penalty)
counter++;
else
break;
}
System.out.println(counter);
}
static class Team implements Comparable<Team>
{
int problems;
int penalty;
public Team(int problems, int penalty)
{
this.problems = problems;
this.penalty = penalty;
}
public int compareTo(Team t)
{
if (problems > t.problems) return -1;
else if (problems < t.problems) return 1;
else if (penalty > t.penalty) return 1;
else if (penalty < t.penalty) return -1;
else return 0;
}
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class LookingForOrder {
static int n;
static int []x,y,memo;
static StringBuilder sb;
static int distance(int i,int j)
{
int dx=x[i]-x[j];
int dy=y[i]-y[j];
return dx*dx+dy*dy;
}
public static int dp(int msk)
{
if(msk==(1<<(n+1))-2)
return 0;
if(memo[msk]!=-1)
return memo[msk];
int ans=10000000;
boolean found=false;
for(int i=1;i<=n && !found;i++)
for(int j=i;j<=n && (msk&1<<i)==0;j++)
if((msk&1<<j)==0)
{
found=true;
int newM=msk|1<<i;
newM|=1<<j;
ans=Math.min(ans, dp(newM)+Math.min(distance(0,i)+distance(i,j)+distance(j,0), distance(0,j)+distance(j,i)+distance(i,0)));
}
return memo[msk]=ans;
}
public static void print(int msk)
{
if(msk==(1<<(n+1))-2)
return ;
for(int i=1;i<=n;i++)
for(int j=i;j<=n && (msk&1<<i)==0;j++)
if((msk&1<<j)==0)
{
int newM=msk|1<<i;
newM|=1<<j;
int d1=distance(0,i)+distance(i,j)+distance(j,0);
int d2=distance(0,j)+distance(j,i)+distance(i,0);
if(dp(msk)== dp(newM)+Math.min(d1,d2))
{
if(i==j)
sb.append("0 "+i+" ");
else if(d1<d2)
sb.append("0 "+i+" "+j+" ");
else
sb.append("0 "+j+" "+i+" ");
print(newM);
return ;
}
}
}
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int xS=sc.nextInt(),yS=sc.nextInt();
n=sc.nextInt();
x=new int [n+1];
y=new int [n+1];
x[0]=xS;y[0]=yS;
for(int i=1;i<=n;i++)
{
x[i]=sc.nextInt();
y[i]=sc.nextInt();
}
memo=new int [1<<(n+1)];
Arrays.fill(memo,-1);
sb=new StringBuilder();
sb.append(dp(0)+"\n");
print(0);
sb.append("0");
System.out.println(sb);
}
static class Scanner
{
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream s)
{
br=new BufferedReader(new InputStreamReader(s));
}
public String nextLine() throws IOException
{
return br.readLine();
}
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 double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
public boolean ready() throws IOException
{
return br.ready();
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n % 2 == 0) {
System.out.println(4 + " " + (n - 4));
} else {
System.out.println(9 + " " + (n - 9));
}
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class pr169D implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer str;
public void solve() throws IOException {
long l = nextLong();
long r = nextLong();
long x = l ^ r;
long i = 1;
while (x >= i)
i *= 2;
out.println(x > i ? x : i - 1);
}
public String nextToken() throws IOException {
while (str == null || !str.hasMoreTokens()) {
str = new StringTokenizer(in.readLine());
}
return str.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (IOException e) {
}
}
public static void main(String[] args) {
new Thread(new pr169D()).start();
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class ER23C {
static long s;
public static void main (String[] args) throws java.lang.Exception {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
long n = in.nextLong();
s = in.nextLong();
long l = 0, h = n;
while (l < h) {
long mid = (l + h ) / 2;
// System.out.println("mid is : " + mid);
// System.out.println("high is : " + h);
//System.out.println("low is : " + l);
if (Ok(mid))
h = mid;
else
l = mid + 1;
}
if (Ok(h))
w.println(n - h + 1);
else
w.println(n - h);
w.close();
}
static boolean Ok(long n) {
int sum = 0;
long temp = n;
while (n > 0) {
sum += (n % 10);
n = n / 10;
}
//System.out.println("n is :" + n + " sum is : " + sum);
return (temp - sum >= s);
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public void skip(int x) {
while (x-- > 0)
read();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextString() {
return next();
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public boolean hasNext() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value != -1;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
logn
|
817_C. Really Big Numbers
|
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.*;
import java.io.*;
public class B {
public void solve() throws IOException {
int n = nextInt();
int k = nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++){
a[i] = nextInt();
}
int[] num = new int[n];
Set<Integer> set = new HashSet<Integer>();
int s = -1;
int l = -1;
for(int i = 0; i < n; i++){
set.add(a[i]);
num[i] = set.size();
if( num[i] == k ){
l = i+1;
set = new HashSet<Integer>();
for(int j = i; j >= 0; j--){
set.add(a[j]);
if( set.size() == k ){
s = j+1;
break;
}
}
break;
}
}
writer.println(s + " " + l);
}
public static void main(String[] args) throws IOException {
new B().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() throws IOException {
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);
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
public class Main {
private void solve() {
int n = in.nextInt();
int k = in.nextInt();
final int[] p = new int[n];
final int[] t = new int[n];
for(int i =0 ; i < n; ++i) {
p[i] = in.nextInt();
t[i] = in.nextInt();
}
Integer[] ord = new Integer[n];
for(int i = 0; i < n; ++i)
ord[i] = i;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n - 1; ++j) {
if (Less(ord[j], ord[j + 1], p, t)) {
Integer tx = ord[j];
ord[j] = ord[j + 1];
ord[j + 1] = tx;
}
}
}
for(int i = 0, j = 0; i < n; i = j) {
for(j = i; j < n && p[ord[i]] == p[ord[j]] && t[ord[i]] == t[ord[j]]; ++j) ;
int first = i+1;
int second = j;
if (first <= k && k <= second) {
out.print(j - i);
return ;
}
}
out.print(0);
}
private boolean Less(Integer i, Integer j, int[] p, int[] t) {
return p[i] < p[j] || p[i] == p[j] && t[i] > t[j];
}
private void run() {
try {
in = new FastScanner();
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Main().run();
}
FastScanner in;
PrintWriter out;
class FastScanner {
public BufferedReader reader;
private StringTokenizer tokenizer;
public FastScanner(String file) {
try {
reader = new BufferedReader(new FileReader(new File(file)));
tokenizer = null;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.util.Scanner;
public class CodeForces {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int ans = 0;
long x = n;
x = x*(x+1)/2;
while (x!=k) {
x-=n;
n--;
ans++;
k++;
}
System.out.println(ans);
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main{
class Node implements Comparable<Node>{
int l;
int r;
public Node(int l,int r){
this.l=l;
this.r=r;
}
public int compareTo(Node c){
int t=Integer.compare(this.r,c.r);
if(t!=0) return t;
t=Integer.compare(this.l,c.l);
return t;
}
}
void solve() {
int n=ni();
int a[]=new int[n+1];
long pref[]=new long[n+1];
for(int i=1;i<=n;i++){
a[i]=ni();
pref[i]=pref[i-1]+a[i];
}
PriorityQueue<Long> q=new PriorityQueue<>();
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++) q.offer(pref[j]-pref[i-1]);
}
int sz=1;
while(!q.isEmpty()){
long val=q.poll();
if(!mp.containsKey(val)){
mp.put(val,sz++);
}
}
vec=new Node[sz][];
int size[]=new int[sz];
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++) size[mp.get(pref[j]-pref[i-1])]++;
}
for(int i=1;i<sz;i++) vec[i]=new Node[size[i]];
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++) {
int idx=mp.get(pref[j]-pref[i-1]);
vec[idx][--size[idx]]=new Node(i,j);
}
}
for(int i=1;i<sz;i++) Arrays.sort(vec[i]);
for(int i=1;i<sz;i++){
solve(vec[i]);
}
pw.println(ans.size());
for(Node p : ans) pw.println(p.l+" "+p.r);
}
HashMap<Long,Integer> mp=new HashMap<>();
Node vec[][];
int cnt=0;
ArrayList<Node> ans=new ArrayList<>();
void solve(Node [] v){
int n=v.length;
if(n==0) return;
int dp[]=new int[n+1];
int prev[]=new int[n+1];
int mx[]=new int[n+1];
int mxid[]=new int[n+1];
for(int i=1;i<=n;i++){
Node p=v[i-1];
dp[i]=dp[i-1];
prev[i]=-1;
int l=1,r=i-1;
int idx=0;
while(l<=r){
int mid=(l+r)>>1;
if(v[mid-1].r<p.l){
idx=mid;
l=mid+1;
}else r=mid-1;
}
if(1+mx[idx]>dp[i]){
dp[i]=1+mx[idx];
prev[i]=mxid[idx];
}
mx[i]=mx[i-1];
mxid[i]=mxid[i-1];
if(dp[i]>mx[i]){
mx[i]=dp[i];
mxid[i]=i;
}
}
if (dp[n] > cnt){
cnt=dp[n];
ans.clear();
int id=n;
while(id>0){
if(dp[id]==dp[id-1]){
id--;
continue;
}
ans.add(new Node(v[id-1].l,v[id-1].r));
id=prev[id];
}
}
}
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 Main().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 (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
//package C;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Fire_Again {
static int N;
static int M;
static int K;
private class Pos {
public int r;
public int c;
int last;
public Pos(int r,int c, int last) {
this.r = r;
this.c = c;
this.last = last;
}
}
static ArrayList<Pos> pos = new ArrayList<>();
static boolean[][] used;// = new boolean[2001][2001];
static int[] rows = {-1,1,0,0};
static int[] cols = {0,0,-1,1};
int LAST = 0;
int lastRow = 1;
int lastCol = 1;
public static void main(String[] args) throws IOException {
Fire_Again fire_again = new Fire_Again();
BufferedReader bufferedReader =
new BufferedReader(new FileReader("input.txt"));
String[] nm = bufferedReader.readLine().split(" ");
N = Integer.parseInt(nm[0]) + 1;
M = Integer.parseInt(nm[1]) + 1;
K = Integer.parseInt(bufferedReader.readLine());
used = new boolean[N][M];
String[] rc = bufferedReader.readLine().split(" ");
for(int k = 0;k < rc.length;k+=2) {
int r = Integer.parseInt(rc[k]);
int c = Integer.parseInt(rc[k+1]);
pos.add(fire_again.new Pos(r,c,0));
}
fire_again.bfs();
PrintStream ps = new PrintStream("output.txt");
ps.printf("%d %d\n",fire_again.lastRow,fire_again.lastCol);
ps.flush();
ps.close();
}
Queue<Pos> queue = new LinkedList<>();
private void bfs() {
queue.addAll(pos);
for(Pos p : pos) {
used[p.r][p.c] = true;
// System.out.println("r = "+(p.r) + " c = " + (p.c));
}
while(!queue.isEmpty()) {
Pos p = queue.poll();
if(p.last > LAST) {
LAST = p.last;
lastRow = p.r;
lastCol = p.c;
}
for(int i = 0;i < rows.length;i++) {
int currR = p.r;
int currC = p.c;
if(currR + rows[i] >= 1 && currR + rows[i] < N &&
currC + cols[i] >= 1 && currC + cols[i] < M &&
!used[currR + rows[i] ] [currC + cols[i] ] ) {
// System.out.println("r = "+(currR+rows[i]) + " c = " + (currC+cols[i]));
queue.add(new Pos(currR+rows[i],currC+cols[i],p.last+1));
used[currR + rows[i] ] [currC + cols[i] ] = true;
}
}
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
/**
*
* @Har_Har_Mahadev
*/
public class D {
private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353;
private static int N = 0;
private static long[][][] dp;
private static long[][] ff;
private static long[][] ss;
public static void process() throws IOException {
int n = sc.nextInt(),m = sc.nextInt(),k = sc.nextInt();
ff = new long[n][m];
ss = new long[n][m];
for(int i = 0; i<n; i++) {
for(int j = 0; j<m-1; j++) {
ff[i][j] = sc.nextLong();
}
}
for(int i = 0; i<n-1; i++) {
for(int j = 0; j<m; j++) {
ss[i][j] = sc.nextLong();
}
}
if(k%2 == 1) {
for(int i = 0; i<n; i++) {
for(int j = 0; j<m; j++)System.out.print(-1+" ");
System.out.println();
}
return;
}
dp = new long[n+1][m+1][11];
for(int i = 0; i<=n; i++) {
for(int j = 0; j<=m; j++)Arrays.fill(dp[i][j], -1);
}
for(int i = 0; i<=n; i++) {
for(int j = 0; j<=m; j++) {
dp[i][j][0] = 0;
}
}
k/=2;
long ans[][] = new long[n][m];
for(int i = 0; i<n; i++) {
for(int j = 0; j<m; j++) {
ans[i][j] = solve(i,j,k,n,m)*2L;
}
}
for(int i = 0; i<n; i++) {
for(int j = 0; j<m; j++)print(ans[i][j]+" ");
println();
}
}
private static long solve(int i, int j, int k, int n, int m) {
if(dp[i][j][k] != -1)return dp[i][j][k];
long ans = Long.MAX_VALUE;
if(i+1<n) {
ans = min(ans,ss[i][j] + solve(i+1, j, k-1, n, m));
}
if(i-1>=0) {
ans = min(ans,ss[i-1][j] + solve(i-1, j, k-1, n, m));
}
if(j+1<m) {
ans = min(ans,ff[i][j] + solve(i, j+1, k-1, n, m));
}
if(j-1>=0) {
ans = min(ans,ff[i][j-1] + solve(i, j-1, k-1, n, m));
}
return dp[i][j][k] = ans;
}
//=============================================================================
//--------------------------The End---------------------------------
//=============================================================================
static FastScanner sc;
static PrintWriter out;
public static void main(String[] args) throws IOException {
boolean oj = true;
if (oj) {
sc = new FastScanner();
out = new PrintWriter(System.out);
} else {
sc = new FastScanner(100);
out = new PrintWriter("output.txt");
}
int t = 1;
// t = sc.nextInt();
while (t-- > 0) {
process();
}
out.flush();
out.close();
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof Pair)) return false;
// Pair key = (Pair) o;
// return x == key.x && y == key.y;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// return result;
// }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static void println(Object o) {
out.println(o);
}
static void println() {
out.println();
}
static void print(Object o) {
out.print(o);
}
static void pflush(Object o) {
out.println(o);
out.flush();
}
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static int max(int x, int y) {
return Math.max(x, y);
}
static int min(int x, int y) {
return Math.min(x, y);
}
static int abs(int x) {
return Math.abs(x);
}
static long abs(long x) {
return Math.abs(x);
}
static long sqrt(long z) {
long sqz = (long) Math.sqrt(z);
while (sqz * 1L * sqz < z) {
sqz++;
}
while (sqz * 1L * sqz > z) {
sqz--;
}
return sqz;
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
static long max(long x, long y) {
return Math.max(x, y);
}
static long min(long x, long y) {
return Math.min(x, y);
}
public static int gcd(int a, int b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
public static long gcd(long a, long b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.longValue();
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static int lower_bound(int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound(int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws FileNotFoundException {
br = new BufferedReader(new InputStreamReader(System.in));
}
FastScanner(int a) throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) throws IOException {
int[] A = new int[n];
for (int i = 0; i != n; i++) {
A[i] = sc.nextInt();
}
return A;
}
long[] readArrayLong(int n) throws IOException {
long[] A = new long[n];
for (int i = 0; i != n; i++) {
A[i] = sc.nextLong();
}
return A;
}
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
/*
Roses are red
Memes are neat
All my test cases time out
Lmao yeet
*/
import java.util.*;
import java.io.*;
public class B
{
public static void main(String args[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
//bin search
//ugh I'm shafting
long x = (long)N;
long low = 0L;
long high = N;
while(low != high)
{
x = (low+high+1)/2;
long add = (x*(x+1))/2;
long y = N-x;
if(add-y > K)
high = x;
else if(add-y == K)
{
System.out.println(y);
break;
}
else
low = x;
}
//run time?
}
public static void sort(int[] arr)
{
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for(int a: arr)
pq.add(a);
for(int i=0; i < arr.length; i++)
arr[i] = pq.poll();
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Pr468B {
public static void main(String[] args) throws IOException {
new Pr468B().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out, true);
solve();
out.flush();
}
int[] which;
boolean[] was;
int[] pa;
int[] pb;
void dfs(int i, boolean fa) {
was[i] = true;
if (fa) {
if (pa[i] == -1) {
out.println("NO");
out.flush();
System.exit(0);
}
which[i] = 0;
which[pa[i]] = 0;
if (pb[pa[i]] != -1 && !was[pb[pa[i]]]) {
dfs(pb[pa[i]], fa);
}
} else {
if (pb[i] == -1) {
out.println("NO");
out.flush();
System.exit(0);
}
which[i] = 1;
which[pb[i]] = 1;
if (pa[pb[i]] != -1 && !was[pa[pb[i]]]) {
dfs(pa[pb[i]], fa);
}
}
}
void solve() throws IOException {
int n = nextInt();
int a = nextInt();
int b = nextInt();
int[] p = new int[n];
HashMap<Integer, Integer> allNums = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
p[i] = nextInt();
if (p[i] >= Math.max(a, b)) {
out.println("NO");
return;
}
allNums.put(p[i], i);
}
pa = new int[n];
pb = new int[n];
Arrays.fill(pa, -1);
Arrays.fill(pb, -1);
which = new int[n];
Arrays.fill(which, -1);
for (int i = 0; i < n; i++) {
if (pa[i] == -1 && allNums.containsKey(a - p[i])) {
pa[i] = allNums.get(a - p[i]);
pa[pa[i]] = i;
}
if (pb[i] == -1 && allNums.containsKey(b - p[i])) {
pb[i] = allNums.get(b - p[i]);
pb[pb[i]] = i;
}
if (pa[i] == -1 && pb[i] == -1) {
out.println("NO");
return;
}
}
was = new boolean[n];
for (int i = 0; i < n; i++) {
if (!was[i] && pa[i] == -1) {
dfs(i, false);
} else if (!was[i] && pb[i] == -1) {
dfs(i, true);
}
}
for (int i = 0; i < n; i++) {
if (!was[i]) {
dfs(i, true);
}
}
out.println("YES");
for (int i = 0; i < n; i++) {
out.print(which[i] + " ");
}
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import static java.util.Arrays.sort;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A {
static void solve() throws Exception {
int n = scanInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanInt();
}
sort(a);
int ans = 0;
ans: while (true) {
for (int i = 0;; i++) {
if (i == n) {
break ans;
}
if (a[i] != 0) {
++ans;
int t = a[i];
a[i] = 0;
for (i++; i < n; i++) {
if (a[i] % t == 0) {
a[i] = 0;
}
}
break;
}
}
}
out.print(ans);
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static String scanString() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
public class x
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
int n;
String d="0";
n=obj.nextInt();
if(n%4==0 || n%7==0 || n%47==0 || n%74==0 || n%447==0 || n%474==0 || n%747==0)
d="YES";
else if(n%444==0 || n%477==0 || n%744==0 || n%774==0 || n%777==0)
d="YES";
else
d="NO";
System.out.print(d);
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.*;
import java.util.Scanner;
public class T
{
public static void main(String[] args) throws IOException
{
T t = new T();
t.run();
t.close();
}
private void close()
{
sc.close();
pw.close();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(reader);
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
void yesno(boolean b)
{
pw.println(b ? "YES" : "NO");
}
void run() throws IOException
{
int n = sc.nextInt();
if (n % 2 == 0)
{
pw.print(4 + " " + (n - 4));
}
else
{
pw.print(9 + " " + (n - 9));
}
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
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;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int balance = in.nextInt();
if (balance >= 0) {
out.println(balance);
return;
}
balance = -balance;
int a = balance / 100;
int b = Math.min(balance % 10, (balance / 10) % 10);
balance = -(a * 10 + b);
out.println(balance);
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class ProblemF {
private static boolean debug = false;
private static int N;
private static int[] A;
private static void solveProblem(InputStream instr) throws Exception {
InputReader sc = new InputReader(instr);
int testCount = 1;
if (debug) {
testCount = sc.nextInt();
}
for (int t = 1; t <= testCount; t++) {
printDebug("------ " + t + " ------");
N = sc.nextInt();
A = readInts(sc, N);
Object result = solveTestCase();
System.out.println(result);
}
}
private static Object solveTestCase() {
int sum[] = new int[N];
sum[0] = A[0];
for (int i = 1; i < N; i++) {
sum[i] = sum[i - 1] + A[i];
}
Map<Integer, List<int[]>> map = new HashMap<>();
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
int groupSum = sum[j] - (i == 0 ? 0 : sum[i - 1]);
map.putIfAbsent(groupSum, new ArrayList<>());
map.get(groupSum).add(new int[]{i, j});
}
}
int max = -1;
List<int[]> maxAnswer = null;
for (Map.Entry<Integer, List<int[]>> entry : map.entrySet()) {
List<int[]> values = entry.getValue();
if (values.size() <= max) {
continue;
}
List<int[]> curr = findMax(values);
if (curr.size() > max) {
max = curr.size();
maxAnswer = curr;
}
}
List<String> answer = new ArrayList<>();
for (int[] value : maxAnswer) {
answer.add((value[0] + 1) + " " + (value[1] + 1));
}
return max + "\n" + joinValues(answer, "\n");
}
private static List<int[]> findMax(List<int[]> values) {
values.sort(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1];
}
});
List<int[]> answer = new ArrayList<>();
int right = -1;
for (int i = 0; i < values.size(); i++) {
int[] value = values.get(i);
if (value[0] > right) {
answer.add(value);
right = value[1];
}
}
return answer;
}
private static int[] readInts(InputReader sc, int N) throws Exception {
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = sc.nextInt();
}
return arr;
}
private static String joinValues(List<? extends Object> list, String delim) {
return list.stream().map(Object::toString).collect(Collectors.joining(delim));
}
private static String joinValues(int[] arr, String delim) {
List<Object> list = new ArrayList<>();
for (Object value : arr) {
list.add(value);
}
return list.stream().map(Object::toString).collect(Collectors.joining(delim));
}
public static void printDebug(Object str) {
if (debug) {
System.out.println("DEBUG: " + str);
}
}
private static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int Chars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws Exception {
if (curChar >= Chars) {
curChar = 0;
Chars = stream.read(buf);
if (Chars <= 0)
return -1;
}
return buf[curChar++];
}
public final int nextInt() throws Exception {
return (int)nextLong();
}
public final long nextLong() throws Exception {
int c = read();
while (isSpaceChar(c)) {
c = read();
if (c == -1)
throw new IOException();
}
boolean negative = false;
if (c == '-') {
negative = true;
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 negative ? (-res) : (res);
}
public final int[] nextIntBrray(int size) throws Exception {
int[] arr = new int[size];
for (int i = 0; i < size; i++)
arr[i] = nextInt();
return arr;
}
public final String next() throws Exception {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.append((char)c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final String nextLine() throws Exception {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.append((char)c);
c = read();
} while (c != '\n' && c != -1);
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static void main(String[] args) throws Exception {
long currTime = System.currentTimeMillis();
if (debug) {
solveProblem(new FileInputStream(new File("input.in")));
System.out.println("Time: " + (System.currentTimeMillis() - currTime));
} else {
solveProblem(System.in);
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.awt.Point;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Solution15A {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException{
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException{
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException{
return Integer.parseInt(readString());
}
long readLong() throws IOException{
return Long.parseLong(readString());
}
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
public static void main(String[] args){
new Solution15A().run();
}
public void run(){
try{
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = "+(t2-t1));
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
static class Utils {
private Utils() {}
public static void mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int leftIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergeSort(a, leftIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
int[] leftArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
}
class Square implements Comparable<Square>{
public Square(int x, int a){
this.x = x;
this.a = a;
}
@Override
public int compareTo(Square o) {
if(this.x > o.x) return 1;
if(this.x < o.x) return -1;
return 0;
}
public int a, x;
}
void solve() throws IOException{
int n = readInt();
int t = readInt();
Square[] houses = new Square[n];
for(int i = 0; i < n; i++){
int a = readInt();
int b = readInt();
houses[i] = new Square(a, b);
}
Arrays.sort(houses);
int count = 0;
for(int i = 0; i < n; i++){
if(i == 0) count++;
else{
if(houses[i].x - houses[i].a/2.0 - t > houses[i-1].x + houses[i-1].a/2.0)
count++;
}
if(i == n - 1) count++;
else{
if(houses[i].x + houses[i].a/2.0 + t <= houses[i+1].x - houses[i+1].a/2.0)
count++;
}
}
out.println(count);
}
static double distance(long x1, long y1, long x2, long y2){
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
static long gcd(long a, long b){
while(a != b){
if(a < b) a -=b;
else b -= a;
}
return a;
}
static long lcm(long a, long b){
return a * b /gcd(a, b);
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.* ;
import java.util.* ;
import java.text.* ;
import java.math.* ;
import static java.lang.Math.min ;
import static java.lang.Math.max ;
import static java.lang.Math.sqrt ;
public class Codeshefcode{
public static void main(String[] args) throws IOException{
Solver Machine = new Solver() ;
Machine.Solve() ;
Machine.Finish() ;
// new Thread(null,new Runnable(){
// public void run(){
// Solver Machine = new Solver() ;
// try{
// Machine.Solve() ;
// Machine.Finish() ;
// }catch(Exception e){
// e.printStackTrace() ;
// System.out.flush() ;
// System.exit(-1) ;
// }catch(Error e){
// e.printStackTrace() ;
// System.out.flush() ;
// System.exit(-1) ;
// }
// }
// },"Solver",1l<<27).start() ;
}
}
class Mod{
static long mod=1000000007 ;
static long d(long a,long b){ return (a*MI(b))%mod ; }
static long m(long a,long b){ return (a*b)%mod ; }
static private long MI(long a){ return pow(a,mod-2) ; }
static long pow(long a,long b){
if(b<0) return pow(MI(a),-b) ;
long val=a ; long ans=1 ;
while(b!=0){
if((b&1)==1) ans = (ans*val)%mod ;
val = (val*val)%mod ;
b/=2 ;
}
return ans ;
}
}
class pair implements Comparable<pair>{
int x ; int y ;
pair(int x,int y){ this.x=x ; this.y=y ;}
public int compareTo(pair p){
return (this.x<p.x ? -1 : (this.x>p.x ? 1 : (this.y<p.y ? -1 : (this.y>p.y ? 1 : 0)))) ;
}
}
class Solver{
Reader ip = new Reader(System.in) ;
PrintWriter op = new PrintWriter(System.out) ;
public void Solve() throws IOException{
int n = ip.i() ; int r = ip.i() ;
double x[] = new double[n] ;
double y[] = new double[n] ;
for(int i=0 ; i<n ; i++) x[i] = ip.i() ;
for(int i=0 ; i<n ; i++){
double my = 0 ;
for(int j=0 ; j<i ; j++)
my = max(my,func(x[j],y[j],r,x[i])) ;
y[i] = my ;
}
for(int i=0 ; i<n ; i++) p((y[i]+r)+" ") ;
pln("") ;
}
double abd(double x,double y){
return x>y ? x-y : y-x ;
}
double func(double x1,double y1,double r,double x2){
if(abd(x1,x2)>(2*r)) return 0 ;
if(abd(x1,x2)==(2*r)) return y1 ;
double dx = x1-x2 ;
double dx2 = dx*dx ;
double val = sqrt(4*r*r-dx2) ;
return y1+val ;
}
void Finish(){
op.flush();
op.close();
}
void p(Object o){
op.print(o) ;
}
void pln(Object o){
op.println(o) ;
}
}
class mylist extends ArrayList<Integer>{}
class myset extends TreeSet<Integer>{}
class mystack extends Stack<Integer>{}
class mymap extends TreeMap<Long,Integer>{}
class Reader{
BufferedReader reader;
StringTokenizer tokenizer;
Reader(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("") ;
}
String s() throws IOException {
while (!tokenizer.hasMoreTokens()){
tokenizer = new StringTokenizer(
reader.readLine()) ;
}
return tokenizer.nextToken();
}
int i() throws IOException {
return Integer.parseInt(s()) ;
}
long l() throws IOException{
return Long.parseLong(s()) ;
}
double d() throws IOException {
return Double.parseDouble(s()) ;
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
import java.math.*;
// **** E1. Rotate Columns (easy version) ****
public class E1 {
static char [] in = new char [1000000];
public static void main (String [] arg) throws Throwable {
int t = nextInt();
C : for (int ii = 0; ii<t; ++ii) {
int n = nextInt();
int m = nextInt();
Pair [] P = new Pair [n*m];
int [][] g = new int [n][m];
for (int i = 0; i<n; ++i) {
for (int j = 0; j<m; ++j) {
g[i][j] = nextInt();
P[j + m*i] = new Pair (i, j, g[i][j]);
}
}
for (int i = 0; i<P.length; ++i) if (P[i] == null) continue C;
Arrays.sort(P);
HashSet<Integer> rotcols =new HashSet<Integer>();
for (int i = 0; i<n; ++i) {
//System.err.println("Adding " + P[i].j + " , " + P[i].L);
rotcols.add(P[i].j);
}
if (n <= 3 || rotcols.size() >= 3) {
//System.err.println("EASY");
int sum = 0;
for (int i = 0; i<n && i < P.length; ++i) sum += P[i].L;
System.out.println(sum);
} else {
// n == 4
if (P.length > 4) rotcols.add(P[4].j);
//Integer [] rr = rotcols.toArray(new Integer[0]);
int [] rot = new int [rotcols.size()];
int maxmax = 0;
A : while (true) {
for (int i = 0; i<rot.length; ++i) {
rot[i]++;
if (rot[i] == n) {
rot[i] = 0;
if (i == rot.length-1) break A;
} else {
break;
}
}
int [] max = new int [n];
for (int i = 0; i<n; ++i) {
int j = 0;
for (int col : rotcols) {
max[i] = Math.max(max[i], g[(i+rot[j])%n][col]);
j++;
}
}
int sum = 0;
for (int m2 : max) sum+= m2;
maxmax = Math.max(maxmax, sum);
}
System.out.println(maxmax);
}
}
}
/************** HELPER CLASSES ***************/
//static class HS extends HashSet<Integer>{public HS(){super();}public HS(int a){super(a);}};
//static class AL extends ArrayList<Integer>{public AL(){super();}public AL(int a){super (a);}};
static class Pair implements Comparable<Pair> {
int i,j;long L; public Pair(int xx, int yy, long LL){i=xx;j=yy;L=LL;}
public int compareTo(Pair p) { return (this.L > p.L) ? -1 : (this.L == p.L) ? this.i - p.i : 1;}
}
/************** FAST IO CODE FOLLOWS *****************/
public static long nextLong() throws Throwable {
long i = System.in.read();boolean neg = false;while (i < 33) i = System.in.read();if (i == 45) {neg=true;i=48;}i = i - 48;
int j = System.in.read();while (j > 32) {i*=10;i+=j-48;j = System.in.read();}return (neg) ? -i : i;
}
public static int nextInt() throws Throwable {return (int)nextLong();}
public static String next() throws Throwable {
int i = 0; while (i < 33 && i != -1) i = System.in.read(); int cptr = 0; while (i >= 33) { in[cptr++] = (char)i; i = System.in.read();}
return new String(in, 0,cptr);
}
/**** LIBRARIES ****/
public static long gcdL(long a, long b) {while (b != 0) {long tmp = b;b = (a % b);a = tmp;}return a;}
public static int gcd(int a, int b) {while (b != 0) {int tmp = b;b = (a % b);a = tmp;}return a;}
public static int[] sieve(int LIM) {
int i,count = 0;
boolean [] b = new boolean [LIM];
for (i = 2;i<LIM; ++i) if (!b[i]) {count++; for (int j = i<<1; j<LIM; j+=i) b[j] = true;}
int [] primes = new int[count];
for (i = 2,count=0;i<LIM;++i) if (!b[i]) primes[count++] = i;
return primes;
}
public static int[] numPrimeFactors(int LIM) {
int i,count = 0;
int [] b = new int [LIM];
for (i = 2;i<LIM; ++i) if (b[i] == 0) {count++; for (int j = i; j<LIM; j+=i) b[j]++;}
return b;
}
public static StringBuilder stringFromArray(int [] a) {
StringBuilder b = new StringBuilder(9*a.length);
for (int i = 0; i<a.length; ++i) {
if (i != 0) b = b.append(' ');
b = b.append(a[i]);
}
return b;
}
public static long modPow (long a, long n, long MOD) { long S = 1; for (;n > 0; n>>=1, a=(a*a)%MOD) if ((n & 1) != 0) S = (a*S) % MOD; return S;}
}
/* Full Problem Text:
This is an easier version of the next problem.
The difference is only in constraints.
You are given a rectangular n \times m matrix a.
In one move you can choose any column and cyclically shift elements in this column.
You can perform this operation as many times as you want (possibly zero).
You can perform this operation to a column multiple times.
After you are done with cyclical shifts, you compute for every row the maximal value in it.
Suppose that for i-th row it is equal r_i.
What is the maximal possible value of r_1+r_2+...+r_n?
*/
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
//package sept;
import java.io.*;
import java.util.*;
public class TimePass {
InputStream is;
PrintWriter out;
String INPUT = "";
//boolean codechef=true;
// String prodKey = "Av#/lL{OyEKiLR+/Ce%(w]^J65;XZe8FVb]]<931_=80E[BVnU^@4xu*J%KG3,CRqIZrUN~JJ+*6QC*CyBd>'$;>O"onO.bQ%{L}";
boolean codechef=true;
void solve()
{
int t=ni();
while(t-->0) {
int n=ni();
int root=(int)Math.sqrt(n/2);
int rootn = (int)Math.sqrt(n);
if (n==1 || n%2!=0) {
out.println("NO");
continue;
}
if (root*root == n/2 || (rootn*rootn == n && rootn%2==0)) {
out.println("YES");
} else {
out.println("NO");
}
}
}
static int comp(int a,int b){
return a+1097*b;
}
static long printNcR(int n, int r)
{
// p holds the value of n*(n-1)*(n-2)...,
// k holds the value of r*(r-1)...
long p = 1, k = 1;
// C(n, r) == C(n, n-r),
// choosing the smaller value
if (n - r < r) {
r = n - r;
}
if (r != 0) {
while (r > 0) {
p *= n;
k *= r;
// gcd of p, k
long m = __gcd(p, k);
// dividing by gcd, to simplify
// product division by their gcd
// saves from the overflow
p /= m;
k /= m;
n--;
r--;
}
// k should be simplified to 1
// as C(n, r) is a natural number
// (denominator should be 1 ) .
}
else {
p = 1;
}
// if our approach is correct p = ans and k =1
return p;
}
static long __gcd(long n1, long n2)
{
long gcd = 1;
for (int i = 1; i <= n1 && i <= n2; ++i) {
// Checks if i is factor of both integers
if (n1 % i == 0 && n2 % i == 0) {
gcd = i;
}
}
return gcd;
}
static long[][] dp;
static long desc(int[] a,int l,int r) {
if (l==r) return 0;
if (dp[l][r]!=-1) return dp[l][r];
dp[l][r] = a[r]-a[l] + Math.min(desc(a,l+1,r),desc(a,l,r-1));
return dp[l][r];
}
static int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
// A function to do counting sort of arr[] according to
// the digit represented by exp.
static void countSort(int arr[], int n, int exp)
{
int output[] = new int[n]; // output array
int i;
int count[] = new int[10];
Arrays.fill(count, 0);
// Store count of occurrences in count[]
for (i = 0; i < n; i++)
count[(arr[i] / exp) % 10]++;
// Change count[i] so that count[i] now contains
// actual position of this digit in output[]
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
// Build the output array
for (i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
// Copy the output array to arr[], so that arr[] now
// contains sorted numbers according to curent digit
for (i = 0; i < n; i++)
arr[i] = output[i];
}
// The main function to that sorts arr[] of size n using
// Radix Sort
static void radixsort(int arr[], int n)
{
// Find the maximum number to know number of digits
int m = getMax(arr, n);
// Do counting sort for every digit. Note that
// instead of passing digit number, exp is passed.
// exp is 10^i where i is current digit number
for (int exp = 1; m / exp > 0; exp *= 10)
countSort(arr, n, exp);
}
static int MAX=1500;
static int prime[], countdiv[];
static int[] getDivisorsArray() {
int n=20000005;
int[] mind = new int[n];
Arrays.fill(mind, -1);
for(int i=2;i<n;i++){
if (mind[i]==-1){
for(int j=i;j<n;j+=i){
if (mind[j]==-1){
mind[j]=i;
}
}
}
}
// int[] nod = new int[n];
// for(int i=2;i<n;i++){
// int prod = i/mind[i];
// if (mind[i] != mind[prod]) {
// nod[i] = nod[prod] + 1;
// } else {
// nod[i] = nod[prod];
// }
// }
return mind;
}
// Simple sieve to find smallest prime factors of numbers
// smaller than MAX
void SieveOfEratosthenes()
{
for (int i = 2; i * i < MAX; ++i)
{
if (prime[i]==0)
for (int j = i * i; j < MAX; j += i)
prime[j] = i;
}
// Prime number will have same divisor
for (int i = 1; i < MAX; ++i)
if (prime[i]==0)
prime[i] = i;
}
// Returns length of the largest subsequence
// with GCD more than 1.
int largestGCDSubsequence(int arr[], int n)
{
int ans = 0;
for (int i=0; i < n; ++i)
{
int element = arr[i];
// Fetch total unique prime divisor of element
while (element > 1)
{
int div = prime[element];
// Increment count[] of Every unique divisor
// we get till now
++countdiv[div];
// Find maximum frequency of divisor
ans = Math.max(ans, countdiv[div]);
while (element % div==0)
element /= div;
}
}
return ans;
}
static boolean check(int x)
{
char[] a=(""+x).toCharArray();
int s=0;
for(int i=0;i<a.length;i++)
{
s+=a[i]-'0';
s%=3;
}
if(s==0)return true;
return false;
}
static int[][] packD(int n,int[] from,int[] to)
{
int[][] g=new int[n][];
int[] p=new int[n];
for(int f:from)
{
p[f]++;
}
int m=from.length;
for(int i=0;i<n;i++)
{
g[i]=new int[p[i]];
}
for(int i=0;i<m;i++)
{
g[from[i]][--p[from[i]]]=to[i];
}
return g;
}
static class Pair3
{
int a,b,c;
public Pair3(int a,int b,int c)
{
this.a=a;
this.b=b;
this.c=c;
}
}
static class Pair
{
int a,b;
public Pair(int a,int b)
{
this.a=a;
this.b=b;
}
}
static long lcm(long a,long b)
{
long val=a;
val*=b;
return (val/gcd(a,b));
}
static long gcd(long a,long b)
{
if(a==0)return b;
return gcd(b%a,a);
}
static int pow(int a, int b, int p)
{
long ans = 1, base = a;
while (b!=0)
{
if ((b & 1)!=0)
{
ans *= base;
ans%= p;
}
base *= base;
base%= p;
b >>= 1;
}
return (int)ans;
}
static int inv(int x, int p)
{
return pow(x, p - 2, p);
}
void run() throws Exception
{
if(codechef)oj=true;
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 TimePass().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)); }
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class template
{
private InputStream is;
private PrintWriter pw;
static char[][] ch;
static int x1,x2,y1,y2,n,m,h,k;
static long dist[][];
static boolean boo[][];
void soln()
{
is = System.in;
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.close();
pw.flush();
// tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception
{
new Thread(null, new Runnable()
{
public void run()
{
try
{
// new CODEFORCES().soln();
} catch (Exception e)
{
System.out.println(e);
}
}
}, "1", 1 << 26).start();
new template().soln();
}
void solve()
{
long n = nl(), k = nl();
if(n==0){
pw.println(0);
return;
}
long MOD = 1000000007;
long pow1 = pow(2,k,MOD), pow2 = pow(2,k+1,MOD);
pw.println(((((n%MOD)*pow2)%MOD) - (pow1-1+MOD)%MOD + 2*MOD)%MOD);
pw.close();
}
long pow(long x, long y, long mod){
long ans = 1;
while(y>0){
if(y%2==0) {
x *= x;
x %= mod;
y/=2;
}
else{
ans *= x;
ans %= mod;
y-=1;
}
}
return ans;
}
long gcd(long a, long b){
if(b==0) return a;
return gcd(b,a%b);
}
void printArray(long[] arr) {
for(long i : arr) pw.print(i +" ");
pw.println();
}
static long min(long x, long y){
return (x<y)?x:y;
}
static class Pair implements Comparable<Pair>{
long val;
int x, y;
Pair(long v, int a, int b){
val = v; x = a; y = b;
}
public int compareTo(Pair p){
return Long.compare(this.val,p.val);
}
}
private static class Queue{
int st = 0;
int et = 0;
Pair[] arr;
public Queue(int len) {
arr = new Pair[len];
}
public boolean isEmpty() {
return st==et;
}
public void add(Pair x) {
arr[et++] = x;
}
public Pair poll() {
return arr[st++];
}
public void clear() {
st = et = 0;
}
}
/*void bfs(int k) {
while(!q.isEmpty()) {
int y = q.poll();
for(long i : amp[y]) {
if(!b[i]) {
D[i][k] = D[y][k]+1;
q.add(i);
b[i] = true;
}
}
}
}
*/
/*
int dfs(int x) {
b[x] = true;
//start[x] = time++;
int ans = 1;
for(int i : amp[x]) {
if(!b[i]) {
ans += dfs(i);
}
}
//end[x] = time;
if(x!= 0 && ans%2==0 && (N-ans)%2==0) cost++;
return ans;
}*/
/*void buildGraph(int n)
{
for (int i = 0; i < n; i++)
{
int x1 = ni() - 1, y1 = ni() - 1;
amp[x1].add(y1);
amp[y1].add(x1);
}
}*/
public static int[] shuffle(int[] a, Random gen)
{
for (int i = 0, n = a.length; i < n; i++)
{
int ind = gen.nextInt(n - i) + i;
int d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
// To Get Input
// Some Buffer Methods
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));
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
public class A {
static class team implements Comparable<team>
{
int problems;
int penalty;
public team(int problems,int penalty)
{
this.penalty=penalty;
this.problems=problems;
}
public int compareTo(team a) {
if (a.problems==this.problems)
return this.penalty - a.penalty;
return a.problems - this.problems;
}
public boolean igual(team a)
{
if (this.problems!=a.problems)
return false;
return (this.penalty==a.penalty);
}
}
static class Scanner
{
BufferedReader rd;
StringTokenizer tk;
public Scanner() throws IOException
{
rd=new BufferedReader(new InputStreamReader(System.in));
tk=new StringTokenizer(rd.readLine());
}
public String next() throws IOException
{
if (!tk.hasMoreTokens())
{
tk=new StringTokenizer(rd.readLine());
return tk.nextToken();
}
return tk.nextToken();
}
public int nextInt() throws NumberFormatException, IOException
{
return Integer.valueOf(this.next());
}
}
static team[] array=new team[100];
static int N,K;
public static void main(String args[]) throws IOException
{
Scanner sc=new Scanner();
N=sc.nextInt();
K=sc.nextInt();
for(int i=0;i<N;i++)
{
array[i]=new team(sc.nextInt(),sc.nextInt());
}
Arrays.sort(array,0,N);
/*
for(int i=0;i<N;i++)
System.out.println(array[i].problems);*/
int shared=0;
for(int i=K-1;i>=0 && array[K-1].igual(array[i]);i--,shared++);
for(int i=K;i<N && array[K-1].igual(array[i]);i++,shared++);
System.out.println(shared);
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.text.DecimalFormat;
import java.io.*;
import java.util.*;
import java.lang.reflect.Array;
/**
* @author Mukesh Singh
*
*/
public class AB {
private InputStream input;
private PrintStream output;
private Scanner inputSc;
public AB(InputStream input, PrintStream output) {
this.input = input;
this.output = output;
init();
}
private void init() {
inputSc = new Scanner(input);
}
static int lineToInt(String line) {
return Integer.parseInt(line);
}
static long lineToLong(String line) {
return Long.parseLong(line);
}
static double lineToDouble(String line) {
return Double.parseDouble(line);
}
public void solve()
{
solveTestCase();
}
/**
* @define global / instance variables
*/
HashMap<Integer,Integer> mat ;
long dist[] ;
int vec[] ;
int ar[] ;
Set<Integer> st ;
boolean isDone[] ;
final long INF = 100000000000000000L ;
/**
* @solve test case
*/
@SuppressWarnings("unchecked")
private void solveTestCase()
{
int i , j , k , n , m , d , l ,b , p , q , r;
long N , M, K;
int x1 , y1 , x2 , y2 ,x;
int a1,a2,b1,b2,a ;
DecimalFormat df = new DecimalFormat("#,###,##0.00");
String str = inputSc.nextLine();
String delims = "[ ]+";
String tokens[] = str.split(delims);
n = lineToInt(tokens[0]);
a = lineToInt(tokens[1]);
b = lineToInt(tokens[2]);
mat = new HashMap<Integer,Integer>() ;
st = new TreeSet<Integer>();
ar = new int[n+4] ;
vec = new int[n+4] ;
str = inputSc.nextLine();
tokens = str.split(delims);
for( i = 1 ; i <= n ; i++ )
{
ar[i] = lineToInt(tokens[i-1]);
mat.put(ar[i],i) ;
st.add(ar[i]);
vec[i] = i ;
}
vec[n+1] = n+1 ;
vec[n+2] = n+2 ;
for( i = 1 ; i <= n ; i++ )
{
x= ar[i];
if(st.contains(a-x))
{
Bing(mat.get(x),mat.get(a-x));
}
else
Bing(n+1 , mat.get(x));
if(st.contains(b-x))
{
Bing(mat.get(x),mat.get(b-x));
}
else
Bing(n+2 , mat.get(x));
}
if(find(n+1)==find(n+2))
{
output.println("NO");
return ;
}
output.println("YES");
for( i =1 ; i<= n ; i ++ )
{
if(find(i)==find(n+1))
output.print("1 ");
else
output.print("0 ");
}
output.println();
}
int find(int x)
{
if(x==vec[x]) return x;
return vec[x]=find(vec[x]);
}
void Bing(int a,int b)
{
int A=find(a);int B=find(b);
if(A==B) return ;
vec[B]=A;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
FileInputStream in = null;
FileOutputStream out = null;
PrintStream ps = null ;
InputStream is = null ;
try
{
is = new FileInputStream("file.in");
out = new FileOutputStream("file.out");
ps = new PrintStream(out);
}
catch ( Exception e )
{}
AB sd = new AB(System.in, System.out);
sd.solve();
try
{
if (is != null)
{
is.close();
}
if (out != null) {
out.close();
}
if (ps != null) {
ps.close();
}
}catch (Exception e){}
//SquareDetector sd = new SquareDetector(System.in, System.out);
//sd.solve();
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
// package Practice1.CF35;
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class CF035C {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(new File("input.txt")/*System.in*/);
int n = s.nextInt();
int m = s.nextInt();
int k = s.nextInt();
// pair[] arr = new pair[n];
Queue<pair> q = new LinkedList<>();
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
boolean[][] visited = new boolean[n][m];
for (int i = 0; i < k; i++) {
int x = s.nextInt() - 1;
int y = s.nextInt() - 1;
visited[x][y] = true;
pair p = new pair(x,y);
// arr[i] = p;
q.add(p);
}
q.add(null);
int[] dx = {0,0,1,-1};
int[] dy = {1,-1,0,0};
int ansX = q.peek().x;
int ansY = q.peek().y;
while(true){
if(q.peek() == null){
q.poll();
q.add(null);
}
pair p = q.poll();
if(p == null){
break;
}
for (int i = 0; i < 4; i++) {
if(isValid(p.x + dx[i],p.y+dy[i],n,m) && !visited[p.x + dx[i]][p.y+dy[i]]){
q.add(new pair(p.x + dx[i],p.y+dy[i]));
ansX = p.x + dx[i];
ansY = p.y + dy[i];
visited[ansX][ansY] = true;
}
}
}
out.println((ansX+1) + " " + (ansY+1));
out.close();
}
public static boolean isValid(int x, int y,int n, int m){
return x >= 0 && x < n && y >= 0 && y < m;
}
private static class pair{
int x;
int y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
/**
* Created by 11815 on 2017/7/1.
*/
public class Main {
private static int[] x = new int[26], y = new int[26], dp = new int[1<<24], pre = new int[1<<24];
private static int dis(int i, int j) {
return (x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x0 = in.nextInt(), y0 = in.nextInt(), n = in.nextInt();
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
x[n] = x0;
y[n] = y0;
int[][] gra = new int[26][26];
for (int i = 0; i < n + 1; i++) {
for (int j = i+1; j < n+1; j++) {
gra[i][j] = gra[j][i] = dis(i,j);
}
}
Arrays.fill(dp, -1);
dp[0] = 0;
for (int i = 0; i < 1 << n; i++) {
if (dp[i] != -1) {
for (int j = 0; j < n; j++) {
if (((1<<j)&i) == 0) {
int t = i | (1<<j), tmp = dp[i] + 2*gra[j][n];
if (dp[t] == -1 || dp[t] > tmp) {
dp[t] = tmp;
pre[t] = i;
}
for (int k = 0; k < n; k++) {
if ((t&(1<<k)) == 0) {
int t2 = t | (1<<k), tmp2 = dp[i] + gra[n][j] + gra[j][k] + gra[k][n];
if (dp[t2] == -1 || dp[t2] > tmp2) {
dp[t2] = tmp2;
pre[t2] = i;
}
}
}
break;
}
}
}
}
int end = (1<<n)-1, cnt = 0;
int[] ans = new int[60];
System.out.println(dp[end]);
while (end != 0) {
int pr = pre[end];
int tem = pr^end;
int a = 0, b = 0;
for (int i = 0; i < n; i++) {
if (((1<<i)&tem)!=0) {
b=a;
a=i+1;
}
}
ans[cnt++] = 0;
ans[cnt++] = a;
if (b>0) {
ans[cnt++] = b;
}
end = pr;
}
ans[cnt++] = 0;
for (int i = cnt-1; i >= 0; i--) {
System.out.print(ans[i] + " ");
}
System.out.print("\n");
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.text.*;
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int t = scan.nextInt();
List<Double> coords = new ArrayList<Double>();
while (n-- > 0) {
double x = scan.nextDouble();
double a = scan.nextDouble() / 2;
coords.add(x - a);
coords.add(x + a);
}
Collections.sort(coords);
int count = 2;
ChoiceFormat f = new ChoiceFormat("-1#0|0#1|0<2");
for (int i = 1; i < coords.size()-2; i+=2) {
count += new Integer(f.format(coords.get(i+1)-coords.get(i)-t));
}
System.out.println(count);
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.*;
import static java.lang.System.*;
import static java.lang.Math.*;
public class C {
static int[] dp;
static int[] f;
static void solve(){
dp = new int[1<<n];
f = new int[1<<n];
Arrays.fill(dp, 1<<29);
dp[0] = 0;
for(int i=0;i<(1<<n);i++){
// out.println("i="+i);
for(int j=0;j<n;j++){
int ni = i | (1<<j);
if( i != ni ){
// out.println("i="+i+",j="+j);
int v = d[j]*2 + dp[i];
if(v < dp[ni]){
// out.println("up:"+ni+" to "+v + " fw="+i);
dp[ni] = v;
f[ni] = i;
}
for(int k=j+1;k<n;k++){
int nni = ni | (1<<k);
if( ni != nni){
int vv = d[j] + t[j][k] + d[k] + dp[i];
if(vv < dp[nni]){
// out.println("up:"+nni+" to "+vv + " fw="+i);
dp[nni] = vv;
f[nni] = i;
}
}
}
break;
}
}
}
out.println(dp[dp.length-1]);
// out.println("dp="+Arrays.toString(dp));
// out.println("f="+Arrays.toString(f));
int idx = dp.length - 1;
out.print("0 ");
while(idx != 0){
int road = idx ^ f[idx];
// out.println("idx = "+idx + " f[idx] = "+f[idx]);
for(int i=0;i<n;i++) if( ((road>>i) & 1) == 1) out.print((i+1)+" ");
idx = f[idx];
out.print("0 ");
}
out.println();
}
static int[] d;
static int[][] t;
static int n;
public static void main(String[] args) {
Scanner sc = new Scanner(in);
int x = sc.nextInt();
int y = sc.nextInt();
n = sc.nextInt();
int[] dx = new int[n];
int[] dy = new int[n];
for(int i=0;i<n;i++){
dx[i] = sc.nextInt();
dy[i] = sc.nextInt();
}
d = new int[n];
for(int i=0;i<n;i++){
d[i] = (x-dx[i])*(x-dx[i]) + (y-dy[i])*(y-dy[i]);
}
t = new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
t[i][j] = (dx[i]-dx[j])*(dx[i]-dx[j]) + (dy[i]-dy[j])*(dy[i]-dy[j]);
}
}
// out.println(Arrays.toString(d));
// out.println(Arrays.deepToString(t));
solve();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class e {
private void main() {
Scanner stdin = new Scanner(System.in);
PrintStream stdout = System.out;
int n = stdin.nextInt();
double[][] p = new double[n][n];
double[][] ans = new double[1<<n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
p[i][j] = stdin.nextDouble();
double[] dieChance = new double[n];
ArrayList<Integer> sel = new ArrayList<Integer>();
for(int i = 0; i < (1<<n); i++) {
sel.clear();
for(int k = 0; k < n; k++) {
if((i & (1<<k)) != 0)
sel.add(k);
}
if(sel.size() == 1) {
ans[i][sel.get(0)] = 0;
continue;
}
for(int j : sel)
dieChance[j] = 0;
for(int j : sel)
for(int k : sel)
dieChance[k] += p[j][k];
for(int j : sel)
dieChance[j] /= sel.size()*(sel.size()-1)/2;
for(int j : sel) {
ans[i][j] = dieChance[j];
for(int k : sel)
ans[i][j] += dieChance[k] * ans[i-(1<<k)][j];
}
}
for(double d : ans[(1<<n)-1])
stdout.format("%f ", 1-d);
stdout.println();
}
public static void main(String[] args) {
new e().main();
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.Scanner;
public class Question267A {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while (t--!=0){
int x=sc.nextInt();
int y=sc.nextInt();
int max=Math.max(x,y);
int min=Math.min(x,y);
int ans=0;
while (min>0 && max>0){
int temp=max;
ans+=temp/min;
max=min;
min=temp%min;
}
System.out.println(ans);
}
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.awt.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(), m = scanner.nextInt();
int[] vertical = new int[n];
for (int i = 0; i < n; i++) {
vertical[i] = scanner.nextInt();
}
Arrays.sort(vertical);
ArrayList<Integer> horisontal = new ArrayList<>();
int amount = 0;
for (int i = 0; i < m; i++) {
int x1 = scanner.nextInt(), x2 = scanner.nextInt(), y = scanner.nextInt();
if (x1 == 1) {
amount++;
horisontal.add(x2);
}
}
Collections.sort(horisontal);
if (amount == 0) {
System.out.println(0);
return;
}
int minVal = amount, horSize = horisontal.size(), verLen = vertical.length;
int h = 0, v = 0;
for (; v < verLen && h < horSize; ) {
while (h < horSize && horisontal.get(h) < vertical[v]){
h++;
amount--;
}
minVal = Math.min(minVal, amount + v);
while (h < horSize && v < verLen && horisontal.get(h) >= vertical[v]){
minVal = Math.min(minVal, amount + v);
v++;
}
}
if(horisontal.get(horSize - 1) < 1E9){
minVal = Math.min(minVal, v);
}
System.out.println(minVal);
}
}
|
nlogn
|
1075_C. The Tower is Going Home
|
CODEFORCES
|
// practice with rainboy
import java.io.*;
import java.util.*;
public class CF256B extends PrintWriter {
CF256B() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF256B o = new CF256B(); o.main(); o.flush();
}
long count(int n, int x, int y, int r) {
long a = 2L * r * r + 2 * r + 1;
int w;
if ((w = 1 - (x - r)) > 0)
a -= (long) w * w;
if ((w = 1 - (y - r)) > 0)
a -= (long) w * w;
if ((w = (x + r) - n) > 0)
a -= (long) w * w;
if ((w = (y + r) - n) > 0)
a -= (long) w * w;
if ((w = r - 1 - (x - 1) - (y - 1)) > 0)
a += (long) w * (w + 1) / 2;
if ((w = r - 1 - (x - 1) - (n - y)) > 0)
a += (long) w * (w + 1) / 2;
if ((w = r - 1 - (n - x) - (y - 1)) > 0)
a += (long) w * (w + 1) / 2;
if ((w = r - 1 - (n - x) - (n - y)) > 0)
a += (long) w * (w + 1) / 2;
return a;
}
void main() {
int n = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
int c = sc.nextInt();
int lower = -1, upper = c;
while (upper - lower > 1) {
int r = (lower + upper) / 2;
if (count(n, x, y, r) >= c)
upper = r;
else
lower = r;
}
println(upper);
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
import java.util.*;
public class PythonIndentation {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
int a[]=new int[t];
int c=0;
a[0]=1;
long mod=(long) (1e9+7);
sc.nextLine();
for(int i=0;i<t;i++)
{
String s=sc.nextLine();
if(s.equals("f"))
c++;
else
{
for(int j=1;j<=c;j++)
{
a[j]=(int) (((a[j]%mod)+(a[j-1]%mod))%mod);
}
}
}
System.out.println(a[c]);
sc.close();
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) throws Exception {
new B().solve();
}
void solve() throws IOException {
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
// Scanner sc = new Scanner(System.in);
String[] sp = in.readLine().split(" ");
int n = Integer.parseInt(sp[0]);
int k = Integer.parseInt(sp[1]);
int[] a = new int[n];
sp = in.readLine().split(" ");
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(sp[i]);
}
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int r = 0;
map.put(a[r], 1);
while (map.size() < k) {
r++;
if (r == n) {
// ng
System.out.println("-1 -1");
return;
}
if (map.containsKey(a[r])) {
map.put(a[r], map.get(a[r]) + 1);
} else {
map.put(a[r], 1);
}
}
int l = 0;
while (map.get(a[l]) > 1) {
map.put(a[l], map.get(a[l]) - 1);
l++;
}
System.out.println((l + 1) + " " + (r + 1));
}
}
//
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A6
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int d = in.nextInt();
int ans=2;
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = in.nextInt();
for(int i=1;i<n;i++)
{
if(a[i]-a[i-1]>2*d)
{
ans += 2;
}
else if(a[i]-a[i-1]==2*d)
ans += 1;
}
System.out.println(ans);
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import com.sun.swing.internal.plaf.basic.resources.basic;
public class Main {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
private void solution() throws IOException {
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[] prev = new int[1 << n];
Arrays.fill(dp, Integer.MAX_VALUE / 2);
dp[0] = 0;
prev[0] = -1;
for (int mask = 0; mask < (1 << n); ++mask) {
if (dp[mask] != Integer.MAX_VALUE / 2) {
for (int next = 0; next < n; ++next) {
if (((mask >> next) & 1) == 0) {
int nmask = mask | (1 << next);
int val = dp[mask] + 2 * getDist(sx, sy, x[next], y[next]);
if (dp[nmask] > val) {
dp[nmask] = val;
prev[nmask] = mask;
}
for (int next2 = next + 1; next2 < n; ++next2) {
if (((nmask >> next2) & 1) == 0) {
int nnmask = nmask | (1 << next2);
int nval = dp[mask] + getDist(sx, sy, x[next], y[next])
+ getDist(x[next], y[next], x[next2], y[next2])
+ getDist(x[next2], y[next2], sx, sy);
if (dp[nnmask] > nval) {
dp[nnmask] = nval;
prev[nnmask] = mask;
}
}
}
break;
}
}
}
}
List<Integer> res = new ArrayList<Integer>();
res.add(0);
int mask = (1 << n) - 1;
while (mask > 0) {
for (int i = 0; i < n; ++i) {
if (((prev[mask] >> i) & 1) == 0 && ((mask >> i) & 1) == 1) {
res.add(i + 1);
}
}
res.add(0);
mask = prev[mask];
}
Collections.reverse(res);
out.println(dp[(1 << n) - 1]);
for (int i = 0; i < res.size(); ++i) {
if (i != 0) {
out.print(" ");
}
out.print(res.get(i));
}
out.println();
out.flush();
}
private int getDist(int x1, int y1, int x2, int y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
private class Scanner {
private StringTokenizer tokenizer;
private BufferedReader reader;
public Scanner(Reader in) {
reader = new BufferedReader(in);
tokenizer = new StringTokenizer("");
}
public boolean hasNext() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String tmp = reader.readLine();
if (tmp == null)
return false;
tokenizer = new StringTokenizer(tmp);
}
return true;
}
public String next() throws IOException {
hasNext();
return tokenizer.nextToken();
}
public String nextLine() throws IOException {
tokenizer = new StringTokenizer("");
return reader.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
public static void main(String[] args) throws IOException {
new Main().solution();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.