src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.util.*;
public class inversions {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] values = new int[N];
for(int i=0;i<N;i++){
values[i] = sc.nextInt();
}
int query = sc.nextInt();
int[][] tasks = new int[query][2];
for(int i=0;i<query;i++){
tasks[i][0] = sc.nextInt();
tasks[i][1] = sc.nextInt();
}
int startinversions = 0;
for(int i=1;i<values.length;i++){
for(int j=i-1;j>=0;j--){
if(values[i]<values[j]){
startinversions++;
}
}
}
int value = startinversions%2;
for(int[] task : tasks){
int n = task[1]-task[0];
if(n*(n+1)/2 % 2 != 0){
value = (value+1)%2;
}
if(value==1){
System.out.println("odd");
}
else{
System.out.println("even");
}
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
/**
* @param args
*/
static long[] dx = new long[]{0, 1, 0, -1};
static long[] dy = new long[]{-1, 0, 1, 0};
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
long N = r.nextLong();
long X = r.nextLong();
long Y = r.nextLong();
long C = r.nextLong();
long lo = 0, hi = N * 2;
while(lo < hi){
long T = (lo + hi) / 2;
long[] NX = new long[4];
long[] NY = new long[4];
for(int d = 0; d < 4; d++){
NX[d] = X + dx[d] * T;
NY[d] = Y + dy[d] * T;
}
long ret = (T + 1) * (T + 1) + T * T;
ret -= half(1 - NY[0]);
ret -= half(NY[2] - N);
ret -= half(NX[1] - N);
ret -= half(1 - NX[3]);
ret += quarter(1 - NY[0] - (N - X + 1));
ret += quarter(1 - NY[0] - (X));
ret += quarter(NY[2] - N - (N - X + 1));
ret += quarter(NY[2] - N - (X));
if(ret < C)lo = T + 1;
else hi = T;
}
System.out.println(lo);
}
private static long half(long x) {
if(x <= 0)return 0;
else return 2 * quarter(x) - x;
}
private static long quarter(long x){
if(x <= 0)return 0;
return x * (x + 1) / 2;
}
}
|
logn
|
256_B. Mr. Bender and Square
|
CODEFORCES
|
import java.io.*;
public class N72A
{
StreamTokenizer in;
PrintWriter out;
int nextInt() throws IOException
{
in.nextToken();
return (int) in.nval;
}
double nextDouble() throws IOException
{
in.nextToken();
return in.nval;
}
public void init() throws Exception
{
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
Reader reader = oj ? new InputStreamReader(System.in) : new FileReader(new File("input.txt"));
Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter(new File("output.txt"));
in = new StreamTokenizer(reader);
out = new PrintWriter(writer);
}
public void solve() throws Exception
{
int n = nextInt();
out.print(2*n - (n/2));
}
public void print() throws Exception
{
out.flush();
}
public void run() throws Exception
{
init();
solve();
print();
}
public static void main(String[] args) throws Exception
{
new N72A().run();
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
public static void main (String [] args) throws IOException {
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int [] nums = new int[n];
args = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
nums[i] = Integer.parseInt(args[i]);
}
Arrays.sort(nums);
int min = nums[0];
for (int i = 1; i < n; i++) {
if (nums[i]>min) {
System.out.println(nums[i]); return;
}
}
System.out.println("NO");
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter pw = new PrintWriter(System.out);
in.nextToken();
int n = (int) in.nval;
double[][] a = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
in.nextToken();
a[i][j] = in.nval;
}
}
double[] dp = new double[1 << n];
dp[(1 << n) - 1] = 1.0;
for (int mask = (1 << n) - 2; mask > 0; mask--) {
int count = Integer.bitCount(mask);
double pPair = 2.0 / ((double) count * (count + 1));
double ans = 0.0;
for (int j = 0; j < n; j++) {
int jj = 1 << j;
if ((jj & mask) != 0) continue;
double p = dp[mask | jj];
double s = 0;
for (int k = 0; k < n; k++) {
int kk = 1 << k;
if ((kk & mask) == 0) continue;
s += a[k][j];
}
ans += s * pPair * p;
}
dp[mask] = ans;
}
for (int i = 0; i < n; i++) {
pw.print(dp[1 << i]);
pw.print(' ');
}
pw.close();
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import static java.util.Arrays.*;
import static java.lang.Math.*;
import java.math.*;
public class Main {
void run() throws IOException {
String s = token();
HashSet <String> h;
int n = s.length();
int r = 0;
loop: for (int i = 1; i <= n; i++) {
h = new HashSet();
for (int j = 0; j < n - i + 1; j++) {
String t = s.substring(j, j + i);
if (h.contains(t)) {
r = i;
continue loop;
} else {
h.add(t);
}
}
}
System.out.println(r);
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
//final String FILENAME = "dvd";
//in = new BufferedReader(new FileReader(new File(FILENAME + ".in")));
//out = new PrintWriter(new File(FILENAME + ".out"));
in = new BufferedReader(new InputStreamReader(System.in));
//in = new Scanner(System.in);
out = new PrintWriter(System.out);
st = new StringTokenizer(" ");
new Main().run();
out.close();
}
static BufferedReader in;
//static Scanner in;
static PrintWriter out;
static StringTokenizer st;
String token() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nint() throws IOException {
return Integer.parseInt(token());
}
long nlong() throws IOException {
return Long.parseLong(token());
}
double ndouble() throws IOException {
return Double.parseDouble(token());
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.*;
import java.text.*;
import java.math.*;
public class Main{
static double EPS=1e-10;
static double PI=Math.acos(-1.0);
static double p[][]=new double[25][25];
static double f[]=new double[1<<20];
static int n;
public static void PR(String s){
System.out.print(s);
}
public static void PR(double s)
{
java.text.DecimalFormat d=new java.text.DecimalFormat("#.0000000");
System.out.print(d.format(s));
}
public static void DP()
{
int i,j,k,cnt;
for(i=0;i<(1<<n);i++) f[i]=0;
f[(1<<n)-1]=1;
for(k=(1<<n)-1;k>=0;k--)
{
cnt=0;
for(i=0;i<n;i++) if((k&(1<<i))!=0) cnt++;
for(i=0;i<n;i++) if((k&(1<<i))!=0)
{
for(j=0;j<n;j++) if(i!=j&&(k&(1<<j))!=0)
{
f[k^(1<<j)]+=f[k]*p[i][j]/((cnt-1)*cnt/2);
}
}
}
}
public static void main(String[] args){
Scanner S=new Scanner(System.in);
while(S.hasNext())
{
n=S.nextInt();
int i,j;
for(i=0;i<n;i++) for(j=0;j<n;j++) p[i][j]=S.nextDouble();
DP();
for(i=0;i<n;i++)
{
if(i!=0) PR(" ");
PR(f[1<<i]);
}
PR("\n");
}
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author madi
*/
public class Speadsheets {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String code = "";
for (int i = 0; i < n; i++) {
long chResult = 0;
long chResult1 = 0;
long nResult = 0;
long nResult1 = 0;
boolean t = false;
boolean k = false;
code = sc.nextLine();
for (int j = 0; j < code.length(); j++) {
char c = code.charAt(j);
if (('Z' - c) < 33) {
if (t) {
chResult1 = chResult;
chResult = 0;
t = false;
k = true;
}
chResult = chResult * 26 + (26 - ('Z' - c));
} else {
t = true;
if (k) {
nResult1 = nResult;
nResult = 0;
k = false;
}
nResult = nResult * 10 + (9 - ('9' - c));
}
}
if (chResult1 == 0) {
System.out.println("R" + nResult + "C" + chResult);
} else {
System.out.println(convert(nResult) + nResult1);
}
}
}
private static String convert(long number) {
String [] chars = new String[]{"Z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"};
String result = "";
int rem = 0;
int m = 0;
while (number > 0) {
m = 0;
rem = (int) (number % 26);
result = chars[rem] + result;
/*if (number == 26) {
number = -1;
}*/
if (number % 26 == 0) {
m = 1;
}
number = number / 26;
number = number - m;
}
return result;
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.lang.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int n=ni();
int a[]=new int[n+1];
for(int i=1;i<=n;i++) a[i]=ni();
int vis[]=new int[101];
int ans=0;
Arrays.sort(a,1,n+1);
for(int i=1;i<=n;i++){
if(vis[a[i]]==1) continue;
ans++;
for(int j=a[i];j<=100;j+=a[i]) vis[j]=1;
}
pw.println(ans);
}
long M = (long)1e9+7;
// END
PrintWriter pw;
StringTokenizer st;
BufferedReader br;
void run() throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
}
public static void main(String[] args) throws Exception {
new Main().run();
}
String ns() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
int ni() {
return Integer.parseInt(ns());
}
long nl() {
return Long.parseLong(ns());
}
double nd() {
return Double.parseDouble(ns());
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class CFDiv1 {
FastScanner in;
PrintWriter out;
boolean canBe(int from, long curVal, long l, long r) {
if (curVal > r)
return false;
for (int i = 0; i <= from; i++)
curVal += 1L << i;
if (curVal >= l)
return true;
return false;
}
long stupid(long l, long r) {
long ans = 0;
for (long i = l; i <= r; i++)
for (long j = l; j <= r; j++)
ans = Math.max(ans, i ^ j);
return ans;
}
long solve2(long l, long r) {
long min = 0;
long max = 0;
for (int i = 62; i >= 0; i--) {
boolean max0 = canBe(i - 1, max, l, r);
boolean max1 = canBe(i - 1, max | (1L << i), l, r);
boolean min0 = canBe(i - 1, min, l, r);
boolean min1 = canBe(i - 1, min | (1L << i), l, r);
if (max0 && min1 && max > min) {
min = min | (1L << i);
} else {
if (max1 && min0) {
max |= (1L << i);
} else {
if (max1 && min1) {
max |= (1L << i);
min |= 1L << i;
} else {
}
}
}
}
return min ^ max;
}
void solve() {
out.println(solve2(in.nextLong(), in.nextLong()));
// System.err.println(solve2(4, 9));
// Random rnd = new Random(312);
// for (int test = 0; test < 10000; test++) {
// System.err.println(test);
// int l = rnd.nextInt(100);
// int r = rnd.nextInt(100) + l;
// long v1 = stupid(l, r);
// long v2 = solve2(l, r);
// if (v1 != v2) {
// System.err.println(v1 + " " + v2);
// System.err.println(l + " " + r);
// throw new AssertionError();
// }
// }
}
void run() {
try {
in = new FastScanner(new File("test.in"));
out = new PrintWriter(new File("test.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
public static void main(String[] args) {
new CFDiv1().runIO();
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.util.Locale;
import java.util.Scanner;
public class E {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double[][]p = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
p[i][j] = sc.nextDouble();
}
}
double[]dp = new double[1<<n];
dp[(1 << n)-1] = 1;
for (int mask = (1 << n)-1; mask > 0; mask--) {
int t = Integer.bitCount(mask);
if (t==1)
continue;
double p0 = 1.0/(t*(t-1)/2);
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
for (int j = 0; j < n; j++) {
if (j != i && (mask & (1 << j)) != 0)
dp[(mask ^ (1 << i))] += dp[mask] * p[j][i]*p0;
}
}
}
}
for (int i = 0; i < n; i++) {
System.out.print(dp[1 << i]+" ");
}
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class ProblemB {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int f1 = a/10;
int b = a;
int last = a%10;
b/=10;
b/=10;
b*=10;
b+=last;
System.out.println(Math.max(a, Math.max(f1, b)));
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.*;
public class First {
StreamTokenizer in;
PrintWriter out;
int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
long nextLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
String nextString() throws IOException {
in.nextToken();
return in.sval;
}
void run() throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
solve();
out.flush();
}
void solve() throws IOException {
int n = nextInt(), k = nextInt(), sum = 0, count = 0;
String str = nextString();
char[] arr = str.toCharArray();
boolean[] bool = new boolean[26];
for(char ch: arr){
bool[((int)ch)-97] = true;
}
for(int i = 0; i < 26; i++){
if(bool[i]){
sum += i+1;
count++;
i += 1;
}
if(count == k) break;
}
if(count == k) out.println(sum);
else out.println(-1);
}
public static void main(String[] args) throws IOException {
new First().run();
}
}
|
linear
|
1011_A. Stages
|
CODEFORCES
|
// 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);
}
}
|
cubic
|
1185_G2. Playlist for Polycarp (hard version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ProblemC {
public static void main(String[] args) throws IOException {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// generateRandom();
int[] pt = readPoint(s);
int n = Integer.valueOf(s.readLine());
int[][] xp = new int[n+1][];
for (int i = 1 ; i <= n ; i++) {
xp[i] = readPoint(s);
}
xp[0] = pt;
int[][] dist = new int[n+1][n+1];
for (int i = 0 ; i <= n ; i++) {
for (int j = 0 ; j <= n ; j++) {
int dx = Math.abs(xp[i][0] - xp[j][0]);
int dy = Math.abs(xp[i][1] - xp[j][1]);
dist[i][j] = dx*dx + dy*dy;
}
}
int[][] dist2 = new int[n+1][n+1];
for (int i = 0 ; i <= n ; i++) {
for (int j = 0 ; j <= n ; j++) {
dist2[i][j] = dist[0][i] + dist[i][j] + dist[j][0];
}
}
int[] dp = new int[1<<n];
int[][] dp_prev = new int[2][1<<n];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 0 ; i < (1<<n) ; i++) {
if (dp[i] == Integer.MAX_VALUE) {
continue;
}
int base = dp[i];
// two
for (int y = 0 ; y < n ; y++) {
if ((i & (1<<y)) >= 1) {
break;
}
for (int z = y+1 ; z < n ; z++) {
if ((i & (1<<z)) >= 1) {
continue;
}
int ti = i | (1<<y) | (1<<z);
int d = dist2[y+1][z+1];
if (dp[ti] > base + d) {
dp[ti] = base + d;
dp_prev[0][ti] = z+1;
dp_prev[1][ti] = y+1;
}
}
}
}
int bestOnes = 0;
for (int i = 0 ; i < (1<<n) ; i++) {
if (dp[i] == Integer.MAX_VALUE) {
continue;
}
int sub = (1<<n) - 1 - i;
int add = 0;
for (int j = 0 ; j < n ; j++) {
if ((sub & (1<<j)) >= 1) {
add += dist[0][j+1] * 2;
}
}
if (dp[i] + add < dp[(1<<n)-1]) {
dp[(1<<n)-1] = dp[i] + add;
bestOnes = sub;
}
}
StringBuffer b = new StringBuffer();
b.append(" 0");
for (int i = 0 ; i < n ; i++) {
if ((bestOnes & (1<<i)) >= 1) {
b.append(" ").append(i+1).append(" ").append(0);
}
}
out.println(dp[(1<<n)-1]);
int nptn = (1<<n)-1-bestOnes;
while (nptn >= 1) {
int i1 = dp_prev[0][nptn];
int i2 = dp_prev[1][nptn];
if (i1 >= 1) {
nptn -= 1<<(i1-1);
b.append(" ").append(i1);
}
if (i2 >= 1) {
nptn -= 1<<(i2-1);
b.append(" ").append(i2);
}
b.append(" ").append(0);
}
out.println(b.substring(1));
out.flush();
}
private static void generateRandom() {
System.out.println("0 0");
System.out.println("24");
for (int i = 0 ; i < 24 ; i++) {
int a = (int)(Math.random() * 200 - 100);
int b = (int)(Math.random() * 200 - 100);
System.out.println(a + " " + b);
}
}
private static int[] readPoint(BufferedReader s) throws IOException {
int[] ret = new int[2];
String[] data = s.readLine().split(" ");
ret[0] = Integer.valueOf(data[0]);
ret[1] = Integer.valueOf(data[1]);
return ret;
}
public static void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Problem
{
static int mod = (int) (1e9+7);
static InputReader in;
static PrintWriter out;
static int[] rt;
static int[] size;
static void initialize(int n){
rt = new int[n + 1];
size = new int[n + 1];
for(int i = 0; i < rt.length; i++){
rt[i] = i;
size[i] = 1;
}
}
static int root(int x){
while(rt[x] != x){
rt[x] = rt[rt[x]];
x = rt[x];
}
return x;
}
static long union(int x,int y){
int root_x = root(x);
int root_y = root(y);
if(root_x == root_y) return 0;
long val = size[root_x] *1l* size[root_y];
if(size[root_x]<size[root_y]){
rt[root_x] = rt[root_y];
size[root_y] += size[root_x];
}
else{
rt[root_y] = rt[root_x];
size[root_x] += size[root_y];
}
return val;
}
static void solve()
{
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int t = 1;
while(t-- > 0){
int n = in.nextInt();
int[] arr = in.nextIntArray(n);
ArrayList<Pair> list = new ArrayList<>();
for(int i = 1; i < n; i++){
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
list.add(new Pair(u, v, Math.max(arr[u],arr[v])));
}
list.sort((p1,p2) -> Integer.compare(p1.i, p2.i));
initialize(n);
long s1 = 0;
for(int i = 0; i < list.size(); i++){
s1 += union(list.get(i).x, list.get(i).y) * list.get(i).i;
}
for(int i = 0; i < list.size(); i++){
Pair p = list.get(i);
p.i = Math.min(arr[p.x],arr[p.y]);
}
list.sort((p1,p2) -> -Integer.compare(p1.i, p2.i));
initialize(n);
long s2 = 0;
for(int i = 0; i < list.size(); i++){
s2 += union(list.get(i).x, list.get(i).y) * list.get(i).i;
}
out.println(s1 - s2);
}
out.close();
}
public static void main(String[] args)
{
new Thread(null ,new Runnable(){
public void run(){
try{
solve();
} catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}
static class Pair implements Comparable<Pair>
{
int x,y;
int i;
Pair (int x,int y)
{
this.x = x;
this.y = y;
}
Pair (int x,int y, int i)
{
this.x = x;
this.y = y;
this.i = i;
}
public int compareTo(Pair o)
{
if(this.x != o.x)
return -Integer.compare(this.x, o.y);
return -Integer.compare(this.y,o.y);
//return 0;
}
public boolean equals(Object o)
{
if (o instanceof Pair)
{
Pair p = (Pair)o;
return p.x == x && p.y==y;
}
return false;
}
@Override
public String toString()
{
return x + " "+ y + " "+i;
}
/*public int hashCode()
{
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}*/
}
static long add(long a,long b){
long x=(a+b);
while(x>=mod) x-=mod;
return x;
}
static long sub(long a,long b){
long x=(a-b);
while(x<0) x+=mod;
return x;
}
static long mul(long a,long b){
long x=(a*b);
while(x>=mod) x-=mod;
return x;
}
static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long gcd(long x,long y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long pow(long n,long p,long m)
{
long result = 1;
if(p==0){
return n;
}
while(p!=0)
{
if(p%2==1)
result *= n;
if(result >= m)
result %= m;
p >>=1;
n*=n;
if(n >= m)
n%=m;
}
return result;
}
static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
|
nlogn
|
915_F. Imbalance Value of a Tree
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class round159A {
static BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer st = new StringTokenizer("");
static int nextInt() throws Exception {
return Integer.parseInt(next());
}
static String next() throws Exception {
while (true) {
if (st.hasMoreTokens()) {
return st.nextToken();
}
String s = br.readLine();
if (s == null) {
return null;
}
st = new StringTokenizer(s);
}
}
public static void main(String[] args) throws Exception {
int n = nextInt();
int m = nextInt();
int k = nextInt();
int[] supply = new int[n];
for (int i = 0; i < n; ++i)
supply[i] = nextInt();
if (m <= k) {
System.out.println(0);
} else {
int have = k;
Arrays.sort(supply);
for(int i = n - 1 ; i >= 0 ; --i){
have--;
have += supply[i];
if(have >= m){
System.out.println(n - i);
return;
}
}
System.out.println(-1);
}
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class MotherOfDragons {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
PrintWriter out = new PrintWriter(System.out, false);
int n = scanner.nextInt();
double k = scanner.nextInt();
long[] graph = new long[n];
for(int i = 0; i < n; i++) {
for(int j =0; j < n; j++) {
int val = scanner.nextInt();
if (val == 1 || i == j) graph[i] |= 1L << j;
}
}
//meet in the middle approach
int szLeft = n/2;
int szRight = n - szLeft;
//max size of clique
int[] dp = new int[1 << szLeft];
int maxMask = 1 << szLeft;
//iterate over every left mask
for(int mask = 1; mask <maxMask; mask++) {
int curMask = mask;
//go over every bit in the mask
for(int j = 0; j < szLeft; j++) {
if (((1 << j) & mask) > 0) {
//update the union of reachability
curMask &= graph[j + szRight] >> szRight;
//can also attempt to pull from prev mask for max size
//will not be optimal if end update happens, but otherwise is useful for dp
dp[mask] = Math.max(dp[mask], dp[mask ^ (1 << j)]);
}
}
//if the union of connectedness is the starting mask then we have a clique
if (mask == curMask) {
dp[mask] = Math.max(dp[mask],Integer.bitCount(mask));
}
}
int ans = 0;
int rmaxMask = 1 << szRight;
for(int mask = 0; mask < rmaxMask; mask++) {
//mask to track if the current creates its own clique
int curMask = mask;
//mask to track the connection between the halves
int oMask = maxMask -1;
for(int j = 0; j < szRight; j++) {
if (((1 << j) & mask) > 0) {
//need to mask out the left side bits
curMask &= (graph[j] & (rmaxMask-1));
//update corresp avail in the left side
oMask &= graph[j] >> szRight;
}
}
//not a clique portion
if (curMask != mask) continue;
//update answer
ans = Math.max(ans, Integer.bitCount(mask) + dp[oMask]);
}
k/=ans;
out.println(k * k * (ans * (ans-1))/2);
out.flush();
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
np
|
839_E. Mother of Dragons
|
CODEFORCES
|
import java.io.*;
import java.util.Scanner;
public class abc{
public static int check(StringBuilder s)
{
int countRemove=0;
if(!s.toString().contains("xxx")) return countRemove;
else{
for(int i=1;i<s.length()-1;i++)
{
if(s.charAt(i-1)=='x' && s.charAt(i)=='x' && s.charAt(i+1)=='x')
{
countRemove++;
}
}
return countRemove;
}
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
//sc= new Scanner(System.in);
String s = sc.next();
StringBuilder sb = new StringBuilder("");
sb.append(s);
System.out.println(check(sb));
}
}
|
linear
|
978_B. File Name
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
BufferedReader kek = new BufferedReader(new InputStreamReader(System.in));
//Scanner skek = new Scanner(System.in);
PrintWriter outkek = new PrintWriter(System.out);
String[] input = kek.readLine().split(" ");
int X0 = Integer.parseInt(input[0]), Y0 = Integer.parseInt(input[1]), N = Integer.parseInt(kek.readLine());
int[] xCoords = new int[N + 1];
int[] yCoords = new int[N + 1];
int[][] distances = new int[N + 1][N + 1];
xCoords[N] = X0;
yCoords[N] = Y0;
for(int i = 0; i < N; i++){
input = kek.readLine().split(" ");
xCoords[i] = Integer.parseInt(input[0]);
yCoords[i] = Integer.parseInt(input[1]);
}
for(int i = 0; i <= N; i++){
for(int j = i + 1; j <= N; j++){
int temp = xCoords[i] - xCoords[j];
int temp2 = yCoords[i] - yCoords[j];
distances[i][j] = (temp * temp) + (temp2 * temp2);
}
}
int[] aa = new int[1 << N];
int[] bb = new int[1 << N];
for(int i = 1; i < 1 << N; i++){
int a = -1;
for(int j = 0; j < N; j++){
if((i & 1 << j) > 0){
a = j;
break;
}
}
int l = i ^ 1 << a;
int dist = distances[a][N] + distances[a][N];
aa[i] = aa[l] + dist;
bb[i] = l;
for(int k = a + 1; k < N; k++){
if((i & 1 << k) > 0) {
l = i ^ 1 << a ^ 1 << k;
dist = distances[a][N] + distances[k][N] + distances[a][k];
if(aa[l] + dist < aa[i]){
aa[i] = aa[l] + dist;
bb[i] = l;
}
}
}
}
int fin = (1 << N) - 1;
outkek.println(aa[fin]);
outkek.print('0');
while (fin != 0){
int temp1 = bb[fin];
int temp2 = fin ^ temp1;
for(int i = 0; i < N; i++){
if((temp2 & 1 << i) > 0){
outkek.print(" " + (i + 1));
}
}
outkek.print(" 0");
fin = temp1;
}
kek.close();
outkek.close();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Solution35C {
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 FileReader("input.txt"));
out = new PrintWriter("output.txt");
}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 Solution35C().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;
}
}
}
void solve() throws IOException{
int n = readInt();
int m = readInt();
int k = readInt();
Point[] focuses = new Point[k];
for(int i = 0; i < k; i++){
int a = readInt() - 1;
int b = readInt() - 1;
focuses[i] = new Point(a,b);
}
int maxI = 0, maxJ = 0;
int max = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++){
int curMin = 1000000;
for(int r = 0; r < k; r++)
if(abs(focuses[r].x - i) + abs(focuses[r].y - j) < curMin){
curMin = abs(focuses[r].x - i) + abs(focuses[r].y - j);
if(curMin < max) break;
}
if(curMin > max){
max = curMin;
maxI = i;
maxJ = j;
}
}
maxI++;
maxJ++;
out.println(maxI + " " + maxJ);
}
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);
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ACodehorsesTShirts solver = new ACodehorsesTShirts();
solver.solve(1, in, out);
out.close();
}
static class ACodehorsesTShirts {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
ArrayList<String>[] arrayLists = new ArrayList[5];
ArrayList<String>[] arrayLists1 = new ArrayList[5];
for (int i = 0; i < 5; i++) {
arrayLists[i] = new ArrayList<>();
arrayLists1[i] = new ArrayList<>();
}
for (int i = 0; i < n; i++) {
String s = in.scanString();
arrayLists[s.length()].add(s);
}
for (int i = 0; i < n; i++) {
String s = in.scanString();
arrayLists1[s.length()].add(s);
}
long ans = 0;
for (int i = 0; i < 5; i++) {
for (int diff = 0; diff < 5; diff++) {
for (int j = 0; j < arrayLists[i].size(); j++) {
int min = Integer.MAX_VALUE;
int index = -1;
for (int k = 0; k < arrayLists1[i].size(); k++) {
int tt = 0;
for (int l = 0; l < i; l++)
if (arrayLists[i].get(j).charAt(l) != arrayLists1[i].get(k).charAt(l)) tt++;
if (tt < min) {
min = tt;
index = k;
}
}
if (min == diff) {
arrayLists1[i].remove(index);
ans += min;
}
}
}
}
out.println(ans);
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public int scanInt() {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
public String scanString() {
int c = scan();
if (c == -1) return null;
while (isWhiteSpace(c)) c = scan();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return res.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class aaaaaaaaaaaaaaaa {
public void run() throws Exception {
Scanner file = new Scanner(System.in);
int a = file.nextInt(), b= file.nextInt(), c = file.nextInt(), n = file.nextInt();
a -= c;
b -= c;
if (a < 0 || b < 0) System.out.println(-1);
else {
int x = a + b + c;
if (x >= n) System.out.println(-1);
else System.out.println(n - x);
}
}
public static void main(String[] args) throws Exception {
new aaaaaaaaaaaaaaaa().run();
}
}
|
constant
|
991_A. If at first you don't succeed...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
String line;
void run()throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
line = bf.readLine();
int i, j, len = line.length(), max=0;
for(i=0; i<len; i++){
for(j=i; j<len; j++){
if(line.indexOf(line.substring(i,j+1), i+1)>0){
if(j-i+1>max) max = j-i+1;
}
}
}
System.out.println(max);
}
public static void main(String[] args)throws IOException {
new A().run();
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
@SuppressWarnings("Duplicates")
public class solveLOL {
FastScanner in;
PrintWriter out;
boolean systemIO = true, multitests = false;
int INF = Integer.MAX_VALUE / 2;
void solve() {
int n = in.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
Arrays.sort(arr);
boolean used[] = new boolean[n];
int k = 0;
for (int i = 0; i < n; i++) {
if (!used[i]) {
used[i] = true;
for (int j = i + 1; j < n; j++) {
if (!used[j] && arr[j] % arr[i] == 0) {
used[j] = true;
}
}
k++;
}
}
System.out.println(k);
}
class pair implements Comparable<pair> {
int a;
int b;
pair(int A, int B) {
this.a = A;
this.b = B;
}
public int compareTo(pair o) {
return a != o.a ? Double.compare(a, o.a) : b - o.b;
}
}
void shuffleArray(long[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
long a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
void printArray(long[] ar) {
for (long k : ar) {
System.out.print(k + " ");
}
System.out.println();
}
void reverseArray(long[] ar) {
for (int i = 0, j = ar.length - 1; i < j; i++, j--) {
long a = ar[i];
ar[i] = ar[j];
ar[j] = a;
}
}
private void run() throws IOException {
if (systemIO) {
in = new solveLOL.FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new solveLOL.FastScanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
}
for (int t = multitests ? in.nextInt() : 1; t-- > 0; )
solve();
out.close();
}
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());
}
}
public static void main(String[] arg) throws IOException {
new solveLOL().run();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.sql.Time;
import java.util.*;
import java.math.BigInteger;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
public class Main{
void run(){
Locale.setDefault(Locale.US);
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
// boolean oj = true;
try{
if( oj ){
sc = new FastScanner( new InputStreamReader(System.in ) );
out = new PrintWriter( new OutputStreamWriter(System.out) );
} else{
sc = new FastScanner(new FileReader("in.txt") );
// sc = new FastScanner(new FileReader("D:\\JavaOlymp\\FatalError\\output.txt") );
out = new PrintWriter( new FileWriter("out.txt") );
}
} catch (Exception e) {
System.exit(-1);
}
long tB = System.currentTimeMillis();
solve();
if( !oj ) System.err.println( "Time: " + (System.currentTimeMillis()-tB)/1e3 );
out.flush();
}
class FastScanner{
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
FastScanner( InputStreamReader a ){
br = new BufferedReader(a);
}
FastScanner( FileReader a ){
br = new BufferedReader(a);
}
String next(){
while( !st.hasMoreTokens() )
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
return null;
}
return st.nextToken();
}
String readLine(){
try {
return br.readLine();
} catch (Exception e) {
return null;
}
}
int nextInt(){ return Integer.parseInt(next()); }
long nextLong(){ return Long.parseLong(next()); }
}
FastScanner sc;
PrintWriter out;
public static void main(String[] args){
new Main().run();
// new Thread( null, new Runnable() {
// @Override
// public void run() {
// new Main().run();
// }
// }, "LOL", 256L * 1024 * 1024 / 2 ).run();
// }, "LOL", 2000 * 1024 * 1024 ).run();
}
void TLE(){ for(;;); }
void MLE(){
int[][] adj = new int[1024*1024][];
for( int i = 0; i < adj.length; ++i )
adj[i] = new int[1024*1024];
}
void exit( int val ){
out.flush();
System.exit(val);
}
//////////////////////////////////////////////////////////////////////////////////////////
int n, m;
boolean[][] grid;
ArrayList<Integer>[] gr;
int c;
int[] mt;
boolean[] u;
boolean try_kuhn( int v ){
if( u[v] ) return false;
u[v] = true;
for( int to : gr[v] ){
if( to == c ) continue;
if( mt[to]==-1 || try_kuhn(mt[to]) ){
mt[to] = v;
return true;
}
}
return false;
}
void solve(){
n = sc.nextInt();
m = sc.nextInt();
grid = new boolean[n+1][n+1];
gr = new ArrayList[n+1];
for( int v = 1; v <= n; ++v ) gr[v] = new ArrayList<Integer>();
for( int it = 0; it < m; ++it ){
int a = sc.nextInt();
int b = sc.nextInt();
grid[a][b] = true;
gr[a].add(b);
}
int ans = Integer.MAX_VALUE;
for( c = 1; c <= n; ++c ){
int curAns = 0;
for( int v = 1; v <= n; ++v )
if( v != c ){
if( !grid[c][v] ) ++curAns;
if( !grid[v][c] ) ++curAns;
}
if( !grid[c][c] ) ++curAns;
mt = new int[n+1];
fill( mt, -1 );
for( int i = 1; i <= n; ++i )
if( i != c ){
u = new boolean[n+1];
try_kuhn(i);
}
int szMt = 0;
for( int i = 1; i <= n; ++i )
if( mt[i] != -1 )
++szMt;
curAns += n - 1 - szMt;
for( int a = 1; a <= n; ++a ){
for( int b : gr[a] ){
if( a==c || b==c ) continue;
if( a!=mt[b] ) ++curAns;
}
}
// out.printf( "%d %d\n", c, curAns );
ans = min( ans, curAns );
}
out.println( ans );
}
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import java.util.Map.Entry;
public class Main {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private PrintWriter pw;
private long mod = 1000000000 + 7;
private StringBuilder ans_sb;
private int size = 1000005;
private long[] fact;
private void soln() {
int n = nextInt();
HashMap<String, Integer>[] s1 = new HashMap[4];
for(int i=0;i<=3;i++) {
s1[i] = new HashMap<>();
}
int cnt = 0;
for(int i=0;i<n;i++) {
String s = nextLine();
if(s1[s.length()-1].containsKey(s)) {
s1[s.length()-1].put(s, s1[s.length()-1].get(s)+1);
}else
s1[s.length()-1].put(s, 1);
}
for(int i=0;i<n;i++) {
String s = nextLine();
if(s1[s.length()-1].containsKey(s)) {
s1[s.length()-1].put(s, s1[s.length()-1].get(s)-1);
if(s1[s.length()-1].get(s) == 0)
s1[s.length()-1].remove(s);
}else {
cnt++;
}
}
pw.println(cnt);
}
private class Pair implements Comparable<Pair>{
long x, y;
int i;
public Pair(long a,long b,int c) {
x = a;
y = b;
i = c;
}
@Override
public int compareTo(
Pair o)
{
return Long.compare(this.x, o.x);
}
public String toString() {
return ""+i;
}
}
private void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
private long pow(long a, long b, long c) {
if (b == 0)
return 1;
long p = pow(a, b / 2, c);
p = (p * p) % c;
return (b % 2 == 0) ? p : (a * p) % c;
}
private long gcd(long n, long l) {
if (l == 0)
return n;
return gcd(l, n % l);
}
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
@Override
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
//new Main().solve();
}
public StringBuilder solve() {
InputReader(System.in);
/*
* try { InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\in.txt"));
* } catch(FileNotFoundException e) {}
*/
pw = new PrintWriter(System.out);
// ans_sb = new StringBuilder();
soln();
pw.close();
// System.out.println(ans_sb);
return ans_sb;
}
public void InputReader(InputStream stream1) {
stream = stream1;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
private long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private void pArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private void pArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
return;
}
private boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private char nextChar() {
int c = read();
while (isSpaceChar(c))
c = read();
char c1 = (char) c;
while (!isSpaceChar(c))
c = read();
return c1;
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
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
* @author dy
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, Scanner in, PrintWriter out) {
long N = in.nextLong();
int K = in.nextInt();
long pipes = 1;
if(N == 1){
out.println(0);return;
}
long left = 0, right = K - 1, find = -1;
while (left <= right){
long mid = (left + right) / 2;
if(mid * mid + (1 - 2 * K) * mid + 2 * (N - 1) <= 0){
find = mid;
right = mid - 1;
}
else
left = mid + 1;
}
out.println(find);
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.util.Scanner;
public class Division {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int l = sc.nextInt();
String c = String.valueOf(l);
if (String.valueOf(c).contains("0") || String.valueOf(c).contains("1")
|| String.valueOf(c).contains("2")
|| String.valueOf(c).contains("3")
|| String.valueOf(c).contains("5")
|| String.valueOf(c).contains("6")
|| String.valueOf(c).contains("8")
|| String.valueOf(c).contains("9"))
if (l % 777 == 0 || l % 774 == 0 || l % 747 == 0 || l % 744 == 0
|| l % 477 == 0 || l % 474 == 0 || l % 447 == 0
|| l % 444 == 0 || l % 77 == 0 || l % 74 == 0
|| l % 47 == 0 || l % 44 == 0 || l % 7 == 0 || l % 4 == 0)
System.out.println("YES");
else
System.out.println("NO");
else
System.out.println("YES");
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public class Main {
static final long MOD = 1000000007L;
//static final long MOD2 = 1000000009L;
//static final long MOD = 998244353L;
//static final long INF = 500000000000L;
static final int INF = 1000000005;
static final int NINF = -1000000005;
//static final long NINF = -1000000000000000000L;
static FastScanner sc;
static PrintWriter pw;
static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
static final int MO = 1200;
public static void main(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(System.out);
int N = sc.ni();
int M = sc.ni();
int K = sc.ni();
int[][] LR = new int[N][M-1];
for (int i = 0; i < N; i++) {
LR[i] = sc.intArray(M-1,0);
}
int[][] UD = new int[N-1][M];
for (int i = 0; i < N-1; i++) {
UD[i] = sc.intArray(M,0);
}
if (K%2==0) {
int T = K/2;
int[][] dist = new int[N][M];
for (int step = 1; step <= T; step++) {
int[][] newDist = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
newDist[i][j] = INF;
//up
if (i > 0) {
newDist[i][j] = Math.min(newDist[i][j],UD[i-1][j]+dist[i-1][j]);
}
//down
if (i < N-1) {
newDist[i][j] = Math.min(newDist[i][j],UD[i][j]+dist[i+1][j]);
}
//left
if (j > 0) {
newDist[i][j] = Math.min(newDist[i][j],LR[i][j-1]+dist[i][j-1]);
}
//right
if (j < M-1) {
newDist[i][j] = Math.min(newDist[i][j],LR[i][j]+dist[i][j+1]);
}
}
}
dist = newDist;
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
pw.print((2*dist[i][j]) + " ");
}
pw.println();
}
} else {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
pw.print("-1 ");
}
pw.println();
}
}
pw.close();
}
public static void sort(int[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
public static void sort(long[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
//Sort an array (immune to quicksort TLE)
public static void sort(int[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
int ablock = a[0]/MO;
int bblock = b[0]/MO;
if (ablock != bblock)
return ablock-bblock;
else
return a[1]-b[1];
}
});
}
public static void sort(long[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else
return 0;
//Ascending order.
}
});
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[][] graph(int N, int[][] edges) {
int[][] graph = new int[N][];
int[] sz = new int[N];
for (int[] e: edges) {
sz[e[0]] += 1;
sz[e[1]] += 1;
}
for (int i = 0; i < N; i++) {
graph[i] = new int[sz[i]];
}
int[] cur = new int[N];
for (int[] e: edges) {
graph[e[0]][cur[e[0]]] = e[1];
graph[e[1]][cur[e[1]]] = e[0];
cur[e[0]] += 1;
cur[e[1]] += 1;
}
return graph;
}
int[] intArray(int N, int mod) {
int[] ret = new int[N];
for (int i = 0; i < N; i++)
ret[i] = ni()+mod;
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N, long mod) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = nl()+mod;
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.util.*;
public class Temppp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long k = sc.nextLong();
long ans = (long) ((java.lang.Math.sqrt((9+(8*(n+k))))-3)/2);
System.out.println(n-ans);
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class MinimumDiameterTree{
public static void main(String[] args) {
InputReader in = new InputReader (System.in);
PrintWriter out = new PrintWriter (System.out);
int n = in.nextInt();
int s = in.nextInt();
int deg[] = new int [n];
for (int i = 1; i < n; ++i) {
deg[in.nextInt() - 1] ++;
deg[in.nextInt() - 1] ++;
}
int l = 0;
for (int i = 0; i < n; ++i)
if (deg[i] == 1) l ++;
out.println((double) 2 * s / l);
out.close();
}
public 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());
}
}
}
|
linear
|
1086_B. Minimum Diameter Tree
|
CODEFORCES
|
import java.util.Scanner;
public class Sasha1113A {
static int solution(int n, int v){
int count;
if(v>=n)
return n-1;
else{
count = (v-1) + ((n-v)*(n-v+1))/2;
}
return count;
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int v = scan.nextInt();
System.out.print(solution(n, v));
}
}
|
constant
|
1113_A. Sasha and His Trip
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
DExplorerSpace solver = new DExplorerSpace();
solver.solve(1, in, out);
out.close();
}
}
static class DExplorerSpace {
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.ri();
int m = in.ri();
int k = in.ri();
int[][] lr = new int[n][m - 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m - 1; j++) {
lr[i][j] = in.ri();
}
}
int[][] ud = new int[n - 1][m];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m; j++) {
ud[i][j] = in.ri();
}
}
if (k % 2 == 1) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.append(-1).append(' ');
}
out.println();
}
return;
}
k /= 2;
int inf = (int) 1e9;
int[][][] dp = new int[k + 1][n][m];
for (int i = 1; i <= k; i++) {
for (int j = 0; j < n; j++) {
for (int t = 0; t < m; t++) {
dp[i][j][t] = inf;
//left
if (t > 0) {
dp[i][j][t] = Math.min(dp[i][j][t], dp[i - 1][j][t - 1] + lr[j][t - 1]);
}
//right
if (t + 1 < m) {
dp[i][j][t] = Math.min(dp[i][j][t], dp[i - 1][j][t + 1] + lr[j][t]);
}
//bot
if (j + 1 < n) {
dp[i][j][t] = Math.min(dp[i][j][t], dp[i - 1][j + 1][t] + ud[j][t]);
}
//top
if (j > 0) {
dp[i][j][t] = Math.min(dp[i][j][t], dp[i - 1][j - 1][t] + ud[j - 1][t]);
}
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
out.append(dp[k][i][j] * 2).append(' ');
}
out.println();
}
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private static final int THRESHOLD = 32 << 10;
private final Writer os;
private StringBuilder cache = new StringBuilder(THRESHOLD * 2);
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
private void afterWrite() {
if (cache.length() < THRESHOLD) {
return;
}
flush();
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput append(int c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput println() {
return append('\n');
}
public FastOutput flush() {
try {
// boolean success = false;
// if (stringBuilderValueField != null) {
// try {
// char[] value = (char[]) stringBuilderValueField.get(cache);
// os.write(value, 0, cache.length());
// success = true;
// } catch (Exception e) {
// }
// }
// if (!success) {
os.append(cache);
// }
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int ri() {
return readInt();
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
}
|
cubic
|
1517_D. Explorer Space
|
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);
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();
int l, r, sum = 0;
int[] a = new int[n+5];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
if (a[i] > a[j]) sum++;
int q = in.nextInt();
while (q-- > 0){
l = in.nextInt();
r = in.nextInt();
sum += (r-l+1)/2;
if (sum % 2 == 1) out.println("odd");
else out.println("even");
}
}
}
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());
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
/*
* Author Ayub Subhaniya
* Institute DA-IICT
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class A
{
InputStream in;
PrintWriter out;
void solve()
{
int n=ni();
int a[]=na(n);
int INV=0;
for (int i=0;i<n;i++)
for (int j=i+1;j<n;j++)
if (a[i]>a[j])
INV++;
boolean even=INV%2==0;
int q=ni();
while (q-->0)
{
int l=ni();
int r=ni();
int len=r-l+1;
len=(len-1)*(len)/2;
if (len%2==1)
even=!even;
if (even)
out.println("even");
else
out.println("odd");
}
}
int MAX = (int)1e5;
long factorial[];
void findfactorial()
{
factorial = new long[MAX + 1];
factorial[0] = 1;
for (int i = 1; i < MAX + 1; i++)
{
factorial[i] = mul(i,factorial[i - 1]);
}
}
long mod=(long)1e9+7;
long add(long a,long b)
{
long x=(a+b);
while(x>=mod) x-=mod;
return x;
}
long sub(long a,long b)
{
long x=(a-b);
while(x<0) x+=mod;
return x;
}
long mul(long a,long b)
{
a%=mod;
b%=mod;
long x=(a*b);
return x%mod;
}
int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
int min(int a,int b)
{
if(a>b)
return b;
else
return a;
}
long max(long a,long b)
{
if(a>b)
return a;
else
return b;
}
long min(long a,long b)
{
if(a>b)
return b;
else
return a;
}
void run() throws Exception
{
String INPUT = "C:/Users/ayubs/Desktop/input.txt";
in = oj ? System.in : new FileInputStream(INPUT);
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception
{
new A().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf)
{
ptrbuf = 0;
try
{
lenbuf = in.read(inbuf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean inSpaceChar(int c)
{
return !(c >= 33 && c <= 126);
}
private int skip()
{
int b;
while ((b = readByte()) != -1 && inSpaceChar(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 (!(inSpaceChar(b)))
{ // when nextLine, (inSpaceChar(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 && !(inSpaceChar(b)))
{
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-')
{
minus = true;
b = readByte();
}
while (true)
{
if (b >= '0' && b <= '9')
{
num = num * 10 + (b - '0');
}
else
{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-')
{
minus = true;
b = readByte();
}
while (true)
{
if (b >= '0' && b <= '9')
{
num = num * 10 + (b - '0');
}
else
{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.util.*;
public class Solution {
public static void main(String[] args){
Scanner cin=new Scanner(System.in);
int n=cin.nextInt();
if(n%4==0 || n%7==0 || n%44==0 || n%47==0 || n%74==0 || n%77==0 || n%444==0 || n%447==0 || n%474==0 ||
n%477==0 || n%744==0 || n%747==0 || n%774==0 ||n%777==0) System.out.print("YES");
else System.out.print("NO");
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Queue;
import java.util.StringTokenizer;
public class CF268_TwoSets {
public static void main(String[] args) {
MyScanner in = new MyScanner();
int N = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] vals = new int[N];
HashMap<Integer, Integer> val2Ind = new HashMap<Integer, Integer>();
for (int i = 0; i < N; i++) {
vals[i] = in.nextInt();
val2Ind.put(vals[i], i);
}
int[] setAssignment = new int[N];
int[] friendA = new int[N];
int[] friendB = new int[N];
Arrays.fill(setAssignment, -1);
Arrays.fill(friendA, -1);
Arrays.fill(friendB, -1);
// Mark partners
for (int i = 0; i < N; i++) {
Integer friendAInd = val2Ind.get(a - vals[i]);
if (friendAInd != null) {
friendA[i] = friendAInd;
}
Integer friendBInd = val2Ind.get(b - vals[i]);
if (friendBInd != null) {
friendB[i] = friendBInd;
}
}
// Find those with only one friend
Queue<Integer> toProc = new ArrayDeque<Integer>();
for (int i = 0; i < N; i++) {
int friends = 0;
if (friendA[i] != -1) {
friends++;
}
if (friendB[i] != -1) {
friends++;
}
if (friends == 1) {
toProc.add(i);
}
}
// Process the one frienders
while (!toProc.isEmpty()) {
int ind = toProc.poll();
if (setAssignment[ind] != -1) {
continue;
}
if (friendA[ind] != -1) {
int other = friendA[ind];
if (setAssignment[other] == -1) {
setAssignment[ind] = 0;
setAssignment[other] = 0;
// Check other's friend
if (friendB[other] != -1) {
int otherOther = friendB[other];
friendB[otherOther] = -1;
toProc.add(otherOther);
}
} else {
System.out.println("NO");
return;
}
}
else if (friendB[ind] != -1) {
int other = friendB[ind];
if (setAssignment[other] == -1) {
setAssignment[ind] = 1;
setAssignment[other] = 1;
// Check other's friend
if (friendA[other] != -1) {
int otherOther = friendA[other];
friendA[otherOther] = -1;
toProc.add(otherOther);
}
} else {
System.out.println("NO");
return;
}
}
else {
System.out.println("NO");
return;
}
}
// Process those with two friends
for(int i = 0; i < N; i++) {
if(setAssignment[i] != -1) {
continue;
}
if(friendA[i] == -1 && friendB[i] == -1) {
System.out.println("NO");
return;
}
// Only possibility should now be that both friends are possible
setAssignment[i] = 0;
setAssignment[friendA[i]] = 0;
}
// Print the result
System.out.println("YES");
StringBuilder sb = new StringBuilder();
for(int i = 0; i < N; i++) {
sb.append(setAssignment[i]);
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb);
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class C {
static BufferedReader br;
static StringTokenizer st;
static PrintWriter pw;
static String nextToken() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
static int nextInt() {
return Integer.parseInt(nextToken());
}
static long nextLong() {
return Long.parseLong(nextToken());
}
static double nextDouble() {
return Double.parseDouble(nextToken());
}
static String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
solve();
pw.close();
}
private static void solve() {
int t = nextInt();
int[] stack = new int[1000000];
for (int i = 0; i < t; i++) {
int n = nextInt();
stack[0] = nextInt();
int id = 1;
pp(stack, id);
for (int j = 1; j < n; j++) {
int x = nextInt();
if (x == 1) {
stack[id++] = x;
} else {
while (true) {
int p = stack[--id];
if (p + 1 == x) {
stack[id++] = x;
break;
}
}
}
pp(stack, id);
}
}
}
private static void pp(int[] stack, int size) {
for (int i = 0; i < size - 1; i++) {
pw.print(stack[i] + ".");
}
pw.println(stack[size - 1]);
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
/**
p * @author prakhar28
*
*/
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[200005]; // line length+1
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n' || c==' ') {
//buf[cnt++]=(byte)c;
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static class FastScanner {
private final BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
public FastScanner() {
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
throw new RuntimeException("Can't read next value", e);
}
}
return stringTokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine(){
String str = "";
try {
str = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void closeall() throws IOException{
printWriter.close();
sc.close();
in.close();
}
static Scanner sc = new Scanner(System.in);
static Reader in = new Reader();
static FastScanner fastScanner = new FastScanner();
static PrintWriter printWriter = new PrintWriter(new BufferedOutputStream(System.out));
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static long INF = (long)(1e18);
int V,E;
ArrayList<Integer> adj[];
HashMap<Integer,Integer> path;
Main(){
}
Main(int v,int e){
V=v;
E=e;
adj=new ArrayList[v];
path = new HashMap<Integer,Integer>();
for(int i=0;i<v;i++)
adj[i] = new ArrayList<>();
}
void addEdge(int u,int v){
adj[u].add(v);
adj[v].add(u);
}
static long power(long a,long k)
{
long m = 1000000007;
long ans=1;
long tmp=a%m;
while(k>0)
{
if(k%2==1)
ans=ans*tmp%m;
tmp=tmp*tmp%m;
k>>=1;
}
return ans;
}
static class Pair /*implements Comparable<Pair>*/{
long F,S;
Pair(long x,long y){
F = x;
S = y;
}
/*public int compareTo(Pair ob){
return this.num-ob.num;
}*/
}
static long gcd(long a,long b) {
if(a<b) {
long t = a;
a = b;
b = t;
}
long r = a%b;
if(r==0)
return b;
return gcd(b,r);
}
static int lower_bound(int[] a,int low,int high,int val) {
while(low!=high) {
int mid = (low+high)/2;
if(a[mid]<val)
low=mid+1;
else
high=mid;
}
return low;
}
static int max(int a,int b) {
return (int)Math.max(a, b);
}
static long max(long a,long b) {
return (long)Math.max(a, b);
}
static int min(int a,int b) {
if(a<b)
return a;
return b;
}
static long mod = 1000000007;
public static void main(String args[])throws IOException{
int n = in.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = in.nextInt();
int inv = 0;
for(int i=0;i<n;i++) {
for(int j=0;j<i;j++) {
if(a[j]>a[i])
inv++;
}
}
inv%=2;
int q = in.nextInt();
for(int i=0;i<q;i++) {
int l = in.nextInt();
int r = in.nextInt();
int num = r-l+1;
inv=(inv+num*(num-1)/2)%2;
if(inv==0)
printWriter.println("even");
else
printWriter.println("odd");
}
closeall();
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class FireAgain {
Scanner in;
PrintWriter out;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
new FireAgain().run();
}
void run() throws IOException {
in = new Scanner(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
solve();
in.close();
out.close();
}
private void solve() {
// TODO Auto-generated method stub
int N = in.nextInt();
int M = in.nextInt();
int[][] burn = new int[N + 1][M + 1];
int K = in.nextInt();
int[] qx = new int[N * M];
int[] qy = new int[N * M];
int first = 0;
int last = 0;
for (int i = 0; i < K; i ++){
qx[last] = in.nextInt();
qy[last] = in.nextInt();
burn[qx[last]][qy[last]] = 1;
last ++;
}
while (first < last){
int x = qx[first];
int y = qy[first];
if (x - 1 > 0 && burn[x - 1][y] == 0){
burn[x - 1][y] = 1;
qx[last] = x - 1;
qy[last] = y;
last ++;
}
if (y - 1 > 0 && burn[x][y - 1] == 0){
burn[x][y - 1] = 1;
qx[last] = x;
qy[last] = y - 1;
last ++;
}
if (x + 1 <= N && burn[x + 1][y] == 0){
burn[x + 1][y] = 1;
qx[last] = x + 1;
qy[last] = y;
last ++;
}
if (y + 1 <= M && burn[x][y + 1] == 0){
burn[x][y + 1] = 1;
qx[last] = x;
qy[last] = y + 1;
last ++;
}
first ++;
}
out.println(qx[last - 1] + " " + qy[last - 1]);
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class MainD {
static final StdIn in = new StdIn();
static final PrintWriter out = new PrintWriter(System.out);
static final long M=(long)1e9+7;
static long[] fac, faci;
public static void main(String[] args) {
int n=in.nextInt();
fac = new long[n+1];
faci = new long[n+1];
fac[0]=faci[0]=1;
for(int i=1; i<=n; ++i)
faci[i]=modI(fac[i]=fac[i-1]*i%M, M);
List<List<Integer>> grps = new ArrayList<List<Integer>>();
for(int i=0; i<n; ++i) {
int ai=in.nextInt();
for(int j=0; ; ++j) {
if(j>=grps.size())
grps.add(new ArrayList<Integer>());
if(grps.get(j).size()>0&&!ps((long)grps.get(j).get(0)*ai))
continue;
grps.get(j).add(ai);
break;
}
}
long[][] dp = new long[grps.size()][n-grps.size()+1];
dp[0][grps.get(0).size()-1]=fac[grps.get(0).size()];
int ad=grps.get(0).size();
for(int i=1; i<grps.size(); ++i) {
for(int j=0; j<dp[i-1].length; ++j) {
if(dp[i-1][j]==0)
continue;
for(int k=0; k<grps.get(i).size(); ++k)
for(int l=Math.max(grps.get(i).size()+j-k-ad-1, 0); l<=Math.min(grps.get(i).size()-k, j); ++l)
dp[i][j+k-l]=(fac[grps.get(i).size()]*nck(j, l)%M*nck(ad+1-j, grps.get(i).size()-k-l)%M*nck(grps.get(i).size()-1, k)%M*dp[i-1][j]+dp[i][j+k-l])%M;
}
ad+=grps.get(i).size();
}
//out.println(Arrays.deepToString(dp));
out.println(dp[grps.size()-1][0]);
out.close();
}
static long modI(long a, long m) {
return (a%=m)<=1?1:((1-modI(m%a, a)*m)/a+m)%m;
}
static long nck(int n, int k) {
return fac[n]*faci[k]%M*faci[n-k]%M;
}
static boolean ps(long x) {
long lb=1, rb=M;
while(lb<=rb) {
long mb=(lb+rb)/2;
if(mb*mb==x)
return true;
if(mb*mb<x)
lb=mb+1;
else
rb=mb-1;
}
return false;
}
static class StdIn {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public StdIn() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public StdIn(InputStream in) {
try{
din = new DataInputStream(in);
} catch(Exception e) {
throw new RuntimeException();
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == ' ' || c == '\n'||c=='\r')
break;
s.append((char)c);
c=read();
}
return s.toString();
}
public String nextLine() {
int c;
while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
StringBuilder s = new StringBuilder();
while (c != -1)
{
if (c == '\n'||c=='\r')
break;
s.append((char)c);
c = read();
}
return s.toString();
}
public int nextInt() {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int n, int os) {
int[] ar = new int[n];
for(int i=0; i<n; ++i)
ar[i]=nextInt()+os;
return ar;
}
public long nextLong() {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long[] readLongArray(int n, long os) {
long[] ar = new long[n];
for(int i=0; i<n; ++i)
ar[i]=nextLong()+os;
return ar;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() {
try{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
} catch(IOException e) {
throw new RuntimeException();
}
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
|
cubic
|
840_C. On the Bench
|
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);
long n = scanner.nextLong();
long x = scanner.nextLong(), y = scanner.nextLong();
long whiteSteps, blackSteps;
if(x == 1 || y == 1){
whiteSteps = (x - 1) + (y - 1);
} else {
whiteSteps = Math.min((x - 1) + Math.abs(y - x), (y - 1) + Math.abs(y - x));
}
if(x == n || y == n){
blackSteps = (n - x) + (n - y);
} else {
blackSteps = Math.min((n - x) + Math.abs(y - x), (n - y) + Math.abs(y - x));
}
if (whiteSteps <= blackSteps){
System.out.println("White");
} else {
System.out.println("Black");
}
}
}
|
constant
|
1075_A. The King's Race
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author unknown
*/
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);
APaintTheNumbers solver = new APaintTheNumbers();
solver.solve(1, in, out);
out.close();
}
static class APaintTheNumbers {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.i();
int[] a = in.ia(n);
RadixSort.radixSort(a);
boolean[] flag = new boolean[n];
int count = 0;
for (int i = 0; i < n; i++) {
if (!flag[i]) {
++count;
flag[i] = true;
for (int j = 0; j < n; j++) {
if (!flag[j] && a[j] % a[i] == 0) {
flag[j] = true;
}
}
}
}
out.printLine(count);
}
}
static class RadixSort {
public static int[] radixSort(int[] f) {
return radixSort(f, f.length);
}
public static int[] radixSort(int[] f, int n) {
// credits uwi
int[] to = new int[n];
{
int[] b = new int[65537];
for (int i = 0; i < n; i++) b[1 + (int) (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < n; i++) to[b[(int) (f[i] & 0xffff)]++] = f[i];
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < n; i++) b[1 + (int) (f[i] >>> 16 & 0xffff)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < n; i++) to[b[(int) (f[i] >>> 16 & 0xffff)]++] = f[i];
int[] d = f;
f = to;
to = d;
}
return f;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0;
private int ptrbuf = 0;
public InputReader(InputStream is) {
this.is = is;
}
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++];
}
public int[] ia(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = i();
return a;
}
public int i() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
import java.math.*;
import static java.lang.Character.isDigit;
import static java.lang.Character.isLowerCase;
import static java.lang.Character.isUpperCase;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Character.isDigit;
public class Main{
public static void main(String[] args) {
new Main().run();
}
Scanner sc=new Scanner(System.in);
void run() {
int n=sc.nextInt();
char[] cs=sc.next().toCharArray();
int h=0;
for(int i=0;i<n;i++)if(cs[i]=='H')h++;
int res=n;
for(int i=0;i<n;i++) {
int val=0;
for(int j=0;j<h;j++)if(cs[(i+j)%n]=='T')val++;
res=min(res,val);
}
System.out.println(res);
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.TreeMap;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.sqrt;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
import static java.util.Collections.reverse;
import static java.util.Collections.reverseOrder;
import static java.util.Collections.sort;
public class Main {
private FastScanner in;
private PrintWriter out;
private void solve() throws IOException {
solveC();
}
private void solveA() throws IOException {
char[] n = in.next().toCharArray(), s = in.next().toCharArray();
out.print(n[0]);
for (int i = 1; i < n.length && n[i] < s[0]; i++)
out.print(n[i]);
out.print(s[0]);
}
private void solveB() throws IOException {
int n = in.nextInt();
long dp[] = new long[n + 1];
for (int i = 1; i <= n; i++) {
dp[i] = i + (i < 3 ? 0 : dp[i - 2]);
}
out.print(dp[n]);
}
private void solveC() throws IOException {
int n = in.nextInt(), prev = -1;
long sum, mod = (long) 1e9 + 7, p;
long[] deep = new long[n + 10];
deep[0] = 1;
char c;
for (int cur = 0; cur < n; cur++) {
c = in.nextLine().charAt(0);
if (prev + 1 != cur) {
sum = 0;
if (c == 'f') {
for (int i = deep.length - 1; i > 0; i--) {
sum += deep[i - 1];
sum %= mod;
deep[i] = sum;
}
deep[0] = 0;
} else {
for (int i = deep.length - 1; i >= 0; i--) {
sum += deep[i];
sum %= mod;
deep[i] = sum;
}
}
}
if (c != 's') {
if (cur == prev + 1) {
for (int i = deep.length - 1; i > 0; i--) {
deep[i] = deep[i - 1];
}
deep[0] = 0;
}
prev = cur;
}
//out.println(Arrays.toString(deep));
}
long ans = 0;
for (int i = 0; i < deep.length; i++) {
ans += deep[i];
ans %= mod;
}
out.println(ans);
}
private void solveD() throws IOException {
}
private void solveE() throws IOException {
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
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 {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.util.Scanner;
public class pillar {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[200005];
for (int i=1;i<=n;i++)
a[i]=sc.nextInt();
for (int i=2;i<n;i++)
if (a[i-1]>a[i]&&a[i]<a[i+1]) {
System.out.println("NO");
return;
}
System.out.println("YES");
}
}
|
linear
|
1197_B. Pillars
|
CODEFORCES
|
import java.util.*;
public class test
{
static boolean isOK(String str, int len)
{
HashSet<String> hs=new HashSet<String>();
for(int i=0;i<=str.length()-len;i++)
{
String s=str.substring(i,len+i);
if(hs.contains(s))
return true;
else
hs.add(s);
}
return false;
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String str=in.next();
int i;
for(i=str.length()-1;i>=1;i--)
if(isOK(str,i))
{
break;
}
System.out.println(i);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class A {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine();
for (int i = s.length() - 1; i > 0; i--)
for (int j = 0; j <= s.length() - i; j++)
if (s.substring(0, j + i - 1).contains(s.substring(j, j + i))
|| s.substring(j + 1).contains(s.substring(j, j + i))) {
System.out.println(i);
return;
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
// upsolve with rainboy
import java.io.*;
import java.util.*;
public class CF1187G extends PrintWriter {
CF1187G() { super(System.out); }
static class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
int k, l; byte[] bb = new byte[1 << 15];
byte getc() {
if (k >= l) {
k = 0;
try { l = in.read(bb); } catch (IOException e) { l = 0; }
if (l <= 0) return -1;
}
return bb[k++];
}
int nextInt() {
byte c = 0; while (c <= 32) c = getc();
int a = 0;
while (c > 32) { a = a * 10 + c - '0'; c = getc(); }
return a;
}
}
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1187G o = new CF1187G(); o.main(); o.flush();
}
static final int INF = 0x3f3f3f3f;
ArrayList[] aa_;
int n_, m_;
int[] pi, dd, bb;
int[] uu, vv, uv, cost;
int[] cc;
void init() {
aa_ = new ArrayList[n_];
for (int u = 0; u < n_; u++)
aa_[u] = new ArrayList<Integer>();
pi = new int[n_];
dd = new int[n_];
bb = new int[n_];
qq = new int[nq];
iq = new boolean[n_];
uu = new int[m_];
vv = new int[m_];
uv = new int[m_];
cost = new int[m_];
cc = new int[m_ * 2];
m_ = 0;
}
void link(int u, int v, int cap, int cos) {
int h = m_++;
uu[h] = u;
vv[h] = v;
uv[h] = u ^ v;
cost[h] = cos;
cc[h << 1 ^ 0] = cap;
aa_[u].add(h << 1 ^ 0);
aa_[v].add(h << 1 ^ 1);
}
int[] qq;
int nq = 1 << 20, head, cnt;
boolean[] iq;
void enqueue(int v) {
if (iq[v])
return;
if (head + cnt == nq) {
if (cnt * 2 <= nq)
System.arraycopy(qq, head, qq, 0, cnt);
else {
int[] qq_ = new int[nq *= 2];
System.arraycopy(qq, head, qq_, 0, cnt);
qq = qq_;
}
head = 0;
}
qq[head + cnt++] = v; iq[v] = true;
}
int dequeue() {
int u = qq[head++]; cnt--; iq[u] = false;
return u;
}
boolean spfa(int s, int t) {
Arrays.fill(pi, INF);
pi[s] = 0;
head = cnt = 0;
enqueue(s);
while (cnt > 0) {
int u = dequeue();
int d = dd[u] + 1;
ArrayList<Integer> adj = aa_[u];
for (int h_ : adj)
if (cc[h_] > 0) {
int h = h_ >> 1;
int p = pi[u] + ((h_ & 1) == 0 ? cost[h] : -cost[h]);
int v = u ^ uv[h];
if (pi[v] > p || pi[v] == p && dd[v] > d) {
pi[v] = p;
dd[v] = d;
bb[v] = h_;
enqueue(v);
}
}
}
return pi[t] != INF;
}
void push(int s, int t) {
int c = INF;
for (int u = t, h_, h; u != s; u ^= uv[h]) {
h = (h_ = bb[u]) >> 1;
c = Math.min(c, cc[h_]);
}
for (int u = t, h_, h; u != s; u ^= uv[h]) {
h = (h_ = bb[u]) >> 1;
cc[h_] -= c; cc[h_ ^ 1] += c;
}
}
void push1(int s, int t) {
for (int u = t, h_, h; u != s; u ^= uv[h]) {
h = (h_ = bb[u]) >> 1;
cc[h_]--; cc[h_ ^ 1]++;
}
}
int edmonds_karp(int s, int t) {
while (spfa(s, t))
push1(s, t);
int c = 0;
for (int h = 0; h < m_; h++)
c += cost[h] * cc[h << 1 ^ 1];
return c;
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int[] ii = new int[k];
for (int h = 0; h < k; h++)
ii[h] = sc.nextInt() - 1;
ArrayList[] aa = new ArrayList[n];
for (int i = 0; i < n; i++)
aa[i] = new ArrayList<Integer>();
for (int h = 0; h < m; h++) {
int i = sc.nextInt() - 1;
int j = sc.nextInt() - 1;
aa[i].add(j);
aa[j].add(i);
}
int t = n + k + 1;
n_ = n * t + 1;
m_ = k + (m * 2 * k + n) * (t - 1);
init();
for (int i = 0; i < n; i++) {
ArrayList<Integer> adj = aa[i];
for (int s = 0; s < t - 1; s++) {
int u = i * t + s;
for (int j : adj) {
int v = j * t + s + 1;
for (int x = 1; x <= k; x++)
link(u, v, 1, c + (x * 2 - 1) * d);
}
}
}
for (int i = 0; i < n; i++)
for (int s = 0; s < t - 1; s++) {
int u = i * t + s, v = u + 1;
link(u, v, k, i == 0 ? 0 : c);
}
for (int h = 0; h < k; h++)
link(n_ - 1, ii[h] * t + 0, 1, 0);
println(edmonds_karp(n_ - 1, 0 * t + t - 1));
}
}
|
cubic
|
1187_G. Gang Up
|
CODEFORCES
|
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 long power(int a, int k) {
if (k == 0)
return 1;
long p = power(a, k / 2);
p = p * p % MD;
if (k % 2 == 1)
p = p * a % MD;
return p;
}
static int[] ff, gg;
static int ch(int n, int k) {
return (int) ((long) ff[n] * gg[n - k] % MD * gg[k] % MD);
}
static int[][][] init(int n, int na, int nb, int nc) {
ff = new int[n + 1];
gg = new int[n + 1];
for (int i = 0, f = 1; i <= n; i++) {
ff[i] = f;
gg[i] = (int) power(f, MD - 2);
f = (int) ((long) f * (i + 1) % MD);
}
int[][][] dp = new int[na + 1][nb + 1][nc + 1];
for (int ma = 0; ma <= na; ma++)
for (int mb = 0; mb <= nb; mb++)
for (int mc = 0; mc <= nc; mc++) {
int x = (int) ((long) ff[ma + mb + mc] * gg[ma] % MD * gg[mb] % MD * gg[mc] % MD);
for (int ma_ = ma == 0 ? 0 : 1; ma_ <= ma; ma_++) {
int cha = ma == 0 ? 1 : ch(ma - 1, ma_ - 1);
for (int mb_ = mb == 0 ? 0 : 1; mb_ <= mb; mb_++) {
int chb = mb == 0 ? 1 : ch(mb - 1, mb_ - 1);
for (int mc_ = mc == 0 ? 0 : 1; mc_ <= mc; mc_++) {
int chc = mc == 0 ? 1 : ch(mc - 1, mc_ - 1);
int y = dp[ma_][mb_][mc_];
if (y == 0)
continue;
x = (int) ((x - (long) y * cha % MD * chb % MD * chc) % MD);
}
}
}
if (x < 0)
x += MD;
dp[ma][mb][mc] = x;
}
for (int ma = 0; ma <= na; ma++)
for (int mb = 0; mb <= nb; mb++)
for (int mc = 0; mc <= nc; mc++)
dp[ma][mb][mc] = (int) ((long) dp[ma][mb][mc] * ff[ma] % MD * ff[mb] % MD * ff[mc] % 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
|
/**
* ******* Created by bla on 14/9/19 6:17 PM*******
*/
import java.io.*;
import java.util.*;
public class A1209 {
public static void main(String[] args) throws IOException {
try (Input input = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
int n = input.nextInt();
int[] arr = input.readIntArray(n);
Arrays.sort(arr);
int ans =0;
boolean[] vis = new boolean[n];
for(int i=0;i<n;i++){
if(!vis[i]){
vis[i]=true;
for(int j=i+1;j<n;j++){
if(!vis[j] && arr[j]%arr[i]==0){
vis[j]=true; }
}
ans++;
}
}
System.out.println(ans);
}
}
interface Input extends Closeable {
String next() throws IOException;
default int nextInt() throws IOException {
return Integer.parseInt(next());
}
default long nextLong() throws IOException {
return Long.parseLong(next());
}
default double nextDouble() throws IOException {
return Double.parseDouble(next());
}
default int[] readIntArray() throws IOException {
return readIntArray(nextInt());
}
default int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextInt();
}
return array;
}
default long[] readLongArray(int size) throws IOException {
long[] array = new long[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextLong();
}
return array;
}
}
private static class StandardInput implements Input {
private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer stringTokenizer;
@Override
public void close() throws IOException {
reader.close();
}
@Override
public String next() throws IOException {
if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;
public class ques3 {
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 static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public String next() {
return nextString();
}
public char nextChar(){
int c=read();
while (isSpaceChar(c)) {
c = read();
}
return (char)c;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public int 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() {
return Long.parseLong(nextString());
}
public Double nextDouble() {
return Double.parseDouble(nextString());
}
}
public static void main(String[] args) {
InputReader sc=new InputReader(System.in);
long n=sc.nextLong();
long s=sc.nextLong();
long start=0,end=n;
while(start<end)
{
long mid=(start+end)/2;
if(func(mid)>=s)
end=mid;
else
start=mid+1;
}
if(func(start)>=s)
System.out.println(n-start+1);
else
System.out.println(0);
}
public static long func(long n)
{
long temp=n;
int sum=0;
while(temp>0)
{
sum+=temp%10;
temp/=10;
}
return n-sum;
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.math.*;
import java.util.*;
import java.io.*;
public class Test5 {
public static void main(String[] z){
StreamTokenizer st = new StreamTokenizer(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
Scanner s = new Scanner(System.in);
int a = s.nextInt(), o=0;
String i = "";
ArrayList<String> l1 = new ArrayList<>(), l2 = new ArrayList<>();
for(int q=0; q<a; q++){
l1.add(s.next());
}
for(int q=0; q<a; q++){
i = s.next();
if(l1.contains(i)) l1.remove(i);
else l2.add(i);
}
Collections.sort(l1);
Collections.sort(l2);
for(int q=0; q<l1.size(); q++){
if(l1.get(q).charAt(l1.get(q).length()-1)!=l2.get(q).charAt(l2.get(q).length()-1)) o++;
}
System.out.println(o);
pw.flush();
}
static class PyraSort {
private static int heapSize;
public static void sort(int[] a) {
buildHeap(a);
while (heapSize > 1) {
swap(a, 0, heapSize - 1);
heapSize--;
heapify(a, 0);
}
}
private static void buildHeap(int[] a) {
heapSize = a.length;
for (int i = a.length / 2; i >= 0; i--) {
heapify(a, i);
}
}
private static void heapify(int[] a, int i) {
int l = 2 * i + 2;
int r = 2 * i + 1;
int largest = i;
if (l < heapSize && a[i] < a[l]) {
largest = l;
}
if (r < heapSize && a[largest] < a[r]) {
largest = r;
}
if (i != largest) {
swap(a, i, largest);
heapify(a, largest);
}
}
private static void swap(int[] a, int i, int j) {
a[i] ^= a[j] ^= a[i];
a[j] ^= a[i];
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
ArrayList<ArrayList<Integer>> fire = new ArrayList<ArrayList<Integer>>();
while (k-- != 0) {
ArrayList<Integer> t = new ArrayList<Integer>();
t.add(sc.nextInt());
t.add(sc.nextInt());
fire.add(t);
}
int maxI = 0, maxJ = 0, maxManhatten = -1;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++){
int curManhatten = Integer.MAX_VALUE;
for(int u = 0; u < fire.size(); u++)
curManhatten = Math.min(curManhatten, manhatten(i, j, fire.get(u).get(0), fire.get(u).get(1)));
if(curManhatten > maxManhatten){
maxManhatten = curManhatten;
maxI = i;
maxJ = j;
}
}
out.print(maxI + " " + maxJ);
out.flush();
out.close();
}
private static int manhatten(int i, int j, Integer a, Integer b) {
return Math.abs(i - a) + Math.abs(j - b);
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
public class helloWorld
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[] ar = new int[200];
String str = in.next();
for(int i = 0; i < str.length(); i++)
ar[ str.charAt(i) ]++;
int ans = 100000;
for(int i = 'A'; i < 'A' + m; i++)
ans = Math.min(ans, ar[i]);
ans *= m;
System.out.println(ans);
in.close();
}
}
|
linear
|
1038_A. Equality
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Practice {
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
String s=sc.nextLine();
//System.out.println(s);
char c[]=s.toCharArray();
ArrayList a =new ArrayList();
for(int i=0;i<c.length;i++)
{
//System.out.println(c[i]);
a.add(c[i]);
}
int x=Collections.frequency(a,'0' );
int y=Collections.frequency(a,'1');
//System.out.println(x+ " "+y );
if(y==0 || y==1)
{
System.out.println(s);
}
else
{
if(y>=2)
{
String s1="1";
for(int i=0;i<x;i++)
{
s1=s1+"0";
}
System.out.println(s1);
}
}
}
}
|
linear
|
976_A. Minimum Binary Number
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
new Solver().run(1);
}
}
class Solver {
private BufferedReader reader = null;
private StringTokenizer st = null;
private static final long MOD = (long)1e9 + 7;
private long x, k;
public void run(int inputType) throws Exception {
if (inputType == 0)
reader = new BufferedReader(new FileReader("input.txt"));
else
reader = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(reader.readLine());
x = Long.parseLong(st.nextToken());
k = Long.parseLong(st.nextToken());
if (x == 0) {
System.out.println(0);
return;
}
long pow = binpow(2, k);
long m = (2 * x) % MOD;
m = (m - 1 < 0) ? MOD - 1 : m - 1;
m = (m * pow) % MOD;
m = (m + 1) % MOD;
System.out.println(m);
reader.close();
}
long binpow(long v, long p) {
long res = 1L;
while(p > 0) {
if ((p & 1) > 0)
res = (res * v) % MOD;
v = (v * v) % MOD;
p /= 2;
}
return res;
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.*;
public class C {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n, r;
n = scan.nextInt();
r = scan.nextInt();
int[] locs = new int[n];
for (int i = 0; i < n; i++) {
locs[i] = scan.nextInt();
}
double[] yPos = new double[n];
Arrays.fill(yPos, 10e100);
yPos[0] = r;
for (int i = 1; i < n; i++) {
double pos = r;
for (int j = 0; j < i; j++) {
int xDist = Math.abs(locs[i] - locs[j]);
if (xDist <= 2 * r) {
double y = (2.0 * r) * (2.0 * r) - (xDist * xDist);
if (Math.abs(y - 0.0) < 0.0000000001) {
y = 0;
} else {
y = Math.sqrt(y);
}
y += yPos[j];
pos = Math.max(pos, y);
} else {
continue;
}
}
yPos[i] = pos;
}
String[] ans = new String[n];
for (int i = 0; i < n; i++) {
ans[i] = "" + yPos[i];
}
System.out.println(String.join(" ", ans));
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class cf1497_Div2_E2 {
static int[] spf;
public static int factor(int n) {
int val = 1;
while (n > 1) {
int cnt = 0;
int p = spf[n];
while (n % p == 0) {
cnt++;
n /= p;
}
if (cnt % 2 == 1)
val *= p;
}
return val;
}
public static void main(String args[]) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = in.nextInt();
int max = (int)(1e7) + 1;
boolean[] prime = new boolean[max + 1];
Arrays.fill(prime, true);
prime[0] = prime[1] = false;
spf = new int[max];
for (int i = 2; i < max; i++) spf[i] = i;
for (int i = 2; i * i < max; i++) {
if (prime[i]) {
spf[i] = i;
for (int j = i * i; j < max; j += i) {
prime[j] = false;
spf[j] = i;
}
}
}
int[] cnts = new int[max];
for ( ; t > 0; t--) {
int n = in.nextInt();
int k = in.nextInt();
int[] vals = new int[n];
for (int i = 0; i < n; i++)
vals[i] = factor(in.nextInt());
// left[i][x] = l where al ... ai such that in x moves it is valid subsequence
int[][] left = new int[n + 1][k + 1];
// x y z w a b c
for (int x = 0; x <= k; x++) {
int l = n;
int now = 0;
for (int i = n - 1; i >= 0; i--) {
while (l - 1 >= 0 && now + ((cnts[vals[l - 1]] > 0) ? 1 : 0) <= x) {
l--;
now += ((cnts[vals[l]] > 0) ? 1 : 0);
// System.out.println(now);
cnts[vals[l]]++;
}
// System.out.println(i + " " + x + " " + l + " " + now);
left[i][x] = l;
if (cnts[vals[i]] > 1) now--;
cnts[vals[i]]--;
}
}
// for (int[] x: left)
// System.out.println(Arrays.toString(x));
int oo = (int)(1e9);
int[][] dp = new int[n + 1][k + 1];
for (int i = 1; i <= n; i++)
Arrays.fill(dp[i], oo);
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= k; j++) {
if (j > 0) dp[i][j] = dp[i][j - 1];
for (int x = 0; x <= j; x++) {
int l = left[i - 1][x];
dp[i][j] = Math.min(dp[i][j], dp[l][j - x] + 1);
}
}
}
int min = Integer.MAX_VALUE;
for (int i = 0; i <= k; i++) {
min = Math.min(min, dp[n][i]);
}
out.println(min);
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = new StringTokenizer("");
}
public String next() throws IOException {
if(st.hasMoreTokens())
return st.nextToken();
else
st = new StringTokenizer(br.readLine());
return next();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
//#
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
//$
}
}
|
cubic
|
1497E2
|
CODEFORCES
|
// No sorcery shall prevail. //
import java.util.*;
import java.io.*;
public class InVoker {
//Variables
static long mod = 1000000007;
static long mod2 = 998244353;
static FastReader inp= new FastReader();
static PrintWriter out= new PrintWriter(System.out);
public static void main(String args[]) {
InVoker g=new InVoker();
g.main();
out.close();
}
int dp[];
int freq[][];
int m;
//Main
void main() {
int n=inp.nextInt();
m=inp.nextInt();
String s=inp.next();
dp=new int[1<<m];
Arrays.fill(dp, -1);
freq=new int[m][m];
for(int i=0;i<n-1;i++) {
int x=s.charAt(i)-'a';
int y=s.charAt(i+1)-'a';
if(x==y) continue;
freq[x][y]++;
freq[y][x]++;
}
out.println(go(0,0));
}
int go(int pos, int mask) {
if(pos==m) return 0;
if(dp[mask]!=-1) return dp[mask];
int gg=Integer.MAX_VALUE;
for(int i=0;i<m;i++) {
if((mask>>i&1)==1) continue;
int cost=0;
for(int j=0;j<m;j++) {
if((mask>>j&1)==1) cost+=freq[i][j]*pos;
else cost-=freq[i][j]*pos;
}
cost+=go(pos+1,mask|(1<<i));
gg=Math.min(gg, cost);
}
return dp[mask]=gg;
}
/*********************************************************************************************************************************************************************************************************
* ti;. .:,:i: :,;;itt;. fDDEDDEEEEEEKEEEEEKEEEEEEEEEEEEEEEEE###WKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWW#WWWWWKKKKKEE :,:. f::::. .,ijLGDDDDDDDEEEEEEE*
*ti;. .:,:i: .:,;itt;: GLDEEGEEEEEEEEEEEEEEEEEEDEEEEEEEEEEE#W#WEKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKKKKKKG. .::. f:,...,ijLGDDDDDDDDEEEEEE *
*ti;. .:,:i: :,;;iti, :fDDEEEEEEEEEEEEEEEKEEEEDEEEEEEEEEEEW##WEEEKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWWKKKKKKEG .::. .f,::,ijLGDDDDDDDDEEEEEE *
*ti;. .:,:i: .,,;iti;. LDDEEEEEEEEEEKEEEEWEEEDDEEEEEEEEEEE#WWWEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWKKKKKEDj .::. .:L;;ijfGDDDDDDDDDEEEEE *
*ti;. .:,:i: .:,;;iii:LLDEEEEEEEEEEEKEEEEEEEEDEEEEEEEEEEEW#WWEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWKWWWWWWWWWWWWWWKKKKKKKEL .::. .:;LijLGGDDDDDDDDEEEEE *
*ti;. .:,:;: :,;;ittfDEEEEEEEEEEEEEEEEKEEEGEEEEEEEEEEEKWWWEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWKKKKKKKELj .::. :,;jffGGDDDDDDDDDEEEE *
*ti;. .:,:i: .,;;tGGDEEEEEEEEEEEKEEEKEEEDEEEEEEEEEEEEWWWEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWKWWWWWWKKKKKKKEEL .::. .:;itDGGDDDDDDDDDEEEE *
*ti;. .:::;: :;ifDEEEEEEEEEEEEKEEEKEEEEEEEEEEEEEEEWWWEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WWWKKKKKKKKEEf .::. :,itfGEDDDDDDDDDDDEE *
*ti;. .:::;: :GGEEEEEEEEEEEKEKEEKEEEEEEEEEEEEEEEEWWEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKKEEDG .::. .,;jfLGKDLDDDDDDEEDD *
*ti;. .:::;: fDEEEEEEKKKKKKKKKEKEEEEEEEEEEEEEEE#WEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#KKKKKKKKKKEEf .:::. .,;tfLGDEDDDDDDDDEEE *
*ti;. :::;: fDEEEEEEKKKKKKKKKKWKEEEEEEEEEEEEEEEWKEEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKKKEEft :::. .,;tfLGDDDKDDDDDDDDD *
*ti;. .::;: fDEEEEEEKKKKKKKWKKKKKEEEEEEEEEEEEE#WEEWEEEEEDEEDEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKEEGG :,:. .,;tfLGGDDDKDDDDDDDD *
*ti;. .:.;: tGDEEEEKKKKKKKKKKKKKKKKKEEEEEEEEEEEWEEKWEEEEEEEDEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKKKKKEEDf :::. .,;tfLGGDDDDEDDDDDDD *
*ti;. .::;: fDEEEEEKKKKKKKKKKKWKKKKKKKKEEEEEEEWWEEWEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKEEEft.::. .,;tfLGGDDDDDDEDDDDD *
*ti;. .:.;: tGDEEEKKKKKKKKKKKKKKKKKKKKKKEKEEEEE#EEWWEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKEEEGD:::. .,;tfLGGDDDDDDDEDDDD *
*ti;. .:.,. LDEEEEKKKKKKKKKKWKWKKKKKKKKKKKKEEEKWEKW#EEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKW##KKKKKKEEEEf,,:. .,;tfLGGDDDDDDDDEDDD *
*ti;. ..:.,. LGDEEEEKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEEW#WEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKK##KKKKKEEEEEfi;,. .,;tfLGGDDDDDDDDDKDD *
*tt;. .:.,: jDEEEEKKKKKKKKKKWWKKKKKKKKKKKKKKKKKWKE#WWEEEEEEEEEEEEEEWEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKWWKKKKEEEEDfG;,: .,;tfLGGDDDDDDDDDDKD *
*tii,. .:.,. tGDEEEEKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKKWWWKEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKW#KKKKEEEEDGGi;,. .,;tfLGGDDDDDDDDDDDE *
*ti;;,:. .:.,: fDEEEEKKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEK#WWKEEEEEEEEEEEEDEEEEEEEEEEEEEEGEEEEEEEEEEEEEEEEEEEKKKKKKKWWKKEEEEEEDDf;;;,. .,;tfLGGDDDDDDDDDDDD *
*tii;,,:.. ...,. ;LEEEEEKKKKKKWKKKKWKKKKKKKKKKKKKKKKKEKKW#WEEEEEEEEEEEEEjEEEEEEEEEKEEEEGEEEEEEEEEKEEEEEEEEEEEEEEEEE#WKEEEEEEDDf;;;;,: .,itfLGGDDDDDDDDDDDD *
*ti;,,,,,:. ...,. LDEEEEKKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKK#W#WEEEEEEEEEEEDDLEEEEEEEEEWEEEEDEEEEEEEEEKEEEEEEEEEEEEEEEEEWWEEEEEEEDDfj,,,,,:. .,itfGGGDDDDDDDDDDDD *
*tii,,,,::::. ...,: .fDEEEEKKKKKKWKKKKWWWKKKKKKKKKKKKKKKEKKW#WWEEEEEEEEEEEKiKEEKEEEEEEWEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEEWWEEEEEEEDDLD:::,,,:. .,ijfGGGDDDDDDDDDDDD *
*ti;:::::::::.. .:.,: LDEEEEKKKKKKKWKKKKWWKKKKKKKKKKKKKKKKtKKWWWWKEEEEEEEEEDiiDEEEEEEEEWWEEEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEWKEEEEEDDDGL:. .:,,,: .,ijLGGGDDDDDDDDDDDD *
*tt;. .::::::::.. ...,: :fDEEEKKKKKKKKKKKKWW#KKKKKKKKKKKKKKKKfKKWWWWKEEEEEEEEDti,DEKEEEEEEWWEEEDEEEEEEEEEKEEEEEEEEEEEEEDEEEEE#WEEEEEGGDGf:. .:,;,:. .,ijLGGDDDDDDDDDDDDD *
*tt;. .:::::::.. ...,: GDEEEKKKKKKKKWKKKKWWWKKKWKKKKKKKWWWKDEKLWWWWKKEEEEEEDEi,LDEEEEEEEEWWEEEEEEEEEEEEEEEEEEEEEEEEEDEDEEEEEW#EEEEDDDDGf,. :,,,:...,ijLGGGDDDDDDDDDDDD *
*tt;. .....::::.. ...,: fDEEEKKKKKKKKWKKKKWWWWKKKWKKKKKKKKKKfWKiWWW#KKEEEEEEEi;.EDfEEEDEEiWWEEEEEEEEEEEEDGKEEEEEEEEEEDEEEEEEEWWEEEEDDDGGLi. .,;,:::,ijLGGGDDDDDDDDDDDD *
*tt;. ....:::::. ...,. iDEEEEKKKKKKKKWKKWKWWWWWKKWWWKKKKKKKKtWKt#WWWKKEEEEEDji..DDKDDEDEGiWKEEEEEEEEEEDDEjEEEEEEEEEEEDEEEEEEEKWKEEDDDDGGff. .:,;,,;ijLGGGDDDDDDDDDDDD *
*tt;. ....::::.. .:.,: .LDEEEKKKKKKKKKKKKWWWWKWWWWWWWWWWKKKKWtKKiDWWWKKKEEEEKi:..DEDDDDDDiiWKEEEEEEEEEEDDEijDEEEEEKEEEEEEEEEEEEWWEEGDDDGGLG. .:,;;iijLGGGDDDDDDDDDDDD *
*tt;. .....:::.. ...,. .fEEEEKKKKKKKKWKKKKWWWWWWWWWWWWWWKWKKKiKDiLWWWWKEEEEEi,..fD:DDDDDti;WEEEEEEEEEEKDDi:iDDEEEEWEEEEEEEEEEEE#WEEGDDDDGGG. :,iitjLGGGDDDDDDDDDDDD *
*tti. .....:::.. ...,. GDEEEKKKKKKKKKWKKKWWW#WWWWWWWWWWWKWKKjiEjitWWWKKWEEEDi...DDLDDDDji;;WEEEEEEEEEEEDEj.iDDEEEEWEEEEEEEEEEEEWWEEDDDDDDGf. .,;tjfLGGDDDDDDDDDDDD *
*tti. ....::::.. ...,. fEEEKKKKKKKKKKKKKKKW#WWWWWWWWWWWWWWWWtiEiiiWWWKKEWKEi....D.EDDDEi;.fWEEEEEEEEEEDDfL.;EDDEEEWEEEEEEEEEEEEWWEEEDDDDDGf. :;ijfLGGDDDDDDDDDDDD *
*tti. ....::::.. ...,. LDEEEKKKKKKKKKKKKKKWWWWWWWWWWWWWWWW####WKiiiWWWKKKEEK,...:E:DDDEii..GWEEEEEEEEDWDDiL.,KDDEEEWEEEEEEEEEEEEWWKEEDDDDDGf: .,itfLGGDDDDDDDDDDDD *
*tti. .....:::.. ...,. fDEEEKKKKKKKKKWKKKKWWWWWWWWWWWWW########WLiiWWWKKKEEjD...G,DDDDi;...EWEEEEEEEEDKDEii..LDDEEEWEEEEEEEEEEEEWWWEEDDDDDGfi .,;tfLGGGDDDDDDDDDDD *
*tti. .....:::.. ...,. iGEEEKKKKKKKKKKWKKKKWWWWWWWWWWWW###########KiWWWKKEEE,.D..D.DDDii:...KKEEEEEEEEEDDj:...tEDEEEWEEEEEEEEEEEEWWWEEEDDDDDLL .,;tjLLGGDDDDDDDDDDD *
*tti. ....::::......:. LEEEKKKKKKKKKKWWKKKWWW#KWWWWWWWW#####W####W##KWWKKEEL..:D.jjDDi;,....KKEEEEEEEDfDDi...:iKDEEEWKEEEEEEEEEEEWWWEEEEDDDDLG .,;tjLLGGDDDDDDDDDDD *
*tti. ...::::::..,. :GEEEKKKKKKKKKKKKWWWWW##WWWWWWWWW##WKWK#W#W####WWKEEK.....G.DDti,.....KKEEEEEEDWGDf.,...iKDEEEWWEEEEEEEEEEEW#WEEEEEDDDGL .,;tjLLGGDDDDDDDDDDD *
*tti. ....::::::,. GDEEKKKKKKKKKKKKKWWWW###WWWWWWWWWW#WWWK###W#####WKEKK.....jDDL;;......KKEEEEEEEEEDi.f...;KDEEEWWEEEEEEEEEEEWWWWEEEEEDDGf .,;tjLLGGDDDDDDDDDDD *
*tti. ....:::,,. .LEEEKKKKKWKKKKKWWWWWW###WWWWWWWWWW#WWKW#WW##W#WWWKEKD:....:DD:;......;KEEEEEEEKiDD..f...,KKEEEWWEEEEEEEEEEEWWWWEEEEEDDDf .:;tjLLGGGDDDDDDDDDD *
*tti. ...::,,,:. GDEEKKKKKKKKKKKKWWWWWWW#WWWWWWWWWWW#KjKWWWWWWWWWWWWEK.j,..;fD.;.......fKEEEEEDKG:Di..,....DKEEEWWEEEEEEKEKKKWWWWEEEEEEDDf .:;tjLLGGDDDDDDDDDDD *
*jti. ...::,,,,:. .fEEEKKKKKWKKKKKKWWWWWWW#WWWWWWWWWWK#KKKWWWWWWWWWWWWWK..f:.:G.,:.......EKEEEEEKK;:E:.......fKEEEWWKEKEKKKKKKKW#WWEEEEEEDDf: .,;tfLLGGDDDDDDDDDDD *
*tti. ...:,,,;;,: iDEEKKKKKWKKKKKKKWWWWWWW#WWWWWWWWWWK#WDKWWKKWWWWWWWWWE..;G:G..,........KKEEEEEKi.Gi..:.....tKEEKWWWKKKKKKKKKKW##WKEEEEEEDfi .,;tfLLGGGDDDDDDDDDD *
*tti. ....::,,;;;,LEEKKKKKKWKKKKKWWWWWWW###WWWWWWWWWWKWWDKWEEEWKKWWWWWKKj.:LG..;.........EKEEEEKG;.G...;.....;KKEKWWWKKKKKKKKKKW##WWKEEEEEDfL .,;tfLGGGDDDDDDDDDDD *
*jti. ...::::,;ijDEEKKKKKWKKKKKKWKWWWWW##WWWWWWWWWWWKK#KKGDGDWEEWKKWKKGE,.i;.:.........:EKEEEKE;.:L...j.....,KWEKWWWKKKKKKKKKK####WKKEEEEDLG .,;tfLGGGGDDDDDDDDDD *
*jti. ...:...,,;GEEKKKKKWWKKKKKWWWWWWWW###WWWWWWWWWKKKWWKiLGGEDEDEKGKKiEG..;...........jKEEEKK;:.G....,.....:KKEWWWWKKKKKKKWKK####WKKKKEEEGL .,;tfLGGGGDDDDDDDDDD *
*jti. ...:. .:,GEEKKKKKWKKKKKWWWWWWWW####WWWWWWWWWKKKWWKii;fDLGDK: EEi:E:.............EKEEKK;;..L...........KKKWWWWKKKKKKKWKK####WKKKWKEEDf .,;tfGGGGDDDDDDDDDDD *
*jti. ...:. ,EEKKKKKWWKKKKKWWWWWWWWW###WWWWWWWWKKKKfWWLt;i,. fi EG..D:.............EKEKK;;..t....:.......KWKWWWWKKKKKKKWKK####WKKKWEEEDf:. .,;tfGGGGDDDDDDDDDDD *
*jti. ...:. GEEKKKKKWKKKKKWWWWWWWWW####WWWWWWWKKKKKt;KKEfff .;t.................KKKKi;:..GtGGfG.......KWWWWWWKKKKKKKWKK###WWWKKKKEEEf,,: .,;tfGGGGDDDDDDDDDDD *
*jti. ...:. GEKKKKKWWKKKKKWWWWWWWWWW##WWWWWWWKKKKKKt;EiKKKK, ...t................jEKKG;;..,.....,LGi....KWWWWWWKKKKKKWKKKW####WKKKKKEEL,,,:. .,;tfGGGDDDDDDDDDDDD *
*jti. ...:. .GEEKKKKKWKKKKKWWWWWWWWWW###WWWWWWWKKKKKKtiE::tGG........................EEEj;;...,.........:D..DKWWWWWWKKKKK#KKW###W#WKKKKKEEfj:,,,:. .,;tfGGGDDDDDDDDDDDD *
*jti. ...:. DEKKKKKWWKKKKKWWWWWWWWW####WWWWWWWKKKKKKiiE:::.::.......................EEi;;...j.....f......:iDKWWWWWWKKKKK#WW######WKKKKKEELG :,,,,:. .,;tfGGGDDDDDDDDDDDD *
*jti. ...:. fEEKKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKK;tE::..........................DD;.;,.::......;........EWWWWWWWKKKKW#WW#####WWKKKWKKELG .:,,,:::,;tfGGGDDDDDDDDDDDD *
*jti. ...:. .DEKEKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKE,iD::..........................D..,;.,;tLffi...........DWDWWWW#KKKWWWWW#####W#KKKWKEEGL .:,;,,,;tfGGGDDDDDDDDDDDD *
*jti. ...:. ;EEKKKKWWKKKKKWWWWWW#WWWW####WWWWWWKKKKKEL:iD:..........................j ..;..;;:.....i,........DKtWWWWWKKWWWWWW#####WWWKKKEKEDf .:,;;;itfGGGDDDDDDDDDDDD *
*jti. ...:. DEKKKKKWWKKKKWWWWWWW#WWWW####WWWWWWKKKKKEj:iG...............................:....................GKiWWWWWKKWW#WWW######WWKKKKKEEf .,;iitfGGGDDDDDDDDDDDD *
*jti. ...:.:EKKKKKWWKKKKKWWWWWWW#WWW#####WWWWWKWKKKKEi:if:.................................iEKEKKKKKKDj......DKiWWWWWKWK##WW#######WWKKK:KEEL .:;itfGGGDDDDDDDDDDDD *
*jji. ...:,DEEKKKWWWKWKKWWWWWWWWWWWW#####WWWWWWWKKKKEi:it..................................j. KKKKKKKKKKKf..DKiWWWWWKWW##WW#######WWKKK,KEEf .,;tfGGGDDDDDDDDDDDD *
*jji. ..L:iDEEKKKWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKKi.i;.................................. . KKKWWWWWWWWK..DGiWWWWWKK##WWW#####W#WWKKKjEKEL, .:;tfGGGDDDDDDDDDDDD *
*jji. .f:::EEEKKKWWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKK;.i,.................................:: KKEKWWWWWWfWK..EiiWWWWWKWW#WW##########KKKD,KELj .:;tfGGDDDDDDDDDDDDD *
*jji. .t::::,DEEKKKWWKKKKWWWWWWWWW#WWWW#####WWWWKKWKKKEK;.i:.................................GDDEEEKKKWWWWWtWWD.E;iWWWWWW###WW#########WWKKK.EEDG .:;tfGGGDDDDDDDDDDDD *
*jji. . j..::::EKEKKKWWWKKKKWWWWWWWWW#WWW######WWWWKKWKKKEK;.t:.................................ELLEDDEEEWWWWEtWK,.KiiWWWWWW###W##########WWKKK:EEEG .;tjfLLGDDDDDDDDDDDDDDD *
*jji. i.::::::,EEEKKWWWKKKKKWWWWWWWWW#WWW#####WWWWWKWKKKKEE,.t..................................DfiEGDDDEEKKKttKWG.KiiWWWWW##WWW##########WWKKK:fEEL ,fGGGDDDDDDDDEEEDDDDDDDDDD *
*jji. .;:..:::::DEEEKKWWWKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKED,.t..................................ifjDDGGEGDKK.ttKKE.DiWWWWW###WW##########WWWKKK:.KELiLGGGGDDDDDDDDDDDDEEEDDDDDDD *
*jji. i.:.::::::,KEEKKWWWKKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKEL:.j..................................GGf,;ifLLED .iiKKi:fWWWWWW##W#W##########WWWKKK:.KKLGGDDDDDDDDDDDDDDDDEDDEEDDDDD *
*jji. .j:.::::::::EEEKKKWWWKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKf:.f..................................:EEfftf .,. ;iE,..jWWWWWWW###W############WWKKK,:KKGDDDDDDDDDDDDDDDDDDDDDDDEDDDD *
*jji. .:.::::::::,,EEEKKWWWKKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKt..G....................................EEELL; .j....tKWWWWWWW################WWWKKtfGKGEDDDDDDDDDDDDDDDDDDDDDDDEEDD *
*jji. :...:::::::,,jEEKKWWWWKKKKKKWWWWWWWWW##KWW#####KWWWWWWKKKKEi..D....................................:jEEE.........;KKWWWWWWWW#WW##W##########WWKKDLGKEKDDDDDDDDDDDDDDDDDDDDDDDDDED *
*jji. i:.::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWW##WWW#####WWWWWWWKKKKKi..D......................................:::::......,KKKWWWWWWWWW#####W########WWWKKKGGKKEGGGGGGGGDDDDDDDDDDDDDDDDDDE *
*jji. i..:::::::::,,tEEKKWWWWKKKKKWWWWWWWWWWW##WW######WWWWWWWKKKKKi..D......................................::::......:EKKKWWWWWWWWWWW##WW########W#WKKWGGKKGGGGGGGGGGGGGGGDDDDDDDDDDDDD *
*jji. .:::::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWWW##WW#####WWWWWWWWKKKKKi..D....................................:::::::::..tELii;KWWWWWWWWWW##WW######WWWWWWKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGDG *
*jjt. :.::::::::,,,,fEEKKWWWWKKKKKKWWWWWWWWWW###WW####WWWWWWW#WKKKKKi..D....................................:::::::.:.,;;;;;;,KKWWWWWWWWW#WW########WWWKKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGGG *
*jji. ;.::::::::,,,,;EEEKWWWWWKKKKKWWWWWWWWWWWW##WW###WKWWWWWK#WKKKKKi..G......................................:::::::,;;;;:...KKKWWWWWWWWWKWW#######WWWWKKGLGKDGGGGGGLLGGGGGGGGGGGGGGGGGGG *
*jjt. f.:::::::::,,,,fEEKKWWWWWKKKKKWWWWWWWWWWW###WW##WKKWWWWWW#WKKKKK;.jt........i.............................:::::::;j;;....:E.KKKWWWWWWWKWW#####W#WWWWKKLLGWEEGGGGGLGGGGGGGGGGGGGGGGGGGG *
*jjt. ...:::::::,,,,,;DEEKWWWWWKKKKKWWWWWWWWWWWW####WWWKKKWWWWWWWWKKKKK;.E;.........t.............................:::::ii;;.....D...KKWWWWWWWKWW#####WWEWWWKKGGGEKKGGGGGLGGGGGGGGGGGGGLGGGGGG *
*fji. ;.:::::::,,,,,;LEEKKWWWWWKKKKKWWWWWWWWWWWW####KWKKKKWWWWWWWWKKKKKi.D;..........j.............................:::tt;,.....:.....KKWWWWWWKWWWW##WWWGWWWKKGGGGKEGGGGGGGGGGGGGGGGGGGLLGGGGL *
*fji. t::::::::,,,,,,;EEEKWWWWWKKKKKKKWWWWWWWWWWW##WKWKKKKKWWWWWWWWKKKKKi:D;............j...........................::LL;,.............KKWWWWWKWWWWWWWWWGWWWKKGGGGKGGGGGGGGGGGGGGGGGGGGLLGGGGL *
*fjt: .:::::::,,,,,,,DEEKWWWWWWKKKKKKKWWWWWWWWWWWWKKWKKKKKKWWWWK#WWKKKKWitE;........... ............................:G;;:...............KKKWWKKWWWWWWWWWGWWWKKGGGGWGGGGGGGGGGGGGGGGGGGGGGGGGGL *
*fjji;:. .f:::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWWKKKKKKKKKKKWWKWWWWWKKKKWGKD;........................................L;;..................DKKWKKWWWWWWWWWGWWWKKDGGGKDGGGGGGGGGGGGGGGGGGGGGGGGGG *
*fjjtii;,:. :::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWKKKKKKKKKKKKWWWWWW#WWKKKKWiEj;......................................:i,;....,...............;KKEKWWWWWWWWWGKWWKKDDGGDEGGGDGGGGGDGGGGGGGGGGGGGGGG *
*fjtiiiii;;:. j::::::,,,,,,,;;EEEKWWWWW#KKKKKWWWWWWWWWKKKKKKWKKKKKKKWWWWWWWWWKKKKWtEL;:....................................;;;:...,;j................:KEEWWWWWWWWWDDWWKKDDDDDKDDDDDDDDDDDDDDDGGGGGGGGGGG *
*fjti;;iiii;;,:::::::,,,,,,,,;EEEKWWWWWWWKKKKWWWWWWWWKKKKKKKWKKKKKKKWWWWWWW#W#KKKKWEEii;...................................f;:....,;L...................EEKWWWWWWWWDDWWKKDDDDDKEDDDDDDDDDDDDDDDDDDDDDGGGG *
*fjt,,,;;;;ii;f::::::,,,,,,,;;EEKWWWWWWWKKKKKWWWKWWKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWKEij;:...............................:G;,.....,;f....................:tKKWWWWWWWDDWWKKDDDDDKKDDDDDDDDDDDDDDDDDDDDDDDDD *
*jjt. ..:,;;;;,::::,,,,,,,,;;GEEWWWWWWWWKKKKWKKWKKKKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWEDi;j;............................,Li;L;;;..,;;f........................KKKKWWWKDDWWKKDDDGDKKGGGGGGGGDGDDDDDDDDDDDDDDD *
*fjt. .:,,,:::::,,,,,,,;;;EEKWWWWWWWKKKKKKWKKKKKKKKKKKKKKKKKKKKKWKKKWKW##W#KKKKWEti;;G;........................tEEEL;;;;;;;;;;L..........................DKKKKKEDDWWKEDGftiLE;;;;itjLGGGGGGDDDDDDDDDDD *
*fjt. .j::::,,,,,,,;;;DEEWWWWWWWWKKKKWKKKKKKKKKKKKKKKKKKKKKKKWKKWWWK##W#KKKKKEii;;;L;...................iDEEEEEEKKi;j;;;;jD.....:......................,KKKKDGGEKKE:::::;E::::::::::,tLGGDDDDDDDDDD *
*fjt. .;:::,,,,,,,;;;;EEKWWWWWWWWKWKKKKKKKKKKKKKKKWKKKKKKKKKKWKKWWWW#WW#KKKKKKii;;;;f;.............:tDEEEEEKKKKKKKKEti;;;L...............................EEKf;:iKKE::::::E::::::::::::::ifDDDDDDDDD *
*fjt: :::,,,,,,,,;;;DEEWWWWWWWWWEKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####KKKKKEiii;;;;f,.........iDEEEEKKKKKKKKKKKKKKKf;iG......i..........................fK::::KKE::::::E::::::::::::::::,tGGDDDDD *
*fjt: t:::,,,,,,;;;;iDEKWWWWWWKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####WKKKKLiii;;;;;L,....,Li;EDEEEEKKKKKKKKKKKKKKKKiG......;:...........................:i:::KKE:::::,E,::::::::::::::::::iGDDDD *
*jjt. f::,,,,,,,;;;;GEEWWWWKEEKEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKWWWWW###WWKKKKiii;;;;;;;G,;L;;iiEEEEEEEKKKKKKKKKKKKKWWKE......;t.........:....................j::KEE:,::,,D,,::::,,,,,,:::::::::tDDD *
*fjt:. ,::,,,,,,,;;;;EEWWKEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKKWWWWW#W#KKKKKKiiiiii;;;;;i;;iiiEEKEEKKWKKKKKKKWKKKKKWWWGi;...;t......,;;;;,....................:,EEE,,,,,,D,,,,,,,,,,,,,,,,::,::::tG *
*fjt:. ,::,,,,,,,;;;;DEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWW#W#KKKKKKiiiii;;i;;;;;iiiKKKEKKKKWWKWWWWWWKKKKWWWWW;;;:;L.....;;;;;;;;;....................,KEE,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,; *
*fjt:. f:,,,,,,,;;;;jEDEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWW#W##KKKKKKiiiiiiii;i;;iiiEKKKKKKKKWKWWWWWWWWKKKWWWWWKi;;i.....,jEEfGi;;;;;...................EED,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,, *
*fjt:. .f::,,,,,,;;jEEDEEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWKWWWWW###KKKKKLiiiiiiiiiiiiiiEEKKKKKKKKWWWWWWWWWWWWKWWWWWWGi;i;,..;jDDDKEGi;;;;;;:................EED,,,,,,D,,,,,,,,,,,,,,,,,,,,,,,,, *
*fjt:. .. ;::,,,,,;;EDDEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKW#WW####KWKKKiiiiiiiiiiiiijKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWt;i;;;;i;DDDDDDGi;;;;;;;;:.............EDf;,,,;,G;;;;;;;;;;;;;;;,,,,,,,,,, *
*fjt:......:,,,,,,;LDDDEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWWKWWWW####KKKKKiiiiiiiiiiijKEKKWKKKKKKKWWWWWWWWWWWWWWWWWWWWWWiLiii;i;DEEEEDDE;i;;;;;;;;;:..........EDi,;;;;;L;;;;;;;;;;;;;;;;;;,,,,,,, *
*fjt:......:,,,,,;EDDDEEKEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKWWWWKKWWW##W#KWKKWEiiiiiijGKKKKKWWKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKi;iiiiDDEEEEEEDEi;;;;;;;;;;;;;,:.....ED;;;;;;;j;;;;;;;;;;;;;;;;;;;;;;;,, *
*fjt:.....t,,,,,;DDDDEEEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKWWWW##WKWKKWKiiiKKKKKKKKKWWKKKKKKKKWWWWWWWWWWWWWWW#WWWWWWWWWiiiiifLEEEEEEEEDi;i;;;;;;;;;;;;.....DD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; *
*fjt:.....G,,,,,GDDDEEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKKWWWKKKWWW###WKWKKWKitKKKKKKKKKWKKKKKKKKKKWWWWWWWWWWWWWW###WWWWWWWWEiiiiiiiEEEEEEEEDGiiii;;;;;;;;;.....GD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; *
*fjt:.....L,,,,;GDDDEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWDGWWW###KKWWKWKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWW####WWWWWWWWWiiiiiiiiEEEEEEEEEEDi;i;;;;;;;;.....Lj;;;;;;i;iiiiii;;;;;;ii;;;;;;;;;;; *
***********************************************************************************************************************************************************************************************************/
void sort(int a[]) {
ArrayList<Integer> list=new ArrayList<>();
for(int x: a) list.add(x);
Collections.sort(list);
for(int i=0;i<a.length;i++) a[i]=list.get(i);
}
void sort(long a[]) {
ArrayList<Long> list=new ArrayList<>();
for(long x: a) list.add(x);
Collections.sort(list);
for(int i=0;i<a.length;i++) a[i]=list.get(i);
}
void ruffleSort(int a[]) {
Random rand=new Random();
int n=a.length;
for(int i=0;i<n;i++) {
int j=rand.nextInt(n);
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
Arrays.sort(a);
}
void ruffleSort(long a[]) {
Random rand=new Random();
int n=a.length;
for(int i=0;i<n;i++) {
int j=rand.nextInt(n);
long temp=a[i];
a[i]=a[j];
a[j]=temp;
}
Arrays.sort(a);
}
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 s="";
try {
s=br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
long fact[];
long invFact[];
void init(int n) {
fact=new long[n+1];
invFact=new long[n+1];
fact[0]=1;
for(int i=1;i<=n;i++) {
fact[i]=mul(i,fact[i-1]);
}
invFact[n]=power(fact[n],mod-2);
for(int i=n-1;i>=0;i--) {
invFact[i]=mul(invFact[i+1],i+1);
}
}
long nCr(int n, int r) {
if(n<r || r<0) return 0;
return mul(fact[n],mul(invFact[r],invFact[n-r]));
}
long mul(long a, long b) {
return a*b%mod;
}
long add(long a, long b) {
return (a+b)%mod;
}
long power(long x, long y) {
long gg=1;
while(y>0) {
if(y%2==1) gg=mul(gg,x);
x=mul(x,x);
y/=2;
}
return gg;
}
// Functions
static long gcd(long a, long b) {
return b==0?a:gcd(b,a%b);
}
static int gcd(int a, int b) {
return b==0?a:gcd(b,a%b);
}
void print(int a[]) {
int n=a.length;
for(int i=0;i<n;i++) out.print(a[i]+" ");
}
void print(long a[]) {
int n=a.length;
for(int i=0;i<n;i++) out.print(a[i]+" ");
}
//Input Arrays
static void input(long a[], int n) {
for(int i=0;i<n;i++) {
a[i]=inp.nextLong();
}
}
static void input(int a[], int n) {
for(int i=0;i<n;i++) {
a[i]=inp.nextInt();
}
}
static void input(String s[],int n) {
for(int i=0;i<n;i++) {
s[i]=inp.next();
}
}
static void input(int a[][], int n, int m) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j]=inp.nextInt();
}
}
}
static void input(long a[][], int n, int m) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j]=inp.nextLong();
}
}
}
}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1141f2_2 {
public static void main(String[] args) throws IOException {
int n = ri(), a[] = ria(n), pre[] = new int[n + 1];
for (int i = 0; i < n; ++i) {
pre[i + 1] = pre[i] + a[i];
}
Map<Integer, List<p>> sums = new HashMap<>();
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= i; ++j) {
sums.computeIfAbsent(pre[i + 1] - pre[j], k -> new ArrayList<>()).add(new p(j, i));
}
}
int k = 0;
List<p> ans = new ArrayList<>();
for (int key : sums.keySet()) {
List<p> segs = sums.get(key);
segs.sort((x, y) -> x.b == y.b ? x.a - y.a : x.b - y.b);
int last = -1, cnt = 0;
for (int i = 0, end = segs.size(); i < end; ++i) {
if (segs.get(i).a > last) {
++cnt;
last = segs.get(i).b;
}
}
if (cnt > k) {
k = cnt;
ans = segs;
}
}
prln(k);
int last = -1;
for (int i = 0, end = ans.size(); i < end; ++i) {
if (ans.get(i).a > last) {
prln(ans.get(i).a + 1, ans.get(i).b + 1);
last = ans.get(i).b;
}
}
close();
}
static class p {
int a, b;
p(int a_, int b_) {
a = a_;
b = b_;
}
@Override
public String toString() {
return "Pair{" + "a = " + a + ", b = " + b + '}';
}
public boolean asymmetricEquals(Object o) {
p p = (p) o;
return a == p.a && b == p.b;
}
public boolean symmetricEquals(Object o) {
p p = (p) o;
return a == p.a && b == p.b || a == p.b && b == p.a;
}
@Override
public boolean equals(Object o) {
return asymmetricEquals(o);
}
public int asymmetricHashCode() {
return Objects.hash(a, b);
}
public int symmetricHashCode() {
return Objects.hash(a, b) + Objects.hash(b, a);
}
@Override
public int hashCode() {
return asymmetricHashCode();
}
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// graph util
static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static void pryesno(boolean b) {prln(b ? "yes" : "no");};
static void pryn(boolean b) {prln(b ? "Yes" : "No");}
static void prYN(boolean b) {prln(b ? "YES" : "NO");}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author niyaznigmatul
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[] b = a.clone();
ArrayUtils.sort(b);
int count = 0;
for (int i = 0; i < n; i++) {
if (a[i] != b[i]) {
++count;
}
}
out.println(count <= 2 ? "YES" : "NO");
}
}
class FastScanner extends BufferedReader {
boolean isEOF;
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
if (isEOF && ret < 0) {
throw new InputMismatchException();
}
isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= -1 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (!isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
class ArrayUtils {
public static void sort(int[] a) {
Random rand = new Random(System.nanoTime());
for (int i = 0; i < a.length; i++) {
int j = rand.nextInt(i + 1);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
Arrays.sort(a);
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.PI;
import static java.lang.System.in;
import static java.lang.System.out;
import static java.lang.System.err;
/*
11
1
1
1
2
2
1
2
1
2
2
3
*/
public class C {
static public void main(String... args) throws Exception {
Foster sc = new Foster();
PrintWriter p = new PrintWriter(out);
int t = sc.nextInt();
while(t--!=0){
int n = sc.nextInt();
int a[] = sc.intArray(n);
ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
for(int i = 0; i < n; i++){
ArrayList<Integer> temp = new ArrayList<>();
if(i-1 < 0){
temp.add(1);
}
else{
ArrayList<Integer> inner = arr.get(i-1);
int last = inner.get(inner.size()-1);
ArrayDeque<Integer> q = new ArrayDeque<>();
for(int j : inner){
q.addLast(j);
}
// if current is one greater then increment
if(last+1 == a[i]){
q.pollLast();
q.addLast(a[i]);
}
// move the chain
else if(a[i]==1){
q.addLast(a[i]);
}
// move back
else{
while(!q.isEmpty() && a[i]-q.peekLast() != 1){
q.pollLast();
}
if(q.isEmpty()) q.addLast(a[i]);
else{
q.pollLast();
q.addLast(a[i]);
}
}
// transfer queue to list
while(!q.isEmpty()){
temp.add(q.pollFirst());
}
}
arr.add(temp);
}
// output answer
for(int i = 0; i < arr.size(); i++){
p.print(arr.get(i).get(0));
for(int j = 1; j < arr.get(i).size(); j++){
p.print("." + arr.get(i).get(j));
}
p.println();
}
}
p.close();
}
static long[] sort(long a[]){
ArrayList<Long> arr = new ArrayList<>();
for(long i : a){
arr.add(i);
}
Collections.sort(arr);
for(int i = 0; i < arr.size(); i++){
a[i] = arr.get(i);
}
return a;
}
static int[] sort(int a[]){
ArrayList<Integer> arr = new ArrayList<>();
for(int i : a){
arr.add(i);
}
Collections.sort(arr);
// Collections.reverse(arr);
for(int i = 0; i < arr.size(); i++){
a[i] = arr.get(i);
}
return a;
}
/*
*/
/*
1. Check overflow in pow function or in general
2. Check indices of read array function
3. Think of an easier solution because the problems you solve are always easy
4. Check iterator of loop
5. If still doesn't work, then jump from the 729th floor 'coz "beta tumse na ho paayega"
Move to top!!
*/
static class Foster {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] intArray(int n) { // Check indices
int arr[] = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
long[] longArray(int n) { // Check indices
long arr[] = new long[n];
for(int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
int[] getBits(int n) { //in Reverse Order
int a[] = new int[31];
for(int i = 0; i < 31; i++) {
if(((1<<i) & n) != 0)
a[i] = 1;
}
return a;
}
static long pow(long... a) {
long mod = Long.MAX_VALUE;
if(a.length == 3) mod = a[2];
long res = 1;
while(a[1] > 0) {
if((a[1] & 1) == 1)
res = (res * a[0]) % mod;
a[1] /= 2;
a[0] = (a[0] * a[0]) % mod;
}
return res;
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();
int a[]=new int[n];
for (int i = 0; i <n ; i++) {
a[i]=sc.nextInt();
}
HashMap<Integer,ArrayList<Node>> h=new HashMap<>();
for (int i = 0; i <n ; i++) {
int sum=0;
for (int j = i; j <n ; j++) {
sum+=a[j];
if(h.containsKey(sum)){
h.get(sum).add(new Node(i,j));
}
else{
ArrayList<Node> temp=new ArrayList<>();
temp.add(new Node(i,j));
h.put(sum,temp);
}
}
}
long ans=0;
ArrayList<Integer> ansList=new ArrayList<>();
for(int x:h.keySet()){
Collections.sort(h.get(x), new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return Integer.compare(o1.r,o2.r);
}
});
ArrayList<Node> l=h.get(x);
//out.println(l);
ArrayList<Integer> temp=new ArrayList<>();
int lasty=Integer.MIN_VALUE;
for (int i = 0; i <l.size() ; i++) {
if(l.get(i).l>lasty){
lasty=l.get(i).r;
temp.add(l.get(i).l);
temp.add(l.get(i).r);
}
}
if(ans<temp.size()){
ansList=temp;
ans=ansList.size();
}
}
out.println(ans/2);
for (int i = 0; i <ansList.size() ; i++) {
out.print((ansList.get(i)+1)+" ");
i++;
out.println((ansList.get(i)+1)+" ");
}
out.close();
}
static class Node{
int l,r;
public Node(int a,int b){
l=a;
r=b;
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
@SuppressWarnings("unused")
public class C{
static long inf = (long)1e15;
public static void main(String[] args) throws IOException {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int tt = fs.nextInt();
outer:
while(tt-->0) {
int n = fs.nextInt();
int[] a = fs.readArray(n);
ArrayList<Integer>[] l = new ArrayList[n];
for(int i=0;i<n;i++) l[i] = new ArrayList<Integer>();
l[0].add(1);
for(int i=1;i<n;i++) {
if(a[i]==1) {
for(int j=0;j<l[i-1].size();j++) l[i].add(l[i-1].get(j));
l[i].add(1);
}
else {
int ind = -1;
for(int j=l[i-1].size()-1;j>=0;j--) {
if(l[i-1].get(j)+1==a[i]) {
ind = j; break;
}
}
for(int j=0;j<ind;j++) l[i].add(l[i-1].get(j));
l[i].add(a[i]);
}
}
for(int i=0;i<n;i++) {
out.print(l[i].get(0));
for(int j=1;j<l[i].size();j++) out.print("."+l[i].get(j));
out.println();
}
}
out.close();
}
static final Random random=new Random();
static <T> void shuffle(T[] arr) {
int n = arr.length;
for(int i=0;i<n;i++ ) {
int k = random.nextInt(n);
T temp = arr[k]; arr[k] = arr[i]; arr[i] = temp;
}
}
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void reverse(int[] arr, int l, int r) {
for(int i=l;i<l+(r-l)/2;i++){
int temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp;
}
}
static void reverse(long[] arr, int l, int r) {
for(int i=l;i<l+(r-l)/2;i++){
long temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp;
}
}
static <T> void reverse(T[] arr, int l, int r) {
for(int i=l;i<l+(r-l)/2;i++) {
T temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp;
}
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next(){
while(!st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
} catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] readArray(int n){
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char nextChar() {
return next().toCharArray()[0];
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
new A().run();
}
private void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
Arrays.sort(a);
int i = 0;
while (i < n && a[i] == a[0])
i++;
if (i < n)
System.out.println(a[i]);
else
System.out.println("NO");
sc.close();
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.util.*;
public class A{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
TreeSet<Integer> v = new TreeSet<Integer>();
for(int i=0;i<n;i++) v.add(sc.nextInt());
Iterator<Integer> it = v.iterator();
it.next();
it.remove();
System.out.println(v.isEmpty() ? "NO" : v.iterator().next());
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class AMain {
static int n;
static int[] best;
static int[][] dist;
static int[] home;
static LinkedList<Integer> ret;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
State curr = new State(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
n = Integer.parseInt(br.readLine());
State[] list = new State[n];
for(int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
list[i] = new State(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
}
dist = new int[n][n];
home = new int[n];
for(int i = 0; i < n; i++) {
home[i] = dist(curr, list[i]);
}
for(int i = 0; i < n; i++) {
dist[i][i] = 2 * home[i];
for(int j = i+1; j < n; j++) {
dist[i][j] = dist(list[i], list[j]) + home[i] + home[j];
}
}
best = new int[1 << (n)];
Arrays.fill(best, -1);
best[0] = 0;
System.out.println(solve(-1 + (1<<n)));
ret = new LinkedList<Integer>();
resolve(-1 + (1<<n));
for(int x: ret)
System.out.print(x + " ");
}
public static int dist(State a, State b) {
int x = a.x-b.x;
int y = a.y-b.y;
return x*x+y*y;
}
public static void resolve(int curr) {
ret.addLast(0);
for(int i = 0; i < n; i++) {
if((curr & (1<<i)) == 0)
continue;
for(int j = i+1; j < n; j++) {
if((curr & (1 << j)) == 0) {
continue;
}
if(dist[i][j] + solve(curr ^ (1<<i) ^ (1 << j)) == best[curr]) {
ret.addLast(i+1);
ret.addLast(j+1);
resolve(curr - (1<<i) - (1<<j));
return;
}
}
if(best[curr] == dist[i][i] + solve(curr ^ (1<<i))) {
ret.addLast(i+1);
resolve(curr - (1<<i));
return;
}
}
}
public static int solve(int curr) {
if(best[curr] != -1)
return best[curr];
int ret = Integer.MAX_VALUE;
for(int i = 0; i < n; i++) {
if((curr & (1<<i)) == 0)
continue;
for(int j = i+1; j < n; j++) {
if((curr & (1 << j)) == 0) {
continue;
}
ret = Math.min(ret, dist[i][j] + solve(curr ^ (1<<i) ^ (1 << j)));
}
ret = Math.min(ret, dist[i][i] + solve(curr ^ (1<<i)));
break;
}
best[curr] = ret;
return ret;
}
static class State {
public int x,y;
public State(int a, int b) {
x=a;
y=b;
}
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class E {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
PrintWriter out = new PrintWriter(System.out, false);
int t = scanner.nextInt();
while(t-->0) {
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] cols = new int[m][n];
for(int i = 0; i < n; i++) {
for(int j =0; j < m; j++) {
cols[j][i] = scanner.nextInt();
}
}
int maxMask = 1 << n;
int[] dp = new int[maxMask];
Arrays.fill(dp, -1);
dp[0] = 0;
for(int i = 0; i < m; i++) {
for(int mask = maxMask-1; mask>=0; mask--) {
int[] arr = cols[i].clone();
for(int j = 0; j < n; j++) {
for(int smask = mask; smask >= 0; smask = (smask-1)&mask) {
if (dp[smask] == -1) continue;
int add = 0;
for(int k = 0; k < n; k++) {
if (((mask^smask)&(1 << k)) > 0) add += arr[k];
}
dp[mask] = Math.max(dp[mask], dp[smask] + add);
if (smask == 0) break;
}
arr = shift(arr);
}
}
}
out.println(dp[maxMask-1]);
}
out.flush();
}
static int[] shift (int[] a) {
int[] b = new int[a.length];
b[0] = a[a.length-1];
for(int i = 0; i < a.length-1; i++) {
b[i+1] = a[i];
}
return b;
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class SolutionC{
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(new File("input.txt"));
PrintWriter output = new PrintWriter("output.txt");
int N = sc.nextInt();
int M = sc.nextInt();
int K = sc.nextInt();
int[] x = new int[K];
int[] y = new int[K];
for(int i = 0 ; i < K ; i++){
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
int max = -1, max_x = -1, max_y = -1;
for(int i = 1 ; i <= N ; i++){
for(int j = 1 ; j <= M ; j++){
int min = Integer.MAX_VALUE;
for(int k = 0 ; k < K ; k++){
min = Math.min(min, Math.abs(x[k] - i) + Math.abs(y[k] - j));
}
if(min > max){
max = min;
max_x = i;
max_y = j;
}
}
}
output.println(max_x + " " + max_y);
output.flush();
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A0023 {
public static void main(String args[]) throws Exception {
new A0023();
}
A0023() throws Exception {
PandaScanner sc = null;
PrintWriter out = null;
try {
sc = new PandaScanner(System.in);
out = new PrintWriter(System.out);
} catch (Exception ignored) {
}
String s = sc.next();
int i = s.length() - 1;
Test: for (; i > 0; i--) {
HashSet<String> set = new HashSet<String>();
for (int j = 0; j + i <= s.length(); j++) {
String ss = s.substring(j, j + i);
if (set.contains(ss)) {
break Test;
}
set.add(ss);
}
}
out.println(i);
out.close();
System.exit(0);
}
//The PandaScanner class, for Panda fast scanning!
public class PandaScanner {
BufferedReader br;
StringTokenizer st;
InputStream in;
PandaScanner(InputStream in) throws Exception {
br = new BufferedReader(new InputStreamReader(this.in = in));
}
public String next() throws Exception {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine().trim());
return next();
}
return st.nextToken();
}
public boolean hasNext() throws Exception {
return (st != null && st.hasMoreTokens()) || in.available() > 0;
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author MaxHeap
*/
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) {
int n = in.nextInt();
int d = in.nextInt();
Set<Integer> pts = new HashSet<>();
int[] x = in.nextIntArray(n);
for (int i = 0; i < n; i++) {
pts.add(x[i] - d);
pts.add(x[i] + d);
}
Set<Integer> ans = new HashSet<>();
for (int pt : pts) {
int min = (int) (1e9 + 10);
for (int i = 0; i < n; i++) {
min = Math.min(Math.abs(x[i] - pt), min);
}
if (min >= d) {
ans.add(pt);
}
}
out.println(ans.size());
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1 << 13];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (this.numChars == -1) {
throw new UnknownError();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException ex) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return -1;
}
}
return this.buf[this.curChar++];
}
}
public int nextInt() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
}
byte sgn = 1;
if (c == 45) {
sgn = -1;
c = this.read();
}
int res = 0;
while (c >= 48 && c <= 57) {
res *= 10;
res += c - 48;
c = this.read();
if (isSpaceChar(c)) {
return res * sgn;
}
}
throw new InputMismatchException();
}
public static boolean isSpaceChar(int c) {
return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collections;
public class Problem1 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
long n=Long.parseLong(br.readLine());
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.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class theyareeverywhere {
public static void main(String[] args) throws Exception {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
PrintWriter w = new PrintWriter(System.out);
//SWEEP LINE BABYY
int n = Integer.parseInt(r.readLine());
char[] pokemans = r.readLine().toCharArray();
int[] counts = new int[52];
boolean[] exists = new boolean[52];
for (int i = 0; i < pokemans.length; i++) {
exists[index(pokemans[i])] = true;
}
int left = 0, right = 0;
counts[index(pokemans[0])] = 1;
int answer = 1000000000;
while (left < n && right < n) {
if (!valid(counts, exists)) {
//move right
right++;
if (right < n)
counts[index(pokemans[right])]++;
} else {
answer = Math.min(answer, right - left + 1);
left++;
if (left - 1 >= 0)
counts[index(pokemans[left - 1])]--;
}
}
w.println(answer);
w.flush();
}
public static boolean valid(int[] counts, boolean[] exists) {
for (int i = 0; i < counts.length; i++) {
if (exists[i] && counts[i] == 0) return false;
}
return true;
}
public static int index(char c) {
if (c >= 'a' && c <= 'z') {
return c - 'a';
} else {
return c - 'A' + 26;
}
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
/*
* UMANG PANCHAL
* DAIICT
*/
import java.util.*;
import java.io.*;
import java.math.*;
import java.util.Comparator;
public class Main
{
private static final Comparator<? super Integer> Comparator = null;
static LinkedList<Integer> adj[];
static ArrayList<Integer> adj1[];
static int[] color,visited1;
static boolean b[],visited[],possible;
static int level[];
static Map<Integer,HashSet<Integer>> s;
static int totalnodes,colored;
static int count[];
static long sum[];
static int nodes;
static long ans=0;
static long[] as=new long[10001];
static long c1=0,c2=0;
static int[] a,d,k;
static int max=100000000;
static long MOD = 1000000007,sm=0,m=Long.MIN_VALUE;
static boolean[] prime=new boolean[1000005];
static int[] levl;
static int[] eat;
static int price[];
static int res[],par[],co[];
static int result=0;
static int[] root,size,du,dv;
static long p=Long.MAX_VALUE;
static int start,end,r=0;
static boolean[] vis1,vis2;
static int to;
static HashMap<Pair,Integer> hs;
static boolean ns;
static Node head;
static String st,t;
static long n;
// --------------------My Code Starts Here----------------------
public static void main(String[] args) throws IOException
{
in=new InputReader(System.in);
w=new PrintWriter(System.out);
int n=ni();
HashMap<String,Integer> hm=new HashMap<String,Integer>();
for(int i=0;i<n;i++)
{
String s=ns();
if(hm.containsKey(s))
hm.put(s,hm.get(s)+1);
else
hm.put(s,1);
}
int ans=0;
for(int i=0;i<n;i++)
{
String s=ns();
if(hm.containsKey(s))
{
if(hm.get(s)==1)
hm.remove(s);
else
hm.put(s,hm.get(s)-1);
}
else
{
ans++;
/* if(s.length()==1)
{
if(s.equals("M"))
{
if(hm.containsKey("S"))
{
if(hm.get("S")==1)
hm.remove("S");
else
hm.put(s,hm.get("S")-1);
}
else if(hm.containsKey("L"))
{
if(hm.get("L")==1)
hm.remove("L");
else
hm.put(s,hm.get("L")-1);
}
}
else if()
}*/
}
}
w.print(ans);
w.close();
}
// --------------------My Code Ends Here------------------------
public static void dfs(int n,boolean[] vis,int cl,int[] c)
{
vis[n]=true;
if(c[n]!=cl)
ns=false;
for(int i:adj[n])
{
if(!vis[i])
{
dfs(i,vis,cl,c);
}
}
}
static long pow(long a, long b, long c) {
if (b == 0)
return 1;
long p = pow(a, b / 2, c);
p = (p * p) % c;
return (b % 2 == 0) ? p : (a * p) % c;
}
public static long kadane(long[] a,int n)
{
long max_here=0,max_so_far=-Long.MAX_VALUE;
for(int i=0;i<n;i++)
{
if(max_here<0)
max_here=0;
max_here+=a[i];
if(max_here>max_so_far)
max_so_far=max_here;
}
return max_so_far;
}
public static class SegmentTreeRMQ
{
int st[]; //array to store segment tree
// A utility function to get minimum of two numbers
int minVal(int x, int y) {
return (x < y) ? y : x;
}
// A utility function to get the middle index from corner
// indexes.
int getMid(int s, int e) {
return s + (e - s) / 2;
}
/* A recursive function to get the minimum value in a given
range of array indexes. The following are parameters for
this function.
st --> Pointer to segment tree
index --> Index of current node in the segment tree. Initially
0 is passed as root is always at index 0
ss & se --> Starting and ending indexes of the segment
represented by current node, i.e., st[index]
qs & qe --> Starting and ending indexes of query range */
int RMQUtil(int ss, int se, int qs, int qe, int index)
{
// If segment of this node is a part of given range, then
// return the min of the segment
if (qs <= ss && qe >= se)
return st[index];
// If segment of this node is outside the given range
if (se < qs || ss > qe)
return Integer.MIN_VALUE;
// If a part of this segment overlaps with the given range
int mid = getMid(ss, se);
return minVal(RMQUtil(ss, mid, qs, qe, 2 * index + 1),
RMQUtil(mid + 1, se, qs, qe, 2 * index + 2));
}
// Return minimum of elements in range from index qs (quey
// start) to qe (query end). It mainly uses RMQUtil()
int RMQ(int n, int qs, int qe)
{
// Check for erroneous input values
if (qs < 0 || qe > n-1 || qs > qe) {
System.out.println("Invalid Input");
return 1;
}
return RMQUtil(0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree for
// array[ss..se]. si is index of current node in segment tree st
int constructSTUtil(int arr[], int ss, int se, int si)
{
// If there is one element in array, store it in current
// node of segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then recur for left and
// right subtrees and store the minimum of two values in this node
int mid = getMid(ss, se);
st[si] = minVal(constructSTUtil(arr, ss, mid, si * 2 + 1),
constructSTUtil(arr, mid + 1, se, si * 2 + 2));
return st[si];
}
/* Function to construct segment tree from given array. This function
allocates memory for segment tree and calls constructSTUtil() to
fill the allocated memory */
void constructST(int arr[], int n)
{
// Allocate memory for segment tree
//Height of segment tree
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
//Maximum size of segment tree
int max_size = 2 * (int) Math.pow(2, x) - 1;
st = new int[max_size]; // allocate memory
// Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, 0);
}
// Driver program to test above functions
}
public static int fact(int n)
{
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
boolean ans=true;
while (n%2==0)
{
if(hm.containsKey(2))
{ hm.put(2,hm.get(2)+1);
ans=false;
}
else
hm.put(2,1);
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
if(hm.containsKey(i))
{hm.put(i,hm.get(i)+1);
ans=false;
}
else
hm.put(i,1);
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
if(hm.containsKey(n))
{hm.put(n,hm.get(n)+1);
ans=false;
}
else
hm.put(n,1);
if(ans)
return hm.size();
else
return -1;
}
public static int binary_search(long[] a,long k,int l,int r)
{
while(l<=r)
{
int mid=(l+r)/2;
if(a[mid]>=k)
{
r=mid-1;
}
else
l=mid+1;
}
return l;
}
static class Pair implements Comparable<Pair>
{
Long x;
Long y;
Pair(long x,long y)
{
this.x=x;
this.y=y;
}
public int compareTo(Pair p)
{
return Long.compare(this.y,p.y);
}
}
public static void removeDuplicates()
{
Node cur=head;
while(cur!=null)
{
// w.println(1);
int k=cur.data;
Node p=cur.next;
Node pre=cur;
while(p!=null)
{
// w.println(2);
if(p.data==k)
{
pre.next=p.next;
p=pre.next;
}
else
{
p=p.next;
pre=pre.next;
}
}
cur=cur.next;
}
}
public static void insert_front(int x)
{
Node f=new Node(x);
f.next=head;
head=f;
}
public static void insert_mid(Node x,int d)
{
if(x==null)
{
w.println("Nothing can be shown");
return;
}
Node nex=x.next;
Node ne=new Node(d);
x.next=ne;
ne.next=nex;
}
public static void insert_end(int x)
{
Node f=new Node(x);
Node temp=head;
while(temp.next!=null)
temp=temp.next;
temp.next=f;
}
public static class Node
{
int data;
Node next;
Node(int d)
{
this.data=d;
this.next=null;
}
}
/*
* PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>()
{
public int compare(Integer o1, Integer o2)
{
return Intege
r.compare(o2,o1);
}
});
*
*
*/
public static void shuffle(long[] a,int n)
{
Random r=new Random();
for(int i=n-1;i>0;i--)
{
int j=r.nextInt(i);
long t=a[j];
a[j]=a[i];
a[i]=t;
}
}
public static void bfs1(int u)
{
Queue<Integer> q=new LinkedList();
q.add(u);
visited[u]=true;
while(!q.isEmpty())
{
//w.print(1);
int p=q.poll();
for(int i=0;i<adj[p].size();i++)
{
if(!visited[adj[p].get(i)])
{
q.add(adj[p].get(i));
visited[adj[p].get(i)]=true;
}
levl[adj[p].get(i)]=levl[p]+1;
}
}
}
public static void bfs2(int u)
{
Queue<Integer> q=new LinkedList();
q.add(u);
vis2[u]=true;
while(!q.isEmpty())
{
int p=q.poll();
for(int i=0;i<adj[p].size();i++)
{
if(!vis2[adj[p].get(i)])
{
dv[adj[p].get(i)]=dv[p]+1;
q.add(adj[p].get(i));
vis2[adj[p].get(i)]=true;
}
}
}
}
public static void buildgraph(int n)
{
adj=new LinkedList[n+1];
visited=new boolean[n];
level=new int[n];
par=new int[n];
for(int i=0;i<=n;i++)
{
adj[i]=new LinkedList<Integer>();
}
}
/*public static long kruskal(Pair[] p)
{
long ans=0;
int w=0,x=0,y=0;
for(int i=0;i<p.length;i++)
{
w=p[i].w;
x=p[i].x;
y=p[i].y;
if(root(x)!=root(y))
{
ans+=w;
union(x,y);
}
}
return ans;
}*/
static class npair implements Comparable<npair>
{
int a,b;
npair(int a,int b)
{
this.a=a;
this.b=b;
//this.index=index;
}
public int compareTo(npair o) {
// TODO Auto-generated method stub
return Integer.compare(this.a,o.a);
}
}
public static int root(int i)
{
while(root[i]!=i)
{
root[i]=root[root[i]];
i=root[i];
}
return i;
}
public static void init(int n)
{
root=new int[n+1];
for(int i=1;i<=n;i++)
root[i]=i;
}
public static void union(int a,int b)
{
int root_a=root(a);
int root_b=root(b);
root[root_a]=root_b;
// size[root_b]+=size[root_a];
}
public static boolean isPrime(long n)
{
// Corner cases
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n%2 == 0 || n%3 == 0)
return false;
for (long i=5; i*i<=n; i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;
return true;
}
public static String ns()
{
return in.nextLine();
}
public static int ni()
{
return in.nextInt();
}
public static long nl()
{
return in.nextLong();
}
public static int[] na(int n)
{
int[] a=new int[n];
for(int i=0;i<n;i++)
a[i]=ni();
return a;
}
public static long[] nla(int n)
{
long[] a=new long[n];
for(int i=0;i<n;i++)
a[i]=nl();
return a;
}
public static void sieve()
{
int n=prime.length;
for(int i=0;i<n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
if(prime[p] == true)
{
for(int i = p*2; i <n; i += p)
prime[i] = false;
}
}
}
public static String rev(String s)
{
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long lcm(long a, long b)
{
return a * (b / gcd(a, b));
}
static long gcd(long a, long b)
{
while (b > 0)
{
long temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
static InputReader in;
static PrintWriter w;
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
}
while (!isSpaceChar(c));
return res * sgn;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
}
while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
}
while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class C
{
static long time = System.currentTimeMillis();
public static void main(String[] args) throws IOException
{
//FastReader infile = new FastReader("test.txt");
FastReader infile = new FastReader(System.in);
int N = infile.nextInt();
int R = infile.nextInt();
double[] xPos = new double[N];
for(int x = 0; x < N; x++)
xPos[x] = infile.nextDouble();
double[] yPos = new double[N];
Arrays.fill(yPos, R);
for(int x = 1; x < N; x++)
{
for(int y = 0; y < x; y++)
if(Math.abs(xPos[x]-xPos[y])<=2*R)
{
yPos[x] = Math.max(yPos[x], yPos[y]+Math.sqrt((2*R)*(2*R)-Math.abs(xPos[x]-xPos[y])*Math.abs(xPos[x]-xPos[y])));
}
}
System.out.print(yPos[0]);
for(int x = 1; x < N; x++)
System.out.print(" "+yPos[x]);
//System.out.println(System.currentTimeMillis()-time);
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(String file) throws IOException
{
br = new BufferedReader(new FileReader(file));
}
public FastReader(InputStream i) throws IOException
{
br = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (Exception e)
{
return false;
}
}
return true;
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Solve{
public static void main(String[] args) throws Exception{
Scanner sc=new Scanner(System.in);
PrintWriter out =new PrintWriter(System.out);
int size=(int)1e7+1;
int[] pr=new int[size];
for(int i=0;i<size;i++){
pr[i]=i;
}
for(int i=2;i*i<size;i++){
if(pr[i]==i){int val=i*i;
for(int j=val;j<=size;j+=val){
pr[j]=j/val;
}
}
}
int t=sc.nextInt();
int[] dp=new int[size];
Arrays.fill(dp,-1);
while(t-->0){
int n=sc.nextInt();
int k=sc.nextInt();
int[] ar=new int[n];
for(int i=0;i<n;i++){
int a=sc.nextInt();
ar[i]=pr[a];
}
int[] ans=new int[k+1];
int[] ind=new int[k+1];
for(int i=0;i<n;i++){
for(int h=k;h>=0;h--){
if(dp[ar[i]]>=ind[h]){
ans[h]++;
ind[h]=i;
}
if(h>0 && (ans[h-1]<ans[h] ||(ans[h-1]==ans[h] && ind[h-1]>ind[h])))
{
ans[h]=ans[h-1];
ind[h]=ind[h-1];
}
}
dp[ar[i]]=i;
}
out.println(ans[k]+1);
for(int i=0;i<n;i++)dp[ar[i]]=-1;
}
out.close();
}
}
|
cubic
|
1497E2
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class Success {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int a = scan.nextInt();
int b=scan.nextInt();
int[] t=new int[n];
for(int i=0;i<n;i++)
{
t[i]=scan.nextInt();
}
Arrays.sort(t);
System.out.println(t[b]-t[b-1]);
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
public class Main {
public static final DecimalFormat DF_3 = new DecimalFormat("0.000");
private static final long MOD = 1000000007;
static int[] readArray(int size, InputReader in, boolean subOne) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = in.nextInt() + (subOne ? -1 : 0);
}
return a;
}
static long[] readLongArray(int size, InputReader in) {
long[] a = new long[size];
for (int i = 0; i < size; i++) {
a[i] = in.nextLong();
}
return a;
}
static void sortArray(int[] a) {
Random random = new Random();
for (int i = 0; i < a.length; i++) {
int randomPos = random.nextInt(a.length);
int t = a[i];
a[i] = a[randomPos];
a[randomPos] = t;
}
Arrays.sort(a);
}
private static long[] allInvs(int n, long mod) {
long[] inv = new long[n + 1];
inv[1] = 1;
for (int i = 2; i <= n; ++i) {
inv[i] = subMod(mod, (mod / i) * inv[(int) (mod % i)] % mod, mod);
}
return inv;
}
private static long subMod(long x, long y, long mod) {
long res = x - y;
if (res < 0) {
return res + mod;
}
return res;
}
private static long fastPow(long x, long y, long mod) {
if (x == 1) {
return 1;
}
if (y == 0) {
return 1;
}
long p = fastPow(x, y / 2, mod) % mod;
p = p * p % mod;
if (y % 2 == 1) {
p = p * x % mod;
}
return p;
}
public static void main(String[] args) throws FileNotFoundException {
// InputReader in = new InputReader(new FileInputStream("input.txt"));
// PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("milkvisits.out")));
//
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
// long start = System.currentTimeMillis();
int n = in.nextInt();
long mod = in.nextLong();
long[] invs = allInvs(n + 3, mod);
long[] facts = new long[n + 2];
facts[0] = 1;
long[] invFacts = new long[n + 2];
invFacts[0] = 1;
for (int i = 1; i < n + 2; i++) {
facts[i] = (facts[i - 1] * i) % mod;
invFacts[i] = (invFacts[i - 1] * invs[i]) % mod;
}
long[] pow2 = new long[n+3];
pow2[0] = 1;
for (int i = 1; i < n+3; i++) {
pow2[i] = pow2[i-1] * 2 % mod;
}
long[][] dp = new long[n + 2][n + 2];
for (int i = 2; i <= n + 1; i++) {
dp[i][1] = invFacts[i - 1] * pow2[i - 2] % mod;
for (int k = 2; k <= n; k++) {
for (int j = i - 2; j >= 1; j--) {
dp[i][k] = (dp[i][k] + dp[j][k - 1] * pow2[ i - j - 2] % mod * invFacts[i - j - 1] % mod) % mod;
}
}
}
long ans = 0;
for (int k = 1; k <= n; k++) {
ans = (ans + dp[n + 1][k] * facts[n - k + 1] % mod) % mod;
}
out.println(ans);
out.close();
}
private static void outputArray(List<Long> ans, PrintWriter out, boolean addOne) {
StringBuilder str = new StringBuilder();
for (int j = 0; j < ans.size(); j++) {
long i = ans.get(j);
long an = i + (addOne ? 1 : 0);
str.append(an);
if (j < ans.size() - 1) {
str.append(' ');
}
}
out.println(str);
// out.flush();
}
private 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 String nextString() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char nextChar() {
return next().charAt(0);
}
public String nextWord() {
return next();
}
private List<Integer>[] readTree(int n) {
return readGraph(n, n - 1);
}
private List<Integer>[] readGraph(int n, int m) {
List<Integer>[] result = new ArrayList[n];
for (int i = 0; i < n; i++) {
result[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = nextInt() - 1;
int v = nextInt() - 1;
result[u].add(v);
result[v].add(u);
}
return result;
}
}
}
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
//package contese_476;
import java.util.*;
public class q1
{
int m=(int)1e9+7;
public class Node
{
int a;
int b;
public void Node(int a,int b)
{
this.a=a;
this.b=b;
}
}
public int mul(int a ,int b)
{
a=a%m;
b=b%m;
return((a*b)%m);
}
public int pow(int a,int b)
{
int x=1;
while(b>0)
{
if(b%2!=0)
x=mul(x,a);
a=mul(a,a);
b=b/2;
}
return x;
}
public 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 sc=new Scanner(System.in);
int n=sc.nextInt();
HashMap<Integer,Integer> h=new HashMap();
//HashMap<Integer,Integer> h1=new HashMap();
int[] a=new int[n];
int x=sc.nextInt();
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
if(h.get(a[i])==null)
{
h.put(a[i], 1);
//h1.put(a[i],i);
}
else
{
System.out.print(0);
System.exit(0);
}
}
for(int i=0;i<n;i++)
{
int num=a[i]&x;
if(num==a[i])
continue;
if(h.get(num)==null)
continue;
else
{
System.out.print(1);
System.exit(0);
}
}
for(int i=0;i<n;i++)
{
int num=a[i]&x;
if(num==a[i])
continue;
if(h.get(num)==null)
h.put(num, 1);
else
{
System.out.print(2);
System.exit(0);
}
}
System.out.print(-1);
}
}
|
linear
|
1013_B. And
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class LCMChallenge {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
if (n < 3) {
System.out.println(n);
} else if (n % 2 == 1) {
System.out.println((long) n * (n - 1) * (n - 2));
} else {
if (n % 3 != 0) {
System.out.println((long) n * (n - 1) * (n - 3));
} else {
System.out.println((long) (n - 1) * (n - 2) * (n - 3));
}
}
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
// Petya and Spiders
// 2012/08/15
public class P111C{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-9;
int h, w;
void run(){
h=sc.nextInt();
w=sc.nextInt();
solve();
}
void solve(){
n=w*h;
g=new long[n];
int[] dx={0, 0, -1, 1};
int[] dy={-1, 1, 0, 0};
for(int y=0; y<h; y++){
for(int x=0; x<w; x++){
for(int k=0; k<4; k++){
int x2=x+dx[k];
int y2=y+dy[k];
if(x2>=0&&x2<w&&y2>=0&&y2<h){
g[y*w+x]|=1L<<(y2*w+x2);
}
}
}
}
mds=(1L<<n)-1;
mds(0, 0, 0);
println((n-Long.bitCount(mds))+"");
}
int n;
long[] g;
long mds;
void mds(long choosed, long removed, long covered){
if(covered==((1L<<n)-1)){
mds=choosed;
return;
}
if(Long.bitCount(choosed)>=Long.bitCount(mds)-1)
return;
long s=covered;
for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){
int i=Long.numberOfTrailingZeros(remained);
s|=(1L<<i)|g[i];
}
if(s!=((1L<<n)-1))
return;
int k=-1;
for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){
int i=Long.numberOfTrailingZeros(remained);
if((covered>>>i&1)==1){
if(Long.bitCount(g[i]&~covered)<=1){
mds(choosed, removed|(1L<<i), covered);
return;
}
}else{
if(Long.bitCount(g[i]&~removed)==0){
mds(choosed|(1L<<i), removed|(1L<<i), covered|(1L<<i)|g[i]);
return;
}else if(Long.bitCount(g[i]&~removed)==1
&&(g[i]&(~removed|~covered))==(g[i]&~removed)){
int j=Long.numberOfTrailingZeros(g[i]&~removed);
mds(choosed|(1L<<j), removed|(1L<<i)|(1L<<j), covered
|(1L<<j)|g[j]);
return;
}
}
if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered))
k=i;
}
if(k==-1)
return;
mds(choosed|(1L<<k), removed|(1L<<k), covered|(1L<<k)|g[k]);
mds(choosed, removed|(1L<<k), covered);
}
void println(String s){
System.out.println(s);
}
void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args){
Locale.setDefault(Locale.US);
new P111C().run();
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
//package educational.round23;
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 C3 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
long n = nl();
long S = nl();
long ret = Math.max(0, n-S+1);
for(long i = S;i <= S + 300 && i <= n;i++){
long b = i;
for(long x = i;x > 0;x /= 10){
b -= x % 10;
}
if(b < S)ret--;
}
out.println(ret);
}
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 C3().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
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class a {
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
OutputStream out=new BufferedOutputStream(System.out);
String s[]=br.readLine().trim().split("\\ ");
BigInteger a1=new BigInteger(s[0]);
BigInteger a=new BigInteger(s[0]);
String q=a.toString();
String q1=q.substring(q.length()-1, q.length());
a=a.subtract(new BigInteger(q1));
//System.out.println(a.toString());
BigInteger c=new BigInteger("1");
BigInteger b=new BigInteger(s[1]);
int z=check(a,a.toString(),b);
if(z==1)
{
out.write("0".getBytes());
out.flush();
//System.out.println("jwefcyuwe");
return;
}
while(a.compareTo(c)>0)
{
BigInteger d=a;
if(d.subtract(c).compareTo(new BigInteger("9"))==-1)
{
break;
}
else
{
BigInteger mid=a;
mid=mid.add(c);
mid=mid.divide(new BigInteger("2"));
//System.out.println(mid.toString());
if(check(mid,mid.toString(),b)==1)
{
c=mid;
c=c.add(new BigInteger("1"));
}
else
{
a=mid;
//System.out.println(a.toString());
}
}
}
q=a.toString();
q1=q.substring(q.length()-1, q.length());
a=a.subtract(new BigInteger(q1));
BigInteger ans=a1.subtract(a);
ans=ans.add(new BigInteger("1"));
out.write(ans.toString().getBytes());
//System.out.print("sfvlksfv");
out.flush();
}
static int check(BigInteger a,String s,BigInteger b)
{
int l=s.length();
long z=0;
for(int i=0;i<l;i++)
{
z+=Long.parseLong(s.substring(i,i+1));
}
BigInteger c=a.subtract(new BigInteger(Long.toString(z)));
//System.out.println(c.toString());
return -1*c.compareTo(b);
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main {
static class Task {
int NN = 500005;
int MOD = 1000000007;
int INF = 2000000000;
long INFINITY = 2000000000000000000L;
public void solve(InputReader in, PrintWriter out) {
int t = in.nextInt();
while(t-->0) {
long n =in.nextLong();
long m = in.nextLong();
long x1 = in.nextLong();
long y1 = in.nextLong();
long x2 = in.nextLong();
long y2 = in.nextLong();
long x3 = in.nextLong();
long y3 = in.nextLong();
long x4 = in.nextLong();
long y4 = in.nextLong();
long w = white(1, 1, m, n);
long b = black(1, 1, m, n);
long whited = 0;
if(x3 > x2 || x4 < x1 || y3 > y2 || y4 < y1) {
whited = black(x1, y1, x2, y2);
} else {
whited = black(x1, y1, x2, y2);
long xm1 = Math.max(x1, x3);
long ym1 = Math.max(y1, y3);
long xm2 = Math.min(x2, x4);
long ym2 = Math.min(y2, y4);
whited -= black(xm1, ym1, xm2, ym2);
}
b -= whited;w += whited;
long blacked = white(x3, y3, x4, y4);
w-= blacked;b += blacked;
out.println(w + " " + b);
}
}
long black(long x1, long y1, long x2, long y2) {
long dx = (x2 - x1) + 1;
long dy = (y2 - y1) + 1;
if((x1+y1)%2!=0) {
return ((dy+1)/2)*((dx+1)/2)+(dy/2)*(dx/2);
}
return ((dy+1)/2)*((dx)/2)+(dy/2)*((dx+1)/2);
}
long white(long x1, long y1, long x2, long y2) {
long dx = (x2 - x1) + 1;
long dy = (y2 - y1) + 1;
if((x1+y1)%2==0) {
return ((dy+1)/2)*((dx+1)/2)+(dy/2)*(dx/2);
}
return ((dy+1)/2)*(dx/2)+(dy/2)*((dx+1)/2);
}
}
static void prepareIO(boolean isFileIO) {
//long t1 = System.currentTimeMillis();
Task solver = new Task();
// Standard IO
if(!isFileIO) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solver.solve(in, out);
//out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0);
out.close();
}
// File IO
else {
String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in";
String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out";
InputReader fin = new InputReader(IPfilePath);
PrintWriter fout = null;
try {
fout = new PrintWriter(new File(OPfilePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
solver.solve(fin, fout);
//fout.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0);
fout.close();
}
}
public static void main(String[] args) {
prepareIO(false);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public InputReader(String filePath) {
File file = new File(filePath);
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokenizer = null;
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
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());
}
}
}
|
constant
|
1080_C. Masha and two friends
|
CODEFORCES
|
import java.io.*;
public class n5D
{
public static void main(String[] args)
{
double a = 0, v = 0, l = 0, d = 0, w = 0;
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
a = Double.parseDouble(str[0]);
v = Double.parseDouble(str[1]);
str = br.readLine().split(" ");
l = Double.parseDouble(str[0]);
d = Double.parseDouble(str[1]);
w = Double.parseDouble(str[2]);
}
catch(Exception e)
{
System.out.println(e);
}
double t1, t2, t3, t4, t5, t, D = 0;
if (w > v) w = v;
t2 = d / v - v / a + w * w / 2 / a / v;
if (t2 >= 0)
{
t1 = v / a;
t3 = t1 - w / a;
}
else
{
if (Math.sqrt(2 * d / a) > (w / a))
{
t1 = Math.sqrt((2 * a * d + w * w) / (a * a * 2));
t3 = t1 - w / a;
}
else
{
t1 = Math.sqrt(2 * d / a);
t3 = 0;
}
t2 = 0;
}
t5 = (l - d - v * v / 2 / a + a * (t1 - t3) * (t1 - t3) / 2) / v;
if (t5 >= 0) t4 = v / a - (t1 - t3);
else
{
t5 = 0;
t4 = -t1 + t3 + Math.sqrt((t1 - t3) * (t1 - t3) + 2 * (l - d) / a);
}
t = t1 + t2 + t3 + t4 + t5;
System.out.println(t);
//System.out.println(t1 + " " + t2 + " " + t3 + " " + t4 + " " + t5);
}
}
|
constant
|
5_D. Follow Traffic Rules
|
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 OlyaAndMagicalSquare {
void solve() {
long[] dp = new long[32];
dp[0] = 0;
for (int i = 1; i < 32; i++) {
dp[i] = 4 * dp[i - 1] + 1;
}
int T = in.nextInt();
L:
while (T-- > 0) {
int n = in.nextInt(); long k = in.nextLong();
if (n > 31) {
out.println("YES " + (n - 1));
continue;
}
long tot = 0;
for (int a = n - 1; a >= 0; a--) {
k -= (1L << (n - a)) - 1;
if (k < 0) break;
if (k == 0) {
out.println("YES " + a);
continue L;
}
long limit = (1L << (n + 1 - a)) - 3;
if (k <= tot || dp[a] > 0 && (k - tot + dp[a] - 1) / dp[a] <= limit) {
out.println("YES " + a);
continue L;
}
tot += dp[a] * limit;
}
out.println("NO");
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new OlyaAndMagicalSquare().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());
}
}
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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 {
static int n;
static int m;
static int steps;
static long[][] distJ;
static long[][] distI;
static long[][][] memo;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
m = in.nextInt();
steps = in.nextInt();
memo = new long[n][m][steps];
distJ = new long[n][m - 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m - 1; j++) {
distJ[i][j] = in.nextLong();
}
}
distI = new long[n - 1][m];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m; j++) {
distI[i][j] = in.nextLong();
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (steps % 2 != 0) {
out.print(-1 + " ");
} else {
out.print(2 * lowestCost(i, j, steps / 2) + " ");
}
}
out.println();
}
}
private long lowestCost(int i, int j, int distance) {
if (distance == 0) {
return 0;
}
if (memo[i][j][distance] > 0) {
return memo[i][j][distance];
}
long minDist = Long.MAX_VALUE;
//j + 1 and j -1
if (j < m - 1) {
// move forward on j
minDist = Math.min(minDist, distJ[i][j] + lowestCost(i, j + 1, distance - 1));
}
if (j > 0) {
// move backward on j
minDist = Math.min(minDist, distJ[i][j - 1] + lowestCost(i, j - 1, distance - 1));
}
if (i < n - 1) {
// move forward on i
minDist = Math.min(minDist, distI[i][j] + lowestCost(i + 1, j, distance - 1));
}
if (i > 0) {
// move backward on i
minDist = Math.min(minDist, distI[i - 1][j] + lowestCost(i - 1, j, distance - 1));
}
//memoize
memo[i][j][distance] = minDist;
return minDist;
}
}
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() {
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
/*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x111C
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int R = Integer.parseInt(st.nextToken());
int C = Integer.parseInt(st.nextToken());
if(R > C)
{
int t = R;
R = C;
C = t;
}
//dp[c][m1][m2] = min spoders in first c columns
int[][][] dp = new int[C+1][1 << R][1 << R];
for(int i=0; i <= C; i++)
for(int mask=0; mask < (1<<R); mask++)
Arrays.fill(dp[i][mask], 69);
for(int mask=0; mask < (1<<R); mask++)
dp[0][0][mask] = 0;
for(int c=1; c <= C; c++)
for(int mask1=0; mask1 < (1<<R); mask1++)
for(int mask2=0; mask2 < (1<<R); mask2++)
for(int mask3=0; mask3 < (1<<R); mask3++)
{
boolean works = true;
for(int b=0; b < R; b++)
if((mask2&(1<<b)) == 0)
{
if(b > 0 && (mask2&(1<<(b-1))) > 0);
else if(b+1 < R && (mask2&(1<<(b+1))) > 0);
else if((mask1&(1<<b)) > 0);
else if((mask3&(1<<b)) > 0);
else works = false;
}
if(works)
dp[c][mask2][mask3] = Math.min(dp[c][mask2][mask3], dp[c-1][mask1][mask2]+Integer.bitCount(mask1));
}
int res = 0;
for(int mask=0; mask < (1<<R); mask++)
res = Math.max(res, R*C-(dp[C][mask][0]+Integer.bitCount(mask)));
System.out.println(res);
}
}
|
np
|
112_E. Petya and Spiders
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class C {
void solve(){
int n = readInt();
int q = readInt();
int max = 0;
int[] a = new int[n];
Deque<Integer> deque = new ArrayDeque<>();
for(int i = 0;i<n;i++){
a[i] = readInt();
deque.addLast(a[i]);
max = Math.max(max, a[i]);
}
List<String> ans = new ArrayList<>();
while(deque.peekFirst() != max){
int one = deque.pollFirst();
int two = deque.pollFirst();
ans.add(one + " " + two);
deque.addFirst(one > two ? one : two);
deque.addLast(one > two ? two : one);
if(one == max) break;
}
for(int i = 0;i<n;i++){
a[i] = deque.pollFirst();
}
for(int i = 0;i<q;i++){
long x = readLong();
if(x <= ans.size()){
out.println(ans.get((int)x - 1));
continue;
}
x -= ans.size();
int y =(int) (x%(n - 1) - 1%(n - 1) + (n - 1)) % (n - 1) + 1;
out.println(max + " " + a[y]);
}
}
public static void main(String[] args) {
new C().run();
}
void run(){
init();
solve();
out.close();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init(){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
String readLine(){
try{
return in.readLine();
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
String readString(){
while(!tok.hasMoreTokens()){
String nextLine = readLine();
if(nextLine == null) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt(){
return Integer.parseInt(readString());
}
long readLong(){
return Long.parseLong(readString());
}
double readDouble(){
return Double.parseDouble(readString());
}
}
|
linear
|
1180_C. Valeriy and Deque
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
long d = reader.nextLong();
int[] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = reader.nextInt();
Arrays.sort(a);
int ans = 2;
for(int i = 0; i < n - 1; i++){
if(a[i + 1] - a[i] > 2 * d) {
ans += 2;
}
else if(a[i + 1] - a[i] == 2 * d)
ans++;
}
System.out.println(ans);
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.ArrayDeque;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author MaxHeap
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FireAgain solver = new FireAgain();
solver.solve(1, in, out);
out.close();
}
static class FireAgain {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int INF = 10000000;
int[][] g = new int[n][m];
for (int[] temp : g) Arrays.fill(temp, -1);
ArrayDeque<IntPair> q = new ArrayDeque<>();
for (int i = 0; i < k; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
g[x][y] = 0;
q.add(new IntPair(x, y));
}
while (!q.isEmpty()) {
IntPair cur = q.poll();
int x = cur.getFirst();
int y = cur.getSecond();
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0 || Math.abs(i) + Math.abs(j) != 1) continue;
int xx = x + i;
int yy = y + j;
if (xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
if (g[xx][yy] != -1) continue;
g[xx][yy] = g[x][y] + 1;
q.add(new IntPair(xx, yy));
}
}
}
int ans = 0, x = -1, y = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] >= ans) {
ans = g[i][j];
x = i + 1;
y = j + 1;
}
}
}
out.println(x + " " + y);
}
}
static class IntPair implements Comparable<IntPair> {
int first;
int second;
public IntPair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(IntPair a) {
if (second == a.second) {
return Integer.compare(first, a.first);
}
return Integer.compare(second, a.second);
}
public String toString() {
return "<" + first + ", " + second + ">";
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IntPair a = (IntPair) o;
if (first != a.first) return false;
return second == a.second;
}
public int hashCode() {
int result = first;
result = 31 * result + second;
return result;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
static class FastReader {
BufferedReader reader;
StringTokenizer st;
public FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String line = reader.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public final class PythonIndentation
{
public static void main(String[] args)
{
new PythonIndentation(System.in, System.out);
}
static class Solver implements Runnable
{
static final int MOD = (int) 1e9 + 7;
int n;
char[] arr;
long[][] dp;
BufferedReader in;
PrintWriter out;
void solve() throws IOException
{
n = Integer.parseInt(in.readLine());
arr = new char[n];
dp = new long[n + 1][n + 1];
for (int i = 0; i < n; i++)
arr[i] = in.readLine().charAt(0);
for (int i = 0; i <= n; i++)
Arrays.fill(dp[i], -1);
dp[0][0] = 1;
if (arr[0] == 's')
out.println(find(1, 0));
else
out.println(find(1, 1));
}
long find(int curr, int backIndents)
{
if (backIndents < 0)
return 0;
if (curr == n)
return 1;
if (dp[curr][backIndents] != -1)
return dp[curr][backIndents];
long ans;
if (arr[curr] == 's')
{
if (arr[curr - 1] == 'f')
ans = find(curr + 1, backIndents);
else
ans = CMath.mod(find(curr + 1, backIndents) + find(curr, backIndents - 1), MOD);
}
else
{
ans = find(curr + 1, backIndents + 1);
if (arr[curr - 1] != 'f')
ans = CMath.mod(ans + find(curr, backIndents - 1), MOD);
}
return dp[curr][backIndents] = ans;
}
public Solver(BufferedReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
@Override public void run()
{
try
{
solve();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
static class CMath
{
static long mod(long number, long mod)
{
return number - (number / mod) * mod;
}
}
private PythonIndentation(InputStream inputStream, OutputStream outputStream)
{
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
PrintWriter out = new PrintWriter(outputStream);
Thread thread = new Thread(null, new Solver(in, out), "PythonIndentation", 1 << 29);
try
{
thread.start();
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
out.flush();
out.close();
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
//Educational Codeforces Round 34
import java.io.*;
import java.util.*;
import java.math.*;
public class TaskD {
public static void main (String[] args) throws IOException {
FastScanner fs = new FastScanner(System.in);
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
int n = fs.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = fs.nextInt();
}
HashMap<Integer,Integer> h = new HashMap<Integer,Integer>(n);
BigInteger s = new BigInteger(""+a[0]);
BigInteger x = new BigInteger("0");
h.put(a[0], 1);
for (int i = 1; i < n; i++) {
x = x.add(new BigInteger(""+(((long)i)*((long)a[i]))));
x = x.subtract(s);
s = s.add(new BigInteger(""+a[i]));
Integer q = null;
q = h.get(a[i]-1);
if (q != null) {
x = x.subtract(new BigInteger(""+q));
}
q = h.get(a[i]+1);
if (q != null) {
x = x.add(new BigInteger(""+q));
}
q = h.get(a[i]);
if (q != null) {
h.put(a[i], q + 1);
} else {
h.put(a[i], 1);
}
}
pw.println(x);
pw.close();
}
static class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner(InputStream i) {
reader = new BufferedReader(new InputStreamReader(i));
tokenizer = new StringTokenizer("");
}
String next() throws IOException {
while(!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
import java.util.*;
import java.math.*;
public class Counterexample {
public static void main(String[] args) {
System.out.println(new Counterexample().solve());
}
String solve() {
Scanner sc = new Scanner(System.in);
final long l = sc.nextLong();
final long r = sc.nextLong();
if ((r - l) > 1) {
long a = l;
long b = l + 1;
long c = l + 2;
while (a < (r - 1)) {
while (b < r) {
while (c <= r) {
if (gcd(a,b) == 1
&& gcd(b,c) == 1
&& gcd(a,c) > 1) {
return Long.toString(a)
+ " "
+ Long.toString(b)
+ " "
+ Long.toString(c);
}
c += 1;
}
c = b + 1;
b += 1;
}
b = a + 1;
a += 1;
}
}
return "-1";
}
long gcd(long a, long b) {
while (b != 0) {
long t = b;
b = a % b;
a = t;
}
return a;
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov (egor@egork.net)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int place = in.readInt() - 1;
final int[] points = new int[count];
final int[] time = new int[count];
IOUtils.readIntArrays(in, points, time);
Comparator<Integer> comparator = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (points[o1] != points[o2])
return points[o2] - points[o1];
return time[o1] - time[o2];
}
};
Integer[] order = ArrayUtils.order(count, comparator);
int answer = 0;
for (int i = 0; i < count; i++) {
if (comparator.compare(order[place], order[i]) == 0)
answer++;
}
out.printLine(answer);
}
}
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 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 static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(outputStream);
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class IOUtils {
public static void readIntArrays(InputReader in, int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readInt();
}
}
}
class ArrayUtils {
public static Integer[] generateOrder(int size) {
Integer[] order = new Integer[size];
for (int i = 0; i < size; i++)
order[i] = i;
return order;
}
public static Integer[] order(int size, Comparator<Integer> comparator) {
Integer[] order = generateOrder(size);
Arrays.sort(order, comparator);
return order;
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author lucasr
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyScanner in = new MyScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
BPhoenixAndPuzzle solver = new BPhoenixAndPuzzle();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class BPhoenixAndPuzzle {
public static MyScanner sc;
public static PrintWriter out;
public void solve(int testNumber, MyScanner sc, PrintWriter out) {
BPhoenixAndPuzzle.sc = sc;
BPhoenixAndPuzzle.out = out;
long n = sc.nextLong();
boolean can = true;
if (n % 2 != 0) can = false;
n /= 2;
while (n > 1 && n % 2 == 0) n /= 2;
long sq = Math.round(Math.pow(n, 0.5));
if (sq * sq != n) can = false;
out.println(can ? "YES" : "NO");
}
}
static class MyScanner {
private BufferedReader br;
private StringTokenizer tokenizer;
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.io.Writer;
import java.math.BigInteger;
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public long recurse(long a, long b) {
if (b <= 1) return a;
return Math.max(a, b)/Math.min(a,b) + recurse(Math.max(a, b) - Math.min(a, b)*(Math.max(a,b)/Math.min(a, b)), Math.min(a, b));
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
long a = in.readLong(), b = in.readLong(), i = 0;
// while(true) {
// if (b <= 1){
// i += a;
// out.print(i);
// return;
// }
// i++;
// long aa = Math.max(a, b);
// long bb = Math.min(a, b);
// aa -= bb;
// a = aa;
// b = bb;
// }
// out.print(i);
out.print(recurse(a, b));
}
}
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 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);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void close() {
writer.close();
}
public void print(long i) {
writer.print(i);
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String s = bf.readLine();
out.println(25);
out.flush();
out.close();
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.