src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
/**
* @author: Prasad Chaudhari
* @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/
* @git: https://github.com/Prasad-Chaudhari
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) throws Exception {
FastIO in = new FastIO(args);
int t = in.ni();
while (t-- > 0) {
int n = in.ni();
LinkedList<Integer> l = new LinkedList<>();
ArrayList<LinkedList<Integer>> al = new ArrayList<>();
for (int i = 0; i < n; i++) {
int p = in.ni();
if (p == 1) {
l.addFirst(1);
} else {
while (true) {
if (l.peekFirst() == p - 1) {
l.addFirst(l.removeFirst() + 1);
break;
} else {
l.removeFirst();
}
}
}
al.add(new LinkedList<>(l));
}
for (LinkedList<Integer> ll : al) {
while (ll.size() > 1) {
System.out.print(ll.removeLast() + ".");
}
System.out.println(ll.remove());
}
System.out.println();
}
in.bw.flush();
}
static boolean willbealive(int i, int a[]) {
if (i < 0 || i >= a.length)
return false;
if (a.length == 1)
return false;
if (a[i] == 1)
return false;
if (i == 0)
return a[1] == 1;
else if (i == a.length - 1)
return a[i - 1] == 1;
else
return (a[i - 1] == 1) ^ (a[i + 1] == 1);
}
static class Data implements Comparable<Data> {
int a, b;
public Data(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Data o) {
if (a == o.a) {
return Integer.compare(b, o.b);
}
return Integer.compare(a, o.a);
}
public static void sort(int a[]) {
Data d[] = new Data[a.length];
for (int i = 0; i < a.length; i++) {
d[i] = new Data(a[i], 0);
}
Arrays.sort(d);
for (int i = 0; i < a.length; i++) {
a[i] = d[i].a;
}
}
}
static class FastIO {
private final BufferedReader br;
private final BufferedWriter bw;
private String s[];
private int index;
public FastIO(String[] args) throws IOException {
if (args.length > 1) {
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(args[0]))));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(args[1]))));
} else {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8"));
}
s = br.readLine().split(" ");
index = 0;
}
public int ni() throws IOException {
return Integer.parseInt(nextToken());
}
public double nd() throws IOException {
return Double.parseDouble(nextToken());
}
public long nl() throws IOException {
return Long.parseLong(nextToken());
}
public String next() throws IOException {
return nextToken();
}
public String nli() throws IOException {
try {
return br.readLine();
} catch (IOException ex) {
}
return null;
}
public int[] gia(int n) throws IOException {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public int[] gia(int n, int start, int end) throws IOException {
validate(n, start, end);
int a[] = new int[n];
for (int i = start; i < end; i++) {
a[i] = ni();
}
return a;
}
public double[] gda(int n) throws IOException {
double a[] = new double[n];
for (int i = 0; i < n; i++) {
a[i] = nd();
}
return a;
}
public double[] gda(int n, int start, int end) throws IOException {
validate(n, start, end);
double a[] = new double[n];
for (int i = start; i < end; i++) {
a[i] = nd();
}
return a;
}
public long[] gla(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nl();
}
return a;
}
public long[] gla(int n, int start, int end) throws IOException {
validate(n, start, end);
long a[] = new long[n];
for (int i = start; i < end; i++) {
a[i] = nl();
}
return a;
}
public void print(String s) throws IOException {
bw.write(s);
}
public void println(String s) throws IOException {
bw.write(s);
bw.newLine();
}
public void print(int s) throws IOException {
bw.write(s + "");
}
public void println(int s) throws IOException {
bw.write(s + "");
bw.newLine();
}
public void print(long s) throws IOException {
bw.write(s + "");
}
public void println(long s) throws IOException {
bw.write(s + "");
bw.newLine();
}
public void print(double s) throws IOException {
bw.write(s + "");
}
public void println(double s) throws IOException {
bw.write(s + "");
bw.newLine();
}
private String nextToken() throws IndexOutOfBoundsException, IOException {
if (index == s.length) {
s = br.readLine().split(" ");
index = 0;
}
return s[index++];
}
private void validate(int n, int start, int end) {
if (start < 0 || end >= n) {
throw new IllegalArgumentException();
}
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
/**
* Created by Omar on 7/22/2016.
*/
import java.util.*;
import java.io.*;
public class CF364C {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int n=Integer.parseInt(br.readLine());
String input=br.readLine();
Set<Character> set = new HashSet<Character>();
for(int i=0;i<input.length();i++){
set.add(input.charAt(i));
}
StringBuilder sb= new StringBuilder();
for(char x:set){
sb.append(x);
}
String substring1=sb.toString();
// //System.out.println(substring1);
// int[] count= new int[52];
// int[] b= new int[52];
//
// char k;
// for(int i=0;i<substring1.length();i++){
// k=substring1.charAt(i);
// //System.out.println((int)'a');
// count[(k-'A')]++;
//
// }
// for(int i=0;i<52;i++){
// b[i]=count[i];
//
// //System.out.println("count "+count[i]);
// }
// int answer=set.size();
//
//
// for(int i=0;i<input.length();i++){
//
// }
// System.out.println(answer);
//
//System.out.println("WAIT");
System.out.println(solve(input,substring1).length());
pw.close();
br.close();
}
public static boolean isEmpty(int[] a){
for(int i=0;i<a.length;i++){
if(a[i]!=0){
return false;
}
}
return true;
}
public static String solve(String S, String T) {
HashMap<Character, Integer> D = new HashMap<>();
HashMap<Character, Integer> GET = new HashMap<>();
int B,E;
for (int i=0; i<T.length();i++) {
char c=T.charAt(i);
if (!D.containsKey(c))
{
D.put(c, 1);
}
else
{
D.put(c, D.get(c) + 1);
}
}
int ccc = 0;
B=0; E=0;
int min = Integer.MAX_VALUE;
// int max = Integer.MIN_VALUE;
String RESULT = "";
while (E < S.length()) {
char c = S.charAt(E);
if (D.containsKey(c)) {
if (GET.containsKey(c)) {
if (GET.get(c) < D.get(c))
ccc++;
//ccc--
GET.put(c, GET.get(c) + 1);
} else {
GET.put(c, 1);
ccc++;
//ccc--
}
}
if (ccc == T.length()) {
// if (ccc != B.length()) {
char test = S.charAt(B);
while (!GET.containsKey(test) ||
GET.get(test) > D.get(test)) {
if (GET.containsKey(test)
&& GET.get(test) >
D.get(test))
// GET.put(test, GET.get(test) - 24);
GET.put(test, GET.get(test) - 1);
//B-=B;
B++;
test = S.charAt(B);
//test += S.charAt(B);
}
if (E - B + 1 < min) {
RESULT = S.substring(B, E + 1);
min = E - B + 1;
}
//}
}
E++;
}
//if(E==0)
return RESULT;
}
}
|
linear
|
701_C. They Are Everywhere
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "" ;
boolean local = false;
int inf=0x7FFFFFFF;
int MOD=(int)(1e9+7);
double eps=1e-5;
double PI=Math.acos(-1);
void solve() {
long maxn=nl();
long L=1,R=maxn,ans=-1;
while (L<=R){
long mid=(L+R)/2;
if(ask(1,1,mid,maxn)<1)L=mid+1;
else{
R=mid-1;
ans=mid;
}
}
if(ask(1,1,ans,maxn)==1 && ask(ans+1,1,maxn,maxn)==1){
Yts1999 a1=gao(1,1,ans,maxn);
Yts1999 a2=gao(ans+1,1,maxn,maxn);
answer(a1,a2);
}else{
L=1;R=maxn;ans=-1;
while (L<=R){
long mid=(L+R)/2;
if(ask(1,1,maxn,mid)<1)L=mid+1;
else{
R=mid-1;
ans=mid;
}
}
Yts1999 a1=gao(1,1,maxn,ans);
Yts1999 a2=gao(1,ans+1,maxn,maxn);
answer(a1,a2);
}
}
void answer(Yts1999 a1,Yts1999 a2){
out.print("!");
a1.print();
a2.print();
out.flush();
}
int ask(long a,long b,long c,long d){
out.printf("? %d %d %d %d",a,b,c,d);
out.println();
out.flush();
return ni();
}
Yts1999 gao(long x1,long x2,long y1,long y2){
long a1=0,a2=0,a3=0,a4=0;
long L,R;
L=x1;R=y1;
while(L<=R){
long mid=(L+R)/2;
if(ask(mid,x2,y1,y2)==1){
a1=mid;
L=mid+1;
}else R=mid-1;
}
L=x1;R=y1;
while(L<=R){
long mid=(L+R)/2;
if(ask(x1,x2,mid,y2)==1){
a3=mid;
R=mid-1;
}else L=mid+1;
}
L=x2;R=y2;
while(L<=R){
long mid=(L+R)/2;
if(ask(x1,mid,y1,y2)==1){
a2=mid;
L=mid+1;
}else R=mid-1;
}
L=x2;R=y2;
while(L<=R){
long mid=(L+R)/2;
if(ask(x1,x2,y1,mid)==1){
a4=mid;
R=mid-1;
}else L=mid+1;
}
return new Yts1999(a1,a2,a3,a4);
}
public class Yts1999 implements Comparable{
public long a,b,c,d;
public Yts1999(long a,long b,long c,long d){
this.a=a;
this.b=b;
this.c=c;
this.d=d;
}
public int compareTo(Object o) {
Yts1999 to=(Yts1999)o;
if(this.d<to.d) return 1;
else if(this.d==to.d) return 0;
else return -1;
}
public void print(){
out.printf(" %d %d %d %d",a,b,c,d);
}
}
long[] exgcd(long a, long b) {
if (b == 0) return new long[]{1,0,a};
long[] res = exgcd(b, a%b);
long t = res[0]; res[0] = res[1]; res[1] = t;
res[1] -= a/b*res[0];
return res;
}
long gcd(long a,long b){
return b==0?a:gcd(b,a%b);
}
long lcm(long a,long b){
return a*b/gcd(a,b);
}
private void run() {
is = local? new ByteArrayInputStream(INPUT.getBytes()):System.in;
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 Main().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte(){
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns(){
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n){
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m){
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n){
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni(){
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl(){
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) { if(local)System.out.println(Arrays.deepToString(o)); }
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
import java.util.*;
public class C {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
char[] s = new char[n];
String line = in.next();
int ct=0,ht=0;
for(int i=0;i<n;i++) //count animals
if(line.charAt(i)=='T')
ct++;
else
ht++;
int cnt = 1000000000;
int[] c = new int[2];
char[] cc = new char[2];
if(ct<ht)
{
c[0] = ct;
c[1] = ht;
cc[0] = 'T';
cc[1] = 'H';
}else{
c[0] = ht;
c[1] = ct;
cc[0] = 'H';
cc[1] = 'T';
}
for(int i=0;i<n;i++)
{
int ptr = i;
for(int j=0;j<c[0];j++) //fill First
{
s[ptr] = cc[0];
ptr = (ptr+1)%n;
}
for(int j=0;j<c[1];j++) //fill Second
{
s[ptr] = cc[1];
ptr = (ptr+1)%n;
}
//check
int ch = 0;
for(int j=0;j<n;j++) //difference
if(s[j]!=line.charAt(j)&&s[j]==cc[0])
ch++;
cnt = Math.min(cnt,ch);
}
System.out.print(cnt);
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Codeforces913F {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int a = input.nextInt();
int b = input.nextInt();
input.close();
final int mod = 998244353;
int frac = multiply(a, inverse(b, mod), mod);
int reverse = (mod+1-frac)%mod;
int[] fracpower = new int[n+1];
int[] reversepower = new int[n+1];
fracpower[0] = 1;
reversepower[0] = 1;
for (int i = 1; i <= n; i++) {
fracpower[i] = multiply(fracpower[i-1], frac, mod);
reversepower[i] = multiply(reversepower[i-1], reverse, mod);
}
int[][] dp1 = new int[n+1][n+1];
dp1[2][1] = 1;
for (int i = 3; i <= n; i++) {
for (int j = 1; j < i; j++) {
if (j == 1) {
dp1[i][j] = fracpower[i-1];
}
else {
dp1[i][j] = multiply(dp1[i-1][j-1], fracpower[i-j], mod);
}
if (j == i-1) {
dp1[i][j] += reversepower[i-1];
dp1[i][j] %= mod;
}
else {
dp1[i][j] += multiply(dp1[i-1][j], reversepower[j], mod);
dp1[i][j] %= mod;
}
}
}
int[][] dp2 = new int[n+1][n+1];
dp2[1][1] = 1;
dp2[2][1] = 1;
dp2[2][2] = 0;
for (int i = 3; i <= n; i++) {
int val = 0;
for (int j = 1; j < i; j++) {
dp2[i][j] = multiply(dp2[j][j], dp1[i][j], mod);
val += dp2[i][j];
val %= mod;
}
dp2[i][i] = (mod+1-val)%mod;
}
/*for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(dp2[i][j] + " ");
}
System.out.println();
}*/
int[] EV = new int[n+1];
EV[1] = 0;
EV[2] = 1;
for (int i = 3; i <= n; i++) {
int val = 0;
for (int j = 1; j < i; j++) {
int r = j*(i-j) + (j*(j-1))/2 + EV[i-j] + EV[j];
r %= mod;
val += multiply(dp2[i][j], r, mod);
val %= mod;
}
val += multiply((i*(i-1))/2, dp2[i][i], mod);
val %= mod;
int s = (mod+1-dp2[i][i])%mod;
EV[i] = multiply(val, inverse(s, mod), mod);
}
System.out.println(EV[n]);
}
public static int multiply(int a, int b, int mod) {
long x = (long)a*(long)b;
return (int) (x%mod);
}
public static int inverse (int a, int n) {
int m = n;
int r1 = 1;
int r2 = 0;
int r3 = 0;
int r4 = 1;
while ((a > 0) && (n > 0)) {
if (n >= a) {
r3 -= r1*(n/a);
r4 -= r2*(n/a);
n = n%a;
}
else {
int tmp = a;
a = n;
n = tmp;
tmp = r1;
r1 = r3;
r3 = tmp;
tmp = r2;
r2 = r4;
r4 = tmp;
}
}
if (a == 0) {
if (r3 >= 0)
return (r3%m);
else
return (m+(r3%m));
}
else {
if (r1 >= 0)
return (r1%m);
else
return (m+(r1%m));
}
}
}
|
quadratic
|
913_F. Strongly Connected Tournament
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.TreeMap;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.Map.Entry;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
F solver = new F();
solver.solve(1, in, out);
out.close();
}
static class F {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.ni();
int[] a = in.na(n);
TreeMap<Integer, TreeMap<Integer, Segment>> map = new TreeMap<>();
int[] pref = new int[n + 1];
for (int i = 0; i < n; i++) {
pref[i + 1] = pref[i] + a[i];
}
for (int i = 0; i < n; i++) {
for (int j = i; j >= 0; j--) {
int val = pref[i + 1] - pref[j];
TreeMap<Integer, Segment> dp = map.computeIfAbsent(val, k -> new TreeMap<>());
if (!dp.containsKey(i)) {
Map.Entry<Integer, Segment> lastEntry = dp.lastEntry();
if (lastEntry == null) {
dp.put(i, new Segment(j, i, 1, null));
} else {
Segment lastValue = lastEntry.getValue();
Map.Entry<Integer, Segment> prev = dp.lowerEntry(j);
if (prev == null) {
if (lastValue.dp >= 1)
dp.put(i, lastValue);
else
dp.put(i, new Segment(j, i, 1, null));
} else if (lastValue.dp >= prev.getValue().dp + 1) {
dp.put(i, lastValue);
} else {
dp.put(i, new Segment(j, i, prev.getValue().dp + 1, prev.getValue()));
}
}
}
}
}
Segment best = null;
for (TreeMap<Integer, Segment> segments : map.values()) {
Segment seg = segments.lastEntry().getValue();
if (best == null || best.dp < seg.dp) {
best = seg;
}
}
if (best == null)
throw new RuntimeException("Null best");
out.println(best.dp);
while (best != null) {
out.printf("%d %d%n", best.from + 1, best.to + 1);
best = best.prev;
}
}
class Segment {
int from;
int to;
int dp;
Segment prev;
public Segment(int from, int to, int dp, Segment prev) {
this.from = from;
this.to = to;
this.dp = dp;
this.prev = prev;
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String ns() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(ns());
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static int t,m,mod=998244353,maxn=1000000,q,n,k;
static int INF=(int)1e8;
void solve(PrintWriter out, Reader in) throws IOException{
n = in.nextInt();
m = in.nextInt();
String str = in.next();
int[][] pre = new int[1<<m][m];
int child=0,head,child2=0;
for(int i=0;i<n;i++){
if(i!=0) child = 1<<(str.charAt(i-1)-'a');
if(i!=n-1) child2 = 1<<(str.charAt(i+1)-'a');
head = str.charAt(i)-'a';
if(i!=0) pre[child][head]++;
if(i!=n-1) pre[child2][head]++;
}
//pre[child][head] - number of elemnts that exists in child and are adjacent to head in the string.
int rmv=0;
for(int i=0;i<m;i++){
head = i;
for(int j=1;j<1<<m;j++){
if(pre[j][i]!=0) continue;
rmv = j-(j&-j);
pre[j][head] = pre[rmv][head]+pre[j^rmv][head];
}
}
int[] dp = new int[1<<m];
for(int i=1;i<1<<m;i++) dp[i] = INF;
// dp[mask] - the minimum cost using a permutation of the set bits in the mask.
int bit=0,full=(1<<m)-1,cnt=0;
for(int j=1;j<1<<m;j++){
for(int i=0;i<m;i++){
if(((1<<i)&j)!=0){
bit = 1<<i;
cnt = cnt(j);
dp[j] = Math.min(dp[j],dp[j^bit]+pre[j^bit][i]*cnt-pre[j^full][i]*cnt);
}
}
}
out.println(dp[full]);
}
static int cnt(int x){
int res=0;
while(x>0){
res+=x&1;
x>>=1;
}
return res;
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
Reader in = new Reader();
Main solver = new Main();
solver.solve(out, in);
out.flush();
out.close();
}
}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution {
private StringTokenizer st;
private BufferedReader in;
private PrintWriter out;
public void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
}
int[] b = a.clone();
Arrays.sort(b);
int diff = 0;
for (int i = 0; i < n; ++i) {
if (a[i] != b[i]) {
diff++;
}
}
out.println(diff <= 2 ? "YES" : "NO");
}
public void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
eat("");
solve();
out.close();
}
void eat(String s) {
st = new StringTokenizer(s);
}
String next() throws IOException {
while (!st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
eat(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new Solution().run();
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.util.Scanner;
import java.io.IOException;
public class kresz {
public static double a;
public static double v;
public static double l;
public static double d;
public static double w;
public static double gyorsulut (double v1, double v2) { //v1 -> v2 mennyi utat tesz meg
return Math.abs((v2*v2-v1*v1)/(2*a));
}
public static double gyorsulido (double v1, double v2) { //v1 -> v2 mennyi idő
return Math.abs((v2-v1)/a);
}
public static void beolvas () throws IOException {
Scanner be = new Scanner (new InputStreamReader (System.in));
a = be.nextDouble();
v = be.nextDouble();
l = be.nextDouble();
d = be.nextDouble();
w = be.nextDouble();
be.close();
}
public static void main (String args[]) throws IOException {
beolvas();
double s = l; //hátralévő út
double t = 0; //eltelt idő
if (v <= w || Math.sqrt(2*a*d) <= w) { //nincs korlátozás
if (gyorsulut(0,v) > l) {
t+=gyorsulido(0, Math.sqrt(2*a*l));
s = 0;
}
else {
s-=gyorsulut(0,v);
t+=gyorsulido(0,v);
}
}
else {
//gyorsuló szakaszok a korlátozásig
if (d < gyorsulut(0,v)+gyorsulut(v,w)) {
double x = Math.sqrt(a*(d-w*w/(2*a))+w*w);
s-=gyorsulut(0,w)+2*gyorsulut(w,x);
t+=gyorsulido(0,w)+2*gyorsulido(w,x);
}
else {
s-=gyorsulut(0,v)+gyorsulut(w,v);
t+=gyorsulido(0,v)+gyorsulido(w,v);
}
//gyorsuló szakaszok a korlátozástól
if (gyorsulut(v,w) > l-d) {
double y = Math.sqrt(2*a*(l-d)+w*w);
s-= gyorsulut(w,y);
t+=gyorsulido(w,y);
}
else {
s-=gyorsulut(w,v);
t+=gyorsulido(w,v);
}
}
t+=s/v; //nem gyorsuló szakaszok ideje
System.out.println(t);
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class java2 {
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int n=r.nextInt();
int []l=new int[1005];
int []ri=new int[1005];
int []candy=new int[1005];
for(int i=1;i<=n;++i)
{
l[i]=r.nextInt();
}
for(int i=1;i<=n;++i)
{
ri[i]=r.nextInt();
}
for(int i=1;i<=n;++i)
{
if(l[i]>i-1||ri[i]>n-i)
{
System.out.println("NO");
System.exit(0);
}
candy[i]=n-l[i]-ri[i];
}
for(int i=1;i<=n;++i)
{
int left=0,right=0;
for(int j=1;j<=i-1;++j)
{
if(candy[j]>candy[i])
{
++left;
}
}
for(int j=i+1;j<=n;++j)
{
if(candy[j]>candy[i])
{
++right;
}
}
if(left!=l[i]||right!=ri[i])
{
System.out.println("NO");
System.exit(0);
}
}
System.out.println("YES");
for(int i=1;i<=n;++i)
{
System.out.print(candy[i]+" ");
}
}
}
|
quadratic
|
1054_C. Candies Distribution
|
CODEFORCES
|
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
for (int i = 0, x; i < N; ++i) {
x = sc.nextInt();
if (x < first) {
second = first;
first = x;
} else if (x > first && x < second) {
second = x;
}
}
if (second == Integer.MAX_VALUE)
System.out.println("NO");
else
System.out.println(second);
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Bag implements Runnable {
private void solve() throws IOException {
int xs = nextInt();
int ys = nextInt();
int n = nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; ++i) {
x[i] = nextInt();
y[i] = nextInt();
}
int[][] pair = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]);
int[] single = new int[n];
for (int i = 0; i < n; ++i) {
single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys));
}
int[] best = new int[1 << n];
int[] prev = new int[1 << n];
for (int set = 1; set < (1 << n); ++set) {
int i;
for (i = 0; i < n; ++i)
if ((set & (1 << i)) != 0)
break;
best[set] = best[set ^ (1 << i)] + single[i];
prev[set] = i + 1;
for (int j = i + 1; j < n; ++j)
if ((set & (1 << j)) != 0) {
int cur = best[set ^ (1 << i) ^ (1 << j)] + pair[i][j];
if (cur < best[set]) {
best[set] = cur;
prev[set] = (i + 1) * 100 + (j + 1);
}
}
}
writer.println(best[(1 << n) - 1]);
int now = (1 << n) - 1;
writer.print("0");
while (now > 0) {
int what = prev[now];
int wa = what % 100 - 1;
int wb = what / 100 - 1;
if (wa >= 0) {
writer.print(" ");
writer.print(wa + 1);
now ^= 1 << wa;
}
if (wb >= 0) {
writer.print(" ");
writer.print(wb + 1);
now ^= 1 << wb;
}
writer.print(" ");
writer.print("0");
}
writer.println();
}
public static void main(String[] args) {
new Bag().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
FastReader sc=new FastReader();
long n=sc.L();
long k=sc.L();
long x=8*(n+k);
x+=9;
x=(long)Math.sqrt(x)-3;
x/=2;
System.out.println(n-x);
}
static int binarysearch(int x,int[] b,int n)
{
int l=0,r=n-1,m=(l+r)/2;
if(x<b[0]||x>b[r])
return -1;
while(l<=r)
{
m=(l+r)/2;
if(b[m]==x)
return m;
if(b[m]>x)
r=m-1;
else
l=m+1;
}
return -1;
}
static int lower(int x,int b[],int n)
{
if(x<b[0])
return -1;
else if(x==b[0])
return 0;
if(x>=b[n-1])
return n-1;
int l=0,r=n-1,m=(l+r)/2;
while(l<=r)
{
m=(l+r)/2;
if(b[m]<=x&&b[m+1]>x)
return m;
else if(b[m]>x&&b[m-1]<=x)
return m-1;
if(b[m]>x)
r=m-1;
else if(b[m]<x)
l=m+1;
}
return -1;
}
static int upper(int x,int b[],int n)
{
if(x<=b[0])
return 0;
else if(x==b[n-1])
return n-1;
if(x>b[n-1])
return -1;
int l=0,r=n-1,m=(l+r)/2;
while(l<=r)
{
m=(l+r)/2;
if(b[m]<x&&b[m+1]>=x)
return m+1;
else if(b[m]>=x&&b[m-1]<x)
return m;
if(b[m]>x)
r=m-1;
else if(b[m]<x)
l=m+1;
}
return -1;
}
static long power(long x, long y, long p)
{
// Initialize result
long res = 1;
// Update x if it is more
// than or equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply x
// with result
if((y & 1)==1)
res = (res * x) % p;
// y must be even now
// y = y / 2
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static 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 I()
{
return Integer.parseInt(next());
}
long L()
{
return Long.parseLong(next());
}
double D()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static int gcd(int a,int b)
{
if(a%b==0)
return b;
return gcd(b,a%b);
}
static float power(float x, int y)
{
float temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
else
{
if(y > 0)
return x * temp * temp;
else
return (temp * temp) / x;
}
}
static long pow(int a,int b)
{
long result=1;
if(b==0)
return 1;
long x=a;
while(b>0)
{
if(b%2!=0)
result*=x;
x=x*x;
b=b/2;
}
return result;
}
static ArrayList<Integer> sieveOfEratosthenes(int n)
{
ArrayList<Integer> arr=new ArrayList<Integer>();
boolean prime[] = new boolean[n+1];
for(int i=2;i<n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
if(prime[p] == true)
{
arr.add(p);
for(int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
return arr;
}
}
|
logn
|
1195_B. Sport Mafia
|
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 bacali
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CNastyaAndAWardrobe solver = new CNastyaAndAWardrobe();
solver.solve(1, in, out);
out.close();
}
static class CNastyaAndAWardrobe {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
long mod = (long) (1e9 + 7);
long n = in.nextLong();
long k = in.nextLong();
if (n == 0) {
out.println(0);
return;
}
long c = (((2 * n - 1) % mod) * pow(2L, k, mod)) % mod + 1;
c %= mod;
out.println(c);
}
public long pow(long a, long b, long mod) {
long result = 1;
while (b > 0) {
if (b % 2 != 0) {
result *= a;
result %= mod;
b--;
}
a *= a;
a %= mod;
b /= 2;
}
return result % mod;
}
}
static class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class FirstClass {
public static void main(String[] args)throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
int arr[] = new int [n];
StringTokenizer st1 = new StringTokenizer(br.readLine());
for(int i = 0 ; i < n ; i++)
{
arr[i] = Integer.parseInt(st1.nextToken());
}
int max = -1;
boolean flag = true;
for(int i = 0 ; i < n ; i++)
{
if(arr[i] > max+1)
{
flag = false;
out.println(i+1);
break;
}
else
{
max = Math.max(max, arr[i]);
}
}
if(flag)
out.println(-1);
out.flush();
out.close();
}
}
|
linear
|
1054_B. Appending Mex
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution {
StreamTokenizer in;
PrintWriter out;
public static void main(String[] args) throws Exception {
new Solution().run();
}
public void run() throws Exception {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter (new OutputStreamWriter(System.out));
solve();
out.flush();
}
int nextInt() throws Exception {
in.nextToken();
return (int) in.nval;
}
String next() throws Exception {
in.nextToken();
return in.sval;
}
public void solve() throws Exception {
int n=nextInt();
String s=next();
String ss = s + s;
int t = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'T') {
t++;
}
}
if (t == 1 || t == n - 1) {
out.println(0);
} else {
int sum = 0;
for (int i = 0; i < t; i++) {
if (s.charAt(i) == 'T') {
sum++;
}
}
int max = sum;
for (int i = 0; i < s.length(); i++) {
if (ss.charAt(i) == 'T') {
if (ss.charAt(i + t) == 'H') {
sum--;
}
} else {
if (ss.charAt(i + t) == 'T') {
sum++;
max = Math.max(max, sum);
}
}
}
out.println(t - max);
}
}
}
|
linear
|
46_C. Hamsters and Tigers
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
D903 solver = new D903();
solver.solve(1, in, out);
out.close();
}
static class D903 {
int N;
long ripple;
BigInteger tot;
long[] nums;
BigInteger[] cs;
public void solve(int testNumber, FastScanner s, PrintWriter out) {
N = s.nextInt();
nums = s.nextLongArray(N);
tot = new BigInteger("0");
cs = new BigInteger[N + 1];
cs[0] = new BigInteger("0");
ripple = 0;
for (int i = 1; i <= N; i++)
cs[i] = cs[i - 1].add(new BigInteger("" + nums[i - 1]));
for (int i = 1; i <= N; i++) {
long cur = nums[i - 1];
// out.printf("%d: cs %d, minus %d%n", i, (cs[N] - cs[i]), cur * (N - i));
tot = tot.add(cs[N].subtract(cs[i])).subtract(new BigInteger("" + (cur * (N - i))));
}
HashMap<Long, Integer> seen = new HashMap<>();
for (long i : nums) {
Integer lo = seen.get(i - 1);
Integer hi = seen.get(i + 1);
if (lo != null)
tot = tot.subtract(new BigInteger("" + lo));
if (hi != null)
tot = tot.add(new BigInteger("" + hi));
if (!seen.containsKey(i))
seen.put(i, 0);
seen.put(i, seen.get(i) + 1);
}
out.println(tot);
}
}
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long[] nextLongArray(int N) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = this.nextLong();
return ret;
}
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
private static class Interval implements Comparable<Interval> {
public int start , end;
public Interval(int start , int end) {
this.start = start;
this.end = end;
}
@Override
public int compareTo(Interval interval) {
return this.end - interval.end;
}
}
private static int getTotal(List<Interval> list) {
int ans = 0 , i , n = list.size();
for (i = 0;i < n;i ++) {
int end = list.get(i).end;
while (i < n && list.get(i).start <= end) {
i ++;
}
i --;
ans ++;
}
return ans;
}
private static void solve(List<Interval> list) {
List<int[]> ans = new ArrayList<>();
int i , n = list.size();
for (i = 0;i < n;i ++) {
int start = list.get(i).start , end = list.get(i).end;
while (i < n && list.get(i).start <= end) {
i ++;
}
i --;
ans.add(new int[] {start , end});
}
System.out.println(ans.size());
for (int[] array : ans) {
System.out.println(array[0] + " " + array[1]);
}
}
private static long[] a = new long[2000];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Map<Long , List<Interval>> map = new HashMap<>();
int i , j , n = scan.nextInt() , max = 0;
long ans = 0;
for (i = 1;i <= n;i ++) {
a[i] = scan.nextLong();
}
for (i = 1;i <= n;i ++) {
long sum = 0;
for (j = i;j <= n;j ++) {
sum += a[j];
if (!map.containsKey(sum)) {
map.put(sum , new ArrayList<>());
}
map.get(sum).add(new Interval(i , j));
}
}
for (List<Interval> list : map.values()) {
Collections.sort(list);
}
for (Map.Entry<Long , List<Interval>> entry : map.entrySet()) {
int total = getTotal(entry.getValue());
if (total > max) {
max = total;
ans = entry.getKey();
}
}
solve(map.get(ans));
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n=scan.nextInt();
int m=scan.nextInt();
int[] game=new int[n];
int[] bill=new int[m];
for (int i = 0; i <n ; i++) {
game[i]=scan.nextInt();
}
for (int i = 0; i <m ; i++) {
bill[i]=scan.nextInt();
}
int i=0;
int j=0;
int ans=0;
while (i<m){
boolean f=true;
for (int k = j; k <n ; k++) {
if (bill[i]>=game[k]){
ans++;
i++;
j=k+1;
f=false;
break;
}
}
if (f){
break;
}
}
System.out.println(ans);
}
}
|
linear
|
1009_A. Game Shopping
|
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 lewin
*/
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);
BTheHat solver = new BTheHat();
solver.solve(1, in, out);
out.close();
}
static class BTheHat {
InputReader in;
OutputWriter out;
int n;
int ask(int student) {
student %= n;
out.println("? " + (student + 1));
out.flush();
return in.nextInt();
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
this.in = in;
this.out = out;
n = in.nextInt();
int a = ask(0), b = ask(n / 2);
if ((a + b) % 2 != 0) {
out.println("! -1");
out.flush();
return;
}
if (a == b) {
out.println("! 1");
out.flush();
return;
}
int lo = 0, hi = n / 2;
while (lo < hi) {
int mid = (lo + hi) / 2;
int f1 = ask(mid), f2 = ask(mid + n / 2);
if (f1 == f2) {
out.println("! " + (mid + 1));
return;
}
if ((a > b) == (f1 > f2)) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
out.println("! " + (lo + 1));
out.flush();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (this.numChars == -1) {
throw new InputMismatchException();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException var2) {
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;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.util.*;
public class A630 {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
long n = scan.nextLong();
System.out.println(25);
}
}
|
constant
|
630_A. Again Twenty Five!
|
CODEFORCES
|
import java.awt.Point;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class A {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
long x = nextLong();
long y = nextLong();
long ans = 0;
while (x > 0 && y > 0) {
if (x > y) {
ans += x / y;
x %= y;
}
else {
ans += y / x;
y %= x;
}
}
System.out.println(ans);
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class CFContest {
public static void main(String[] args) throws Exception {
boolean local = System.getProperty("ONLINE_JUDGE") == null;
boolean async = false;
Charset charset = Charset.forName("ascii");
FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset);
Task task = new Task(io, new Debug(local));
if (async) {
Thread t = new Thread(null, task, "dalt", 1 << 27);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
t.join();
} else {
task.run();
}
if (local) {
io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M");
}
io.flush();
}
public static class Task implements Runnable {
final FastIO io;
final Debug debug;
int inf = (int) 1e8;
public Task(FastIO io, Debug debug) {
this.io = io;
this.debug = debug;
}
@Override
public void run() {
solve();
}
public void solve() {
int n = io.readInt();
int k = io.readInt();
int l = 0;
int r = n;
while (l < r) {
int m = (l + r + 1) >> 1;
if (when(n, m) < k) {
r = m - 1;
} else {
l = m;
}
}
io.cache.append(l);
}
public long when(int n, int t) {
long put = n - t;
return (put + 1) * put / 2 - t;
}
}
public static class FastIO {
public final StringBuilder cache = new StringBuilder();
private final InputStream is;
private final OutputStream os;
private final Charset charset;
private StringBuilder defaultStringBuf = new StringBuilder(1 << 8);
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastIO(InputStream is, OutputStream os, Charset charset) {
this.is = is;
this.os = os;
this.charset = charset;
}
public FastIO(InputStream is, OutputStream os) {
this(is, os, Charset.forName("ascii"));
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
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;
}
public long readLong() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
long 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;
}
public double readDouble() {
boolean sign = true;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+';
next = read();
}
long val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
if (next != '.') {
return sign ? val : -val;
}
next = read();
long radix = 1;
long point = 0;
while (next >= '0' && next <= '9') {
point = point * 10 + next - '0';
radix = radix * 10;
next = read();
}
double result = val + (double) point / radix;
return sign ? result : -result;
}
public String readString(StringBuilder builder) {
skipBlank();
while (next > 32) {
builder.append((char) next);
next = read();
}
return builder.toString();
}
public String readString() {
defaultStringBuf.setLength(0);
return readString(defaultStringBuf);
}
public int readLine(char[] data, int offset) {
int originalOffset = offset;
while (next != -1 && next != '\n') {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(char[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(byte[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (byte) next;
next = read();
}
return offset - originalOffset;
}
public char readChar() {
skipBlank();
char c = (char) next;
next = read();
return c;
}
public void flush() {
try {
os.write(cache.toString().getBytes(charset));
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasMore() {
skipBlank();
return next != -1;
}
}
public static class Debug {
private boolean allowDebug;
public Debug(boolean allowDebug) {
this.allowDebug = allowDebug;
}
public void assertTrue(boolean flag) {
if (!allowDebug) {
return;
}
if (!flag) {
fail();
}
}
public void fail() {
throw new RuntimeException();
}
public void assertFalse(boolean flag) {
if (!allowDebug) {
return;
}
if (flag) {
fail();
}
}
private void outputName(String name) {
System.out.print(name + " = ");
}
public void debug(String name, int x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, long x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, double x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, int[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, long[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, double[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, Object x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, Object... x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.deepToString(x));
}
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import sun.reflect.generics.tree.Tree;
import java.io.*;
import java.util.*;
public class A2 {
static Scanner in; static int next() throws Exception {return in.nextInt();};
// static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;}
// static BufferedReader in;
static PrintWriter out;
public static void main(String[] args) throws Exception {
in = new Scanner(System.in);
// in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
// in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = next(), k = next()-1;
int x[] = new int[n];
for (int i = 0;i < n;i++) x[i] = (100-next())*100+next();
Arrays.sort(x);
int res = 0, t = x[k];
for (int i = 0;i < n;i++) if (t == x[i]) res++;
out.println(res);
out.println();
out.close();
}
}
|
nlogn
|
166_A. Rank List
|
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int tests = in.nextInt();
for (int t = 0; t < tests; t++) {
int numLines = in.nextInt();
// greedy, maintain stack, keep stack as big as possible
int stackIdx = -1;
int[] stack = new int[10000];
String prev = "";
for (int x = 0; x < numLines; x++) {
int depth = 0;
int next = in.nextInt();
boolean found = false;
for (int i = stackIdx; i >= 0; i--) {
if (next == stack[i] + 1) {
depth = i;
found = true;
break;
}
}
if (found == true) {
stackIdx = depth;
stack[depth] = next;
for (int i = 0; i <= depth; i++) {
if (i != 0) {
out.print(".");
}
out.print(stack[i]);
}
out.println();
} else if (next == 1) {
stackIdx++;
stack[stackIdx] = 1;
for (int i = 0; i <= stackIdx; i++) {
if (i != 0) {
out.print(".");
}
out.print(stack[i]);
}
out.println();
} else {
// start a new one
stackIdx = 0;
stack[0] = next;
out.println(next);
}
}
}
}
}
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();
}
public void print(int i) {
writer.print(i);
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class thing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
String s = in.next();
int[][] count = new int[m][m];
int[] dp = new int[1 << m];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for(int i = 1; i < n; i++) {
int a = s.charAt(i)-'a';
int b = s.charAt(i-1)-'a';
count[a][b]++;
count[b][a]++;
}
for(int i = 1; i < (1 << m); i++) {
int pos = set_bits(i);
for(int j = 0; (i >> j) != 0; j++) {
if(((i >> j) & 1) == 0) continue;
int sum = 0;
for(int mask = i, y = 0; y < m; mask >>= 1, y++) {
if(y == j) continue;
if((mask & 1) == 1) sum += count[j][y];
else sum -= count[j][y];
}
int calc = dp[i-(1<<j)] + pos*sum;
dp[i] = Math.min(dp[i], calc);
}
}
System.out.println(dp[(1 << m)-1]);
}
public static int set_bits(int n) {
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}
}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.math.*;
import static java.util.stream.Collectors.*;
import static java.util.Map.Entry.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws IOException
{
final long mod=(long) (1e9+7);
Reader s=new Reader();
PrintWriter pt=new PrintWriter(System.out);
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int T=s.nextInt();
// int T=Integer.parseInt(br.readLine());
// int T=1;
while(T-->0)
{
long n=s.nextInt();
long sq1=n/2;
long sq2=n/4;
if(isPerfectSquare(sq1)&&sq1*2==n||isPerfectSquare(sq2)&&sq2*4==n)
pt.println("YES");
else
pt.println("NO");
}
pt.close();
}
static void divideBy2(int arr[], int n) {
for(int i=0;i<n;i++) {
arr[i]=arr[i]>>1;
}
}
static boolean isEven(int arr[], int n) {
for(int i=0;i<n;i++) {
if(arr[i]%2==1)
return false;
}
return true;
}
static boolean isPartition(int arr[], int n) {
int sum = 0;
int i, j;
// Calculate sum of all elements
for (i = 0; i < n; i++)
sum += arr[i];
if (sum % 2 != 0)
return false;
boolean part[][]=new boolean[sum/2+1][n+1];
// initialize top row as true
for (i = 0; i <= n; i++)
part[0][i] = true;
// initialize leftmost column, except part[0][0], as false
for (i = 1; i <= sum / 2; i++)
part[i][0] = false;
// Fill the partition table in bottom up manner
for (i = 1; i <= sum / 2; i++) {
for (j = 1; j <= n; j++) {
part[i][j] = part[i][j - 1];
if (i >= arr[j - 1])
part[i][j] = part[i][j]
|| part[i - arr[j - 1]][j - 1];
}
}
return part[sum / 2][n];
}
static int setBit(int S, int j) { return S | 1 << j; }
static int clearBit(int S, int j) { return S & ~(1 << j); }
static int toggleBit(int S, int j) { return S ^ 1 << j; }
static boolean isOn(int S, int j) { return (S & 1 << j) != 0; }
static int turnOnLastZero(int S) { return S | S + 1; }
static int turnOnLastConsecutiveZeroes(int S) { return S | S - 1; }
static int turnOffLastBit(int S) { return S & S - 1; }
static int turnOffLastConsecutiveBits(int S) { return S & S + 1; }
static int lowBit(int S) { return S & -S; }
static int setAll(int N) { return (1 << N) - 1; }
static int modulo(int S, int N) { return (S & N - 1); } //S%N, N is a power of 2
static boolean isPowerOfTwo(int S) { return (S & S - 1) == 0; }
static boolean isWithin(long x, long y, long d, long k) {
return x*k*x*k + y*k*y*k <= d*d;
}
static long modFact(long n,
long p)
{
if (n >= p)
return 0;
long result = 1;
for (int i = 1; i <= n; i++)
result = (result * i) % p;
return result;
}
static int sum(int[] arr, int n)
{
int inc[]=new int[n+1];
int dec[]=new int[n+1];
inc[0] = arr[0];
dec[0] = arr[0];
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (arr[j] > arr[i]) {
dec[i] = max(dec[i], inc[j] + arr[i]);
}
else if (arr[i] > arr[j]) {
inc[i] = max(inc[i], dec[j] + arr[i]);
}
}
}
return max(inc[n - 1], dec[n - 1]);
}
static long nc2(long a) {
return a*(a-1)/2;
}
public static int numberOfprimeFactors(int n)
{
// Print the number of 2s that divide n
HashSet<Integer> hs = new HashSet<Integer>();
while (n%2==0)
{
hs.add(2);
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)
{
hs.add(i);
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
hs.add(n);
return hs.size();
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void reverse(int arr[],int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
static void reverse(long arr[],int start, int end)
{
long temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
static boolean isPrime(int 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 (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int p2(int n) {
int k=0;
while(n>1) {
if(n%2!=0)
return k;
n/=2;
k++;
}
return k;
}
static boolean isp2(int n) {
while(n>1) {
if(n%2==1)
return false;
n/=2;
}
return true;
}
static int binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
return mid;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
return -1;
}
static void print(int a[][]) {
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
}
static int max (int x, int y) {
return (x > y)? x : y;
}
static int search(Pair[] p, Pair pair) {
int l=0, r=p.length;
while (l <= r) {
int m = l + (r - l) / 2;
if (p[m].compareTo(pair)==0)
return m;
if (p[m].compareTo(pair)<0)
l = m + 1;
else
r = m - 1;
}
return -1;
}
static void pa(int a[])
{
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
static void pa(long a[])
{
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
static void reverseArray(int arr[],
int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
static boolean isPalindrome(String s) {
int l=s.length();
for(int i=0;i<l/2;i++)
{
if(s.charAt(i)!=s.charAt(l-i-1))
return false;
}
return true;
}
static long nc2(long n, long m) {
return (n*(n-1)/2)%m;
}
static long c(long a) {
return a*(a+1)/2;
}
static int next(long[] arr, long target)
{
int start = 0, end = arr.length - 1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
// Move to right side if target is
// greater.
if (arr[mid] < target) {
start = mid + 1;
}
// Move left side.
else {
ans = mid;
end = mid - 1;
}
}
return ans;
}
static int prev(long[] arr, long target)
{
int start = 0, end = arr.length - 1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
// Move to left side if target is
// lesser.
if (arr[mid] > target) {
end = mid - 1;
}
// Move right side.
else {
ans = mid;
start = mid + 1;
}
}
return ans;
}
static long power(long x, long y, long p)
{
long res = 1;
x = x % p;
while (y > 0)
{
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long modInverse(long n, long p)
{
return power(n, p-2, p);
}
static long nCrModP(long n, long r,
long p)
{
if(r>n)
return 0;
if (r == 0)
return 1;
long[] fac = new long[(int) (n+1)];
fac[0] = 1;
for (int i = 1 ;i <= n; i++)
fac[i] = fac[i-1] * i % p;
return (fac[(int) n]* modInverse(fac[(int) r], p)
% p * modInverse(fac[(int) (n-r)], p)
% p) % p;
}
static String reverse(String str)
{
return new StringBuffer(str).reverse().toString();
}
static long fastpow(long x, long y, long m)
{
if (y == 0)
return 1;
long p = fastpow(x, y / 2, m) % m;
p = (p * p) % m;
if (y % 2 == 0)
return p;
else
return (x * p) % m;
}
static boolean isPerfectSquare(long l)
{
return Math.pow((long)Math.sqrt(l),2)==l;
}
static void merge(long[] arr, int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long [n1];
long R[] = new long [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
static void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
static void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
static void sort(long arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
static class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int a,int b){
this.a=a;
this.b=b;
}
public int compareTo(Pair p){
if(a>p.a)
return 1;
if(a==p.a)
return (b-p.b);
return -1;
}
}
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[128]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] ar = new int[n];
for (int i = 0; i < n; i++)
ar[i] = in.nextInt();
Arrays.sort(ar);
int x1 = ar[b-1];
int x2 = ar[b];
System.out.println(x2-x1);
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.awt.Point;
import static java.lang.Math.*;
public class P274A {
public static int i(String s) { return Integer.parseInt(s); }
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] arr = in.readLine().split(" ");
int n = i(arr[0]);
long k = i(arr[1]);
long[] A = new long[n];
arr = in.readLine().split(" ");
for(int i=0; i<n; i++)
A[i] = i(arr[i]);
shuffle(A);
Arrays.sort(A);
Set<Long> BAN = new HashSet<Long>();
int ans = 0;
for(int i=0; i<n; i++) {
if(!BAN.contains(A[i])) {
ans++;
BAN.add(A[i]*k);
}
}
System.out.println(ans);
}
public static void shuffle(long[] array) {
for (int i = array.length; i > 1; i--) {
long temp = array[i - 1];
int randIx = (int) (Math.random() * i);
array[i - 1] = array[randIx];
array[randIx] = temp;
}
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import com.sun.java_cup.internal.runtime.virtual_parse_stack;
import java.util.Arrays;
import java.util.Scanner;
/**
* Created by ali on 2/3/14.
*/
public class D
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
boolean [][] graph = new boolean[n][n];
for(int i = 0 ; i < m ; i++)
{
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
graph[a][b] = true;
}
int res = Integer.MAX_VALUE;
for(int center = 0 ; center < n ; center++)
{
int calc = 0;
for(int i = 0 ; i < n ; i++)
{
if(!graph[center][i])
calc++;
if(!graph[i][center])
calc++;
}
if(!graph[center][center])
calc--;
int [] match = new int[n];
Arrays.fill(match, -1);
int max = 0;
for(int i = 0 ; i < n ; i++)
if(i != center)
if(can(i, graph, new boolean[n], center, match))
max++;
int unusable = m - (2*n - 1 - calc) - max;
calc += unusable;
calc += (2*(n-1) - 2*max)/2;
res = Math.min(res, calc);
}
System.out.println(res);
}
private static boolean can(int at, boolean[][] graph, boolean[] visited, int center, int [] match)
{
if(visited[at])
return false;
visited[at] = true;
for(int to = 0 ; to < graph.length ; to++)
if(graph[at][to])
if(to != center)
if(match[to] == -1 || can(match[to], graph, visited, center, match))
{
match[to] = at;
return true;
}
return false;
}
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n=in.nextInt();
int m=in.nextInt();
int k=in.nextInt();
Integer []cap=new Integer[n];
for(int i=0;i<n;i++) {
cap[i]=in.nextInt();
}
Arrays.sort(cap, Collections.reverseOrder());
int count=0;
while(k<m && count<cap.length) {
k+=(cap[count]-1);
++count;
}
if(k>=m) {
out.println(count);
} else {
out.println(-1);
}
}
}
class InputReader {
StringTokenizer st;
BufferedReader in;
public InputReader(InputStream ins)
{
in = new BufferedReader(new InputStreamReader(ins));
}
public String nextToken()
{
while(st==null || !st.hasMoreTokens())
{
try {
st=new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(nextToken());
}
}
|
nlogn
|
257_A. Sockets
|
CODEFORCES
|
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class _909C {
private static final int MOD = 1000000007;
private static void solve(Scanner scan, PrintWriter pw) {
int n = scan.nextInt();
scan.nextLine();
// dp[i][j] is the number ways the ith statement is indented j times
int[][] dp = new int[n][n];
int[][] dpSums = new int[n][n];
dp[0][0] = 1;
for(int i = 0; i < n; i++) {
dpSums[0][i] = 1;
}
boolean lastIsSimple = scan.nextLine().equals("s");
for(int i = 1; i < n; i++) {
if(lastIsSimple) {
dp[i][0] = dpSums[i-1][n-1];
dpSums[i][0] = dp[i][0];
for(int j = 1; j < n; j++) {
dp[i][j] = (dpSums[i-1][n-1] - dpSums[i-1][j-1] + MOD) % MOD;
dpSums[i][j] = (dp[i][j] + dpSums[i][j-1]) % MOD;
}
}
else {
dp[i][0] = 0;
dpSums[i][0] = 0;
for(int j = 1; j < n; j++) {
dp[i][j] = dp[i-1][j-1];
dpSums[i][j] = (dp[i][j] + dpSums[i][j-1]) % MOD;
}
}
lastIsSimple = scan.nextLine().equals("s");
}
System.out.println(dpSums[n-1][n-1]);
}
public static void main(String[] args) {
Scanner scan = new Scanner(new BufferedInputStream(System.in, 1024 * 64));
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out, 1024 * 64));
solve(scan, pw);
pw.flush();
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
public class E {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner(System.in);
FastPrinter out = new FastPrinter(System.out);
E runner = new E();
runner.run(sc, out);
out.close();
}
int N, L;
long[][] mat;
long[] dp;
public void run(FastScanner sc, FastPrinter out) throws Exception {
L = sc.nextInt();
N = sc.nextInt();
mat = new long[N][N];
char[] arr = sc.next().toCharArray();
for (int i = 0; i < L - 1; i++) {
int cur = arr[i] - 'a';
int next = arr[i + 1] - 'a';
if (cur != next) {
mat[cur][next]++;
mat[next][cur]++;
}
}
dp = new long[1 << N];
Arrays.fill(dp, -1);
dp[(1 << N) - 1] = 0;
long ans = solve(0);
out.println(ans);
}
private long solve(int mask) {
if (dp[mask] == -1) {
long value = 0;
for (int i = 0; i < N; i++) {
if ((mask & (1 << i)) == 0) {
for (int j = 0; j < N; j++) {
if ((mask & (1 << j)) != 0) {
value += mat[i][j];
}
}
}
}
long ans = Long.MAX_VALUE;
for (int i = 0; i < N; i++) {
if ((mask & (1 << i)) == 0) {
long temp = solve(mask | 1 << i);
if (temp < ans) {
ans = temp;
}
}
}
ans += value;
dp[mask] = ans;
}
return dp[mask];
}
public void shuffle(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int r = (int) (Math.random() * arr.length);
if (i != r) {
arr[i] ^= arr[r];
arr[r] ^= arr[i];
arr[i] ^= arr[r];
}
}
}
static class FastScanner {
final private int BUFFER_SIZE = 1 << 10;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastScanner() {
this(System.in);
}
public FastScanner(InputStream stream) {
din = new DataInputStream(stream);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastScanner(String fileName) throws IOException {
Path p = Paths.get(fileName);
buffer = Files.readAllBytes(p);
bytesRead = buffer.length;
}
int[] nextIntArray(int N) throws IOException {
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = nextInt();
}
return arr;
}
String nextLine() throws IOException {
int c = read();
while (c != -1 && isEndline(c))
c = read();
if (c == -1) {
return null;
}
StringBuilder res = new StringBuilder();
do {
if (c >= 0) {
res.appendCodePoint(c);
}
c = read();
} while (!isEndline(c));
return res.toString();
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
String next() throws Exception {
int c = readOutSpaces();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
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 {
if (din == null) {
bufferPointer = 0;
bytesRead = -1;
} else {
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++];
}
private int readOutSpaces() throws IOException {
while (true) {
if (bufferPointer == bytesRead) fillBuffer();
int c = buffer[bufferPointer++];
if (!isSpaceChar(c)) {
return c;
}
}
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
public int[][] readGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception {
int[][] adj = new int[N][];
int[] numNodes = new int[N];
int[][] input = new int[M][2];
for (int i = 0; i < M; i++) {
int a = nextInt();
int b = nextInt();
if (zeroIndexed) {
a--;
b--;
}
input[i][0] = a;
input[i][1] = b;
numNodes[a]++;
if (bidirectional) numNodes[b]++;
}
for (int i = 0; i < N; i++) {
adj[i] = new int[numNodes[i]];
numNodes[i] = 0;
}
for (int i = 0; i < M; i++) {
int a = input[i][0];
int b = input[i][1];
adj[a][numNodes[a]++] = b;
if (bidirectional) adj[b][numNodes[b]++] = a;
}
return adj;
}
public int[][][] readWeightedGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception {
int[][][] adj = new int[N][][];
int[] numNodes = new int[N];
int[][] input = new int[M][3];
for (int i = 0; i < M; i++) {
int a = nextInt();
int b = nextInt();
if (zeroIndexed) {
a--;
b--;
}
int d = nextInt();
input[i][0] = a;
input[i][1] = b;
input[i][2] = d;
numNodes[a]++;
if (bidirectional) numNodes[b]++;
}
for (int i = 0; i < N; i++) {
adj[i] = new int[numNodes[i]][2];
numNodes[i] = 0;
}
for (int i = 0; i < M; i++) {
int a = input[i][0];
int b = input[i][1];
int d = input[i][2];
adj[a][numNodes[a]][0] = b;
adj[a][numNodes[a]][1] = d;
numNodes[a]++;
if (bidirectional) {
adj[b][numNodes[b]][0] = a;
adj[b][numNodes[b]][1] = d;
numNodes[b]++;
}
}
return adj;
}
}
static class FastPrinter {
static final char ENDL = '\n';
StringBuilder buf;
PrintWriter pw;
public FastPrinter(OutputStream stream) {
buf = new StringBuilder();
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public FastPrinter(String fileName) throws Exception {
buf = new StringBuilder();
pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
}
public FastPrinter(StringBuilder buf) {
this.buf = buf;
}
public void print(int a) {
buf.append(a);
}
public void print(long a) {
buf.append(a);
}
public void print(char a) {
buf.append(a);
}
public void print(char[] a) {
buf.append(a);
}
public void print(double a) {
buf.append(a);
}
public void print(String a) {
buf.append(a);
}
public void print(Object a) {
buf.append(a.toString());
}
public void println() {
buf.append(ENDL);
}
public void println(int a) {
buf.append(a);
buf.append(ENDL);
}
public void println(long a) {
buf.append(a);
buf.append(ENDL);
}
public void println(char a) {
buf.append(a);
buf.append(ENDL);
}
public void println(char[] a) {
buf.append(a);
buf.append(ENDL);
}
public void println(double a) {
buf.append(a);
buf.append(ENDL);
}
public void println(String a) {
buf.append(a);
buf.append(ENDL);
}
public void println(Object a) {
buf.append(a.toString());
buf.append(ENDL);
}
public void printf(String format, Object... args) {
buf.append(String.format(format, args));
}
public void close() {
pw.print(buf);
pw.close();
}
public void flush() {
pw.print(buf);
pw.flush();
buf.setLength(0);
}
}
}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
import java.util.Scanner;
import javafx.geometry.Point2D;
public class ChessKing {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long size = input.nextLong();
long a = input.nextLong();
long b = input.nextLong();
long sum = a+b;
long d = sum-2;
long d1 = size*2 - sum;
if(d<d1) System.out.println("White");
else if(d>d1) System.out.println("Black");
else System.out.println("White");
}
}
|
constant
|
1075_A. The King's Race
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main1 {
static int dr[] = { 0, 0, 1, -1 };
static int dc[] = { 1, -1, 0, 0 };
static boolean isValid(int r, int c) {
if (r >= n || r < 0 || c >= m || c < 0)
return false;
return true;
}
static int grid[][];
static int n, m;
public static void main(String[] args) throws IOException {
FastReader input = new FastReader();
PrintWriter out = new PrintWriter("output.txt");
n = input.nextInt();
m = input.nextInt();
grid = new int[n][m];
int k = input.nextInt();
for (int i = 0; i < n; i++) {
Arrays.fill(grid[i], Integer.MAX_VALUE);
}
Queue<Pair> q = new LinkedList<Pair>();
for (int i = 0; i < k; i++) {
int x = input.nextInt() - 1;
int y = input.nextInt() - 1;
q.add(new Pair(x, y));
grid[x][y] = 0;
while (!q.isEmpty()) {
Pair cur = q.poll();
for (int j = 0; j < dr.length; j++) {
int r = cur.x;
int c = cur.y;
int nr = r + dr[j];
int nc = c + dc[j];
int dist = grid[r][c] + 1;
if (isValid(nr, nc) && grid[nr][nc] > dist) {
grid[nr][nc] = dist;
q.add(new Pair(nr, nc));
}
}
}
}
int max = -1;
int x = -1;
int y = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] > max) {
max = grid[i][j];
x = i + 1;
y = j + 1;
}
}
}
out.println(x + " " + y);
out.flush();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File("input.txt")));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
String str = "";
str = br.readLine();
return str;
}
}
static class con {
static int IINF = (int) 1e9;
static int _IINF = (int) -1e9;
static long LINF = (long) 1e15;
static long _LINF = (long) -1e15;
static double EPS = 1e-9;
}
static class Triple implements Comparable<Triple> {
int x;
int y;
int z;
Triple(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int compareTo(Triple o) {
if (x == o.x && y == o.y)
return z - o.z;
if (x == o.x)
return y - o.y;
return x - o.x;
}
}
static class Pair implements Comparable<Pair> {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if (x == o.x)
return y - o.y;
return x - o.x;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
static void shuffle(int[] a) {
for (int i = 0; i < a.length; i++) {
int r = i + (int) (Math.random() * (a.length - i));
int tmp = a[r];
a[r] = a[i];
a[i] = tmp;
}
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
import javax.lang.model.util.ElementScanner6;
import java.io.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(inp, out);
out.close();
}
static class Solver {
class pair implements Comparable<pair>{
int i;
long dist;
public pair(int i,long dist)
{
this.i=i;
this.dist=dist;
}
public int compareTo(pair p)
{
return Long.compare(this.dist,p.dist);
}
}
class Node implements Comparable < Node > {
int i;
int cnt;
Node(int i, int cnt) {
this.i = i;
this.cnt = cnt;
}
public int compareTo(Node n) {
if (this.cnt == n.cnt) {
return Integer.compare(this.i, n.i);
}
return Integer.compare(this.cnt, n.cnt);
}
}
public boolean done(int[] sp, int[] par) {
int root;
root = findSet(sp[0], par);
for (int i = 1; i < sp.length; i++) {
if (root != findSet(sp[i], par))
return false;
}
return true;
}
public int findSet(int i, int[] par) {
int x = i;
boolean flag = false;
while (par[i] >= 0) {
flag = true;
i = par[i];
}
if (flag)
par[x] = i;
return i;
}
public void unionSet(int i, int j, int[] par) {
int x = findSet(i, par);
int y = findSet(j, par);
if (x < y) {
par[y] = x;
} else {
par[x] = y;
}
}
public long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
public boolean isPrime(int n)
{
for(int i=2;i<n;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
public void minPrimeFactor(int n, int[] s) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
s[1] = 1;
s[2] = 2;
for (int i = 4; i <= n; i += 2) {
prime[i] = false;
s[i] = 2;
}
for (int i = 3; i <= n; i += 2) {
if (prime[i]) {
s[i] = i;
for (int j = 2 * i; j <= n; j += i) {
prime[j] = false;
s[j] = i;
}
}
}
}
public void findAllPrime(int n, ArrayList < Node > al, int s[]) {
int curr = s[n];
int cnt = 1;
while (n > 1) {
n /= s[n];
if (curr == s[n]) {
cnt++;
continue;
}
Node n1 = new Node(curr, cnt);
al.add(n1);
curr = s[n];
cnt = 1;
}
}
public int binarySearch(int n, int k) {
int left = 1;
int right = 100000000 + 5;
int ans = 0;
while (left <= right) {
int mid = (left + right) / 2;
if (n / mid >= k) {
left = mid + 1;
ans = mid;
} else {
right = mid - 1;
}
}
return ans;
}
public boolean checkPallindrom(String s) {
char ch[] = s.toCharArray();
for (int i = 0; i < s.length() / 2; i++) {
if (ch[i] != ch[s.length() - 1 - i])
return false;
}
return true;
}
public void remove(ArrayList < Integer > [] al, int x) {
for (int i = 0; i < al.length; i++) {
for (int j = 0; j < al[i].size(); j++) {
if (al[i].get(j) == x)
al[i].remove(j);
}
}
}
public long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public void printDivisors(long n, ArrayList < Long > al) {
// Note that this loop runs till square root
for (long i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
// If divisors are equal, print only one
if (n / i == i) {
al.add(i);
} else // Otherwise print both
{
al.add(i);
al.add(n / i);
}
}
}
}
public static long constructSegment(long seg[], long arr[], int low, int high, int pos) {
if (low == high) {
seg[pos] = arr[low];
return seg[pos];
}
int mid = (low + high) / 2;
long t1 = constructSegment(seg, arr, low, mid, (2 * pos) + 1);
long t2 = constructSegment(seg, arr, mid + 1, high, (2 * pos) + 2);
seg[pos] = t1 + t2;
return seg[pos];
}
public static long querySegment(long seg[], int low, int high, int qlow, int qhigh, int pos) {
if (qlow <= low && qhigh >= high) {
return seg[pos];
} else if (qlow > high || qhigh < low) {
return 0;
} else {
long ans = 0;
int mid = (low + high) / 2;
ans += querySegment(seg, low, mid, qlow, qhigh, (2 * pos) + 1);
ans += querySegment(seg, mid + 1, high, qlow, qhigh, (2 * pos) + 2);
return ans;
}
}
public static int lcs(char[] X, char[] Y, int m, int n) {
if (m == 0 || n == 0)
return 0;
if (X[m - 1] == Y[n - 1])
return 1 + lcs(X, Y, m - 1, n - 1);
else
return Integer.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));
}
public static long recursion(long start, long end, long cnt[], int a, int b) {
long min = 0;
long count = 0;
int ans1 = -1;
int ans2 = -1;
int l = 0;
int r = cnt.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (cnt[mid] >= start) {
ans1 = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
l = 0;
r = cnt.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (cnt[mid] <= end) {
ans2 = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
if (ans1 == -1 || ans2 == -1 || ans2 < ans1) {
// System.out.println("min1 "+min);
min = a;
return a;
} else {
min = b * (end - start + 1) * (ans2 - ans1 + 1);
}
if (start == end) {
// System.out.println("min "+min);
return min;
}
long mid = (end + start) / 2;
min = Long.min(min, recursion(start, mid, cnt, a, b) + recursion(mid + 1, end, cnt, a, b));
// System.out.println("min "+min);
return min;
}
public int dfs_util(ArrayList < Integer > [] al, boolean vis[], int x, int[] s, int lvl[]) {
vis[x] = true;
int cnt = 1;
for (int i = 0; i < al[x].size(); i++) {
if (!vis[al[x].get(i)]) {
lvl[al[x].get(i)] = lvl[x] + 1;
cnt += dfs_util(al, vis, al[x].get(i), s, lvl);
}
}
s[x] = cnt;
return s[x];
}
public void dfs(ArrayList[] al, int[] s, int[] lvl) {
boolean vis[] = new boolean[al.length];
for (int i = 0; i < al.length; i++) {
if (!vis[i]) {
lvl[i] = 1;
dfs_util(al, vis, i, s, lvl);
}
}
}
public int[] computeLps(String s)
{
int ans[] =new int[s.length()];
char ch[] = s.toCharArray();
int n = s.length();
int i=1;
int len=0;
ans[0]=0;
while(i<n)
{
if(ch[i]==ch[len])
{
len++;
ans[i]=len;
i++;
}
else
{
if(len!=0)
{
len=ans[len-1];
}
else
{
ans[i]=len;
i++;
}
}
}
return ans;
}
private void solve(InputReader inp, PrintWriter out1) {
int n = inp.nextInt();
int m = inp.nextInt();
long k = inp.nextLong();
long arr[] = new long[n];
for(int i=0;i<n;i++)
{
arr[i] = inp.nextLong();
}
long ans=0;
for(int i=0;i<m;i++)
{
long sum=0;
for(int j=i;j<n;j++)
{
if(j%m==i)
{
if(sum<0)
{
sum=0;
}
sum-=k;
}
sum+=arr[j];
ans=Math.max(ans,sum);
}
}
System.out.println(ans);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
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());
}
}
}
class ele implements Comparable < ele > {
int value;
int i;
boolean flag;
public ele(int value, int i) {
this.value = value;
this.i = i;
this.flag = false;
}
public int compareTo(ele e) {
return Integer.compare(this.value, e.value);
}
}
|
quadratic
|
1197_D. Yet Another Subarray Problem
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main
{
static MyScanner scan;
static PrintWriter pw;
static long MOD = 1_000_000_007;
static long INF = 2_000_000_000_000_000_000L;
static long inf = 2_000_000_000;
public static void main(String[] args) {
new Thread(null, null, "_", 1 << 27) {
public void run() {
try {
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static void solve() throws java.lang.Exception {
//initIo(true, "");
initIo(false, "");
StringBuilder sb = new StringBuilder();
int t = ni();
while (t-->0) {
int n = ni();
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
ArrayList<Integer> prev = new ArrayList<>();
prev.add(1);
ni();
for(int i=1;i<n;i++) {
int x = ni();
ans.add(prev);
ArrayList<Integer> next = new ArrayList<>();
int idx = -1;
for(int j=prev.size()-1;j>=0;--j) {
if(prev.get(j)==x-1) {
for(int k=0;k<j;++k) {
next.add(prev.get(k));
}
next.add(x);
idx = j;
break;
}
}
if(idx==-1) {
assert_in_range("x", x, 1, 1);
for(int e : prev) {
next.add(e);
}
next.add(1);
}
prev = next;
}
ans.add(prev);
for(ArrayList<Integer> list: ans) {
print(list);
}
}
pw.flush();
pw.close();
}
static void print(ArrayList<Integer> list) {
for(int i=0;i<list.size();i++) {
pw.print(list.get(i));
if(i==list.size()-1) {
continue;
}
pw.print(".");
}
pl();
}
static void assert_in_range(String varName, int n, int l, int r) {
if (n >=l && n<=r) return;
System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r);
System.exit(1);
}
static void assert_in_range(String varName, long n, long l, long r) {
if (n>=l && n<=r) return;
System.out.println(varName + " is not in range. Actual: "+n+" l : "+l+" r: "+r);
System.exit(1);
}
static void initIo(boolean isFileIO, String suffix) throws IOException {
scan = new MyScanner(isFileIO, suffix);
if(isFileIO) {
pw = new PrintWriter("/Users/dsds/Desktop/output"+suffix+".txt");
}
else {
pw = new PrintWriter(System.out, true);
}
}
static int ni() throws IOException
{
return scan.nextInt();
}
static long nl() throws IOException
{
return scan.nextLong();
}
static double nd() throws IOException
{
return scan.nextDouble();
}
static String ne() throws IOException
{
return scan.next();
}
static String nel() throws IOException
{
return scan.nextLine();
}
static void pl()
{
pw.println();
}
static void p(Object o)
{
pw.print(o+" ");
}
static void pl(Object o)
{
pw.println(o);
}
static void psb(StringBuilder sb)
{
pw.print(sb);
}
static void pa(String arrayName, Object arr[])
{
pl(arrayName+" : ");
for(Object o : arr)
p(o);
pl();
}
static void pa(String arrayName, int arr[])
{
pl(arrayName+" : ");
for(int o : arr)
p(o);
pl();
}
static void pa(String arrayName, long arr[])
{
pl(arrayName+" : ");
for(long o : arr)
p(o);
pl();
}
static void pa(String arrayName, double arr[])
{
pl(arrayName+" : ");
for(double o : arr)
p(o);
pl();
}
static void pa(String arrayName, char arr[])
{
pl(arrayName+" : ");
for(char o : arr)
p(o);
pl();
}
static void pa(String arrayName, TreeSet<Integer> set)
{
pl(arrayName+" : ");
for(Object o : set)
p(o);
pl();
}
static void pa(String arrayName, boolean arr[])
{
pl(arrayName+" : ");
for(boolean o : arr)
p(o);
pl();
}
static void pa(String listName, List list)
{
pl(listName+" : ");
for(Object o : list)
p(o);
pl();
}
static void pa(String arrayName, Object[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(Object o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, int[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(int o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, long[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(long o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, char[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(char o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, double[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(double o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, boolean[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(boolean o : arr[i])
p(o);
pl();
}
}
static class MyScanner
{
BufferedReader br;
StringTokenizer st;
MyScanner(boolean readingFromFile, String suffix) throws IOException
{
if(readingFromFile) {
br = new BufferedReader(new FileReader("/Users/ddfds/Desktop/input"+suffix+".txt"));
}
else {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String nextLine()throws IOException
{
return br.readLine();
}
String next() throws IOException
{
if(st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException
{
return Integer.parseInt(next());
}
long nextLong() throws IOException
{
return Long.parseLong(next());
}
double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
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.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prakharjain
*/
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);
F2SameSumBlocksHard solver = new F2SameSumBlocksHard();
solver.solve(1, in, out);
out.close();
}
static class F2SameSumBlocksHard {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
long[] a = in.nextLongArray(n);
long[] p = in.calculatePrefixSum(a);
Map<Long, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
long sum = 0;
for (int j = i; j < n; j++) {
sum += a[j];
map.merge(sum, 1, (x, y) -> x + y);
}
}
List<sum> sums = new ArrayList<>();
for (long sum : map.keySet()) {
sums.add(new sum(sum, map.get(sum)));
}
sums.sort((x, y) -> y.c - x.c);
int ans = -1;
int[] fca = null;
long mxsum = -1;
for (int i = 0; i < sums.size(); i++) {
sum cs = sums.get(i);
long sum = cs.sum;
long c = cs.c;
if (c < ans) {
continue;
}
Map<Long, Integer> lm = new HashMap<>();
int[] ca = new int[n];
lm.put(0l, -1);
for (int j = 0; j < n; j++) {
long val = p[j];
if (j > 0) {
ca[j] = ca[j - 1];
}
long req = val - sum;
if (lm.containsKey(req)) {
int li = lm.get(req);
if (li == -1)
ca[j] = Math.max(1, ca[j]);
else
ca[j] = Math.max(1 + ca[li], ca[j]);
}
lm.put(val, j);
}
if (ca[n - 1] > ans) {
ans = ca[n - 1];
mxsum = sum;
fca = ca;
}
}
List<Integer> al = new ArrayList<>();
long sum = 0;
for (int i = n - 1; i >= 0; i--) {
if (i > 0 && fca[i] != fca[i - 1]) {
sum = 0;
al.add(i + 1);
do {
sum += a[i];
i--;
} while (i >= 0 && sum != mxsum);
i++;
al.add(i + 1);
} else if (i == 0) {
if (a[i] == mxsum) {
al.add(i + 1);
al.add(i + 1);
}
}
}
out.println(al.size() / 2);
for (int i = al.size() - 1; i >= 0; i -= 2) {
out.println(al.get(i) + " " + al.get(i - 1));
}
}
class sum {
long sum;
int c;
public sum(long sum, int c) {
this.sum = sum;
this.c = c;
}
}
}
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 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 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 long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] calculatePrefixSum(long[] a) {
int n = a.length;
long[] prefixSum = new long[n];
prefixSum[0] = a[0];
for (int i = 1; i < n; i++) {
prefixSum[i] = prefixSum[i - 1] + a[i];
}
return prefixSum;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class SonyaAndHotels {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int d = sc.nextInt();
int[] locs = new int[n];
for (int i = 0; i < n; i++) {
locs[i] = sc.nextInt();
}
Arrays.sort(locs);
int count = 2;
for (int i = 0; i < locs.length-1; i++) {
if(locs[i+1]-locs[i]==2*d){
count++;
}else if(locs[i+1]-locs[i]>2*d){
count+=2;
}
}
System.out.println(count);
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.util.Scanner;
public class AlexAndARhombus {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println(n*n+(n-1)*(n-1));
sc.close();
}
}
|
constant
|
1180_A. Alex and a Rhombus
|
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.PriorityQueue;
import java.util.Random;
import java.util.StringTokenizer;
public class Solution{
static FastScanner fs = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
static int n, d;
public static void main(String[] args) throws IOException {
// FastScanner fs = new FastScanner();
// PrintWriter out = new PrintWriter(System.out);
int tt = 1;
while(tt-->0) {
n = fs.nextInt();
int l = 1, r = 1 + n/2;
d = getB(l);
if(d%2!=0) {
out.println("! -1");
out.flush();
return;
}
if(d==0) {
out.println("! 1");
out.flush();
return;
}
while(l<r) {
int mid = (l+r)/2;
if(check(mid)) {
l = mid + 1;
}
else {
r = mid;
}
int f = 1;
}
out.println("! "+l);
}
out.close();
}
static boolean check(int i) {
int k = getB(i);
if(sig(d)==sig(k)) {
return true;
}
return false;
}
static int getB(int i) {
out.println("? "+i);
out.flush();
int x1 = fs.nextInt();
int j = i + n/2;
if(j>n) j -= n;
out.println("? "+j);
out.flush();
int x2 = fs.nextInt();
return x1 - x2;
}
static int sig(int x) {
if(x>0) return 1;
else if(x<0) return -1;
return 0;
}
static final Random random=new Random();
static <T> void shuffle(T[] arr) {
int n = arr.length;
for(int i=0;i<n;i++ ) {
int k = random.nextInt(n);
T temp = arr[k]; arr[k] = arr[i]; arr[i] = temp;
}
}
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n); long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void reverse(int[] arr, int l, int r) {
for(int i=l;i<l+(r-l)/2;i++){
int temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp;
}
}
static void reverse(long[] arr, int l, int r) {
for(int i=l;i<l+(r-l)/2;i++){
long temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp;
}
}
static <T> void reverse(T[] arr, int l, int r) {
for(int i=l;i<l+(r-l)/2;i++) {
T temp = arr[i]; arr[i] = arr[r-i+l-1]; arr[r-i+l-1] = temp;
}
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next(){
while(!st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
} catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] readArray(int n){
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().toCharArray()[0];
}
}
}
|
logn
|
1019_B. The hat
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
long n = Long.parseLong(st.nextToken());
long s = Long.parseLong(st.nextToken());
long posible = binarySearch(n,s);
long dig, answer;
long i, cmed;
for (i = posible; i >= 0; i--) {
dig = 0;
cmed = i;
while (cmed > 0) {
dig = dig+cmed%10;
cmed/=10;
}
if (i-dig < s) {
break;
}
}
answer = n-i;
System.out.println(answer);
}
private static long binarySearch(long n, long s){
long med=n, l = 0, r = n, cmed, dig;
while(l<=r){
med = (l+r)/2;
cmed = med;
dig = 0;
while (cmed > 0) {
dig = dig+cmed%10;
cmed/=10;
}
if (med-dig == s) {
break;
}else {
if (med-dig > s) {
r = med-1;
}else {
l = med+1;
}
}
//System.out.println(med);
}
return med;
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class B1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int testCount = in.nextInt();
for (int test = 0; test < testCount; test++) {
String src = in.next();
if (src.matches("^R\\d+C\\d+$")) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(src);
m.find();
int r = Integer.parseInt(m.group(0));
m.find();
int c = Integer.parseInt(m.group(0));
System.out.println(toBase26(c) + r);
} else {
Pattern p = Pattern.compile("[A-Z]+");
Matcher m = p.matcher(src);
m.find();
String c = m.group(0);
p = Pattern.compile("\\d+");
m = p.matcher(src);
m.find();
int r = Integer.parseInt(m.group(0));
System.out.println("R" + r + "C" + toBase10(c));
}
}
}
private static String toBase26(int n) {
String res = "";
do {
n -= 1;
res = (char)('A' + (n % 26)) + res;
n /= 26;
} while (n > 0);
return res;
}
private static int toBase10(String x) {
int n = 0;
char[] digits = x.toCharArray();
for (int i = 0; i < digits.length; i++) {
n *= 26;
n += digits[i] - 'A' + 1;
}
return n;
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import static java.lang.Math.*;
import java.io.*;
import java.util.*;
public class Template {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String next() {
while (st==null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (Exception e) {}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
class Point implements Comparable<Point> {
int x, y;
public Point(int x, int y) {
this.x=x;
this.y=y;
}
public int compareTo(Point o) {
return x-o.x;
}
public String toString() {
return x + " " + y;
}
}
public void run() throws Exception {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
Long start = System.currentTimeMillis();
int n = nextInt();
long k = nextLong();
long[] a = new long[n];
TreeMap<Long, Integer> st = new TreeMap<Long, Integer>();
for (int i=0; i<n; i++) {
a[i] = nextLong();
st.put(a[i], 1);
}
Arrays.sort(a);
for (int i=0; i<n; i++) {
if (a[i] % k == 0) {
long x = a[i] / k;
if (st.containsKey(x)) {
int y = st.get(x);
st.remove(a[i]);
st.put(a[i], y + 1);
}
}
}
int ans = 0;
for (int i=0; i<n; i++) {
//System.err.println(a[n-i-1] + " " + st.get(a[n-i-1]));
ans+=(st.get(a[n-i-1]) + 1) / 2;
if (a[n-i-1] % k == 0) {
long x = a[n-i-1] / k;
if (st.containsKey(x)) {
//System.err.println(x);
st.remove(x);
st.put(x, 0);
}
}
}
out.println(ans);
Long end = System.currentTimeMillis();
out.close();
}
public static void main(String[] args) throws Exception {
new Template().run();
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class B {
static int first(int n)
{
int res = 0;
while(n > 0 && (n & 1) == 0){
n >>= 1;
res++;
}
return res;
}
public static void main(String[] args) throws Exception
{
Scanner bf = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = bf.nextInt(), m = bf.nextInt();
ArrayList<Integer> [] adjList = new ArrayList[n];
for (int i = 0; i < adjList.length; i++)
{
adjList[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i++)
{
int u = bf.nextInt()-1, v = bf.nextInt()-1;
adjList[u].add(v);
adjList[v].add(u);
}
long [][] memo = new long[(1<<n)][n];
for (int i = 0; i < n; i++)
{
memo[1<<i][i] = 1;
}
long ans = 0;
for (int i = 1; i < 1<<n; i++)
{
if(Integer.bitCount(i) == 1) continue;
for (int j = 0; j < n; j++)
{
if((i & (1<<j)) == 0 || j == first(i)) continue;
for(int v:adjList[j])
memo[i][j] += memo[i^(1<<j)][v];
}
}
for (int i = 1; i < 1<<n; i++)
{
if(Integer.bitCount(i) < 3) continue;
int t = first(i);
for (int j = 0; j < n; j++)
{
if(adjList[j].contains(t))
ans += memo[i][j];
}
}
out.println(ans/2);
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s)
{
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader fileReader)
{
br = new BufferedReader(fileReader);
}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
public String nextLine() throws IOException
{
return br.readLine();
}
public boolean ready() throws IOException
{
return br.ready();
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
public class Solver {
StringTokenizer st;
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws NumberFormatException,
IOException {
Solver solver = new Solver();
solver.open();
long time = System.currentTimeMillis();
solver.solve();
if (!"true".equals(System.getProperty("ONLINE_JUDGE"))) {
System.out.println("Spent time: "
+ (System.currentTimeMillis() - time));
}
solver.close();
}
public void open() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
public String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
public void solve() throws NumberFormatException, IOException {
int n = nextInt();
int k = nextInt();
int[] ar = new int[n];
int[] ex = new int[100005];
int dif = 0;
for(int i=0;i<n;i++){
int tmp = nextInt();
ar[i] = tmp;
if (ex[tmp]++==0){
dif++;
}
}
if (dif<k){
out.println("-1 -1");
return;
}
Arrays.fill(ex, 0);
dif = 0;
int right = 0;
while(dif<k){
int tmp = ar[right];
if(ex[tmp]++==0){
dif++;
}
right++;
}
int left = 0;
while (ex[ar[left]]-- > 1) left++;
out.println((left+1)+" "+right);
}
public void close() {
out.flush();
out.close();
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.math.*;
import static java.util.stream.Collectors.*;
import static java.util.Map.Entry.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws Exception
{
final long mod=(long) (1e9+7);
final long mod1=(long) 998244353;
Reader s=new Reader();
PrintWriter pt=new PrintWriter(System.out);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int T=s.nextInt();
// int T=Integer.parseInt(br.readLine());
// int T=1;
while(T-->0)
{
int n=s.nextInt();
int arr[]=new int[n];
int brr[]=new int[n];
int e=-1;
for(int i=0;i<n;i++) {
arr[i]=s.nextInt();
if(e==-1) {
brr[e+1]=arr[i];
e++;
}
else {
if(arr[i]==1) {
e++;
brr[e]=arr[i];
}
else {
int j=e;
for(j=e;j>=0;j--) {
if((arr[i]-1)==brr[j])
break;
}
e=j;
brr[e]=arr[i];
}
}
pt.print(brr[0]);
for(int j=1;j<=e;j++) {
pt.print("."+brr[j]);
}
pt.println();
}
}
pt.close();
}
static boolean allOne(String str) {
for(int i=0;i<str.length();i++) {
if(str.charAt(i)=='0')
return false;
}
return true;
}
static boolean isPartition(int arr[], int n) {
int sum = 0;
int i, j;
// Calculate sum of all elements
for (i = 0; i < n; i++)
sum += arr[i];
if (sum % 2 != 0)
return false;
boolean part[][]=new boolean[sum/2+1][n+1];
// initialize top row as true
for (i = 0; i <= n; i++)
part[0][i] = true;
// initialize leftmost column, except part[0][0], as false
for (i = 1; i <= sum / 2; i++)
part[i][0] = false;
// Fill the partition table in bottom up manner
for (i = 1; i <= sum / 2; i++) {
for (j = 1; j <= n; j++) {
part[i][j] = part[i][j - 1];
if (i >= arr[j - 1])
part[i][j] = part[i][j]
|| part[i - arr[j - 1]][j - 1];
}
}
return part[sum / 2][n];
}
static int setBit(int S, int j) { return S | 1 << j; }
static int clearBit(int S, int j) { return S & ~(1 << j); }
static int toggleBit(int S, int j) { return S ^ 1 << j; }
static boolean isOn(int S, int j) { return (S & 1 << j) != 0; }
static int turnOnLastZero(int S) { return S | S + 1; }
static int turnOnLastConsecutiveZeroes(int S) { return S | S - 1; }
static int turnOffLastBit(int S) { return S & S - 1; }
static int turnOffLastConsecutiveBits(int S) { return S & S + 1; }
static int lowBit(int S) { return S & -S; }
static int setAll(int N) { return (1 << N) - 1; }
static int modulo(int S, int N) { return (S & N - 1); } //S%N, N is a power of 2
static boolean isPowerOfTwo(int S) { return (S & S - 1) == 0; }
static boolean isWithin(long x, long y, long d, long k) {
return x*k*x*k + y*k*y*k <= d*d;
}
static long modFact(long n,
long p)
{
if (n >= p)
return 0;
long result = 1;
for (int i = 1; i <= n; i++)
result = (result * i) % p;
return result;
}
static int sum(int[] arr, int n)
{
int inc[]=new int[n+1];
int dec[]=new int[n+1];
inc[0] = arr[0];
dec[0] = arr[0];
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (arr[j] > arr[i]) {
dec[i] = max(dec[i], inc[j] + arr[i]);
}
else if (arr[i] > arr[j]) {
inc[i] = max(inc[i], dec[j] + arr[i]);
}
}
}
return max(inc[n - 1], dec[n - 1]);
}
static long nc2(long a) {
return a*(a-1)/2;
}
public static int numberOfprimeFactors(int n)
{
// Print the number of 2s that divide n
HashSet<Integer> hs = new HashSet<Integer>();
while (n%2==0)
{
hs.add(2);
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)
{
hs.add(i);
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
hs.add(n);
return hs.size();
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void reverse(int arr[],int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
static void reverse(long arr[],int start, int end)
{
long temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
static boolean isPrime(int 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 (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int p2(int n) {
int k=0;
while(n>1) {
if(n%2!=0)
return k;
n/=2;
k++;
}
return k;
}
static boolean isp2(int n) {
while(n>1) {
if(n%2==1)
return false;
n/=2;
}
return true;
}
static int binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
return mid;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
return -1;
}
static void print(int a[][]) {
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
}
static int max (int x, int y) {
return (x > y)? x : y;
}
static int search(Pair[] p, Pair pair) {
int l=0, r=p.length;
while (l <= r) {
int m = l + (r - l) / 2;
if (p[m].compareTo(pair)==0)
return m;
if (p[m].compareTo(pair)<0)
l = m + 1;
else
r = m - 1;
}
return -1;
}
static void pa(int a[])
{
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
static void pa(long a[])
{
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
static void reverseArray(int arr[],
int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
static boolean isPalindrome(String s) {
int l=s.length();
for(int i=0;i<l/2;i++)
{
if(s.charAt(i)!=s.charAt(l-i-1))
return false;
}
return true;
}
static long nc2(long n, long m) {
return (n*(n-1)/2)%m;
}
static long c(long a) {
return a*(a+1)/2;
}
static int next(long[] arr, long target)
{
int start = 0, end = arr.length - 1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
// Move to right side if target is
// greater.
if (arr[mid] < target) {
start = mid + 1;
}
// Move left side.
else {
ans = mid;
end = mid - 1;
}
}
return ans;
}
static int prev(long[] arr, long target)
{
int start = 0, end = arr.length - 1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
// Move to left side if target is
// lesser.
if (arr[mid] > target) {
end = mid - 1;
}
// Move right side.
else {
ans = mid;
start = mid + 1;
}
}
return ans;
}
static long power(long x, long y, long p)
{
long res = 1;
x = x % p;
while (y > 0)
{
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long modInverse(long n, long p)
{
return power(n, p-2, p);
}
static long nCrModP(long n, long r,
long p)
{
if(r>n)
return 0;
if (r == 0)
return 1;
long[] fac = new long[(int) (n+1)];
fac[0] = 1;
for (int i = 1 ;i <= n; i++)
fac[i] = fac[i-1] * i % p;
return (fac[(int) n]* modInverse(fac[(int) r], p)
% p * modInverse(fac[(int) (n-r)], p)
% p) % p;
}
static String reverse(String str)
{
return new StringBuffer(str).reverse().toString();
}
static long fastpow(long x, long y, long m)
{
if (y == 0)
return 1;
long p = fastpow(x, y / 2, m) % m;
p = (p * p) % m;
if (y % 2 == 0)
return p;
else
return (x * p) % m;
}
static boolean isPerfectSquare(long l)
{
return Math.pow((long)Math.sqrt(l),2)==l;
}
static void merge(long[] arr, int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long [n1];
long R[] = new long [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
static void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
static void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
static void sort(long arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
static class Pair implements Comparable<Pair>{
int a;
int b;
Pair(int a,int b){
this.a=a;
this.b=b;
}
public int compareTo(Pair p){
if(a>p.a)
return 1;
if(a==p.a)
return (b-p.b);
return -1;
}
}
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[128]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.*;
import java.util.*;
import java.lang.*;
public class A {
private BufferedReader in;
private StringTokenizer st;
void solve() throws IOException{
int len = 0;
String x = next();
HashSet<String> h = new HashSet<String>();
for (int i = 0; i < x.length(); i++) {
for (int j = i+1; j <= x.length(); j++) {
String y = x.substring(i,j);
if(h.contains(y)){
if(y.length()>len) len = y.length();
}
else h.add(y);
}
}
System.out.println(len);
}
A() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
eat("");
solve();
}
private void eat(String str) {
st = new StringTokenizer(str);
}
String next() throws IOException {
while (!st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
eat(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) throws IOException {
new A();
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {
}
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
private void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = nextInt();
int m[] = new int[n];
for(int i = 0; i < n; i++)
m[i] = nextInt();
sort(m);
m[n - 1] = m[n - 1] != 1 ? 1 : 2;
sort(m);
for(int i = 0; i < n; i++){
if(i != 0) out.print(" ");
out.print(m[i]);
}
out.println();
in.close();
out.close();
}
void chk(boolean b) {
if (b)
return;
System.out.println(new Error().getStackTrace()[1]);
exit(999);
}
void deb(String fmt, Object... args) {
System.out.printf(Locale.US, fmt + "%n", args);
}
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int n=ni(),m=ni();
int a[][]=new int[n+1][m+1];
for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) a[i][j]=ni();
if(n==1){
int mn=Integer.MAX_VALUE;
for(int i=1;i<m;i++) mn=Math.min(mn,Math.abs(a[1][i]-a[1][i+1]));
pw.println(mn) ;
return ;
}
mn1=new int[n+1][n+1];
mn2=new int[n+1][n+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j) continue;
mn1[i][j]=mn2[i][j]=Integer.MAX_VALUE;
for(int k=1;k<=m;k++){
mn1[i][j]=Math.min(mn1[i][j],Math.abs(a[i][k]-a[j][k]));
// if(i==3 && j==4) pw.println(a[i][k]+" "+a[j][k]);
}
for(int k=1;k<m;k++){
mn2[i][j]=Math.min(mn2[i][j],Math.abs(a[i][k+1]-a[j][k]));
}
//if(m==1) mn2[i][j]=0;
}
}
// pw.println(mn1[3][4]);
dp=new int[17][1<<16][17];
for(int i=1;i<17;i++) for(int j=0;j<(1<<16);j++) Arrays.fill(dp[i][j],-1);
int ans=0;
for(int i=1;i<=n;i++){
ans=Math.max(ans,go(2,1<<(i-1),i,i,n));
}
pw.println(ans);
}
int mn1[][],mn2[][];
int dp[][][];
int go(int i,int mask,int prev,int first,int n){
if(i>n){
// if(mn2[first][prev]==0) pw.println(prev+" "+first+" "+mn2[first][prev]);
return mn2[first][prev];
}
if(dp[first][mask][prev]!=-1) return dp[first][mask][prev];
int cc=0;
for(int k=1;k<=n;k++){
if((mask&(1<<(k-1)))==0){
cc=Math.max(cc,Math.min(mn1[prev][k],go(i+1,mask|(1<<(k-1)),k,first,n)));
//if(mn1[prev][k]==0) pw.println(mn1[prev][k]+" "+prev+" "+k);
}
}
dp[first][mask][prev]=cc;
return cc;
}
long M= (long)1e9+7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Main().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.awt.Point;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
public class C {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new FileReader(new File("input.txt")));
PrintWriter out = new PrintWriter(new File("output.txt"));
int n = in.nextInt();
int m = in.nextInt();
int[][] T = new int[n][m];
int k = in.nextInt();
int[] X = new int[k];
int[] Y = new int[k];
for (int i = 0; i < k; i++) {
X[i] = in.nextInt() - 1;
Y[i] = in.nextInt() - 1;
}
int max = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
int min = Integer.MAX_VALUE;
for (int ii = 0; ii < k; ii++)
min = Math.min(min,
Math.abs(i - X[ii]) + Math.abs(j - Y[ii]));
max = Math.max(max, T[i][j] = min);
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (T[i][j] == max) {
out.println((i + 1) + " " + (j + 1));
out.flush();
return;
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A{
static int n,m,start;
static boolean [][] adj;
static long [][] mem;
public static void main(String[] args)throws Throwable {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
m=sc.nextInt();
adj=new boolean [n][n];
for(int i=0;i<m;i++){
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
adj[u][v]=true;
adj[v][u]=true;
}
mem=new long [n+1][(1<<n)];
for(int i=0;i<=n;i++)
Arrays.fill(mem[i], -1);
long ans=0;
for(int i=0;i<n;i++){
start=i;
ans+=dp(i, (1<<i));
}
System.out.println(ans/2);
}
public static long dp(int i,int msk){
if(mem[i][msk]!=-1)
return mem[i][msk];
long ans=0;
if(adj[i][start] && Integer.bitCount(msk)>2)
ans++;
for(int j=start+1;j<n;j++){
if(adj[i][j] && (msk & (1<<j))==0){
ans+=dp(j, msk | (1<<j));
}
}
return mem[i][msk]=ans;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nova
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
sum += a[i];
}
Arrays.sort(a);
int res = 0;
int mySum = 0;
int hisSum = sum;
for (int i = n - 1; i >= 0; i--) {
mySum += a[i];
hisSum -= a[i];
res++;
if (mySum > hisSum) break;
}
out.println(res);
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
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++) {
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
|
nlogn
|
160_A. Twins
|
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);
}
}
|
cubic
|
1185_G2. Playlist for Polycarp (hard version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CF125A {
private void work() throws IOException {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(
System.in)));
int n = sc.nextInt();
System.out.printf("%d %d %d\n", 0, 0, n);
System.out.close();
}
public static void main(String[] args) throws IOException {
new CF125A().work();
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.math.BigDecimal;
import java.util.*;
import java.math.BigInteger;
public class Main {
static Long[] a = new Long[205000];
static Long[] postfix=new Long[205000];
static HashMap<Long,Long> check=new HashMap<Long,Long>();
public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
long k, j, p,sum,equal,bigone,lessone,cnt;
BigInteger ans;
int i,n;
while (cin.hasNext()) {
n=cin.nextInt();
check.clear();
for(i=1;i<=n;i++)
{
a[i]=cin.nextLong();
}
postfix[n+1]=0L;
for(i=n;i>=1;i--) {
postfix[i] = postfix[i + 1] + a[i];
if (check.containsKey(a[i]) == true) {
Long v = check.get(a[i]);
v += 1;
check.put(a[i], v);
}
else
check.put(a[i],1L);
}
ans=BigInteger.ZERO;
for(i=1;i<n;i++){
Long v=check.get(a[i]);
v--;
check.put(a[i],v);
equal=check.get(a[i]);
bigone=0L;
lessone=0L;
if(check.containsKey(a[i]+1L)==true)
bigone=check.get(a[i]+1L);
if(check.containsKey(a[i]-1L)==true)
lessone=check.get(a[i]-1L);
sum=postfix[i]-bigone*(a[i]+1L)-lessone*(a[i]-1L)-equal*a[i]-a[i];
cnt=n-i-bigone-lessone-equal;
ans=ans.add(BigInteger.valueOf(a[i]*cnt).subtract(BigInteger.valueOf(sum)));
}
System.out.println(ans.multiply(BigInteger.valueOf(-1)));
}
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class A {
private static final int INF = (int) 1e9 + 7;
public static void main(String[] args) {
FastScanner fs=new FastScanner();
PrintWriter pr = new PrintWriter(System.out);
// int T=fs.nextInt();
// for (int tt=1; tt<=T; tt++) {
int n = fs.nextInt(), m = fs.nextInt(), k = fs.nextInt();
int[][] right = new int[n][m -1], down = new int[n - 1][m];
for(int i = 0; i < n; i++) right[i] = fs.readArray(m - 1);
for(int i = 0; i < n - 1; i++) down[i] = fs.readArray(m);
if (k % 2 == 1) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) pr.print(-1 + " ");
pr.println();
}
} else {
int[][][] dp = new int[k / 2 + 1][n][m];
for(int r = 1; 2 * r <= k; r++) {
for(int i = 0; i < n; i++) Arrays.fill(dp[r][i], INF);
for(int i = 0; i < n; i++)
for(int j = 0; j + 1 < m; j++) {
int cost = right[i][j];
dp[r][i][j] = Integer.min(dp[r][i][j], dp[r - 1][i][j + 1] + cost);
dp[r][i][j + 1] = Integer.min(dp[r][i][j + 1], dp[r - 1][i][j] + cost);
}
for(int i = 0; i + 1 < n; i++)
for(int j = 0; j < m; j++) {
int cost = down[i][j];
dp[r][i][j] = Integer.min(dp[r][i][j], dp[r - 1][i + 1][j] + cost);
dp[r][i + 1][j] = Integer.min(dp[r][i + 1][j], dp[r - 1][i][j] + cost);
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
pr.print(2 * dp[k/2][i][j] + " ");
}
pr.println();
}
}
// }
pr.flush();
pr.close();
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Codechef{
static int max=Integer.MIN_VALUE;
static int res=0;
static int[] checkMax(int arr[],int j){
int sum=0;
int x=arr[j];
while(x!=0){
if(j+1==15){
j=0;
}else{
arr[j+1]=arr[j+1]+1;
}
// if(arr[j+1]%2==0){
// sum=sum+arr[j+1];
// if(sum>=max){
// max=sum;
// }
// }
x--;
j++;
}
return arr;
}
public static void main(String []args){
Scanner sc = new Scanner (System.in);
long a [] = new long [14];
long b [] = new long [14];
long p,q,r,s,max = 0;
for(int i = 0; i < 14; i++) a[i] = sc.nextInt();
for(int i = 0; i < 14; i++){
p = a[i]%14;
q = a[i]/14;
r = 0;
s = 0;
for(int j = 0; j < 14; j++) b[j] = a[j];
b[i] = 0;
int j = (i+1)%14;
for(; r < p; r++) {
b[j]++;
j=(j+1)%14;
}
for( j = 0; j < 14; j++) {
b[j] += q;
if(b[j] % 2 == 0) s+= b[j];
}
max = Math.max(max,s);
}
System.out.println(max);
}
}
|
constant
|
975_B. Mancala
|
CODEFORCES
|
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
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();
long k=in.nextInt();
if(n==1){
out.println(0);
return;
}
long max=k*(k-1)/2+1;
if(max<n){
out.println("-1");
return;
}
long low=1,high=k-1;
long ans=k-1;
while (low<=high){
long mid=(low+high)/2;
long val=mid*mid-mid*(2*k-1)+2*n-2;
if(val>0){
low=mid+1;
}
else {
ans=mid;
high=mid-1;
}
}
out.println(ans);
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.util.*;
import java.math.*;
import java.io.*;
public class CF1068A {
public CF1068A() {
FS scan = new FS();
long n = scan.nextLong(), m = scan.nextLong(), k = scan.nextLong(), l = scan.nextLong();
long ceil = (k + l + m - 1) / m;
if(k + l <= n && ceil * m <= n) System.out.println(ceil);
else System.out.println(-1);
}
class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next() {
while(!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch(Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int nextInt() { return Integer.parseInt(next()); }
public long nextLong() { return Long.parseLong(next()); }
}
public static void main(String[] args) { new CF1068A(); }
}
|
constant
|
1068_A. Birthday
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Main{
public static void main(String[] Args) throws Exception {
Scanner sc = new Scanner(new FileReader("input.txt"));
int n,m,k;
Integer lx,ly;
boolean d[][];
n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt();
d = new boolean [n+1][m+1];
for(int i=0;i<=n;++i)
for(int j=0;j<=m;++j)
d[i][j]=false;
Queue< pair > q = new LinkedList< pair >();
lx = ly = -1;
for(int i=0;i<k;++i){
int x,y; x = sc.nextInt(); y = sc.nextInt();
q.add(new pair(x,y)); lx = x; ly = y;
d[x][y]=true;
}
int dx [] = {0,0,1,-1};
int dy [] = {-1,1,0,0};
while(!q.isEmpty()){
pair tp = q.remove();
int x = tp.x; int y = tp.y;
for(int i=0;i<4;++i){
int nx = x+dx[i]; int ny = y+dy[i];
if(nx<1 || nx>n || ny<1 || ny>m || d[nx][ny] ) continue;
d[nx][ny]=true;
q.add(new pair(nx,ny));
lx = nx; ly = ny;
}
}
FileWriter fw = new FileWriter("output.txt");
fw.write(lx.toString()); fw.write(" "); fw.write(ly.toString());;
fw.flush();
}
}
class pair {
public int x,y;
public pair(int _x,int _y){ x = _x; y = _y; }
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.lang.*;
import static java.lang.Math.*;
public class TaskA implements Runnable {
long m = (int) 1e9 + 7;
PrintWriter w;
InputReader c;
/*Global Variables*/
public void run() {
c = new InputReader(System.in);
w = new PrintWriter(System.out);
int n = c.nextInt();
int a[] = scanArrayI(n);
boolean vis[] = new boolean[n];
Arrays.sort(a);
int ans=0;
for(int i=0;i<n;i++){
if(vis[i]) continue;
vis[i] = true;
for(int j=i+1;j<n;j++){
if(a[j]%a[i] == 0){
vis[j] = true;
}
}
ans++;
boolean check = false;
for(int j=0;j<n;j++){
if(!vis[j]) check = true;
}
if(!check) break;
}
w.println(ans);
w.close();
}
class pair{
int x,y,step;
@Override
public String toString() {
return "pair{" +
"x=" + x +
", y=" + y +
", step=" + step +
'}';
}
public pair(int x, int y, int s) {
this.x = x;
this.y = y;
step = s;
}
}
/*Template Stuff*/
class HashMapUtil<T, U> {
void addHash(HashMap<T, Integer> hm, T a) {
if (hm.containsKey(a)) hm.put(a, hm.get(a) + 1);
else hm.put(a, 1);
}
void iterateHashMap(HashMap<T, U> hm) {
for (Map.Entry<T, U> e : hm.entrySet()) {
T key = e.getKey();
U value = e.getValue();
}
}
}
public int search(int input[], int search) {
int low = 0;
int high = input.length - 1;
int mid;
while (low <= high) {
mid = low + ((high - low) / 2);
if (input[mid] == search) {
return mid;
} else if (input[mid] < search) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
public void sort(int arr[]) {
int n = arr.length, mid, h, s, l, i, j, k;
int[] res = new int[n];
for (s = 1; s < n; s <<= 1) {
for (l = 0; l < n - 1; l += (s << 1)) {
h = min(l + (s << 1) - 1, n - 1);
mid = min(l + s - 1, n - 1);
i = l;
j = mid + 1;
k = l;
while (i <= mid && j <= h) res[k++] = (arr[i] <= arr[j] ? arr[i++] : arr[j++]);
while (i <= mid) res[k++] = arr[i++];
while (j <= h) res[k++] = arr[j++];
for (k = l; k <= h; k++) arr[k] = res[k];
}
}
}
public int nextPowerOf2(int num) {
if (num == 0) {
return 1;
}
if (num > 0 && (num & (num - 1)) == 0) {
return num;
}
while ((num & (num - 1)) > 0) {
num = num & (num - 1);
}
return num << 1;
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void sortbyColumn(int arr[][], int col) {
Arrays.sort(arr, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
return (Integer.valueOf(o1[col]).compareTo(o2[col]));
}
});
}
public void printArray(int[] a) {
for (int i = 0; i < a.length; i++)
w.print(a[i] + " ");
w.println();
}
public int[] scanArrayI(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = c.nextInt();
return a;
}
public long[] scanArrayL(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = c.nextLong();
return a;
}
public void printArray(long[] a) {
for (int i = 0; i < a.length; i++)
w.print(a[i] + " ");
w.println();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new TaskA(), "TaskA", 1 << 26).start();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.regex.*;
public class Main{
static long dp[][][][]=new long [16][16][16][4];
static void ini() {
for(int i=0;i<16;i++) {
for(int j=0;j<16;j++) {
for(int k=0;k<16;k++) {
for(int l=0;l<4;l++) {
dp[i][j][k][l]=-1L;
}
}
}
}
}
static int chk(long i) {
if(i==0L)
return 1;
else
return 0;
}
static long f(long a,long b,long c,int taken) {
int got=(int) (a+b+c);
int have=chk(a)+chk(b)+chk(c);
if(have==2) {
if(got==1)
return 1L;
else
return 0L;
}
if(dp[(int) a][(int) b][(int) c][taken]!=-1) {
return dp[(int) a][(int) b][(int) c][taken];
}
long ans=0L;
if(taken == 0) {
if(a!=0)
ans+=(a*f(a-1,b,c,1))%mod; ans%=mod;
if(b!=0)
ans+=(b*f(a,b-1,c,2))%mod; ans%=mod;
if(c!=0)
ans+=(c*f(a,b,c-1,3))%mod; ans%=mod;
}
else {
ans+=((taken==1 || a==0)?0L:(a*f(a-1,b,c,1))%mod)%mod; ans%=mod;
ans+=((taken==2 || b==0)?0L:(b*f(a,b-1,c,2))%mod)%mod; ans%=mod;
ans+=((taken==3 || c==0)?0L:(c*f(a,b,c-1,3))%mod)%mod; ans%=mod;
}
dp[(int) a][(int) b][(int) c][taken]=ans;
return ans;
}
public static void main(String[] args)
{
InputReader in=new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n=in.nextInt();
int total=in.nextInt();
int t[]=new int[n];
int g[]=new int[n];
for(int i=0;i<n;i++) {
t[i]=in.nextInt();
g[i]=in.nextInt();
}
long ans=0L;
for(int i=0;i<(1<<n);i++) {
int sum=0;
int a[]=new int[4];
for(int j=0;j<n;j++) {
if(((i>>j)&1)==1) {
sum+=t[j];
a[g[j]]++;
}
}
if(sum==total) {
ini();
ans=(ans+f(a[1],a[2],a[3],0))%mod;
}
}
pw.println(ans);
pw.flush();
pw.close();
}
private 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;
}
static class tri implements Comparable<tri> {
int p, c, l;
tri(int p, int c, int l) {
this.p = p;
this.c = c;
this.l = l;
}
public int compareTo(tri o) {
return Integer.compare(l, o.l);
}
}
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);
}
}
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public static int[] suffle(int[] a,Random gen)
{
int n = a.length;
for(int i=0;i<n;i++)
{
int ind = gen.nextInt(n-i)+i;
int temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
/* public static long primeFactorization(long n)
{
HashSet<Integer> a =new HashSet<Integer>();
long cnt=0;
for(int i=2;i*i<=n;i++)
{
while(a%i==0)
{
a.add(i);
a/=i;
}
}
if(a!=1)
cnt++;
//a.add(n);
return cnt;
}*/
public static void sieve(boolean[] isPrime,int n)
{
for(int i=1;i<n;i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for(int i=2;i*i<n;i++)
{
if(isPrime[i] == true)
{
for(int j=(2*i);j<n;j+=i)
isPrime[j] = false;
}
}
}
public static int GCD(int a,int b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static long GCD(long a,long b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static void extendedEuclid(int A,int B)
{
if(B==0)
{
d = A;
p = 1 ;
q = 0;
}
else
{
extendedEuclid(B, A%B);
int temp = p;
p = q;
q = temp - (A/B)*q;
}
}
public static long LCM(long a,long b)
{
return (a*b)/GCD(a,b);
}
public static int LCM(int a,int b)
{
return (a*b)/GCD(a,b);
}
public static int binaryExponentiation(int x,int n)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static long binaryExponentiation(long x,long n)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static int modularExponentiation(int x,int n,int M)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x%M*x)%M;
n=n/2;
}
return result;
}
public static long modularExponentiation(long x,long n,long M)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result%M * x%M)%M;
x=(x%M * x%M)%M;
n=n/2;
}
return result;
}
public static long modInverse(int A,int M)
{
return modularExponentiation(A,M-2,M);
}
public static long modInverse(long A,long M)
{
return modularExponentiation(A,M-2,M);
}
public static boolean isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0)
return false;
for (int i=5; i*i<=n; i=i+6)
{
if (n%i == 0 || n%(i+2) == 0)
return false;
}
return true;
}
public static long[] shuffle(long[] a, Random gen){
for(int i = 0, n = a.length;i < n;i++){
int ind = gen.nextInt(n-i)+i;
long d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
static class pair implements Comparable<pair>{
Long x;
Long y;
Integer z;
pair(long l,long y2,int z){
this.x=l;
this.y=y2;
this.z=z;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString(){
return (x+" "+y);
}
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class B{
public static void main(String[] args)
{
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = fs.nextInt();
for(int tt=0;tt<t;tt++)
{
int n = fs.nextInt();
int[] arr = fs.readArray(n);
List<String> ans = new ArrayList();
List<Integer> temp = new ArrayList();
temp.add(arr[0]);
ans.add(""+arr[0]);
for(int i=1;i<n;i++)
{
int ch = arr[i];
if(ch == 1)
{
temp.add(1);
StringBuilder sb = new StringBuilder();
for(int j=0;j<temp.size();j++)
{
sb.append(temp.get(j));
if(j != temp.size()-1)
{
sb.append('.');
}
}
ans.add(sb.toString());
}
else
{
int j = temp.size()-1;
while(j>=0)
{
if(ch - temp.get(j) == 1)
{
temp.set(j,ch);
break;
}
else
{
j--;
}
}
int extra = temp.size()-1;
while(extra>j)
{
temp.remove(temp.size()-1);
extra--;
}
StringBuilder sb = new StringBuilder();
for(int jj=0;jj<temp.size();jj++)
{
sb.append(temp.get(jj));
if(jj != temp.size()-1)
{
sb.append('.');
}
}
ans.add(sb.toString());
}
// out.println("Here: "+temp);
}
for(String str:ans)
{
out.println(str);
}
}
out.close();
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
public static int[] sort(int[] arr)
{
List<Integer> temp = new ArrayList();
for(int i:arr)temp.add(i);
Collections.sort(temp);
int start = 0;
for(int i:temp)arr[start++]=i;
return arr;
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.*;
public class ProblemA {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int t = s.nextInt();
TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();
// int x = 0 ;
while(s.hasNextInt())
{
int i = s.nextInt();
int j = s.nextInt();
map.put(i,j);
// x++;
// if(x == 2)
// break;
}
int count = 0;
double left = -100000;
double right;
int size;
for(Integer i : map.keySet())
{
size = map.get(i);
right = (double)i - (double)size/2.0;
if(right - left > t)
{
count+=2;
}
if(right - left == t)
{
count++;
}
left = (double)i + (double)size/2.0;
}
System.out.println(count);
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out));
// String fileName = "C-large-practice";
// ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".out")));
new Main(io).solve();
// new Main(io).solveLocal();
io.close();
}
ConsoleIO io;
Main(ConsoleIO io) {
this.io = io;
}
ConsoleIO opt;
Main(ConsoleIO io, ConsoleIO opt) {
this.io = io;
this.opt = opt;
}
List<List<Integer>> gr = new ArrayList<>();
long MOD = 1_000_000_007;
public void solve() {
StringBuilder sb = new StringBuilder();
int q = io.ri();
for(int i = 0; i < q; i++){
long n = io.readLong();
long k = io.readLong();
if(i>0)sb.append(System.lineSeparator());
boolean done = false;
if(n==2 && k == 3){
sb.append("NO");
done = true;
}
for(int p = 0;n>0 && !done;p++, n--){
long count = (1L << (p*2));
if(k>count){
k-=count;
}else{
long path = p==0?1:(1L<<(p-1))*2+((1L<<(p-1))-1)*2+1;
if(k<path){
sb.append("YES " + n);
}else{
sb.append("YES " + (n-1));
}
done = true;
}
}
if(!done){
sb.append("NO");
}
}
io.writeLine(sb.toString());
}
}
class ConsoleIO {
BufferedReader br;
PrintWriter out;
public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;}
public void flush(){this.out.flush();}
public void close(){this.out.close();}
public void writeLine(String s) {this.out.println(s);}
public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
public void writeWord(String s){
this.out.print(s);
}
public void writeIntArray(int[] a, int k, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k; i++) {
if (i > 0) sb.append(separator);
sb.append(a[i]);
}
this.writeLine(sb.toString());
}
public void writeLongArray(long[] a, int k, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k; i++) {
if (i > 0) sb.append(separator);
sb.append(a[i]);
}
this.writeLine(sb.toString());
}
public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }}
public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
public long[] readLongArray() {
String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length];
for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
return r;
}
public int[] readIntArray() {
String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
return r;
}
public int[] readIntArray(int n) {
int[] res = new int[n];
char[] all = this.readLine().toCharArray();
int cur = 0;boolean have = false;
int k = 0;
boolean neg = false;
for(int i = 0;i<all.length;i++){
if(all[i]>='0' && all[i]<='9'){
cur = cur*10+all[i]-'0';
have = true;
}else if(all[i]=='-') {
neg = true;
}
else if(have){
res[k++] = neg?-cur:cur;
cur = 0;
have = false;
neg = false;
}
}
if(have)res[k++] = neg?-cur:cur;
return res;
}
public int ri() {
try {
int r = 0;
boolean start = false;
boolean neg = false;
while (true) {
int c = br.read();
if (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
start = true;
} else if (!start && c == '-') {
start = true;
neg = true;
} else if (start || c == -1) return neg ? -r : r;
}
} catch (Exception ex) {
return -1;
}
}
public long readLong() {
try {
long r = 0;
boolean start = false;
boolean neg = false;
while (true) {
int c = br.read();
if (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
start = true;
} else if (!start && c == '-') {
start = true;
neg = true;
} else if (start || c == -1) return neg ? -r : r;
}
} catch (Exception ex) {
return -1;
}
}
public String readWord() {
try {
boolean start = false;
StringBuilder sb = new StringBuilder();
while (true) {
int c = br.read();
if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') {
sb.append((char)c);
start = true;
} else if (start || c == -1) return sb.toString();
}
} catch (Exception ex) {
return "";
}
}
public char readSymbol() {
try {
while (true) {
int c = br.read();
if (c != ' ' && c != '\r' && c != '\n' && c != '\t') {
return (char) c;
}
}
} catch (Exception ex) {
return 0;
}
}
//public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }}
}
class Pair {
public Pair(int a, int b) {this.a = a;this.b = b;}
public int a;
public int b;
}
class PairLL {
public PairLL(long a, long b) {this.a = a;this.b = b;}
public long a;
public long b;
}
class Triple {
public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;}
public int a;
public int b;
public int c;
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
import java.awt.Point;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Testt {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
public static void main(String[] args) {
new Testt().run();
}
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;
}
}
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);
}
}
public void solve() throws IOException {
int n = readInt();
int [] a = new int [n];
for (int i = 0; i < n; i++){
a[i] = readInt();
}
mergeSort(a);
int sum = 0;
for (int i = 0; i <n; i++){
sum+=a[i];
}
int sum2 = 0;
int ans = 0;
for (int i = n-1; i >=0; i-- ){
sum2+=a[i];
sum-=a[i];
ans++;
if (sum2>sum){
break;
}
}
out.print(ans);
}
/* for (int i =0; i<n; i++){
out.print(a[i]+" ");
}*/
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Solution1515B {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver1515B solver = new Solver1515B();
int n = in.nextInt();
for (int i = 0; i < n; i++) {
solver.solve(i, in, out);
}
out.close();
}
static class Solver1515B {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
boolean f = false;
if (n % 2 == 0) {
int s = (int) Math.sqrt(n / 2);
if (s * s == n / 2) {
f = true;
}
}
if (n % 4 == 0) {
int s = (int) Math.sqrt(n / 4);
if (s * s == n / 4) {
f = true;
}
}
if (f) {
out.println("YES");
} else {
out.println("NO");
}
}
}
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());
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.util.Scanner;
public class c {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long n = scan.nextLong();
long s = scan.nextLong();
scan.close();
long start = s - s % 10;
while (start <= n && !isBig(start, s)) {
start += 10;
}
if (start > n) {
System.out.println(0);
} else {
System.out.println(n - start + 1);
}
}
private static boolean isBig(long a, long s) {
char[] digits = ("" + a).toCharArray();
int counter = 0;
for (int i = 0; i < digits.length; i++) {
counter += digits[i] - '0';
}
return a - counter >= s;
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
final int MOD = (int) (1e9 + 7);
long[][] C;
long[] fact;
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
precalc(n);
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
a[i] = removeSquares(a[i]);
}
int[] g = getGroupSizes(a);
long ans = solve(g);
for (int x : g) {
ans = ans * fact[x] % MOD;
}
out.println(ans);
}
private long solve(int[] a) {
// For a description, see http://petr-mitrichev.blogspot.com/2017/07/a-week7.html
long[] d = new long[1];
d[0] = 1;
int totalPositions = 1;
for (int x : a) {
long[] nd = new long[d.length + x + 1];
for (int s = 0; s < d.length; s++) {
if (d[s] == 0) {
continue;
}
for (int m = 1; m <= x; m++) {
for (int p = 0; p <= s && p <= m; p++) {
long cur = d[s];
cur = cur * C[s][p] % MOD;
cur = cur * C[totalPositions - s][m - p] % MOD;
cur = cur * f(x, m) % MOD;
int ns = s + x - m - p;
if (ns >= 0 && ns < nd.length) {
nd[ns] += cur;
if (nd[ns] >= MOD) {
nd[ns] -= MOD;
}
}
}
}
}
if (totalPositions == 1) {
totalPositions = x + 1;
} else {
totalPositions += x;
}
d = nd;
}
return d[0];
}
private long f(int n, int k) {
if (n < k) {
return 0;
}
n -= k;
return C[n + k - 1][k - 1];
}
private void precalc(int n) {
fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i < fact.length; i++) {
fact[i] = i * fact[i - 1] % MOD;
}
C = new long[1000][1000];
C[0][0] = 1;
for (int i = 1; i < C.length; i++) {
C[i][0] = 1;
for (int j = 1; j < C.length; j++) {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
if (C[i][j] >= MOD) {
C[i][j] -= MOD;
}
}
}
}
private int[] getGroupSizes(int[] a) {
Arrays.sort(a);
List<Integer> res = new ArrayList<>();
for (int i = 0; i < a.length; ) {
int j = i;
while (j < a.length && a[i] == a[j]) {
++j;
}
res.add(j - i);
i = j;
}
int[] r = new int[res.size()];
for (int i = 0; i < r.length; i++) {
r[i] = res.get(i);
}
return r;
}
private int removeSquares(int n) {
int res = 1;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
int cur = 0;
while (n % d == 0) {
n /= d;
++cur;
}
if (cur % 2 == 1) {
res *= d;
}
}
}
if (n > 1) {
res *= n;
}
return res;
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
cubic
|
840_C. On the Bench
|
CODEFORCES
|
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class realfast implements Runnable {
private static final int INF = (int) 1e9;
int time[]= new int[15];
int g[]= new int [15];
public void solve() throws IOException
{
int n = readInt();
int t = readInt();
for(int i=0;i<n;i++)
{
time[i]=readInt();
g[i]=readInt();
}
long dp[][]= new long [(int)Math.pow(2,n)][4];
for(int i =0;i<(int)Math.pow(2,n);i++)
{
for(int j=0;j<=3;j++)
dp[i][j]=-1;
}
long val = cal(dp,0,0,0,t);
out.println(val);
}
public long cal(long dp[][], int mask , int genre , int t ,int T )
{
int val = dp.length;
if(t>T)
{
return 0;
}
if(t==T)
{
return 1;
}
if(dp[mask][genre]!=-1)
return dp[mask][genre];
dp[mask][genre]=0;
int i=1;
int count=0;
while(i<val)
{
if((i&mask)==0&&g[count]!=genre)
{
dp[mask][genre] = ((dp[mask][genre]%1000000007)+ cal(dp,mask|i,g[count],t+time[count],T)%1000000007)%1000000007;
}
i=2*i;
count++;
}
return dp[mask][genre];
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
new Thread(null, new realfast(), "", 128 * (1L << 20)).start();
}
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private BufferedReader reader;
private StringTokenizer tokenizer;
private PrintWriter out;
@Override
public void run() {
try {
if (ONLINE_JUDGE || !new File("input.txt").exists()) {
reader = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
reader = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
solve();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
reader.close();
} catch (IOException e) {
// nothing
}
out.close();
}
}
private String readString() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
@SuppressWarnings("unused")
private int readInt() throws IOException {
return Integer.parseInt(readString());
}
@SuppressWarnings("unused")
private long readLong() throws IOException {
return Long.parseLong(readString());
}
@SuppressWarnings("unused")
private double readDouble() throws IOException {
return Double.parseDouble(readString());
}
}
class edge implements Comparable<edge>{
int u ;
int v ;
int val;
edge(int u1, int v1 , int val1)
{
this.u=u1;
this.v=v1;
this.val=val1;
}
public int compareTo(edge e)
{
return this.val-e.val;
}
}
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
//package baobab;
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
Solver solver = new Solver();
}
static class Solver {
IO io;
public Solver() {
this.io = new IO();
try {
solve();
} catch (RuntimeException e) {
if (!e.getMessage().equals("Clean exit")) {
throw e;
}
} finally {
io.close();
}
}
/****************************** START READING HERE ********************************/
void solve() {
long x = io.nextLong();
long k = io.nextLong();
if (x==0) done(0);
long ans = pow(2,k) * ((2*x - 1)%MOD) + 1;
io.println(ans%MOD);
}
long pow(long base, long exp) {
if (exp == 0) return 1L;
long x = pow(base, exp/2);
long ans = x * x;
ans %= MOD;
if (exp % 2 != 0) {
ans *= base;
ans %= MOD;
}
return ans;
}
void solve2() {
long x = io.nextLong();
long k = io.nextLong();
if (x==0) done(0);
// TODO how to exclude from counts cases where dresses are negative?
long checkPointA = min(10000, k);
double count = x;
long i=0;
for (; i<checkPointA; i++) {
count *= 2;
count -= 0.5;
count %= MOD;
}
List<Double> bah = new ArrayList<>();
List<Long> meh = new ArrayList<>();
while (true) {
bah.add(count);
meh.add(i);
long j = 2*i;
if (j > k || j < 0) break;
i = j;
count *= count;
count %= MOD;
}
while (!bah.isEmpty()) {
long muller = meh.get(meh.size()-1);
long cand = i + muller;
if (cand > k || cand < 0) {
meh.remove(meh.size()-1);
bah.remove(bah.size()-1);
continue;
}
i = cand;
count *= meh.get(meh.size()-1);
count %= MOD;
}
for (; i<k; i++) {
count *= 2;
count -= 0.5;
count %= MOD;
}
// last month no eating
count *= 2;
count %= MOD;
io.println(Math.round(count));
}
/************************** UTILITY CODE BELOW THIS LINE **************************/
long MOD = (long)1e9 + 7;
boolean closeToZero(double v) {
// Check if double is close to zero, considering precision issues.
return Math.abs(v) <= 0.0000000000001;
}
class DrawGrid {
void draw(boolean[][] d) {
System.out.print(" ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" " + x + " ");
}
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print((d[y][x] ? "[x]" : "[ ]"));
}
System.out.println("");
}
}
void draw(int[][] d) {
int max = 1;
for (int y=0; y<d.length; y++) {
for (int x=0; x<d[0].length; x++) {
max = Math.max(max, ("" + d[y][x]).length());
}
}
System.out.print(" ");
String format = "%" + (max+2) + "s";
for (int x=0; x<d[0].length; x++) {
System.out.print(String.format(format, x) + " ");
}
format = "%" + (max) + "s";
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" [" + String.format(format, (d[y][x])) + "]");
}
System.out.println("");
}
}
}
class IDval implements Comparable<IDval> {
int id;
long val;
public IDval(int id, long val) {
this.val = val;
this.id = id;
}
@Override
public int compareTo(IDval o) {
if (this.val < o.val) return -1;
if (this.val > o.val) return 1;
return this.id - o.id;
}
}
private class ElementCounter {
private HashMap<Long, Integer> elements;
public ElementCounter() {
elements = new HashMap<>();
}
public void add(long element) {
int count = 1;
Integer prev = elements.get(element);
if (prev != null) count += prev;
elements.put(element, count);
}
public void remove(long element) {
int count = elements.remove(element);
count--;
if (count > 0) elements.put(element, count);
}
public int get(long element) {
Integer val = elements.get(element);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class StringCounter {
HashMap<String, Integer> elements;
public StringCounter() {
elements = new HashMap<>();
}
public void add(String identifier) {
int count = 1;
Integer prev = elements.get(identifier);
if (prev != null) count += prev;
elements.put(identifier, count);
}
public void remove(String identifier) {
int count = elements.remove(identifier);
count--;
if (count > 0) elements.put(identifier, count);
}
public long get(String identifier) {
Integer val = elements.get(identifier);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class DisjointSet {
/** Union Find / Disjoint Set data structure. */
int[] size;
int[] parent;
int componentCount;
public DisjointSet(int n) {
componentCount = n;
size = new int[n];
parent = new int[n];
for (int i=0; i<n; i++) parent[i] = i;
for (int i=0; i<n; i++) size[i] = 1;
}
public void join(int a, int b) {
/* Find roots */
int rootA = parent[a];
int rootB = parent[b];
while (rootA != parent[rootA]) rootA = parent[rootA];
while (rootB != parent[rootB]) rootB = parent[rootB];
if (rootA == rootB) {
/* Already in the same set */
return;
}
/* Merge smaller set into larger set. */
if (size[rootA] > size[rootB]) {
size[rootA] += size[rootB];
parent[rootB] = rootA;
} else {
size[rootB] += size[rootA];
parent[rootA] = rootB;
}
componentCount--;
}
}
class Trie {
int N;
int Z;
int nextFreeId;
int[][] pointers;
boolean[] end;
/** maxLenSum = maximum possible sum of length of words */
public Trie(int maxLenSum, int alphabetSize) {
this.N = maxLenSum;
this.Z = alphabetSize;
this.nextFreeId = 1;
pointers = new int[N+1][alphabetSize];
end = new boolean[N+1];
}
public void addWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) {
next = nextFreeId++;
pointers[curr][c] = next;
}
curr = next;
}
end[curr] = true;
}
public boolean hasWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) return false;
curr = next;
}
return end[curr];
}
}
private static class Prob {
/** For heavy calculations on probabilities, this class
* provides more accuracy & efficiency than doubles.
* Math explained: https://en.wikipedia.org/wiki/Log_probability
* Quick start:
* - Instantiate probabilities, eg. Prob a = new Prob(0.75)
* - add(), multiply() return new objects, can perform on nulls & NaNs.
* - get() returns probability as a readable double */
/** Logarithmized probability. Note: 0% represented by logP NaN. */
private double logP;
/** Construct instance with real probability. */
public Prob(double real) {
if (real > 0) this.logP = Math.log(real);
else this.logP = Double.NaN;
}
/** Construct instance with already logarithmized value. */
static boolean dontLogAgain = true;
public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
this.logP = logP;
}
/** Returns real probability as a double. */
public double get() {
return Math.exp(logP);
}
@Override
public String toString() {
return ""+get();
}
/***************** STATIC METHODS BELOW ********************/
/** Note: returns NaN only when a && b are both NaN/null. */
public static Prob add(Prob a, Prob b) {
if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
if (nullOrNaN(a)) return copy(b);
if (nullOrNaN(b)) return copy(a);
double x = Math.max(a.logP, b.logP);
double y = Math.min(a.logP, b.logP);
double sum = x + Math.log(1 + Math.exp(y - x));
return new Prob(sum, dontLogAgain);
}
/** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
public static Prob multiply(Prob a, Prob b) {
if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
return new Prob(a.logP + b.logP, dontLogAgain);
}
/** Returns true if p is null or NaN. */
private static boolean nullOrNaN(Prob p) {
return (p == null || Double.isNaN(p.logP));
}
/** Returns a new instance with the same value as original. */
private static Prob copy(Prob original) {
return new Prob(original.logP, dontLogAgain);
}
}
class Binary implements Comparable<Binary> {
/**
* Use example: Binary b = new Binary(Long.toBinaryString(53249834L));
*
* When manipulating small binary strings, instantiate new Binary(string)
* When just reading large binary strings, instantiate new Binary(string,true)
* get(int i) returns a character '1' or '0', not an int.
*/
private boolean[] d;
private int first; // Starting from left, the first (most remarkable) '1'
public int length;
public Binary(String binaryString) {
this(binaryString, false);
}
public Binary(String binaryString, boolean initWithMinArraySize) {
length = binaryString.length();
int size = Math.max(2*length, 1);
first = length/4;
if (initWithMinArraySize) {
first = 0;
size = Math.max(length, 1);
}
d = new boolean[size];
for (int i=0; i<length; i++) {
if (binaryString.charAt(i) == '1') d[i+first] = true;
}
}
public void addFirst(char c) {
if (first-1 < 0) doubleArraySize();
first--;
d[first] = (c == '1' ? true : false);
length++;
}
public void addLast(char c) {
if (first+length >= d.length) doubleArraySize();
d[first+length] = (c == '1' ? true : false);
length++;
}
private void doubleArraySize() {
boolean[] bigArray = new boolean[(d.length+1) * 2];
int newFirst = bigArray.length / 4;
for (int i=0; i<length; i++) {
bigArray[i + newFirst] = d[i + first];
}
first = newFirst;
d = bigArray;
}
public boolean flip(int i) {
boolean value = (this.d[first+i] ? false : true);
this.d[first+i] = value;
return value;
}
public void set(int i, char c) {
boolean value = (c == '1' ? true : false);
this.d[first+i] = value;
}
public char get(int i) {
return (this.d[first+i] ? '1' : '0');
}
@Override
public int compareTo(Binary o) {
if (this.length != o.length) return this.length - o.length;
int len = this.length;
for (int i=0; i<len; i++) {
int diff = this.get(i) - o.get(i);
if (diff != 0) return diff;
}
return 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i=0; i<length; i++) {
sb.append(d[i+first] ? '1' : '0');
}
return sb.toString();
}
}
/************************** Range queries **************************/
class FenwickMin {
long n;
long[] original;
long[] bottomUp;
long[] topDown;
public FenwickMin(int n) {
this.n = n;
original = new long[n+2];
bottomUp = new long[n+2];
topDown = new long[n+2];
}
public void set(int modifiedNode, long value) {
long replaced = original[modifiedNode];
original[modifiedNode] = value;
// Update left tree
int i = modifiedNode;
long v = value;
while (i <= n) {
if (v > bottomUp[i]) {
if (replaced == bottomUp[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i-x;
v = Math.min(v, bottomUp[child]);
}
} else break;
}
if (v == bottomUp[i]) break;
bottomUp[i] = v;
i += (i&-i);
}
// Update right tree
i = modifiedNode;
v = value;
while (i > 0) {
if (v > topDown[i]) {
if (replaced == topDown[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i+x;
if (child > n+1) break;
v = Math.min(v, topDown[child]);
}
} else break;
}
if (v == topDown[i]) break;
topDown[i] = v;
i -= (i&-i);
}
}
public long getMin(int a, int b) {
long min = original[a];
int prev = a;
int curr = prev + (prev&-prev); // parent right hand side
while (curr <= b) {
min = Math.min(min, topDown[prev]); // value from the other tree
prev = curr;
curr = prev + (prev&-prev);;
}
min = Math.min(min, original[prev]);
prev = b;
curr = prev - (prev&-prev); // parent left hand side
while (curr >= a) {
min = Math.min(min,bottomUp[prev]); // value from the other tree
prev = curr;
curr = prev - (prev&-prev);
}
return min;
}
}
class FenwickSum {
public long[] d;
public FenwickSum(int n) {
d=new long[n+1];
}
/** a[0] must be unused. */
public FenwickSum(long[] a) {
d=new long[a.length];
for (int i=1; i<a.length; i++) {
modify(i, a[i]);
}
}
/** Do not modify i=0. */
void modify(int i, long v) {
while (i<d.length) {
d[i] += v;
// Move to next uplink on the RIGHT side of i
i += (i&-i);
}
}
/** Returns sum from a to b, *BOTH* inclusive. */
long getSum(int a, int b) {
return getSum(b) - getSum(a-1);
}
private long getSum(int i) {
long sum = 0;
while (i>0) {
sum += d[i];
// Move to next uplink on the LEFT side of i
i -= (i&-i);
}
return sum;
}
}
class SegmentTree {
/** Query sums with log(n) modifyRange */
int N;
long[] p;
public SegmentTree(int n) {
/* TODO: Test that this works. */
for (N=2; N<n; N++) N *= 2;
p = new long[2*N];
}
public void modifyRange(int a, int b, long change) {
muuta(a, change);
muuta(b+1, -change);
}
void muuta(int k, long muutos) {
k += N;
p[k] += muutos;
for (k /= 2; k >= 1; k /= 2) {
p[k] = p[2*k] + p[2*k+1];
}
}
public long get(int k) {
int a = N;
int b = k+N;
long s = 0;
while (a <= b) {
if (a%2 == 1) s += p[a++];
if (b%2 == 0) s += p[b--];
a /= 2;
b /= 2;
}
return s;
}
}
/***************************** Graphs *****************************/
List<Integer>[] toGraph(IO io, int n) {
List<Integer>[] g = new ArrayList[n+1];
for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
for (int i=1; i<=n-1; i++) {
int a = io.nextInt();
int b = io.nextInt();
g[a].add(b);
g[b].add(a);
}
return g;
}
class Graph {
HashMap<Long, List<Long>> edges;
public Graph() {
edges = new HashMap<>();
}
List<Long> getSetNeighbors(Long node) {
List<Long> neighbors = edges.get(node);
if (neighbors == null) {
neighbors = new ArrayList<>();
edges.put(node, neighbors);
}
return neighbors;
}
void addBiEdge(Long a, Long b) {
addEdge(a, b);
addEdge(b, a);
}
void addEdge(Long from, Long to) {
getSetNeighbors(to); // make sure all have initialized lists
List<Long> neighbors = getSetNeighbors(from);
neighbors.add(to);
}
// topoSort variables
int UNTOUCHED = 0;
int FINISHED = 2;
int INPROGRESS = 1;
HashMap<Long, Integer> vis;
List<Long> topoAns;
List<Long> failDueToCycle = new ArrayList<Long>() {{ add(-1L); }};
List<Long> topoSort() {
topoAns = new ArrayList<>();
vis = new HashMap<>();
for (Long a : edges.keySet()) {
if (!topoDFS(a)) return failDueToCycle;
}
Collections.reverse(topoAns);
return topoAns;
}
boolean topoDFS(long curr) {
Integer status = vis.get(curr);
if (status == null) status = UNTOUCHED;
if (status == FINISHED) return true;
if (status == INPROGRESS) {
return false;
}
vis.put(curr, INPROGRESS);
for (long next : edges.get(curr)) {
if (!topoDFS(next)) return false;
}
vis.put(curr, FINISHED);
topoAns.add(curr);
return true;
}
}
public class StronglyConnectedComponents {
/** Kosaraju's algorithm */
ArrayList<Integer>[] forw;
ArrayList<Integer>[] bacw;
/** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */
public int getCount(int n, int[] mista, int[] minne) {
forw = new ArrayList[n+1];
bacw = new ArrayList[n+1];
for (int i=1; i<=n; i++) {
forw[i] = new ArrayList<Integer>();
bacw[i] = new ArrayList<Integer>();
}
for (int i=0; i<mista.length; i++) {
int a = mista[i];
int b = minne[i];
forw[a].add(b);
bacw[b].add(a);
}
int count = 0;
List<Integer> list = new ArrayList<Integer>();
boolean[] visited = new boolean[n+1];
for (int i=1; i<=n; i++) {
dfsForward(i, visited, list);
}
visited = new boolean[n+1];
for (int i=n-1; i>=0; i--) {
int node = list.get(i);
if (visited[node]) continue;
count++;
dfsBackward(node, visited);
}
return count;
}
public void dfsForward(int i, boolean[] visited, List<Integer> list) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : forw[i]) {
dfsForward(neighbor, visited, list);
}
list.add(i);
}
public void dfsBackward(int i, boolean[] visited) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : bacw[i]) {
dfsBackward(neighbor, visited);
}
}
}
class LCAFinder {
/* O(n log n) Initialize: new LCAFinder(graph)
* O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */
int[] nodes;
int[] depths;
int[] entries;
int pointer;
FenwickMin fenwick;
public LCAFinder(List<Integer>[] graph) {
this.nodes = new int[(int)10e6];
this.depths = new int[(int)10e6];
this.entries = new int[graph.length];
this.pointer = 1;
boolean[] visited = new boolean[graph.length+1];
dfs(1, 0, graph, visited);
fenwick = new FenwickMin(pointer-1);
for (int i=1; i<pointer; i++) {
fenwick.set(i, depths[i] * 1000000L + i);
}
}
private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) {
visited[node] = true;
entries[node] = pointer;
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
for (int neighbor : graph[node]) {
if (visited[neighbor]) continue;
dfs(neighbor, depth+1, graph, visited);
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
}
}
public int find(int a, int b) {
int left = entries[a];
int right = entries[b];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
long mixedBag = fenwick.getMin(left, right);
int index = (int) (mixedBag % 1000000L);
return nodes[index];
}
}
/**************************** Geometry ****************************/
class Point {
int y;
int x;
public Point(int y, int x) {
this.y = y;
this.x = x;
}
}
boolean segmentsIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
// Returns true if segment 1-2 intersects segment 3-4
if (x1 == x2 && x3 == x4) {
// Both segments are vertical
if (x1 != x3) return false;
if (min(y1,y2) < min(y3,y4)) {
return max(y1,y2) >= min(y3,y4);
} else {
return max(y3,y4) >= min(y1,y2);
}
}
if (x1 == x2) {
// Only segment 1-2 is vertical. Does segment 3-4 cross it? y = a*x + b
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
double y = a34 * x1 + b34;
return y >= min(y1,y2) && y <= max(y1,y2) && x1 >= min(x3,x4) && x1 <= max(x3,x4);
}
if (x3 == x4) {
// Only segment 3-4 is vertical. Does segment 1-2 cross it? y = a*x + b
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double y = a12 * x3 + b12;
return y >= min(y3,y4) && y <= max(y3,y4) && x3 >= min(x1,x2) && x3 <= max(x1,x2);
}
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
if (closeToZero(a12 - a34)) {
// Parallel lines
return closeToZero(b12 - b34);
}
// Non parallel non vertical lines intersect at x. Is x part of both segments?
double x = -(b12-b34)/(a12-a34);
return x >= min(x1,x2) && x <= max(x1,x2) && x >= min(x3,x4) && x <= max(x3,x4);
}
boolean pointInsideRectangle(Point p, List<Point> r) {
Point a = r.get(0);
Point b = r.get(1);
Point c = r.get(2);
Point d = r.get(3);
double apd = areaOfTriangle(a, p, d);
double dpc = areaOfTriangle(d, p, c);
double cpb = areaOfTriangle(c, p, b);
double pba = areaOfTriangle(p, b, a);
double sumOfAreas = apd + dpc + cpb + pba;
if (closeToZero(sumOfAreas - areaOfRectangle(r))) {
if (closeToZero(apd) || closeToZero(dpc) || closeToZero(cpb) || closeToZero(pba)) {
return false;
}
return true;
}
return false;
}
double areaOfTriangle(Point a, Point b, Point c) {
return 0.5 * Math.abs((a.x-c.x)*(b.y-a.y)-(a.x-b.x)*(c.y-a.y));
}
double areaOfRectangle(List<Point> r) {
double side1xDiff = r.get(0).x - r.get(1).x;
double side1yDiff = r.get(0).y - r.get(1).y;
double side2xDiff = r.get(1).x - r.get(2).x;
double side2yDiff = r.get(1).y - r.get(2).y;
double side1 = Math.sqrt(side1xDiff * side1xDiff + side1yDiff * side1yDiff);
double side2 = Math.sqrt(side2xDiff * side2xDiff + side2yDiff * side2yDiff);
return side1 * side2;
}
boolean pointsOnSameLine(double x1, double y1, double x2, double y2, double x3, double y3) {
double areaTimes2 = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return (closeToZero(areaTimes2));
}
class PointToLineSegmentDistanceCalculator {
// Just call this
double minDistFromPointToLineSegment(double point_x, double point_y, double x1, double y1, double x2, double y2) {
return Math.sqrt(distToSegmentSquared(point_x, point_y, x1, y1, x2, y2));
}
private double distToSegmentSquared(double point_x, double point_y, double x1, double y1, double x2, double y2) {
double l2 = dist2(x1,y1,x2,y2);
if (l2 == 0) return dist2(point_x, point_y, x1, y1);
double t = ((point_x - x1) * (x2 - x1) + (point_y - y1) * (y2 - y1)) / l2;
if (t < 0) return dist2(point_x, point_y, x1, y1);
if (t > 1) return dist2(point_x, point_y, x2, y2);
double com_x = x1 + t * (x2 - x1);
double com_y = y1 + t * (y2 - y1);
return dist2(point_x, point_y, com_x, com_y);
}
private double dist2(double x1, double y1, double x2, double y2) {
return Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2);
}
}
/****************************** Math ******************************/
long gcd(long... v) {
/** Chained calls to Euclidean algorithm. */
if (v.length == 1) return v[0];
long ans = gcd(v[1], v[0]);
for (int i=2; i<v.length; i++) {
ans = gcd(ans, v[i]);
}
return ans;
}
long gcd(long a, long b) {
/** Euclidean algorithm. */
if (b == 0) return a;
return gcd(b, a%b);
}
int[] generatePrimesUpTo(int last) {
/* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */
int[] div = new int[last+1];
for (int x=2; x<=last; x++) {
if (div[x] > 0) continue;
for (int u=2*x; u<=last; u+=x) {
div[u] = x;
}
}
return div;
}
long lcm(long a, long b) {
/** Least common multiple */
return a * b / gcd(a,b);
}
class BaseConverter {
/* Palauttaa luvun esityksen kannassa base */
public String convert(Long number, int base) {
return Long.toString(number, base);
}
/* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */
public String convert(String number, int baseFrom, int baseTo) {
return Long.toString(Long.parseLong(number, baseFrom), baseTo);
}
/* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */
public long longify(String number, int baseFrom) {
return Long.parseLong(number, baseFrom);
}
}
class BinomialCoefficients {
/** Total number of K sized unique combinations from pool of size N (unordered)
N! / ( K! (N - K)! ) */
/** For simple queries where output fits in long. */
public long biCo(long n, long k) {
long r = 1;
if (k > n) return 0;
for (long d = 1; d <= k; d++) {
r *= n--;
r /= d;
}
return r;
}
/** For multiple queries with same n, different k. */
public long[] precalcBinomialCoefficientsK(int n, int maxK) {
long v[] = new long[maxK+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,maxK); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
}
}
return v;
}
/** When output needs % MOD. */
public long[] precalcBinomialCoefficientsK(int n, int k, long M) {
long v[] = new long[k+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,k); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
v[j] %= M;
}
}
return v;
}
}
/**************************** Strings ****************************/
class Zalgo {
public int pisinEsiintyma(String haku, String kohde) {
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
int max = 0;
for (int i=haku.length(); i<z.length; i++) {
max = Math.max(max, z[i]);
}
return max;
}
public int[] toZarray(char[] s) {
int n = s.length;
int[] z = new int[n];
int a = 0, b = 0;
for (int i = 1; i < n; i++) {
if (i > b) {
for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++;
}
else {
z[i] = z[i - a];
if (i + z[i - a] > b) {
for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++;
a = i;
b = i + z[i] - 1;
}
}
}
return z;
}
public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) {
// this is alternative use case
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
List<Integer> indexes = new ArrayList<>();
for (int i=haku.length(); i<z.length; i++) {
if (z[i] < haku.length()) continue;
indexes.add(i);
}
return indexes;
}
}
class StringHasher {
class HashedString {
long[] hashes;
long[] modifiers;
public HashedString(long[] hashes, long[] modifiers) {
this.hashes = hashes;
this.modifiers = modifiers;
}
}
long P;
long M;
public StringHasher() {
initializePandM();
}
HashedString hashString(String s) {
int n = s.length();
long[] hashes = new long[n];
long[] modifiers = new long[n];
hashes[0] = s.charAt(0);
modifiers[0] = 1;
for (int i=1; i<n; i++) {
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
modifiers[i] = (modifiers[i-1] * P) % M;
}
return new HashedString(hashes, modifiers);
}
/**
* Indices are inclusive.
*/
long getHash(HashedString hashedString, int startIndex, int endIndex) {
long[] hashes = hashedString.hashes;
long[] modifiers = hashedString.modifiers;
long result = hashes[endIndex];
if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M;
if (result < 0) result += M;
return result;
}
// Less interesting methods below
/**
* Efficient for 2 input parameter strings in particular.
*/
HashedString[] hashString(String first, String second) {
HashedString[] array = new HashedString[2];
int n = first.length();
long[] modifiers = new long[n];
modifiers[0] = 1;
long[] firstHashes = new long[n];
firstHashes[0] = first.charAt(0);
array[0] = new HashedString(firstHashes, modifiers);
long[] secondHashes = new long[n];
secondHashes[0] = second.charAt(0);
array[1] = new HashedString(secondHashes, modifiers);
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M;
secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M;
}
return array;
}
/**
* Efficient for 3+ strings
* More efficient than multiple hashString calls IF strings are same length.
*/
HashedString[] hashString(String... strings) {
HashedString[] array = new HashedString[strings.length];
int n = strings[0].length();
long[] modifiers = new long[n];
modifiers[0] = 1;
for (int j=0; j<strings.length; j++) {
// if all strings are not same length, defer work to another method
if (strings[j].length() != n) {
for (int i=0; i<n; i++) {
array[i] = hashString(strings[i]);
}
return array;
}
// otherwise initialize stuff
long[] hashes = new long[n];
hashes[0] = strings[j].charAt(0);
array[j] = new HashedString(hashes, modifiers);
}
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
for (int j=0; j<strings.length; j++) {
String s = strings[j];
long[] hashes = array[j].hashes;
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
}
}
return array;
}
void initializePandM() {
ArrayList<Long> modOptions = new ArrayList<>(20);
modOptions.add(353873237L);
modOptions.add(353875897L);
modOptions.add(353878703L);
modOptions.add(353882671L);
modOptions.add(353885303L);
modOptions.add(353888377L);
modOptions.add(353893457L);
P = modOptions.get(new Random().nextInt(modOptions.size()));
modOptions.clear();
modOptions.add(452940277L);
modOptions.add(452947687L);
modOptions.add(464478431L);
modOptions.add(468098221L);
modOptions.add(470374601L);
modOptions.add(472879717L);
modOptions.add(472881973L);
M = modOptions.get(new Random().nextInt(modOptions.size()));
}
}
/*************************** Technical ***************************/
private class IO extends PrintWriter {
private InputStreamReader r;
private static final int BUFSIZE = 1 << 15;
private char[] buf;
private int bufc;
private int bufi;
private StringBuilder sb;
public IO() {
super(new BufferedOutputStream(System.out));
r = new InputStreamReader(System.in);
buf = new char[BUFSIZE];
bufc = 0;
bufi = 0;
sb = new StringBuilder();
}
/** Print, flush, return nextInt. */
private int queryInt(String s) {
io.println(s);
io.flush();
return nextInt();
}
/** Print, flush, return nextLong. */
private long queryLong(String s) {
io.println(s);
io.flush();
return nextLong();
}
/** Print, flush, return next word. */
private String queryNext(String s) {
io.println(s);
io.flush();
return next();
}
private void fillBuf() throws IOException {
bufi = 0;
bufc = 0;
while(bufc == 0) {
bufc = r.read(buf, 0, BUFSIZE);
if(bufc == -1) {
bufc = 0;
return;
}
}
}
private boolean pumpBuf() throws IOException {
if(bufi == bufc) {
fillBuf();
}
return bufc != 0;
}
private boolean isDelimiter(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
}
private void eatDelimiters() throws IOException {
while(true) {
if(bufi == bufc) {
fillBuf();
if(bufc == 0) throw new RuntimeException("IO: Out of input.");
}
if(!isDelimiter(buf[bufi])) break;
++bufi;
}
}
public String next() {
try {
sb.setLength(0);
eatDelimiters();
int start = bufi;
while(true) {
if(bufi == bufc) {
sb.append(buf, start, bufi - start);
fillBuf();
start = 0;
if(bufc == 0) break;
}
if(isDelimiter(buf[bufi])) break;
++bufi;
}
sb.append(buf, start, bufi - start);
return sb.toString();
} catch(IOException e) {
throw new RuntimeException("IO.next: Caught IOException.");
}
}
public int nextInt() {
try {
int ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
ret *= 10;
ret -= (int)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
} else {
throw new RuntimeException("IO.nextInt: Invalid int.");
}
++bufi;
}
if(positive) {
if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextInt: Caught IOException.");
}
}
public long nextLong() {
try {
long ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret *= 10;
ret -= (long)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
} else {
throw new RuntimeException("IO.nextLong: Invalid long.");
}
++bufi;
}
if(positive) {
if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextLong: Caught IOException.");
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
void print(Object output) {
io.println(output);
}
void done(Object output) {
print(output);
done();
}
void done() {
io.close();
throw new RuntimeException("Clean exit");
}
long min(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
double min(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
int min(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
long max(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
double max(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
int max(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.solve());
}
private int solve() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[m];
for (int i = 0; i < m; ++i) a[i] = in.nextInt();
if (n > m) return 0;
Map<Integer, Integer> map = new HashMap<>();
for (int k: a) map.put(k, map.getOrDefault(k, 0) + 1);
List<Integer> keySet = new ArrayList<>(map.keySet());
int end = m / n;
keySet.sort((u, v) -> -Integer.compare(u, v));
do {
int count = 0;
for (int k: keySet) {
count += map.get(k) / end;
if (count >= n) return end;
}
} while (--end > 0);
return 0;
}
}
|
nlogn
|
1011_B. Planning The Expedition
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class a implements Runnable{
public static void main(String[] args) {
new Thread(null, new a(), "process", 1<<26).start();
}
public void run() {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
//PrintWriter out = new PrintWriter("file.out");
Task solver = new Task();
//int t = scan.nextInt();
int t = 1;
for(int i = 1; i <= t; i++) solver.solve(i, scan, out);
out.close();
}
static class Task {
static final int inf = Integer.MAX_VALUE;
public void solve(int testNumber, FastReader sc, PrintWriter pw) {
//CHECK FOR QUICKSORT TLE
//***********************//
//CHECK FOR INT OVERFLOW
//***********************//
int n = sc.nextInt();
int[][] arr = new int[n][];
long sums[] = new long[n];
HashMap<Integer, Integer> map1 = new HashMap<>();
HashMap<Integer, Integer> map2 = new HashMap<>();
ArrayList<Integer> arrs = new ArrayList<Integer>();
arrs.add(0);
int incc = 1;
long sum = 0;
for(int i = 0; i < n; i++) {
int k = sc.nextInt();
arr[i] = new int[k];
for(int j = 0; j < k; j++) {
sum += (arr[i][j] = sc.nextInt());
sums[i] += arr[i][j];
map1.put(arr[i][j], incc++);
map2.put(arr[i][j], i);
arrs.add(arr[i][j]);
}
}
if(sum % n != 0) {
pw.println("No");
return;
}
cycle[] masktocyc = new cycle[1<<n];
long goal = sum / n;
ArrayList<cycle> cycs = new ArrayList<cycle>();
int[] graph = new int[incc];
l:
for(int i = 1; i < incc; i++) {
cycle c = new cycle();
int curr = i;
int val = arrs.get(i);
int ind = map2.get(val);
if(graph[i] != 0) continue;
do {
long ch = (goal - sums[ind] + val);
if(ch > inf || ch < -inf || !map1.containsKey((int)ch)) {
continue l;
}
val = (int)(ch);
graph[curr] = map1.get(val);
//pw.println(curr + " - " + map1.get(ch));
curr = map1.get(val);
c.add(ind, val);
ind = map2.get(val);
}
while(graph[curr] == 0);
for(tup x : c.arr) {
if(sums[x.a] - arrs.get(curr) + x.b == goal) break;
c.mask -= (1<<x.a);
x.a = -inf;
x.b = -inf;
}
int[] freq = new int[15];
for(tup x : c.arr) {
if(x.a >= 0) {
freq[x.a]++;
if(freq[x.a] > 1) continue l;
}
}
//for(tup x : c.arr) System.out.printf("%d %d%n", x.a, x.b);
//System.out.println(c.mask);
cycs.add(c);
masktocyc[c.mask] = c;
}
ArrayList<cycle>[] dp = new ArrayList[1<<n];
for(int m = 0; m < (1<<n); m++) {
dp[m] = new ArrayList<cycle>();
if(masktocyc[m] != null) {
dp[m].add(masktocyc[m]);
continue;
}
for(int s = m; s > 0; s = (s - 1) & m) {
if(dp[s].size() > 0 && dp[m ^ s].size() > 0) {
dp[m].addAll(dp[s]);
dp[m].addAll(dp[m ^ s]);
break;
}
}
}
if(dp[(1<<n) - 1].size() > 0) {
pw.println("Yes");
int[] ans1 = new int[n];
int[] ans2 = new int[n];
for(cycle x : dp[(1<<n) - 1]) {
for(tup y : x.arr) {
if(y.b != -inf) {
ans1[map2.get(y.b)] = y.a+1;
ans2[map2.get(y.b)] = y.b;
}
}
}
for(int i = 0; i < n; i++) {
pw.printf("%d %d%n", ans2[i], ans1[i]);
}
}
else pw.println("No");
}
static class cycle {
ArrayList<tup> arr = new ArrayList<>();
int mask = 0;
public cycle(){}
void add(int ind, int val) {
arr.add(new tup(ind, val));
mask += (1<<ind);
}
}
}
static long binpow(long a, long b, long m) {
a %= m;
long res = 1;
while (b > 0) {
if ((b & 1) == 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
static void sort(int[] x){
shuffle(x);
Arrays.sort(x);
}
static void sort(long[] x){
shuffle(x);
Arrays.sort(x);
}
static class tup implements Comparable<tup>{
int a, b;
tup(int a,int b){
this.a=a;
this.b=b;
}
@Override
public int compareTo(tup o){
return Integer.compare(o.b,b);
}
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(i + 1);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(i + 1);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
np
|
1242_C. Sum Balance
|
CODEFORCES
|
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
public class E1 {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner(System.in);
FastPrinter out = new FastPrinter(System.out);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
new E1().run(sc, out);
}
out.close();
}
int N, M, arr[][], ans;
public void run(FastScanner sc, FastPrinter out) throws Exception {
N = sc.nextInt();
M = sc.nextInt();
arr = new int[N][M];
int[][] nums = new int[N * M][3];
int count = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
int v = sc.nextInt();
arr[i][j] = v;
nums[count++] = new int[] { v, j, i };
}
}
Arrays.sort(nums, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
return b[0] - a[0];
}
});
// System.err.println(Arrays.deepToString(arr));
// System.err.println(Arrays.deepToString(nums));
if (N == 4 && M > 1) {
int colCount = 0;
HashMap<Integer, Integer> map = new HashMap<>();
// I believe you only need top 6 numbers?
for (int i = 0; i < 8; i++) {
int col = nums[i][1];
Integer newCol = map.get(col);
if (newCol == null) {
map.put(col, colCount++);
}
}
int[][] arr = new int[N][colCount];
for (int i = 0; i < 8; i++) {
int val = nums[i][0];
int col = map.get(nums[i][1]);
int row = nums[i][2];
arr[row][col] = val;
}
// System.err.println(Arrays.deepToString(arr));
solve(0, arr);
} else {
ans = 0;
for (int i = 0; i < N; i++) {
ans += nums[i][0];
}
}
System.out.println(ans);
}
private void solve(int index, int[][] arr) {
if (index == arr[0].length) {
int temp = 0;
for (int i = 0; i < arr.length; i++) {
int m = 0;
for (int j = 0; j < arr[i].length; j++) {
m = Math.max(m, arr[i][j]);
}
temp += m;
}
ans = Math.max(temp, ans);
} else {
for (int t = 0; t < N; t++) {
int v = arr[0][index];
for (int i = 0; i < N - 1; i++) {
arr[i][index] = arr[i + 1][index];
}
arr[N - 1][index] = v;
solve(index + 1, arr);
}
}
}
static class FastScanner {
final private int BUFFER_SIZE = 1 << 10;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastScanner() {
this(System.in);
}
public FastScanner(InputStream stream) {
din = new DataInputStream(stream);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastScanner(String fileName) throws IOException {
Path p = Paths.get(fileName);
buffer = Files.readAllBytes(p);
bytesRead = buffer.length;
}
int[] nextIntArray(int N) throws IOException {
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = nextInt();
}
return arr;
}
String nextLine() throws IOException {
int c = read();
while (c != -1 && isEndline(c))
c = read();
if (c == -1) {
return null;
}
StringBuilder res = new StringBuilder();
do {
if (c >= 0) {
res.appendCodePoint(c);
}
c = read();
} while (!isEndline(c));
return res.toString();
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
String next() throws Exception {
int c = readOutSpaces();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
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 {
if (din == null) {
bufferPointer = 0;
bytesRead = -1;
} else {
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++];
}
private int readOutSpaces() throws IOException {
while (true) {
if (bufferPointer == bytesRead) fillBuffer();
int c = buffer[bufferPointer++];
if (!isSpaceChar(c)) {
return c;
}
}
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
public int[][] readGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception {
int[][] adj = new int[N][];
int[] numNodes = new int[N];
int[][] input = new int[M][2];
for (int i = 0; i < M; i++) {
int a = nextInt();
int b = nextInt();
if (zeroIndexed) {
a--;
b--;
}
input[i][0] = a;
input[i][1] = b;
numNodes[a]++;
if (bidirectional) numNodes[b]++;
}
for (int i = 0; i < N; i++) {
adj[i] = new int[numNodes[i]];
numNodes[i] = 0;
}
for (int i = 0; i < M; i++) {
int a = input[i][0];
int b = input[i][1];
adj[a][numNodes[a]++] = b;
if (bidirectional) adj[b][numNodes[b]++] = a;
}
return adj;
}
public int[][][] readWeightedGraph(int N, int M, boolean zeroIndexed, boolean bidirectional) throws Exception {
int[][][] adj = new int[N][][];
int[] numNodes = new int[N];
int[][] input = new int[M][3];
for (int i = 0; i < M; i++) {
int a = nextInt();
int b = nextInt();
if (zeroIndexed) {
a--;
b--;
}
int d = nextInt();
input[i][0] = a;
input[i][1] = b;
input[i][2] = d;
numNodes[a]++;
if (bidirectional) numNodes[b]++;
}
for (int i = 0; i < N; i++) {
adj[i] = new int[numNodes[i]][2];
numNodes[i] = 0;
}
for (int i = 0; i < M; i++) {
int a = input[i][0];
int b = input[i][1];
int d = input[i][2];
adj[a][numNodes[a]][0] = b;
adj[a][numNodes[a]][1] = d;
numNodes[a]++;
if (bidirectional) {
adj[b][numNodes[b]][0] = a;
adj[b][numNodes[b]][1] = d;
numNodes[b]++;
}
}
return adj;
}
}
static class FastPrinter {
static final char ENDL = '\n';
StringBuilder buf;
PrintWriter pw;
public FastPrinter(OutputStream stream) {
buf = new StringBuilder();
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public FastPrinter(String fileName) throws Exception {
buf = new StringBuilder();
pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
}
public FastPrinter(StringBuilder buf) {
this.buf = buf;
}
public void print(int a) {
buf.append(a);
}
public void print(long a) {
buf.append(a);
}
public void print(char a) {
buf.append(a);
}
public void print(char[] a) {
buf.append(a);
}
public void print(double a) {
buf.append(a);
}
public void print(String a) {
buf.append(a);
}
public void print(Object a) {
buf.append(a.toString());
}
public void println() {
buf.append(ENDL);
}
public void println(int a) {
buf.append(a);
buf.append(ENDL);
}
public void println(long a) {
buf.append(a);
buf.append(ENDL);
}
public void println(char a) {
buf.append(a);
buf.append(ENDL);
}
public void println(char[] a) {
buf.append(a);
buf.append(ENDL);
}
public void println(double a) {
buf.append(a);
buf.append(ENDL);
}
public void println(String a) {
buf.append(a);
buf.append(ENDL);
}
public void println(Object a) {
buf.append(a.toString());
buf.append(ENDL);
}
public void printf(String format, Object... args) {
buf.append(String.format(format, args));
}
public void close() {
pw.print(buf);
pw.close();
}
public void flush() {
pw.print(buf);
pw.flush();
buf.setLength(0);
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(r.readLine());
String[] line = r.readLine().split("[ ]+");
int[] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = Integer.parseInt(line[i]);
Arrays.sort(a);
boolean found = false;
for(int i = 0; i < n && !found; i++)
if(a[i] != 1)found = true;
if(found){
System.out.println(1);
for(int i = 1; i < n; i++)
System.out.println(a[i-1]);
}else{
for(int i = 0; i < n-1; i++)
System.out.println(1);
System.out.println(2);
}
}
}
|
nlogn
|
135_A. Replacement
|
CODEFORCES
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class A {
static MyScanner sc;
static PrintWriter pw;
public static void main(String[] args) throws Throwable {
sc = new MyScanner();
pw = new PrintWriter(System.out);
n = sc.nextInt();
T = sc.nextLong();
p = new int[n];
l = new int[n];
x = new int[n];
t = new int[n];
adj = new ArrayList[n];
for (int i = 0; i < n; i++)
x[i] = sc.nextInt();
for (int i = 0; i < n; i++)
t[i] = sc.nextInt();
adj[0] = new ArrayList<>();
for (int i = 1; i < n; i++) {
adj[i] = new ArrayList<>();
p[i] = sc.nextInt() - 1;
l[i] = sc.nextInt();
adj[p[i]].add(i);
}
ftCnt = new long[N];
ftSum = new long[N];
ans = new long[n];
dfs(0);
pw.println(ans[0]);
pw.flush();
pw.close();
}
static int n;
static long T;
static int[] p, l, x, t;
static ArrayList<Integer>[] adj;
static long[] ans;
static void dfs(int u) {
update(t[u], x[u], 1L * x[u] * t[u]);
ans[u] = getMaxCnt();
long[] vals = {-1, -1, -1};
for (int v : adj[u]) {
T -= 2 * l[v];
dfs(v);
vals[0] = ans[v];
Arrays.sort(vals);
T += 2 * l[v];
}
if (u != 0) {
if (vals[1] != -1)
ans[u] = Math.max(ans[u], vals[1]);
} else {
if (vals[2] != -1)
ans[u] = Math.max(ans[u], vals[2]);
}
update(t[u], -x[u], -1L * x[u] * t[u]);
}
static int N = (int) 1e6 + 2;
static long[] ftCnt, ftSum;
static void update(int idx, long cnt, long val) {
while (idx < N) {
ftCnt[idx] += cnt;
ftSum[idx] += val;
idx += (idx & -idx);
}
}
static long getSum(int idx) {
long ret = 0;
while (idx > 0) {
ret += ftSum[idx];
idx -= (idx & -idx);
}
return ret;
}
static long getCnt(int idx) {
long ret = 0;
while (idx > 0) {
ret += ftCnt[idx];
idx -= (idx & -idx);
}
return ret;
}
static long getMaxCnt() {
int start = 1, end = N - 1, ans = N - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (getSum(mid) >= T) {
ans = mid;
end = mid - 1;
} else
start = mid + 1;
}
long remT = T - (ans > 1 ? getSum(ans - 1) : 0);
long cnt = (ans > 1 ? getCnt(ans - 1) : 0);
long cntOfVal = getCnt(ans) - cnt;
cnt += Math.min(cntOfVal, remT / ans);
return cnt;
}
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;
}
}
}
|
nlogn
|
1099_F. Cookies
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main implements Runnable {
public void _main() throws IOException {
long a = nextLong();
long b = nextLong();
long res = 0;
while (b > 0) {
res += a / b;
long t = a % b;
a = b;
b = t;
}
out.println(res);
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
private String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String rl = in.readLine();
if (rl == null)
return null;
st = new StringTokenizer(rl);
}
return st.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(next());
}
private long nextLong() throws IOException {
return Long.parseLong(next());
}
private double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) {
Locale.setDefault(Locale.UK);
new Thread(new Main()).start();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//in = new BufferedReader(new FileReader("a.in"));
//out = new PrintWriter(new FileWriter("a.out"));
_main();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(202);
}
}
}
|
constant
|
343_A. Rational Resistance
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner s= new Scanner(System.in);
int n=s.nextInt();StringBuilder sb=new StringBuilder();
long[] a=new long[n/2];
for(int i=0;i<n/2;i++){
a[i]=s.nextLong();
}int j=0;long[] a2=new long[n/2];long[] a1=new long[n/2];
a1[j]=a[a.length-1]/2;
a2[j]=a[a.length-1]-a[a.length-1]/2;
for(int i=(n-1)/2-1;i>=0;i--){
// a1[j]=a[i]/2;a2[j++]=a[i]-a[i]/2;
long n1=a1[j];
if((a[i]-n1)<a2[j]){
a2[j+1]=a2[j++];a1[j]=a[i]-a2[j];
}else{a1[++j]=n1;a2[j]=a[i]-n1;}
}int k=0;//int[] ans=new int[2*n];
for(int i=(n-1)/2;i>=0;i--)
sb.append(a1[i]+" ");
for(int i=0;i<n/2;i++)
sb.append(a2[i]+" ");
System.out.println(sb.toString());
}
}
|
linear
|
1093_C. Mishka and the Last Exam
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class B {
static double max;
static int n, A, b[], l[];
static int sw[];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int k = sc.nextInt();
A = sc.nextInt();
b = new int[n];
l = new int[n];
sw = new int[n];
for(int i=0; i<n; i++) {
b[i] = sc.nextInt();
l[i] = sc.nextInt();
}
max = 0;
search(k, 0);
System.out.println(max);
}
static void search(int k, int m) {
if(max == 1) return;
if(m == n) {
if(k > 0) return;
double pr[] = new double[n];
for(int i=0; i<n; i++) {
pr[i] = Math.min(100, l[i] + 10*sw[i])*1./100;
}
double ex = 0;
for(int i=0; i<1<<n; i++) {
double p = 1;
int cnt = 0;
int lv = 0;
for(int j=0; j<n; j++) {
if((i&(1<<j))>0) {
p *= pr[j];
cnt++;
}
else {
p *= (1-pr[j]);
lv += b[j];
}
}
if(cnt > n/2) {
ex += p;
}
else {
ex += p*A/(A+lv);
}
}
max = Math.max(max, ex);
return;
}
for(int i=k; i>=0; i--) {
sw[m] = i;
search(k-i, m+1);
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
eat("");
}
void eat(String s) {
st = new StringTokenizer(s);
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
throw new IOError(e);
}
}
boolean hasNext() {
while (!st.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
eat(s);
}
return true;
}
String next() {
hasNext();
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
np
|
105_B. Dark Assembly
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
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);
TaskE2 solver = new TaskE2();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class TaskE2 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
TaskE2.Column[] columns = new TaskE2.Column[m];
for (int i = 0; i < m; ++i) columns[i] = new TaskE2.Column(new int[n]);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
columns[j].vals[i] = in.nextInt();
}
}
for (int i = 0; i < m; ++i) columns[i].initMax();
Arrays.sort(columns, new Comparator<TaskE2.Column>() {
public int compare(TaskE2.Column o1, TaskE2.Column o2) {
return o2.max - o1.max;
}
});
if (columns.length > n) {
columns = Arrays.copyOf(columns, n);
}
out.println(solveOne(columns));
}
private int solveOne(TaskE2.Column[] columns) {
int n = columns[0].vals.length;
int[] best = new int[1 << n];
int[] next = new int[1 << n];
int[] tmp = new int[1 << n];
for (TaskE2.Column c : columns) {
System.arraycopy(best, 0, next, 0, best.length);
for (int rot = 0; rot < n; ++rot) {
System.arraycopy(best, 0, tmp, 0, best.length);
for (int i = 0, pos = rot; i < n; ++i, ++pos) {
if (pos >= n) pos = 0;
int val = c.vals[pos];
for (int j = 0; j < tmp.length; ++j)
if ((j & (1 << i)) == 0) {
tmp[j ^ (1 << i)] = Math.max(tmp[j ^ (1 << i)], tmp[j] + val);
}
}
for (int j = 0; j < tmp.length; ++j) {
next[j] = Math.max(next[j], tmp[j]);
}
}
int[] aa = best;
best = next;
next = aa;
}
return best[best.length - 1];
}
static class Column {
int[] vals;
int max;
public Column(int[] vals) {
this.vals = vals;
}
void initMax() {
max = 0;
for (int x : vals) max = Math.max(max, x);
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.io.*;
import java.util.StringTokenizer;
public class NewYearCurling908C {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner();
int n = in.nextInt();
double r = (double) in.nextInt();
double[] answers = new double[n];
double[] xCoords = new double[n];
for (int i = 0; i < n; i++) xCoords[i] = (double) in.nextInt();
answers[0] = r;
for (int i = 1; i < n; i++) {
double bound = r;
for (int j = 0; j < i; j++) {
double xDif = xCoords[i] - xCoords[j];
double y = answers[j];
double yNew = y + Math.sqrt(4 * r * r - xDif * xDif);
if (yNew > bound) bound = yNew;
}
answers[i] = bound;
}
for (int i = 0; i < n; i++) System.out.print(answers[i] + " ");
System.out.println();
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
st = null;
try {
return br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
// editorial sol
public class cf1238e {
public static void main(String[] args) throws IOException {
int n = rni(), m = ni(), cnt[][] = new int[m][m], dp[] = new int[1 << m], all = (1 << m) - 1;
char[] s = rcha();
for (int i = 1; i < n; ++i) {
++cnt[s[i] - 'a'][s[i - 1] - 'a'];
++cnt[s[i - 1] - 'a'][s[i] - 'a'];
}
fill(dp, IBIG);
dp[0] = 0;
int cnt_bit[] = new int[1 << m], min_bit[] = new int[1 << m], d[][] = new int[1 << m][m];
for (int mask = 1; mask <= all; ++mask) {
cnt_bit[mask] = 1 + cnt_bit[mask & (mask - 1)];
for (int i = 0; i < n; ++i) {
if ((mask & (1 << i)) > 0) {
min_bit[mask] = i;
break;
}
}
}
for (int mask = 1; mask <= all; ++mask) {
for (int i = 0; i < m; ++i) {
d[mask][i] = d[mask ^ (1 << min_bit[mask])][i] + cnt[i][min_bit[mask]];
}
}
for (int mask = 0; mask <= all; ++mask) {
for (int i = 0; i < m; ++i) {
if ((mask & (1 << i)) > 0) {
continue;
}
int pos = cnt_bit[mask], next = mask | (1 << i);
dp[next] = min(dp[next], dp[mask] + pos * (d[mask][i] - d[all ^ next][i]));
}
}
prln(dp[all]);
close();
}
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();}}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
import java.util.*;
public class ex1 {
public static void main(String[] args) {
int n,i,j;
Scanner scan = new Scanner(System.in);
n = Integer.parseInt(scan.nextLine());
if(n>=0)
System.out.println(n);
else if(n<0) {
n=-1*n;
i=n/10;
j=(n/100)*10+n%10;
i=-i;
j=-j;
if(i>=j)
System.out.println(i);
else
System.out.println(j);
}
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.util.Map;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.HashSet;
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] p = new int[n];
for (int i = 0; i < n; ++i)
p[i] = in.nextInt();
Map<Integer, Integer> position = new HashMap<>(n);
for (int i = 0; i < n; ++i)
position.put(p[i], i);
DisjointSet sets = new DisjointSet(n);
for (int i = 0; i < n; ++i) {
if (position.containsKey(a - p[i]))
sets.joinSet(i, position.get(a - p[i]));
if (position.containsKey(b - p[i]))
sets.joinSet(i, position.get(b - p[i]));
}
Group[] groups = new Group[n];
for (int i = 0; i < n; ++i)
if (sets.getSet(i) == i)
groups[i] = new Group();
for (int i = 0; i < n; ++i)
groups[sets.getSet(i)].value.add(p[i]);
int[] answer = new int[n];
for (Group group : groups) if (group != null) {
if (group.check(a)) {
for (int key : group.value)
answer[position.get(key)] = 0;
} else if (group.check(b)) {
for (int key : group.value)
answer[position.get(key)] = 1;
} else {
out.println("NO");
return;
}
}
out.println("YES");
for (int i = 0; i < n; ++i) {
if (i > 0) out.print(' ');
out.print(answer[i]);
}
out.println();
}
class Group {
Set<Integer> value = new HashSet<>();
boolean check(int sum) {
for (int key : value)
if (!value.contains(sum - key))
return false;
return true;
}
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
class DisjointSet {
private final int[] label;
private int numSets;
private Listener listener;
public DisjointSet(int n, Listener listener) {
label = new int[n];
Arrays.fill(label, -1);
numSets = n;
this.listener = listener;
}
public DisjointSet(int n) {
this(n, null);
}
public int getSet(int at) {
if (label[at] < 0) return at;
return label[at] = getSet(label[at]);
}
public boolean sameSet(int u, int v) {
return getSet(u) == getSet(v);
}
public boolean joinSet(int u, int v) {
if (sameSet(u, v)) return false;
u = getSet(u);
v = getSet(v);
if (label[u] < label[v]) {
int tmp = u;
u = v;
v = tmp;
}
label[v] += label[u];
label[u] = v;
--numSets;
if (listener != null) listener.joined(u, v);
return true;
}
public static interface Listener {
public void joined(int joinedRoot, int root);
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Contest {
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s=br.readLine().split(" ");
BigInteger x = new BigInteger(s[0]);
BigInteger k = new BigInteger(s[1]);
BigInteger mod = new BigInteger(String.valueOf((int) (Math.pow(10, 9) + 7)));
BigInteger two = new BigInteger("2");
BigInteger interm = two.modPow(k, mod);
BigInteger res = interm.multiply(x).add(interm.multiply(x)).subtract(interm).add(BigInteger.ONE).mod(mod);
if(x.equals(BigInteger.ZERO)) {
System.out.println("0");
return;
}
System.out.println(res);
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
public static void quickSort(int[] a, int from, int to) {
if (to - from <= 1) {
return;
}
int i = from;
int j = to - 1;
int x = a[from + (new Random()).nextInt(to - from)];
while (i <= j) {
while (a[i] < x) {
i++;
}
while (a[j] > x) {
j--;
}
if (i <= j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
i++;
j--;
}
}
quickSort(a, from, j + 1);
quickSort(a, j + 1, to);
}
public void solve() {
int n = in.nextInt();
HashSet<Long> ans = new HashSet<>();
Long d = in.nextLong();
long[] a = new long[n];
for (int i = 0; i < a.length; i++) {
a[i] = in.nextInt();
}
for (int i = 0; i < a.length; i++) {
long x = a[i] - d;
boolean flag = true;
for (int j = 0; j < a.length; j++) {
if (Math.abs(a[j] - x) < d) {
flag = false;
break;
}
}
if (flag) {
ans.add(x);
}
x = a[i] + d;
flag = true;
for (int j = 0; j < a.length; j++) {
if (Math.abs(a[j] - x) < d) {
flag = false;
break;
}
}
if (flag) {
ans.add(x);
}
}
out.println(ans.size());
}
public void run() {
try {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
}
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] args) {
new A().run();
}
}
|
linear
|
1004_A. Sonya and Hotels
|
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 {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int[] a = IOUtils.readIntArray(in, n);
MiscUtils.decreaseByOne(a);
int m = in.readInt();
int parity = inversions(a) % 2;
boolean[] lengthToParityFlip = new boolean[n + 1];
for (int length = 1; length < lengthToParityFlip.length; length++) {
lengthToParityFlip[length] = (((length * (length - 1) / 2) % 2) == 1);
}
for (int query = 0; query < m; query++) {
int l = in.readInt() - 1, r = in.readInt() - 1;
int length = r - l + 1;
if (lengthToParityFlip[length]) {
parity ^= 1;
}
out.printLine(parity == 0 ? "even" : "odd");
}
}
private int inversions(int[] a) {
int res = 0;
for (int j = 0; j < a.length; j++) {
for (int i = j + 1; i < a.length; i++) {
if (a[i] < a[j]) {
res++;
}
}
}
return res;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class MiscUtils {
public static void decreaseByOne(int[]... arrays) {
for (int[] array : arrays) {
for (int i = 0; i < array.length; i++) {
array[i]--;
}
}
}
}
static class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = in.readInt();
}
return array;
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package newpackage;
import java.util.*;
/**
*
* @author parpaorsa
*/
public class NewClass {
static Scanner in=new Scanner(System.in);
public static void main(String[] args) {
int n = in.nextInt(),ans=Integer.MAX_VALUE,t=0;
String x = in.next();
for (int i = 0; i < n; i++) {
if(x.charAt(i)=='-')t--;
else t++;
ans=Math.min(ans,t);
}
if(ans <= 0)
System.out.println(Math.abs(ans)+t);
else
System.out.println(t);
}
}
|
linear
|
1159_A. A pile of stones
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Solver {
StringTokenizer st;
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws NumberFormatException, IOException {
Solver solver = new Solver();
solver.open();
solver.solve();
solver.close();
}
public void open() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
public String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
public void solve() throws NumberFormatException, IOException {
int n = nextInt();
int[] ar = new int[n];
int sum = 0;
for (int i=0;i<n;i++){
ar[i]=nextInt();
sum+=ar[i];
}
Arrays.sort(ar);
int me = 0;
int k = 0;
while (me<=sum){
k++;
int coin = ar[ar.length-k];
me += coin;
sum -= coin;
}
out.println(k);
}
public void close() {
out.flush();
out.close();
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class TaskB implements Runnable {
boolean prime[] = new boolean[(int)1e6+10];
InputReader c;
PrintWriter w;
public void run() {
c = new InputReader(System.in);
w = new PrintWriter(System.out);
char a[] = c.next().toCharArray(), b[] = c.next().toCharArray();
int n = a.length, m = b.length;
int[][] prefix = new int[m][2];
for(int i=0;i<m;i++){
if(i!=0) {
prefix[i][0] = prefix[i-1][0];
prefix[i][1] = prefix[i-1][1];
}
prefix[i][b[i] - '0']++;
//w.println(prefix[i][0]+" "+prefix[i][1]);
}
long res = 0;
for(int i=0;i<n;i++){
int temp = a[i] - '0';
res += prefix[m - n + i][temp^1];
if(i!=0) res -= prefix[i-1][temp^1];
}
w.println(res);
w.close();
}
void sieveOfEratosthenes(int n) {
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*p; i <= n; i += p)
prime[i] = false;
}
}
}
class pair implements Comparable<pair>{
char ch;
int ind;
@Override
public String toString() {
return "pair{" +
"ch=" + ch +
", ind=" + ind +
'}';
}
public pair(char ch, int ind) {
this.ch = ch;
this.ind = ind;
}
public int compareTo(pair car) {
if(this.ch==car.ch)
return this.ind - car.ind;
return this.ch - car.ch;
}
}
public static void sortbyColumn(int arr[][], int col){
Arrays.sort(arr, new Comparator<int[]>()
{
public int compare(int[] o1, int[] o2){
return(Integer.valueOf(o1[col]).compareTo(o2[col]));
}
});
}
static long gcd(long a, long b){
if (b == 0)
return a;
return gcd(b, a % b);
}
public static class DJSet {
public int[] upper;
public DJSet(int n) {
upper = new int[n];
Arrays.fill(upper, -1);
}
public int root(int x) {
return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
}
public boolean equiv(int x, int y) {
return root(x) == root(y);
}
public boolean union(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (upper[y] < upper[x]) {
int d = x;
x = y;
y = d;
}
upper[x] += upper[y];
upper[y] = x;
}
return x == y;
}
}
public static int[] radixSort(int[] f) {
int[] to = new int[f.length];
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
public void printArray(int[] a){
for(int i=0;i<a.length;i++)
w.print(a[i]+" ");
w.println();
}
public int[] scanArrayI(int n){
int a[] = new int[n];
for(int i=0;i<n;i++)
a[i] = c.nextInt();
return a;
}
public long[] scanArrayL(int n){
long a[] = new long[n];
for(int i=0;i<n;i++)
a[i] = c.nextLong();
return a;
}
public void printArray(long[] a){
for(int i=0;i<a.length;i++)
w.print(a[i]+" ");
w.println();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new TaskB(),"TaskB",1<<26).start();
}
}
|
linear
|
608_B. Hamming Distance Sum
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;
public class Main extends PrintWriter {
static BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
// static Scanner s=new Scanner(System.in);
Main () { super(System.out); }
public static void main(String[] args) throws IOException{
Main d1=new Main ();d1.main();d1.flush();
}
void main() throws IOException {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb = new StringBuffer();
StringBuffer sb1 = new StringBuffer();
PrintWriter out = new PrintWriter(System.out);
int t=1;
// t=i(s()[0]);
while(t-->0) {
//dp[i]=a[i]+max(dp[j]) S.T. j<i and h[j]<h[i];
String[] s1 = s();
int n = i(s1[0]);
long[] a=new long[n];
arr(a,n);
HashMap<Long,Integer>[] dp=new HashMap[n];
long[] presum=new long[n];
for(int i=0;i<n;i++){
if(i==0){
presum[i]=a[i];
}else{
presum[i]=a[i]+presum[i-1];
}
}HashMap<Long,TreeMap<Integer,Long> > tm=new HashMap<>();int ans=0;long maxsum=0;
for(int i=0;i<n;i++){
dp[i]=new HashMap<>();
for(int j=-1;j<i;j++){
long sum=0;
if(j==-1) sum=presum[i];else sum=presum[i]-presum[j];
// if(sum==5&&i==5) System.out.println(tm.get(sum).floorKey(4));
if(tm.containsKey(sum)&&tm.get(sum).floorKey(j)!=null){
dp[i].put(sum,Math.max(dp[i].getOrDefault(sum,0),dp[tm.get(sum).floorKey(j)].getOrDefault(sum,0)+1));
if(dp[i].get(sum)>ans){
maxsum=sum;
}
ans=Math.max(ans,dp[i].get(sum));
}else if(dp[i].containsKey(sum)==false){
if(dp[i].getOrDefault(sum,0)<1) dp[i].put(sum,1);
if(dp[i].get(sum)>ans){
maxsum=sum;
}
ans=Math.max(ans,1);
}
long val=dp[i].getOrDefault(sum,0);
// if(tm.containsKey(sum)&&tm.get(sum).floorKey(i-1)!=null){
if(!tm.containsKey(sum)||tm.get(sum).floorKey(i-1)==null||dp[tm.get(sum).floorKey(i-1)].getOrDefault(sum,0)<val) {
// val = Math.max(val, dp[tm.get(sum).floorKey(i - 1)].getOrDefault(sum, 0));
TreeMap<Integer, Long> tt = new TreeMap<>();
tt.put(i, val);
tm.put(sum, tt);
}
// }
}
}int cnt=0;int last=-1;
for(int i=0;i<n;i++){
for(int j=i-1;j>=-1;j--){
long sum=0;
if(j==-1) sum=presum[i];
else sum=presum[i]-presum[j];
if(dp[i].getOrDefault(maxsum,0)>cnt&&maxsum==sum){
sb.append(j+2+" "+(i+1)+"\n");cnt++;
break;
}
}
} System.out.println(ans);
// System.out.println(dp[5].get(5L)+" "+dp[4].get(5L));
System.out.println(sb);
}
}
// System.out.println(sb);
long[] st;
void buildtree(int i,int s,int e,long[] a){
if(s==e){
st[i]=a[s];
return;
}
int mid=(s+e)/2;
buildtree(2*i,s,mid,a);
buildtree(2*i+1,mid+1,e,a);
st[i]=Math.min(st[2*i],st[2*(i)+1]);
}
long query(int i,int s,int e,int qs,int qe){
if(qs>e||qe<s) return Integer.MIN_VALUE;
if(s>=qs&&e<=qe) return st[i];
int mid=(s+e)/2;
long l=query(2*i,s,mid,qs,qe);
long r=query(2*i+1,mid+1,e,qs,qe);
return Math.max(l,r);
}
void pointupdate(int i,int s,int e,int qi,long [] a){
if(s==e){
st[i]=a[s];return;
}
int mid=(s+e)/2;
if(qi<=mid) pointupdate(2*i,s,mid,qi,a);
else pointupdate(2*(i)+1,mid+1,e,qi,a);
st[i]=Math.max(st[2*i],st[2*i+1]);
}
public void arr(long[] a,int n) throws IOException{
// BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
String[] s2=s();
for(int i=0;i<n;i++){
a[i]=i(s2[i]);
}
}
public void sort(int[] a,int l,int h){
if(l==h) return;
int mid=(l+h)/2;
sort(a,l,mid);
sort(a,mid+1,h);
merge(a,l,(l+h)/2,h);
}
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static String[] s() throws IOException {
return s.readLine().trim().split("\\s+");
}
static int i(String ss) {
return Integer.parseInt(ss);
}
static long l(String ss) {
return Long.parseLong(ss);
}
}
class Student {
long a;int b;int c;
public Student(int a,int b) {
this.a=a;this.c=c;this.b=b;
}
}
class Pair {
int a,b,c;
public Pair(int a,int b){
this.a=a;this.b=b;this.c=c;}
}
class Sortbyroll implements Comparator<Student> {
public int compare(Student a, Student b){
if(a.b==b.b) return (int)b.a-(int)a.a;
return a.b-b.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.StringTokenizer;
public class D {
public static void main(String[] args) throws IOException {
new D().solve();
}
static final double EPS = 1e-10;
Parser parser;
enum Result {
UNDER, OVER
}
private void solve() throws IOException {
this.parser = new Parser(new BufferedReader(new InputStreamReader(System.in)));
double a = parser.nextInt();
double vmax = parser.nextInt();
double l = parser.nextInt();
double d = parser.nextInt();
double w = parser.nextInt();
double low = 0;
double high = 20000;
while (Math.abs(high - low) > 1e-10) {
double accelerateTime = (low + high) / 2;
Result res = check(accelerateTime, a, vmax, d, w).result;
if (res == Result.UNDER) {
low = accelerateTime;
} else {
high = accelerateTime;
}
}
IP ip = check(high, a, vmax, d, w);
TV tv = tv(ip.v, l - d, a, vmax);
PrintWriter pw = new PrintWriter(System.out);
pw.printf("%.5f\n", ip.time + tv.time);
pw.close();
}
private IP check(double accelerateTime, double a, double vmax, double d, double w) {
DV dv = dv(0, a, accelerateTime, vmax);
if (dv.d > d) {
return new IP(accelerateTime, dv.v, Result.OVER);
}
Double slowTime = time2MakeDist(-a, dv.v, d - dv.d);
if (slowTime == null) {
return new IP(0, 0, Result.UNDER);
}
double vDown = dv.v - a * slowTime;
if (vDown < w) {
return new IP(0, 0, Result.UNDER);
} else {
return new IP(accelerateTime + slowTime, vDown, Result.OVER);
}
}
static class IP {
final double time;
final double v;
final Result result;
IP(double time, double v, Result result) {
this.time = time;
this.v = v;
this.result = result;
}
}
static class DV {
final double d;
final double v;
DV(double d, double v) {
this.d = d;
this.v = v;
}
}
static class TV {
final double time;
final double v;
TV(double time, double v) {
this.time = time;
this.v = v;
}
}
static Double time2MakeDist(double a, double v0, double dist) {
return quadric(a / 2, v0, -dist);
}
static TV tv(double v0, double d, double a, double vmax) {
double acTime = (vmax - v0) / a;
double unboundedTime = time2MakeDist(a, v0, d);
if (unboundedTime > acTime) {
double ad = dist(v0, a, acTime);
return new TV(acTime + (d - ad) / vmax, vmax);
} else {
return new TV(unboundedTime, v0 + a * unboundedTime);
}
}
static DV dv(double v0, double a, double time, double vmax) {
double time2maxV = (vmax - v0) / a;
if (time2maxV < time) {
return new DV(dist(v0, a, time2maxV) + dist(vmax, 0, time - time2maxV), vmax);
} else {
return new DV(dist(v0, a, time), v0 + a * time);
}
}
static double dist(double v0, double a, double time) {
return v0 * time + a * time * time / 2;
}
static Double quadric(final double a, final double b, final double c) {
double d = b * b - 4 * a * c;
if (d < -EPS) {
return null;
}
d = Math.abs(d);
double x1 = (-b + Math.sqrt(d)) / (2 * a);
double x2 = (-b - Math.sqrt(d)) / (2 * a);
double r = Integer.MAX_VALUE;
if (x1 > -EPS) {
r = x1;
}
if (x2 > -EPS) {
r = Math.min(r, x2);
}
if (r == Integer.MAX_VALUE) {
throw new RuntimeException("BOTVA");
}
return r;
}
static class Parser {
final BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public Parser(BufferedReader bufferedReader) {
this.br = bufferedReader;
}
String nextToken() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class B
{
public static void main(String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
long n = in.nextLong();
long k = in.nextLong();
if(n == 1)
{
System.out.println(0);
return;
}
if(n <= k)
{
System.out.println(1);
return;
}
long lb = 2, ub = k;
long sum = ((k)*(k-1))/2;
if(sum+1 < n)
{
System.out.println(-1);
return;
}
while(ub - lb > 1)
{
long mid = (lb+ub)/2;
long s = ((mid-1)*(mid-2))/2;
if(n - (sum-s+1) < 0)
lb = mid;
else
ub = mid;
}
long rem = n - (sum - ((ub-1)*(ub-2))/2 + 1);
long res = k - ub + 1;
if(rem == 0)
{
System.out.println(res);
return;
}
rem++;
if(!(rem >= 2 && rem < ub))
{
System.out.println(-1);
return;
}
System.out.println(res+1);
}
}
|
logn
|
287_B. Pipeline
|
CODEFORCES
|
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class FireAgain
{
public static void main(String[] args) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
Scanner sc = new Scanner(in);
int h = sc.nextInt();
int w = sc.nextInt();
int k = sc.nextInt();
int[] xk = new int[k];
int[] yk = new int[k];
for(int i = 0; i < k; i++)
{
int y = sc.nextInt()-1;
int x = sc.nextInt()-1;
xk[i] = x;
yk[i] = y;
}
int best = -1;
int bestx = -1;
int besty = -1;
for(int x = 0; x < w; x++)
{
for(int y = 0; y < h; y++)
{
int cur = 99999;
for(int f = 0; f < k; f++)
{
cur = Math.min(cur, Math.abs(xk[f] - x)+Math.abs(yk[f] - y));
}
if(cur > best)
{
best = cur;
bestx = x;
besty = y;
}
}
}
// System.out.println((besty+1) + " " + (bestx+1));
String s = (besty+1) + " " + (bestx+1);
out.write(s.getBytes());
}finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class E {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt(),k=sc.nextInt();
boolean [][]adj=new boolean[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
adj[i][j]=sc.nextInt()==1;
int n1=n/2,n2=n-n1;
int []clique=new int [1<<n1];
for(int msk=1;msk<1<<n1;msk++)
{
boolean ok=true;
for(int i=0;i<n1;i++) if((msk & 1<<i) !=0)
for(int j=i+1;j<n1;j++)
if((msk & 1<<j) !=0 && !adj[i][j])
ok=false;
if(ok)
clique[msk]=Integer.bitCount(msk);
}
int []edges=new int [n2];
for(int i=0;i<n2;i++)
{
int msk=0;
for(int j=0;j<n1;j++)
if(adj[i+n1][j])
msk|=1<<j;
edges[i]=msk;
}
int max=0;
for(int msk=1;msk<1<<n1;msk++)
for(int i=0;i<n1;i++)
if((msk & 1<<i) !=0)
max=Math.max(max, clique[msk]=Math.max(clique[msk], clique[msk^(1<<i)]));
for(int msk=1;msk<1<<n2;msk++)
{
int all=(1<<n1)-1;
for(int j=0;j<n2;j++)
if((msk & 1<<j) !=0)
all &=edges[j];
boolean ok=true;
for(int i=0;i<n2;i++) if((msk & 1<<i) !=0)
for(int j=i+1;j<n2;j++)
if((msk & 1<<j) !=0 && !adj[i+n1][j+n1])
ok=false;
if(ok)
max=Math.max(max, Integer.bitCount(msk)+clique[all]);
}
out.printf("%.9f\n",k*1.0*k*(max-1)/(2*max));
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public boolean ready() throws IOException {return br.ready();}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
}
}
|
np
|
839_E. Mother of Dragons
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A{
InputStream is;
PrintWriter out;
String INPUT = "";
public void solve(){
int n=ni();
int ans=0;
int[] arr=na(n);
for(int i=0;i<n;i++){
for(int j=i+1; j<n; j++){
if(arr[i] > arr[j]){
ans^=1;
}
}
}
int m=ni();
while(m-->0){
int a=ni(), b=ni();
int diff=Math.abs(a-b)+1;
ans = ans ^ ((((diff-1)*diff)/2)%2);
out.println(ans==0 ? "even" : "odd");
}
}
void print(int n, long[][] memo){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
out.print(memo[i][j]+" ");
}
out.println();
}
}
void run(){
is = new DataInputStream(System.in);
out = new PrintWriter(System.out);
int t=1;while(t-->0)solve();
out.flush();
}
public static void main(String[] args)throws Exception{new A().run();}
//Fast I/O code is copied from uwi code.
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();
}
}
static int i(long x){return (int)Math.round(x);}
static class Pair implements Comparable<Pair>{
long fs,sc;
Pair(long a,long b){
fs=a;sc=b;
}
public int compareTo(Pair p){
if(this.fs>p.fs)return 1;
else if(this.fs<p.fs)return -1;
else{
return i(this.sc-p.sc);
}
//return i(this.sc-p.sc);
}
public String toString(){
return "("+fs+","+sc+")";
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
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);
new TaskC().solve(in, out);
out.close();
}
}
class TaskC {
static final long mod=1000000009;
public void solve(InputReader in,PrintWriter out) {
int n=in.nextInt();
int m=in.nextInt();
int k=in.nextInt();
int l=0,r=m/k;
while(l<r) {
int mid=(l+r)>>>1;
if(good(n,m,k,mid)){
r=mid;
}
else{
l=mid+1;
}
}
Mat u=new Mat();
u.set(k,1,0,0);
Mat v=new Mat();
v.set(2,0,k,1);
u=u.mul(v.powMat(l));
out.println((u.e[0][0]-k+(m-l*k)+mod)%mod);
}
private boolean good(int n, int m, int k, int mid) {
n-=mid*k;
m-=mid*k;
int ans=n/k*(k-1)+n%k;
if(ans>=m)
return true;
return false;
}
private static class Mat {
long[][] e=new long[2][2];
Mat mul(Mat u) {
Mat s=new Mat();
s.set(0,0,0,0);
for(int i=0;i<2;i++) {
for(int j=0;j<2;j++) {
for(int k=0;k<2;k++){
s.e[i][j]=(s.e[i][j]+e[i][k]*u.e[k][j])%mod;
}
}
}
return s;
}
Mat powMat(int k) {
Mat u=this;
Mat s=new Mat();
s.set(1,0,0,1);
while(k!=0) {
if(k%2==1) {
s=s.mul(u);
}
u=u.mul(u);
k/=2;
}
return s;
}
void set(long i, long j, long k, long l) {
e[0][0]=i;
e[0][1]=j;
e[1][0]=k;
e[1][1]=l;
}
}
}
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());
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.util.*;
import static java.lang.System.out;
public final class LookingForOrder {
private static Map<Integer, Integer> es = new HashMap<Integer, Integer>();
private static void init() { for (int i = 0; i <= 24; i++) es.put(1 << i, i); }
private static int x, y;
private static int[] xs, ys;
private static int sqr(int i) { return i * i; }
private static int dist(int i, int j) {
return sqr(x - xs[i]) + sqr(y - ys[i]) +
sqr(xs[i] - xs[j]) + sqr(ys[i] - ys[j]) +
sqr(x - xs[j]) + sqr(y - ys[j]);
}
private static int n;
private static int[] tb, prevs;
private static int recur(int j) {
if (j == 0 || es.get(j) != null || tb[j] != 0) return tb[j];
int bl = j & -j;
int b = j ^ bl;
tb[j] = recur(bl) + recur(b);
prevs[j] = bl;
for (int i = es.get(bl) + 1; i <25; i++) {
if (((1 << i) & b) == 0) continue;
int k = bl | 1 << i;
int v = dist(es.get(bl), es.get(1 << i)) + recur(j ^ k);
if (v >= tb[j]) continue;
tb[j] = v;
prevs[j] = k;
}
return tb[j];
}
public static void main(String[] args) {
init();
Scanner s = new Scanner(System.in);
x = s.nextInt(); y = s.nextInt();
n = s.nextInt();
xs = new int[n]; ys = new int[n];
tb = new int[1 << n]; prevs = new int[1 << n];
for (int i = 0; i < n; i++) {
xs[i] = s.nextInt(); ys[i] = s.nextInt();
tb[1 << i] = sqr(x - xs[i]) + sqr(y - ys[i]) << 1;
}
int all = (1 << n) - 1;
out.println(recur(all));
StringBuilder sb = new StringBuilder();
int p = prevs[all];
int c = all;
while(p != 0 && p != c) {
if ((p ^ (p & -p)) == 0) sb.append("0 " + (es.get(p & -p) + 1) + " ");
else sb.append("0 " + (es.get(p & -p) + 1) + " " + (es.get(p ^ (p & -p)) + 1) + " ");
c = c ^ p;
p = prevs[c];
}
if ((c ^ (c & -c)) == 0) sb.append("0 " + (es.get(c & -c) + 1) + " 0");
else sb.append("0 " + (es.get(c & -c) + 1) + " " + (es.get(c ^ (c & -c)) + 1) + " 0");
out.println(sb);
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.*;
import java.util.StringTokenizer;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class Main {
FastScanner in;
PrintWriter out;
void run() {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
public static void main(String[] args) {
new Main().run();
}
void solve() {
int t = in.nextInt();
for (int sdfsdf = 0; sdfsdf < t; sdfsdf++) {
long n = in.nextLong();
long k = in.nextLong();
if (n == 1) {
if (k == 1) {
out.println("YES 0");
} else {
out.println("NO");
}
continue;
}
if (k == 3) {
if (n == 2) {
out.println("NO");
} else {
out.println("YES " + (n - 1));
}
continue;
}
long cuts = 1;
long squares = 4;
int zoom = 1;
while (k > cuts + squares) {
cuts += squares;
squares *= 4;
zoom++;
}
if (zoom > n) {
out.println("NO");
continue;
}
if (zoom == n && k > cuts) {
out.println("NO");
continue;
}
long current_cuts = k - cuts;
if (current_cuts > squares - (2L * Math.sqrt(squares) - 1L)) {
out.println("YES " + (n - zoom - 1L));
} else {
out.println("YES " + (n - zoom));
}
}
}
}
|
logn
|
1080_D. Olya and magical square
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.