src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class a1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int a[] = new int[n];
HashMap<Integer,ArrayList<Integer>> h = new HashMap<>();
boolean visited[] = new boolean[n];
for(int i=0;i<n;i++)
{
a[i] = s.nextInt();
}
Arrays.sort(a);
for(int i=0;i<n;i++) {
if(h.containsKey(a[i])) {
ArrayList<Integer> temp = h.get(a[i]);
temp.add(i);
h.put(a[i],temp);
}
else {
ArrayList<Integer> k =new ArrayList<>();
k.add(i);
h.put(a[i], k);
}
}
int ctr=0;
for(int i=0;i<n;i++) {
if(!visited[i]) {
//System.out.println(a[i]);
ctr++;
for(int j=a[i];j<=100;j+=a[i]) {
if(h.containsKey(j)) {
ArrayList<Integer> m = h.get(j);
for(int k=0;k<m.size();k++) {
visited[m.get(k)]=true;
}
h.remove(j);
}
}
}
}
System.out.println(ctr);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.LinkedList;
import java.util.Locale;
import java.util.Scanner;
public class A{
void exe(){
LinkedList<Integer> list=new LinkedList<Integer>();
for(int i=2;i<=1000;i++)
if(isPrime(i))
list.add(i);
Object[] primes=list.toArray();
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
int cnt=0;
for(int c=2;c<=n;c++){
if(!isPrime(c))
continue;
for(int i=0;i<primes.length-1;i++){
int p1=(Integer)primes[i];
int p2=(Integer)primes[i+1];
if(c==1+p1+p2){
// System.out.println("c="+c+", i="+p1+", j="+p2);
cnt++;
}
}
}
if(cnt>=k){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
boolean isPrime(int n){
if(n<=1)return false;
if(n==2)return true;
if(n%2==0)return false;
int m=(int)Math.sqrt(n)+1;
for(int i=3;i<=m;i+=2)
if(n%i==0)
return false;
return true;
}
public static void main(String[] args){
Locale.setDefault(Locale.US);
new A().exe();
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
/**
* @author derrick20
*/
import java.io.*;
import java.util.*;
public class SameSumBlocks {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
int[] pre = new int[N + 1];
for (int i = 1; i <= N; i++) {
pre[i] = pre[i - 1] + sc.nextInt();
}
// var sumMap = new HashMap<Integer, ArrayList<Pair>>();
// var sums = new ArrayList<Pair>();
Pair[] sums = new Pair[N * (N + 1) / 2];
int k = 0;
for (int i = 1; i <= N; i++) {
for (int j = i; j <= N; j++) {
int sum = pre[j] - pre[i - 1];
// sumMap.computeIfAbsent(sum, val -> new ArrayList<>()).add(new Pair(i, j, sum));
sums[k++] = new Pair(i, j, sum);
}
}
Arrays.sort(sums, (p1, p2) -> p1.sum - p2.sum != 0 ? p1.sum - p2.sum : p1.r - p2.r);
var ans = new ArrayList<Pair>();
int i = 0;
while (i < k) {
var group = new ArrayList<Pair>();
int last = 0;
int j = i;
while (j < k && sums[j].sum == sums[i].sum) {
if (sums[j].l > last) {
group.add(sums[j]);
last = sums[j].r;
}
j++;
}
// System.out.println(group);
if (group.size() > ans.size()) {
ans = group;
}
i = j;
}
out.println(ans.size());
for (Pair p : ans) {
out.println(p);
}
out.close();
}
static class Pair {
int l, r, sum;
public Pair(int ll, int rr, int ss) {
l = ll; r = rr; sum = ss;
}
public String toString() {
return l + " " + r;
}
}
static class FastScanner {
private int BS = 1<<16;
private char NC = (char)0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt=1;
boolean neg = false;
if(c==NC)c=getChar();
for(;(c<'0' || c>'9'); c = getChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=getChar()) {
res = (res<<3)+(res<<1)+c-'0';
cnt*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/cnt;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=getChar();
while(c>32) {
res.append(c);
c=getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=getChar();
while(c!='\n') {
res.append(c);
c=getChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=getChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class cf {
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
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 double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
pw.println(n/2+1);
pw.close();
}
}
|
constant
|
964_A. Splits
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int S=Integer.parseInt(s1[1]);
if(S%n==0)
System.out.println(S/n);
else
System.out.println(S/n+1);
}
}
|
constant
|
1061_A. Coins
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.util.function.Consumer;
public class Solution {
static MyScanner sc;
private static PrintWriter out;
static long M2 = 1_000_000_000L + 7;
private static HashMap<Long, Long>[] mods;
public static void main(String[] s) throws Exception {
StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append("7 3\n" +
// "1 5 2 6 3 7 4\n" +
// "2 5 3\n" +
// "4 4 1\n" +
// "1 7 3");
//
// Random r = new Random(5);
// stringBuilder.append("100000 5000 ");
// for (int i = 0; i < 100000; i++) {
// stringBuilder.append(" " + (r.nextInt(2000000000) - 1000000000) + " ");
//
// }
// for (int k = 0; k < 5000; k++) {
// stringBuilder.append(" 1 100000 777 ");
// }
if (stringBuilder.length() == 0) {
sc = new MyScanner(System.in);
} else {
sc = new MyScanner(new BufferedReader(new StringReader(stringBuilder.toString())));
}
out = new PrintWriter(new OutputStreamWriter(System.out));
initData();
solve();
out.flush();
}
private static void solve() throws IOException {
int n = sc.nextInt();
int[] data = sc.na(n);
boolean ev = true;
for (int t = 0; t < n - 1; t++) {
for (int x = t + 1; x < n; x++) {
if (data[t] > data[x]) {
ev = !ev;
}
}
}
int m = sc.nextInt();
for (int i = 0; i < m; i++) {
int dd = -sc.nextInt() + sc.nextInt();
int dm = (dd + 1) * dd / 2;
if (dm % 2 == 1) {
ev = !ev;
}
out.println(ev ? "even" : "odd");
}
}
private static void initData() {
}
private static boolean isset(long i, int k) {
return (i & (1 << k)) > 0;
}
private static void solveT() throws IOException {
int t = sc.nextInt();
while (t-- > 0) {
solve();
}
}
private static long gcd(long l, long l1) {
if (l > l1) return gcd(l1, l);
if (l == 0) return l1;
return gcd(l1 % l, l);
}
private static long pow(long a, long b, long m) {
if (b == 0) return 1;
if (b == 1) return a;
long pp = pow(a, b / 2, m);
pp *= pp;
pp %= m;
return (pp * (b % 2 == 0 ? 1 : a)) % m;
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
MyScanner(BufferedReader br) {
this.br = br;
}
public MyScanner(InputStream in) {
this(new BufferedReader(new InputStreamReader(in)));
}
void findToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String next() {
findToken();
return st.nextToken();
}
Integer[] nab(int n) {
Integer[] k = new Integer[n];
for (int i = 0; i < n; i++) {
k[i] = sc.fi();
}
return k;
}
int[] na(int n) {
int[] k = new int[n];
for (int i = 0; i < n; i++) {
k[i] = sc.fi();
}
return k;
}
long[] nl(int n) {
long[] k = new long[n];
for (int i = 0; i < n; i++) {
k[i] = sc.nextLong();
}
return k;
}
int nextInt() {
return Integer.parseInt(next());
}
int fi() {
String t = next();
int cur = 0;
boolean n = t.charAt(0) == '-';
for (int a = n ? 1 : 0; a < t.length(); a++) {
cur = cur * 10 + t.charAt(a) - '0';
}
return n ? -cur : cur;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import static java.util.Arrays.*;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import java.util.*;
import java.math.*;
import java.io.*;
public class A implements Runnable
{
String file = "input";
boolean TEST = System.getProperty("ONLINE_JUDGE") == null;
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();
qsort(b);
//sortInt(b);
int count = 0;
for(int i = 0; i < a.length; i++)
if(a[i] != b[i]) count++;
if(count == 0 || count == 2) out.println("YES");
else out.println("NO");
}
void qsort(int[] a)
{
List<Integer> as = new ArrayList<Integer>();
for(int x : a) as.add(x);
Collections.shuffle(as);
for(int i = 0; i < a.length; i++) a[i] = as.get(i);
sort(a);
}
Random rnd = new Random();
void sortInt(int[] a)
{
sortInt(a, 0, a.length - 1);
}
void sortInt(int[] a, int from, int to)
{
if(from >= to) return;
int i = from - 1;
int p = rnd.nextInt(to - from + 1) + from;
int t = a[p]; a[p] = a[to]; a[to] = t;
for(int j = from; j < to; j++)
if(a[j] <= a[to])
{
i++;
t = a[i]; a[i] = a[j]; a[j] = t;
}
t = a[i + 1]; a[i + 1] = a[to]; a[to] = t;
sortInt(a, i + 2, to);
while(i >= 0 && a[i] == a[i + 1]) i--;
sortInt(a, from, i);
}
String next() throws IOException
{
while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(input.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());
}
void print(Object... o)
{
System.out.println(deepToString(o));
}
void gcj(Object o)
{
String s = String.valueOf(o);
out.println("Case #" + test + ": " + s);
System.out.println("Case #" + test + ": " + s);
}
BufferedReader input;
PrintWriter out;
StringTokenizer st;
int test;
void init() throws IOException
{
if(TEST) input = new BufferedReader(new FileReader(file + ".in"));
else input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
}
public static void main(String[] args) throws IOException
{
new Thread(null, new A(), "", 1 << 22).start();
}
public void run()
{
try
{
init();
if(TEST)
{
int runs = nextInt();
for(int i = 0; i < runs; i++) solve();
}
else solve();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Main {
int work(int x){
if(x%2==0)return x+1;
else return x-1;
}
static int N = 200050;
class Node implements Comparable <Node>{
int x, id;
Node(int x, int id){
this.x = x; this.id = id;
}
public int compareTo(Node o){
return Integer.compare(x, o.x);
}
public String toString(){
return id + "=" + x;
}
}
class Edge{
int from, to, nex;
Edge (int from, int to, int nex){
this.from = from;
this.to = to;
this.nex = nex;
}
}
Edge[] edge = new Edge[N*10];
int[] head = new int[N];
int edgenum;
void addedge(int u, int v){
Edge E = new Edge(u, v, head[u]);
edge[edgenum] = E;
head[u] = edgenum ++;
}
int n;
int[] p = new int[N], ans = new int[N];
int a, b, max;
Map<Integer, Integer> map = new HashMap();
boolean match(int x, int y, int col){
int P = map.get(x);
if(map.containsKey(y-x) == false)
return false;
int Q = map.get(y - x);
if(ans[Q] == -1 || x * 2 == y){
ans[Q] = ans[P] = col;
}
else {
if(match(a+b-2*y+x, y, col))
ans[Q] = ans[P] = col;
else return false;
}
return true;
}
boolean solve(){
if(max >= a && max >= b)return false;
for(int i = 1; i <= n; i++)
if(ans[i] == -1)
{
if(match(p[i], a, 0)==false && match(p[i], b, 1) == false)
return false;
}
return true;
}
void init(){
n = cin.nextInt();
a = cin.nextInt(); b = cin.nextInt();
max = 0;
for(int i = 1; i <= n; i++){
ans[i] = -1;
p[i] = cin.nextInt();
map.put(p[i], i);
if(p[i] > max) max = p[i];
}
}
public void work(){
init();
if(solve()){
out.println("YES");
for(int i = 1; i <= n; i++)out.print(ans[i]+" "); out.println();
}
else
out.println("NO");
}
Main() {
cin = new Scanner(System.in);
out = new PrintWriter(System.out);
}
public static void main(String[] args) {
Main e = new Main();
e.work();
out.close();
}
public Scanner cin;
public static PrintWriter out;
}
/*
http://blog.csdn.net/keshuai19940722/article/details/39528801
*/
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
//Scanner sc = new Scanner();
Reader in = new Reader();
Main solver = new Main();
solver.solve(out, in);
out.flush();
out.close();
}
static int INF = (int)1e9;
static int maxn = (int)2e5+5;
static int mod= 998244353 ;
static int n,m,k,t,q,d,cnt=2;
void solve(PrintWriter out, Reader in) throws IOException{
n = in.nextInt();
Integer[] arr = new Integer[n];
for(int i=0;i<n;i++) arr[i] = in.nextInt();
boolean[] vis = new boolean[n];
Arrays.sort(arr);
int cnt=0;
for(int i=0;i<n;i++){
if(vis[i]) continue;
cnt++;
vis[i]=true;
for(int j=i+1;j<n;j++){
if(!vis[j]){
if(arr[j]%arr[i]==0){
vis[j]=true;
}
}
}
}
out.println(cnt);
}
//<>
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;
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.*;
public class A {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String s = sc.next();
for (int l = s.length(); l > 0; --l) {
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < s.length() - l + 1; ++i)
if (set.contains(s.substring(i, i + l))) {
System.out.println(l);
return;
} else {
set.add(s.substring(i, i + l));
}
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.*;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Pattern rc_style = Pattern.compile("R[0-9]+C[0-9]+");
int n = input.nextInt();
while(n-- > 0) {
String str = input.next();
Matcher m = rc_style.matcher(str);
if(m.matches()) {
String nums[] = str.split("[RC]");
String row = nums[1];
String col = nums[2];
String buffer = "";
int col_num = Integer.valueOf(col);
while(col_num > 0) {
if(col_num % 26 > 0) {
buffer += (char)(col_num % 26 + 'A' - 1);
col_num /= 26;
} else {
buffer += 'Z';
col_num /= 26;
col_num--;
}
}
for(int i = buffer.length() - 1; i >= 0; i--)
System.out.print(buffer.charAt(i));
System.out.println(row);
} else {
String col = str.split("[0-9]+")[0];
String row = str.split("[A-Z]+")[1];
int col_num = 0;
int shift = 1;
for(int i = col.length() - 1; i >= 0; i--) {
col_num += (int) (col.charAt(i) - 'A' + 1) * shift;
shift *= 26;
}
System.out.println("R" + row + "C" + col_num);
}
}
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
/**
* Problem:
* Source:
* Link:
*
* @author Alexei Ostrovski
*/
import java.io.*;
import java.util.*;
public class SpidersSolver {
public static final boolean DEBUG = false;
public static void main(String[] args) {
//redirect input and output
if (DEBUG)
{
try {
System.setIn(new FileInputStream("input.txt"));
//System.setOut(new PrintStream("input.txt"));
} catch (IOException e) {
//nothing
}
}
Scanner sc = new Scanner(System.in);
//read data
int n = sc.nextInt(), m = sc.nextInt();
//solve
if (n < m) {
int tmp = n;
n = m;
m = tmp;
}
// Now (n >= m) && (m <= 6)
int pow = 1;
for (int i = 0; i < m; i++)
pow *= 2;
int[] count = new int[pow];
for (int cur = 0; cur < pow; cur++)
{
int x = cur;
while (x > 0)
{
count[cur] += (x % 2);
x /= 2;
}
count[cur] = m - count[cur];
}
//System.out.println(Arrays.toString(count));
int[][] C = new int[pow][pow];
for (int cur = 0; cur < pow; cur++)
{
C[0][cur] = 0;//count[cur];
for (int last = 1; last < pow; last++)
C[last][cur] = Integer.MIN_VALUE;
}
for (int i = 0; i < n; i++)
{
int[][] newC = new int[pow][pow];
for (int cur = 0; cur < pow; cur++)
for (int next = 0; next < pow; next++)
{
int mask = cur | (cur << 1) | (cur >> 1) | next;
mask %= pow;
int max = 0;
for (int last = 0; last < pow; last++)
if (((last | mask) == pow - 1) && (max < count[cur] + C[last][cur]))
max = count[cur] + C[last][cur];
newC[cur][next] = max;
}
C = newC;
}
int result = 0;
for (int cur = 0; cur < pow; cur++)
result = Math.max(result, C[cur][0]);
//output
System.out.println(result);
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution {
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
void solve() throws IOException {
String s = next();
int u = s.indexOf('R');
int v = s.indexOf('C');
if (u == 0 && v != -1 && u < v) {
String a = s.substring(u + 1, v);
String b = s.substring(v + 1);
try {
int aa = Integer.parseInt(a);
int bb = Integer.parseInt(b) - 1;
int pow = 26, len = 1;
while (bb >= pow) {
bb -= pow;
pow *= 26;
++len;
}
String r = "";
for (int i = 0; i < len; ++i) {
r = ((char)(bb % 26 + 'A')) + r;
bb /= 26;
}
out.println(r + aa);
return;
} catch (NumberFormatException e) {
}
}
u = 0;
while (u < s.length() && Character.isLetter(s.charAt(u))) {
++u;
}
String a = s.substring(0, u);
String b = s.substring(u);
out.println("R" + b + "C" + toInt(a));
}
private int toInt(String a) {
int r = 0;
for (int i = 0; i < a.length(); ++i) {
r *= 26;
r += a.charAt(i) - 'A';
}
int pow = 1;
for (int i = 0; i < a.length(); ++i) {
r += pow;
pow *= 26;
}
return r;
}
Solution() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
eat("");
int tests = nextInt();
for (int test = 0; test < tests; ++test) {
solve();
}
in.close();
out.close();
}
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 Solution();
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Govnokod {
public static void main(String args[]) {
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
while (true) {
String str = br.readLine();
int i = Integer.parseInt(str);
System.out.println(i*2-i/2);
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.BufferedReader;
// import java.io.FileInputStream;
// import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
// import static java.util.Collections.sort;
import static java.util.Comparator.comparingInt;
public class Main {
FastScanner in;
PrintWriter out;
private void solve() throws IOException {
solveA();
// solveB();
// solveC();
// solveD();
// solveE();
// solveF();
}
private void solveA() throws IOException {
int n = in.nextInt();
TreeMap<String, Integer> map = new TreeMap<>();
for (int i = 0; i < n; i++) {
String s = in.next();
map.put(s, map.getOrDefault(s, 0) + 1);
}
for (int i = 0; i < n; i++) {
String s = in.next();
map.put(s, map.getOrDefault(s, 0) - 1);
}
long ans = 0;
for (String i : map.keySet())
ans += abs(map.get(i));
out.println(ans / 2);
}
private void solveB() throws IOException {
int n = in.nextInt();
int time = (int) 1e9, ans = -1;
for (int i = 0; i < n; i++) {
int a = in.nextInt() - i;
if ((a + (n - 1)) / n < time) {
time = (a + (n - 1)) / n;
ans = i;
}
}
out.println(ans + 1);
}
class PairC {
int i, j;
PairC(int i, int j) {
this.i = i;
this.j = j;
}
public String toString() {
return "(" + i + ", " + j + ")";
}
}
private void solveC() throws IOException {
int n = in.nextInt(), k = in.nextInt();
int[][] a = new int[4][n];
for (int i = 0; i < 4; i++)
for (int j = 0; j < n; j++)
a[i][j] = in.nextInt() - 1;
int[] empty = new int[4];
PairC[] from = new PairC[k];
for (int i = 1; i < 3; i++)
for (int j = 0; j < n; j++)
if (a[i][j] != -1)
from[a[i][j]] = new PairC(i, j);
else
empty[i]++;
PairC[] to = new PairC[k];
for (int i = 0; i < 4; i += 3)
for (int j = 0; j < n; j++)
if (a[i][j] != -1)
to[a[i][j]] = new PairC(i, j);
out.println(Arrays.toString(from));
out.println(Arrays.toString(to));
ArrayList<int[]> ans = new ArrayList<>();
int cnt = 0;
for (int i = 0; i < k; i++) {
if (abs(from[i].i - to[i].i) == 1) {
if (from[i].j == to[i].j) {
ans.add(new int[]{i, to[i].i, to[i].j});
a[from[i].i][from[i].j] = 0;
empty[from[i].i]++;
cnt++;
}
} else if (from[i].j == to[i].j && a[(from[i].i + to[i].i) / 2][to[i].j] == 0) {
ans.add(new int[]{i, (from[i].i + to[i].i) / 2, to[i].j});
ans.add(new int[]{i, to[i].i, to[i].j});
a[from[i].i][from[i].j] = 0;
empty[from[i].i]++;
cnt++;
}
}
for (int i = 1; i < 3; i++) {
if (empty[i] > 0) {
for (int j = 0; j < k; j++) {
if (from[j].i == i && true) {
}
}
}
}
while (true) {
boolean flag = false;
for (int i = 0; i < k; i++) {
if (abs(from[i].i - to[i].i) == 1 && abs(from[i].j - to[i].j) <= empty[i]) {
}
}
if (!flag)
break;
}
if (cnt == k) {
out.println(ans.size());
for (int[] i : ans) {
for (int j : i)
out.print(j + 1 + " ");
out.println();
}
} else
out.println(-1);
}
private void solveD() throws IOException {
int n = in.nextInt();
int[] a = new int[n * 2];
for (int i = 0; i < n * 2; i++)
a[i] = in.nextInt();
long ans = 0;
for (int i = 0; i < 2 * n; i += 2) {
int j = i + 1;
while (a[i] != a[j])
j++;
ans += j - i - 1;
while (j > i + 1)
a[j] = a[--j];
}
out.println(ans);
}
class PairE implements Comparable<PairE> {
long x, y;
int id;
boolean b;
PairE(long x, long y, int id) {
this.x = x;
this.y = y;
this.id = id;
b = false;
}
@Override
public int compareTo(PairE o) {
return x != o.x ? Long.compare(x, o.x) : Long.compare(y, o.y);
}
}
private void solveE() throws IOException {
int n = in.nextInt();
PairE[] p = new PairE[n];
for (int i = 0; i < n; i++)
p[i] = new PairE(in.nextLong(), in.nextLong(), i);
shuffle(p);
sort(p);
long X = 0, Y = 0;
long max = 225 * (long) 1e10;
for (int i = 0; i < n; i++) {
if ((X + p[i].x) * (X + p[i].x) + (Y + p[i].y) * (Y + p[i].y) < (X - p[i].x) * (X - p[i].x) + (Y - p[i].y) * (Y - p[i].y)) {
p[i].b = true;
X += p[i].x;
Y += p[i].y;
} else {
p[i].b = false;
X -= p[i].x;
Y -= p[i].y;
}
}
sort(p, comparingInt(o -> o.id));
for (int i = 0; i < n; i++) {
out.print(p[i].b ? 1 : -1);
if (i + 1 < n)
out.print(" ");
}
out.println();
}
void shuffle(PairE[] a) {
PairE b;
Random r = new Random();
for (int i = a.length - 1, j; i > 0; i--) {
j = r.nextInt(i + 1);
b = a[j];
a[j] = a[i];
a[i] = b;
}
}
private void solveF() throws IOException {
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next().replace(',', '.'));
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.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 Nasko
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
if (N == 1) {
out.println(1);
} else if (N == 2) {
out.println(2);
} else if (N == 3) {
out.println(6);
} else {
long best = Long.MIN_VALUE;
best = Math.max(best, lcm(N, lcm(N - 1, N - 2)));
best = Math.max(best, lcm(N, lcm(N - 2, N - 3)));
best = Math.max(best, lcm(N, lcm(N - 1, N - 3)));
best = Math.max(best, lcm(N - 1, lcm(N - 2, N - 3)));
out.println(best);
}
}
private long lcm(long a, long b) {
return a * (b / gcd(a, b));
}
private long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
}
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());
}
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class CF {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int n = in.nextInt();
if (n >= 0) {
out.println(n);
} else {
int res = n;
n = Math.abs(n);
String s = String.valueOf(Math.abs(n));
if (s.length() == 1) {
res = 0;
} else {
res = Math.max(-Integer.parseInt(s.substring(0, s.length() - 1)), res);
res = Math.max(-Integer.parseInt(s.substring(0, s.length() - 2) + s.charAt(s.length() - 1)), res);
}
out.println(res);
}
out.close();
}
}
class InputReader {
public BufferedReader reader;
public 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());
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.Random;
import java.util.Comparator;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
E2RotateColumnsHardVersion solver = new E2RotateColumnsHardVersion();
int testCount = in.scanInt();
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class E2RotateColumnsHardVersion {
int[][] dp;
int[] cur;
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int m = in.scanInt();
int[][] ar = new int[n][m];
int[][] max = new int[m][2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) ar[i][j] = in.scanInt();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
max[i][0] = Math.max(max[i][0], ar[j][i]);
}
max[i][1] = i;
}
CodeHash.shuffle(max);
Arrays.sort(max, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
return -o1[0] + o2[0];
}
});
dp = new int[2][1 << n];
cur = new int[1 << n];
for (int i = 0; i < Math.min(m, n); i++) {
Arrays.fill(cur, 0);
Arrays.fill(dp[i & 1], 0);
for (int j = 0; j < 1 << n; j++) {
for (int k = 0; k < n; k++) {
int sum = 0;
for (int l = 0; l < n; l++) {
if ((j & (1 << l)) != 0) {
sum += (ar[(k + l) % n][max[i][1]]);
}
}
cur[j] = Math.max(cur[j], sum);
}
}
for (int j = 0; j < (1 << n); j++) {
for (int k = j; ; k = (k - 1) & j) {
dp[i & 1][j] = Math.max(dp[i & 1][j], dp[(i - 1) & 1][k] + cur[j ^ k]);
if (k == 0) break;
}
}
}
out.println(dp[Math.min(n, m) & 1 ^ 1][(1 << n) - 1]);
}
}
static class CodeHash {
public static void shuffle(int[][] ar) {
Random rd = new Random(new Random().nextInt());
for (int i = 0; i < ar.length; i++) {
int index = rd.nextInt(ar.length);
int[] temp = ar[i];
ar[i] = ar[index];
ar[index] = temp;
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public int scanInt() {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.Map.*;
public class codeforces {
static int count =0;
static boolean f=false;
static int [] arr;
static PrintWriter pw=new PrintWriter(System.out);
static void solve(int index , int mask) {
if(index==arr.length) {
int sum1=0; int sum2=0;
for(int i=0;i<arr.length;i++) {
if((mask & 1<<i)!=0) sum1+=arr[i];
}
return;
}
solve(index+1, mask | 1<<index);
solve(index+1, mask);
}
public static void main(String [] args) throws IOException, InterruptedException {
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
int y=sc.nextInt();
pair [] arr=new pair[x];
for(int i=0;i<x;i++) arr[i]=new pair(i, sc.nextInt(),0);
for(int i=0;i<x;i++) arr[i].y=sc.nextInt();
Arrays.sort(arr);
PriorityQueue<Integer> qq=new PriorityQueue<>();
//pw.println(Arrays.toString(arr));
Long [] list=new Long [x];
long sum=0;
for(int i=0;i<x;i++) {
pair w=arr[i];
if(qq.size()<y) {
qq.add(w.y);
sum+=w.y;
list[w.i]=sum;
}else if(!qq.isEmpty()) {
sum+=w.y;
list[w.i]=sum;
int first=qq.poll();
if(w.y>first) {
sum-=first;
qq.add(w.y);
}else {
qq.add(first);
sum-=w.y;
}
} else list[w.i]=(long) w.y;
//pw.println(qq);
}
for(Long w:list) pw.print(w+" ");
pw.flush();
pw.close();
}
static class pair implements Comparable<pair>{
String name; int x,y,i ;
public pair(String name , int x) {
this.name=name; this.x=x;
}
public pair (int i,int x,int y) {
this.i=i; this.x=x; this.y=y;
}
public int compareTo(pair o) {
return x-o.x;
}
public int compareTo1(pair o) {
if(!name.equals(o.name))
return name.compareTo(o.name);
return x-o.x;
}
public String toString() {
return i+" "+x+" "+y;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
|
nlogn
|
994_B. Knights of a Polygonal Table
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1209e1_2 {
public static void main(String[] args) throws IOException {
int t = ri();
while (t --> 0) {
int n = rni(), m = ni(), a[][] = new int[m][n], dp[] = new int[1 << n];
for (int i = 0; i < n; ++i) {
int[] row = ria(m);
for (int j = 0; j < m; ++j) {
a[j][i] = row[j];
}
}
for (int i = 0; i < m; ++i) {
for (int r = 0; r < 1 << n; ++r) {
for (int j = 0; j < n; ++j) {
if ((r & (1 << j)) == 0) {
continue;
}
dp[r] = max(dp[r], dp[r ^ (1 << j)] + a[i][j]);
}
}
for (int r = 0; r < 1 << n; ++r) {
int s = r;
for (int j = 0; j < n; ++j) {
if ((s & 1) != 0) {
s = (s >> 1) | (1 << (n - 1));
} else {
s >>= 1;
}
dp[s] = max(dp[s], dp[r]);
}
}
}
prln(dp[(1 << n) - 1]);
}
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;}
// 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());}
// 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 boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;};
static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;}
static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;}
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
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
static PrintWriter pw;
static _Scanner sc;
public static void main(String[] args) throws Exception {
sc = new _Scanner(System.in);
pw = new PrintWriter(System.out);
//long startTime = System.currentTimeMillis();
//int t = sc.nextInt();
int t = 1;
while (t-- > 0) {
solve();
}
pw.flush();
//System.out.println("time: " + (System.currentTimeMillis() - startTime));
}
private static void solve() throws Exception {
int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt();
int[][] h = new int[n][m - 1];
int[][] v = new int[n - 1][m];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m - 1; ++j) {
h[i][j] = sc.nextInt();
}
}
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < m; ++j) {
v[i][j] = sc.nextInt();
}
}
if (k % 2 == 1) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (j > 0) {
pw.print(" ");
}
pw.print(-1);
}
pw.println();
}
return;
}
k = k / 2;
long[][] d = new long[n][m];
for (int ki = 0; ki < k; ++ki) {
long[][] dk = new long[n][m];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
long val = Integer.MAX_VALUE;
if (j < m - 1) {
val = Math.min(val, d[i][j + 1] + h[i][j]);
}
if (i < n - 1) {
val = Math.min(val, d[i + 1][j] + v[i][j]);
}
if (j > 0) {
val = Math.min(val, d[i][j - 1] + h[i][j - 1]);
}
if (i > 0) {
val = Math.min(val, d[i - 1][j] + v[i - 1][j]);
}
dk[i][j] = val;
}
}
d = dk;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (j > 0) {
pw.print(" ");
}
pw.print(d[i][j] * 2);
}
pw.println();
}
}
static class Shuffle {
static void run(int[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * in.length);
int tmp = in[i];
in[i] = in[idx];
in[idx] = tmp;
}
}
static void run(long[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * in.length);
long tmp = in[i];
in[i] = in[idx];
in[idx] = tmp;
}
}
static <T> void run(List<T> in) {
for (int i = 0; i < in.size(); i++) {
int idx = (int) (Math.random() * in.size());
T tmp = in.get(i);
in.set(i, in.get(idx));
in.set(idx, tmp);
}
}
}
static class _Scanner {
StringTokenizer st;
BufferedReader br;
_Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
_Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int[] intArr(int n) throws IOException {
int[] in = new int[n];
for (int i = 0; i < n; i++) in[i] = nextInt();
return in;
}
long[] longArr(int n) throws IOException {
long[] in = new long[n];
for (int i = 0; i < n; i++) in[i] = nextLong();
return in;
}
int[] intArrSorted(int n) throws IOException {
int[] in = new int[n];
for (int i = 0; i < n; i++) in[i] = nextInt();
Shuffle.run(in);
Arrays.sort(in);
return in;
}
long[] longArrSorted(int n) throws IOException {
long[] in = new long[n];
for (int i = 0; i < n; i++) in[i] = nextLong();
Shuffle.run(in);
Arrays.sort(in);
return in;
}
Integer[] IntegerArr(int n) throws IOException {
Integer[] in = new Integer[n];
for (int i = 0; i < n; i++) in[i] = nextInt();
return in;
}
Long[] LongArr(int n) throws IOException {
Long[] in = new Long[n];
for (int i = 0; i < n; i++) in[i] = nextLong();
return in;
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
char nextChar() throws IOException {
return nextToken().charAt(0);
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
boolean ready() throws IOException {
return br.ready();
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.util.*;
// VK Cup 2012 Round2 Unofficial Div2 Edition
public class Main {
void A(){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int[] h = new int[n];
for(int i=0; i<n; i++){
h[i] = sc.nextInt();
}
Arrays.sort(h);
System.out.println(h[b]-h[b-1]);
}
public static void main(String[] args) {
new Main().A();
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.util.*;
public class Subtractions {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int count = kb.nextInt();
while(count > 0) {
int smaller = kb.nextInt();
int larger = kb.nextInt();
int ops = 0;
while(smaller > 0 && larger > 0) {
if(smaller > larger) {
int temp = smaller;
smaller = larger;
larger = temp;
}
ops += larger/smaller;
larger = larger % smaller;
}
System.out.println(ops);
count--;
}
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
//package;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
import java.lang.*;
import java.io.*;
import java.awt.Point;
public class evenness {
public static void main(String[] args){
try{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int i, n, temp=1;
String str = "";
int[] arr;
int r;
while (temp!= '\n'){
temp = System.in.read();
//if (temp=='\n')
//break;
str = str.concat(Character.toString((char)temp));
}
str = str.replaceAll("[^0-9]", "");
n = Integer.parseInt(str);
temp=1;
str="";
arr = new int[n];
for (i=0;i<n;i++){
while (temp!=' ' && temp!=-1){
temp = System.in.read();
//if (temp==' ' || temp==-1)
//break;
str = str.concat(Character.toString((char)temp));
}
str = str.replaceAll("[^0-9]", "");
arr[i] = Integer.parseInt(str);
str="";
temp=1;
}
r=(arr[2]%2);
if ((arr[0]%2)==(arr[1]%2)){
r=(arr[0]%2);
}
for (i=0;i<n;i++){
if ((arr[i]%2)!=r){
System.out.println(i+1);
break;
}
}
}catch (Exception e){
System.out.println("OH NOES " + e);
}
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import javax.print.attribute.standard.RequestingUserName;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
int tc = in.nextInt();
for(int i = 0; i < tc; i++)
solver.solve(i, in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int k = in.nextInt();
int[] s = getArray(in.nextToken());
int[] a = getArray(in.nextToken());
int[] b = getArray(in.nextToken());
int[] per = new int[k];
boolean[] used = new boolean[k];
Arrays.fill(per , -1);
if(!check(s , a, per.clone(), k, used)){
out.println("NO");
return;
}
for(int i = 0; i < s.length; i++){
if(per[s[i]] != -1){
continue;
}
for(int j = 0; j < k; j++){
if(used[j]){
continue;
}
per[s[i]] = j;
used[j] = true;
if(check(s , a , per.clone() , k, used)){
break;
}
per[s[i]] = -1;
used[j] = false;
}
}
for(int i = 0; i < s.length; i++){
if(per[s[i]] == -1){
out.println("NO");
return;
}
s[i] = per[s[i]];
}
if(cmp(s , b) > 0){
out.println("NO");
return;
}
int last = 0;
for(int i = 0; i < k; i++){
if(per[i] == -1) {
while(used[last])last++;
per[i] = last;
used[last] = true;
}
}
char[] result = new char[k];
for(int i = 0; i < k; i++){
result[i] = (char)('a' + per[i]);
}
out.println("YES");
out.println(new String(result));
}
private int cmp(int[] a, int[] b){
for(int i = 0; i < a.length; i++){
if(a[i] != b[i]){
return a[i] < b[i] ? -1 : 1;
}
}
return 0;
}
private boolean check(int[] s, int[] a, int[] per, int k, boolean[] used) {
int res[] = new int[s.length];
int last = k - 1;
for(int i = 0; i < res.length; ++i){
if(per[s[i]] == -1){
while(last >= 0 && used[last]){
last--;
}
if(last < 0){
return false;
}
per[s[i]] = last;
last--;
}
res[i] = per[s[i]];
}
return cmp(a , res) <= 0;
}
private int[] getArray(String nextToken) {
int result[] = new int[nextToken.length()];
for(int i = 0; i < nextToken.length(); i++){
result[i] = nextToken.charAt(i) - 'a';
}
return result;
}
}
static class InputReader {
BufferedReader in;
StringTokenizer tok;
public InputReader(InputStream stream){
in = new BufferedReader(new InputStreamReader(stream), 32768);
tok = null;
}
String nextToken()
{
String line = "";
while(tok == null || !tok.hasMoreTokens()) {
try {
if((line = in.readLine()) != null)
tok = new StringTokenizer(line);
else
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return tok.nextToken();
}
int nextInt(){
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
|
quadratic
|
1086_C. Vasya and Templates
|
CODEFORCES
|
/*
bts songs to dance to:
I need U
Run
ON
Filter
I'm fine
*/
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
public class x1517D2
{
static final int INF = Integer.MAX_VALUE/3;
public static void main(String hi[]) throws Exception
{
FastScanner infile = new FastScanner();
int N = infile.nextInt();
int M = infile.nextInt();
int K = infile.nextInt();
int[][] weights1 = new int[N][M-1];
for(int r=0; r < N; r++)
weights1[r] = infile.nextInts(M-1);
int[][] weights2 = new int[N-1][M];
for(int r=0; r < N-1; r++)
weights2[r] = infile.nextInts(M);
//all are -1 if K is odd
int[][] res = new int[N][M];
if(K%2 == 1)
{
StringBuilder sb = new StringBuilder();
for(int r=0; r < N; r++)
{
for(int c=0; c < M; c++)
sb.append("-1 ");
sb.append("\n");
}
System.out.print(sb);
return;
}
int[][] dp = new int[N][M];
StringBuilder sb = new StringBuilder();
for(int k=0; k < K/2; k++)
{
int[][] next = new int[N][M];
for(int r=0; r < N; r++)
Arrays.fill(next[r], INF);
for(int r=0; r < N; r++)
for(int c=0; c < M; c++)
{
if(r > 0)
next[r-1][c] = min(next[r-1][c], dp[r][c]+weights2[r-1][c]);
if(r+1 < N)
next[r+1][c] = min(next[r+1][c], dp[r][c]+weights2[r][c]);
if(c > 0)
next[r][c-1] = min(next[r][c-1], dp[r][c]+weights1[r][c-1]);
if(c+1 < M)
next[r][c+1] = min(next[r][c+1], dp[r][c]+weights1[r][c]);
}
dp = next;
}
for(int r=0; r < N; r++)
{
for(int x: dp[r])
sb.append((2*x)+" ");
sb.append("\n");
}
System.out.print(sb);
}
}
class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
public class D {
int N,M;
int[] a,l,r;
private void solve() {
N = nextInt();
a = new int[N];
for(int i = 0;i < N;i++) {
a[i] = nextInt();
}
M = nextInt();
l = new int[M];
r = new int[M];
for(int i = 0;i < M;i++) {
l[i] = nextInt();
r[i] = nextInt();
}
int count = 0;
for(int i = 0;i < N - 1;i++) {
for(int j = i + 1;j < N;j++) if (a[i] > a[j]) {
count++;
}
}
for(int i = 0;i < M;i++) {
count += (r[i] - l[i] + 1) * (r[i] - l[i]) / 2;
count %= 2;
out.println(count == 0 ? "even" : "odd");
}
}
public static void main(String[] args) {
out.flush();
new D().solve();
out.close();
}
/* Input */
private static final InputStream in = System.in;
private static final PrintWriter out = new PrintWriter(System.out);
private final byte[] buffer = new byte[2048];
private int p = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (p < buflen)
return true;
p = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0)
return false;
return true;
}
public boolean hasNext() {
while (hasNextByte() && !isPrint(buffer[p])) {
p++;
}
return hasNextByte();
}
private boolean isPrint(int ch) {
if (ch >= '!' && ch <= '~')
return true;
return false;
}
private int nextByte() {
if (!hasNextByte())
return -1;
return buffer[p++];
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = -1;
while (isPrint((b = nextByte()))) {
sb.appendCodePoint(b);
}
return sb.toString();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
|
quadratic
|
911_D. Inversion Counting
|
CODEFORCES
|
import java.io.DataInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
public class div168C {
public static void main(String[] args) throws Exception{
div168C a=new div168C();
Parserdoubt pd=a.new Parserdoubt(System.in);
StringBuffer sb = new StringBuffer();
ArrayList<Integer> arr=new ArrayList<Integer>();
int max=0;
int n=pd.nextInt();
int k=pd.nextInt();
for(int i=0;i<n;i++){
arr.add(pd.nextInt());
max=Math.max(max, arr.get(i));
}
Collections.sort(arr);
int count=0;
int[] mat=new int[n+1];
for(int i=n-1;i>=0;i--){
if(mat[i]!=1){
int x=arr.get(i);
if(x%k==0){
int ans=Collections.binarySearch(arr, x/k);
// System.out.println("index "+ans);
if(ans>=0&&arr.get(ans)==(x/k)){
count++;
mat[ans]=1;
}
else{
count++;
}
}
else{
count++;
}
}
}
/*for(int i=0;i<arr.size();i++){
System.out.print(arr.get(i)+" ");
}
System.out.println();
*/
if(n==1)
count=1;
System.out.println(count);
}
class Parserdoubt
{
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parserdoubt(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String nextString() throws Exception
{
StringBuffer sb=new StringBuffer("");
byte c = read();
while (c <= ' ') c = read();
do
{
sb.append((char)c);
c=read();
}while(c>' ');
return sb.toString();
}
public char nextChar() throws Exception
{
byte c=read();
while(c<=' ') c= read();
return (char)c;
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
}
|
nlogn
|
274_A. k-Multiple Free Set
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collection;
import java.util.AbstractList;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Deque;
import java.util.ArrayDeque;
import java.util.NoSuchElementException;
import java.util.ConcurrentModificationException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author cunbidun
*/
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);
DPairOfLines solver = new DPairOfLines();
solver.solve(1, in, out);
out.close();
}
static class DPairOfLines {
private static final int INF = (int) 2e9 + 7;
private InputReader in;
private PrintWriter out;
public void solve(int testNumber, InputReader in, PrintWriter out) {
this.in = in;
this.out = out;
int n = in.nextInt();
if (n <= 4) {
out.println("YES");
return;
}
TreeList<PairII> list = new TreeList<>();
PairII[] a = new PairII[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = (new PairII(in.nextInt(), in.nextInt()));
list.add(a[i]);
}
PairII pos1 = new PairII(INF, INF);
PairII pos2 = new PairII(INF, INF);
for (int i = 1; i <= 5; i++) {
for (int j = i + 1; j <= 5; j++) {
for (int k = j + 1; k <= 5; k++) {
int x1 = a[i].first;
int y1 = a[i].second;
int x2 = a[j].first;
int y2 = a[j].second;
int x = a[k].first;
int y = a[k].second;
long s = (long) (y2 - y1) * x + (long) (x1 - x2) * y + ((long) x2 * y1 - (long) x1 * y2);
if (s == 0) {
pos1 = a[i];
pos2 = a[j];
}
}
}
}
if (pos1.equals(new PairII(INF, INF))) {
out.println("NO");
return;
}
int x1 = pos1.first;
int y1 = pos1.second;
int x2 = pos2.first;
int y2 = pos2.second;
for (int i = 0; i < list.size(); i++) {
int x = list.get(i).first;
int y = list.get(i).second;
long s = (long) (y2 - y1) * x + (long) (x1 - x2) * y + ((long) x2 * y1 - (long) x1 * y2);
if (s == 0) {
list.remove(i);
i--;
}
}
if (list.size() <= 2) {
out.println("YES");
return;
}
x1 = list.get(0).first;
y1 = list.get(0).second;
x2 = list.get(1).first;
y2 = list.get(1).second;
for (int i = 0; i < list.size(); i++) {
int x = list.get(i).first;
int y = list.get(i).second;
long s = (long) (y2 - y1) * x + (long) (x1 - x2) * y + ((long) x2 * y1 - (long) x1 * y2);
if (s == 0) {
list.remove(i);
i--;
}
}
if (list.size() == 0) {
out.println("YES");
} else out.println("NO");
}
}
static interface OrderedIterator<E> extends Iterator<E> {
}
static class PairII implements Comparable<PairII> {
public int first;
public int second;
public PairII(int first, int second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PairII pair = (PairII) o;
return first == pair.first && second == pair.second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(PairII o) {
int value = Integer.compare(first, o.first);
if (value != 0) {
return value;
}
return Integer.compare(second, o.second);
}
}
static class TreeList<E> extends AbstractList<E> {
private TreeList.AVLNode<E> root;
private int size;
public TreeList() {
super();
}
public TreeList(final Collection<? extends E> coll) {
super();
if (!coll.isEmpty()) {
root = new TreeList.AVLNode<>(coll);
size = coll.size();
}
}
public E get(final int index) {
return root.get(index).getValue();
}
public int size() {
return size;
}
public Iterator<E> iterator() {
// override to go 75% faster
return listIterator(0);
}
public ListIterator<E> listIterator() {
// override to go 75% faster
return listIterator(0);
}
public ListIterator<E> listIterator(final int fromIndex) {
return new TreeList.TreeListIterator<>(this, fromIndex);
}
public int indexOf(final Object object) {
// override to go 75% faster
if (root == null) {
return -1;
}
return root.indexOf(object, root.relativePosition);
}
public boolean contains(final Object object) {
return indexOf(object) >= 0;
}
public Object[] toArray() {
final Object[] array = new Object[size()];
if (root != null) {
root.toArray(array, root.relativePosition);
}
return array;
}
public void add(final int index, final E obj) {
modCount++;
if (root == null) {
root = new TreeList.AVLNode<>(index, obj, null, null);
} else {
root = root.insert(index, obj);
}
size++;
}
public boolean addAll(final Collection<? extends E> c) {
if (c.isEmpty()) {
return false;
}
modCount += c.size();
final TreeList.AVLNode<E> cTree = new TreeList.AVLNode<>(c);
root = root == null ? cTree : root.addAll(cTree, size);
size += c.size();
return true;
}
public E set(final int index, final E obj) {
final TreeList.AVLNode<E> node = root.get(index);
final E result = node.value;
node.setValue(obj);
return result;
}
public E remove(final int index) {
modCount++;
final E result = get(index);
root = root.remove(index);
size--;
return result;
}
public void clear() {
modCount++;
root = null;
size = 0;
}
static class AVLNode<E> {
private TreeList.AVLNode<E> left;
private boolean leftIsPrevious;
private TreeList.AVLNode<E> right;
private boolean rightIsNext;
private int height;
private int relativePosition;
private E value;
private AVLNode(final int relativePosition, final E obj,
final TreeList.AVLNode<E> rightFollower, final TreeList.AVLNode<E> leftFollower) {
this.relativePosition = relativePosition;
value = obj;
rightIsNext = true;
leftIsPrevious = true;
right = rightFollower;
left = leftFollower;
}
private AVLNode(final Collection<? extends E> coll) {
this(coll.iterator(), 0, coll.size() - 1, 0, null, null);
}
private AVLNode(final Iterator<? extends E> iterator, final int start, final int end,
final int absolutePositionOfParent, final TreeList.AVLNode<E> prev, final TreeList.AVLNode<E> next) {
final int mid = start + (end - start) / 2;
if (start < mid) {
left = new TreeList.AVLNode<>(iterator, start, mid - 1, mid, prev, this);
} else {
leftIsPrevious = true;
left = prev;
}
value = iterator.next();
relativePosition = mid - absolutePositionOfParent;
if (mid < end) {
right = new TreeList.AVLNode<>(iterator, mid + 1, end, mid, this, next);
} else {
rightIsNext = true;
right = next;
}
recalcHeight();
}
E getValue() {
return value;
}
void setValue(final E obj) {
this.value = obj;
}
TreeList.AVLNode<E> get(final int index) {
final int indexRelativeToMe = index - relativePosition;
if (indexRelativeToMe == 0) {
return this;
}
final TreeList.AVLNode<E> nextNode = indexRelativeToMe < 0 ? getLeftSubTree() : getRightSubTree();
if (nextNode == null) {
return null;
}
return nextNode.get(indexRelativeToMe);
}
int indexOf(final Object object, final int index) {
if (getLeftSubTree() != null) {
final int result = left.indexOf(object, index + left.relativePosition);
if (result != -1) {
return result;
}
}
if (value == null ? value == object : value.equals(object)) {
return index;
}
if (getRightSubTree() != null) {
return right.indexOf(object, index + right.relativePosition);
}
return -1;
}
void toArray(final Object[] array, final int index) {
array[index] = value;
if (getLeftSubTree() != null) {
left.toArray(array, index + left.relativePosition);
}
if (getRightSubTree() != null) {
right.toArray(array, index + right.relativePosition);
}
}
TreeList.AVLNode<E> next() {
if (rightIsNext || right == null) {
return right;
}
return right.min();
}
TreeList.AVLNode<E> previous() {
if (leftIsPrevious || left == null) {
return left;
}
return left.max();
}
TreeList.AVLNode<E> insert(final int index, final E obj) {
final int indexRelativeToMe = index - relativePosition;
if (indexRelativeToMe <= 0) {
return insertOnLeft(indexRelativeToMe, obj);
}
return insertOnRight(indexRelativeToMe, obj);
}
private TreeList.AVLNode<E> insertOnLeft(final int indexRelativeToMe, final E obj) {
if (getLeftSubTree() == null) {
setLeft(new TreeList.AVLNode<>(-1, obj, this, left), null);
} else {
setLeft(left.insert(indexRelativeToMe, obj), null);
}
if (relativePosition >= 0) {
relativePosition++;
}
final TreeList.AVLNode<E> ret = balance();
recalcHeight();
return ret;
}
private TreeList.AVLNode<E> insertOnRight(final int indexRelativeToMe, final E obj) {
if (getRightSubTree() == null) {
setRight(new TreeList.AVLNode<>(+1, obj, right, this), null);
} else {
setRight(right.insert(indexRelativeToMe, obj), null);
}
if (relativePosition < 0) {
relativePosition--;
}
final TreeList.AVLNode<E> ret = balance();
recalcHeight();
return ret;
}
private TreeList.AVLNode<E> getLeftSubTree() {
return leftIsPrevious ? null : left;
}
private TreeList.AVLNode<E> getRightSubTree() {
return rightIsNext ? null : right;
}
private TreeList.AVLNode<E> max() {
return getRightSubTree() == null ? this : right.max();
}
private TreeList.AVLNode<E> min() {
return getLeftSubTree() == null ? this : left.min();
}
TreeList.AVLNode<E> remove(final int index) {
final int indexRelativeToMe = index - relativePosition;
if (indexRelativeToMe == 0) {
return removeSelf();
}
if (indexRelativeToMe > 0) {
setRight(right.remove(indexRelativeToMe), right.right);
if (relativePosition < 0) {
relativePosition++;
}
} else {
setLeft(left.remove(indexRelativeToMe), left.left);
if (relativePosition > 0) {
relativePosition--;
}
}
recalcHeight();
return balance();
}
private TreeList.AVLNode<E> removeMax() {
if (getRightSubTree() == null) {
return removeSelf();
}
setRight(right.removeMax(), right.right);
if (relativePosition < 0) {
relativePosition++;
}
recalcHeight();
return balance();
}
private TreeList.AVLNode<E> removeMin() {
if (getLeftSubTree() == null) {
return removeSelf();
}
setLeft(left.removeMin(), left.left);
if (relativePosition > 0) {
relativePosition--;
}
recalcHeight();
return balance();
}
private TreeList.AVLNode<E> removeSelf() {
if (getRightSubTree() == null && getLeftSubTree() == null) {
return null;
}
if (getRightSubTree() == null) {
if (relativePosition > 0) {
left.relativePosition += relativePosition;
}
left.max().setRight(null, right);
return left;
}
if (getLeftSubTree() == null) {
right.relativePosition += relativePosition - (relativePosition < 0 ? 0 : 1);
right.min().setLeft(null, left);
return right;
}
if (heightRightMinusLeft() > 0) {
// more on the right, so delete from the right
final TreeList.AVLNode<E> rightMin = right.min();
value = rightMin.value;
if (leftIsPrevious) {
left = rightMin.left;
}
right = right.removeMin();
if (relativePosition < 0) {
relativePosition++;
}
} else {
// more on the left or equal, so delete from the left
final TreeList.AVLNode<E> leftMax = left.max();
value = leftMax.value;
if (rightIsNext) {
right = leftMax.right;
}
final TreeList.AVLNode<E> leftPrevious = left.left;
left = left.removeMax();
if (left == null) {
// special case where left that was deleted was a double link
// only occurs when height difference is equal
left = leftPrevious;
leftIsPrevious = true;
}
if (relativePosition > 0) {
relativePosition--;
}
}
recalcHeight();
return this;
}
private TreeList.AVLNode<E> balance() {
switch (heightRightMinusLeft()) {
case 1:
case 0:
case -1:
return this;
case -2:
if (left.heightRightMinusLeft() > 0) {
setLeft(left.rotateLeft(), null);
}
return rotateRight();
case 2:
if (right.heightRightMinusLeft() < 0) {
setRight(right.rotateRight(), null);
}
return rotateLeft();
default:
throw new RuntimeException("tree inconsistent!");
}
}
private int getOffset(final TreeList.AVLNode<E> node) {
if (node == null) {
return 0;
}
return node.relativePosition;
}
private int setOffset(final TreeList.AVLNode<E> node, final int newOffest) {
if (node == null) {
return 0;
}
final int oldOffset = getOffset(node);
node.relativePosition = newOffest;
return oldOffset;
}
private void recalcHeight() {
height = Math.max(
getLeftSubTree() == null ? -1 : getLeftSubTree().height,
getRightSubTree() == null ? -1 : getRightSubTree().height) + 1;
}
private int getHeight(final TreeList.AVLNode<E> node) {
return node == null ? -1 : node.height;
}
private int heightRightMinusLeft() {
return getHeight(getRightSubTree()) - getHeight(getLeftSubTree());
}
private TreeList.AVLNode<E> rotateLeft() {
final TreeList.AVLNode<E> newTop = right; // can't be faedelung!
final TreeList.AVLNode<E> movedNode = getRightSubTree().getLeftSubTree();
final int newTopPosition = relativePosition + getOffset(newTop);
final int myNewPosition = -newTop.relativePosition;
final int movedPosition = getOffset(newTop) + getOffset(movedNode);
setRight(movedNode, newTop);
newTop.setLeft(this, null);
setOffset(newTop, newTopPosition);
setOffset(this, myNewPosition);
setOffset(movedNode, movedPosition);
return newTop;
}
private TreeList.AVLNode<E> rotateRight() {
final TreeList.AVLNode<E> newTop = left;
final TreeList.AVLNode<E> movedNode = getLeftSubTree().getRightSubTree();
final int newTopPosition = relativePosition + getOffset(newTop);
final int myNewPosition = -newTop.relativePosition;
final int movedPosition = getOffset(newTop) + getOffset(movedNode);
setLeft(movedNode, newTop);
newTop.setRight(this, null);
setOffset(newTop, newTopPosition);
setOffset(this, myNewPosition);
setOffset(movedNode, movedPosition);
return newTop;
}
private void setLeft(final TreeList.AVLNode<E> node, final TreeList.AVLNode<E> previous) {
leftIsPrevious = node == null;
left = leftIsPrevious ? previous : node;
recalcHeight();
}
private void setRight(final TreeList.AVLNode<E> node, final TreeList.AVLNode<E> next) {
rightIsNext = node == null;
right = rightIsNext ? next : node;
recalcHeight();
}
private TreeList.AVLNode<E> addAll(TreeList.AVLNode<E> otherTree, final int currentSize) {
final TreeList.AVLNode<E> maxNode = max();
final TreeList.AVLNode<E> otherTreeMin = otherTree.min();
// We need to efficiently merge the two AVL trees while keeping them
// balanced (or nearly balanced). To do this, we take the shorter
// tree and combine it with a similar-height subtree of the taller
// tree. There are two symmetric cases:
// * this tree is taller, or
// * otherTree is taller.
if (otherTree.height > height) {
// CASE 1: The other tree is taller than this one. We will thus
// merge this tree into otherTree.
// STEP 1: Remove the maximum element from this tree.
final TreeList.AVLNode<E> leftSubTree = removeMax();
// STEP 2: Navigate left from the root of otherTree until we
// contains a subtree, s, that is no taller than me. (While we are
// navigating left, we store the nodes we encounter in a stack
// so that we can re-balance them in step 4.)
final Deque<TreeList.AVLNode<E>> sAncestors = new ArrayDeque<>();
TreeList.AVLNode<E> s = otherTree;
int sAbsolutePosition = s.relativePosition + currentSize;
int sParentAbsolutePosition = 0;
while (s != null && s.height > getHeight(leftSubTree)) {
sParentAbsolutePosition = sAbsolutePosition;
sAncestors.push(s);
s = s.left;
if (s != null) {
sAbsolutePosition += s.relativePosition;
}
}
// STEP 3: Replace s with a newly constructed subtree whose root
// is maxNode, whose left subtree is leftSubTree, and whose right
// subtree is s.
maxNode.setLeft(leftSubTree, null);
maxNode.setRight(s, otherTreeMin);
if (leftSubTree != null) {
leftSubTree.max().setRight(null, maxNode);
leftSubTree.relativePosition -= currentSize - 1;
}
if (s != null) {
s.min().setLeft(null, maxNode);
s.relativePosition = sAbsolutePosition - currentSize + 1;
}
maxNode.relativePosition = currentSize - 1 - sParentAbsolutePosition;
otherTree.relativePosition += currentSize;
// STEP 4: Re-balance the tree and recalculate the heights of s's ancestors.
s = maxNode;
while (!sAncestors.isEmpty()) {
final TreeList.AVLNode<E> sAncestor = sAncestors.pop();
sAncestor.setLeft(s, null);
s = sAncestor.balance();
}
return s;
}
otherTree = otherTree.removeMin();
final Deque<TreeList.AVLNode<E>> sAncestors = new ArrayDeque<>();
TreeList.AVLNode<E> s = this;
int sAbsolutePosition = s.relativePosition;
int sParentAbsolutePosition = 0;
while (s != null && s.height > getHeight(otherTree)) {
sParentAbsolutePosition = sAbsolutePosition;
sAncestors.push(s);
s = s.right;
if (s != null) {
sAbsolutePosition += s.relativePosition;
}
}
otherTreeMin.setRight(otherTree, null);
otherTreeMin.setLeft(s, maxNode);
if (otherTree != null) {
otherTree.min().setLeft(null, otherTreeMin);
otherTree.relativePosition++;
}
if (s != null) {
s.max().setRight(null, otherTreeMin);
s.relativePosition = sAbsolutePosition - currentSize;
}
otherTreeMin.relativePosition = currentSize - sParentAbsolutePosition;
s = otherTreeMin;
while (!sAncestors.isEmpty()) {
final TreeList.AVLNode<E> sAncestor = sAncestors.pop();
sAncestor.setRight(s, null);
s = sAncestor.balance();
}
return s;
}
}
static class TreeListIterator<E> implements ListIterator<E>, OrderedIterator<E> {
private final TreeList<E> parent;
private TreeList.AVLNode<E> next;
private int nextIndex;
private TreeList.AVLNode<E> current;
private int currentIndex;
private int expectedModCount;
private TreeListIterator(final TreeList<E> parent, final int fromIndex) throws IndexOutOfBoundsException {
super();
this.parent = parent;
this.expectedModCount = parent.modCount;
this.next = parent.root == null ? null : parent.root.get(fromIndex);
this.nextIndex = fromIndex;
this.currentIndex = -1;
}
private void checkModCount() {
if (parent.modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
public boolean hasNext() {
return nextIndex < parent.size();
}
public E next() {
checkModCount();
if (!hasNext()) {
throw new NoSuchElementException("No element at index " + nextIndex + ".");
}
if (next == null) {
next = parent.root.get(nextIndex);
}
final E value = next.getValue();
current = next;
currentIndex = nextIndex++;
next = next.next();
return value;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
checkModCount();
if (!hasPrevious()) {
throw new NoSuchElementException("Already at start of list.");
}
if (next == null) {
next = parent.root.get(nextIndex - 1);
} else {
next = next.previous();
}
final E value = next.getValue();
current = next;
currentIndex = --nextIndex;
return value;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex() - 1;
}
public void remove() {
checkModCount();
if (currentIndex == -1) {
throw new IllegalStateException();
}
parent.remove(currentIndex);
if (nextIndex != currentIndex) {
// remove() following next()
nextIndex--;
}
// the AVL node referenced by next may have become stale after a remove
// reset it now: will be retrieved by next call to next()/previous() via nextIndex
next = null;
current = null;
currentIndex = -1;
expectedModCount++;
}
public void set(final E obj) {
checkModCount();
if (current == null) {
throw new IllegalStateException();
}
current.setValue(obj);
}
public void add(final E obj) {
checkModCount();
parent.add(nextIndex, obj);
current = null;
currentIndex = -1;
nextIndex++;
expectedModCount++;
}
}
}
static class InputReader extends InputStream {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
nlogn
|
961_D. Pair Of Lines
|
CODEFORCES
|
import java.util.*;
public class vas2 {
public static void main( String[] args ) {
Scanner in = new Scanner( System.in );
int n = in.nextInt();
String st = in.next();
int[] a = new int[n];
for ( int i = 0; i < n; i++ )
a[i] = st.charAt( i ) - 48;
boolean c = false;
for ( int i = 1; !c && i < n; i++ ) {
int s = 0;
for ( int j = 0; j < i; j++ )
s += a[j];
int t = 0;
for ( int j = i; j < n; j++ ) {
t += a[j];
if ( t > s )
if ( t - a[j] != s )
break;
else
t = a[j];
}
if ( t == s )
c = true;
}
System.out.println( c ? "YES" : "NO" );
}
}
|
quadratic
|
1030_C. Vasya and Golden Ticket
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class P111C{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-9;
int h, w;
void run(){
h=sc.nextInt();
w=sc.nextInt();
solve();
}
void shuffle(int[] is){
Random rand=new Random();
for(int i=is.length-1; i>=1; i--){
int j=rand.nextInt(i+1);
int t=is[i];
is[i]=is[j];
is[j]=t;
}
}
void solve(){
n=w*h;
g=new long[n];
int[] dx={0, 0, -1, 1};
int[] dy={-1, 1, 0, 0};
for(int y=0; y<h; y++){
for(int x=0; x<w; x++){
for(int k=0; k<4; k++){
int x2=x+dx[k];
int y2=y+dy[k];
if(x2>=0&&x2<w&&y2>=0&&y2<h){
g[y*w+x]|=1L<<(y2*w+x2);
}
}
}
}
candidate=new int[n];
mds=(1L<<n)-1;
mds(0, 0, 0);
println((n-Long.bitCount(mds))+"");
}
int n;
long[] g;
long mds;
int[] candidate;
void mds(long choosed, long removed, long covered){
if(Long.bitCount(choosed)>=Long.bitCount(mds))
return;
if(covered==((1L<<n)-1)){
if(Long.bitCount(choosed)<Long.bitCount(mds))
mds=choosed;
return;
}
long s=covered;
for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){
int i=Long.numberOfTrailingZeros(remained);
s|=(1L<<i)|g[i];
}
if(s!=((1L<<n)-1))
return;
int k=-1;
for(long remained=~removed&((1L<<n)-1); remained!=0; remained&=remained-1){
int i=Long.numberOfTrailingZeros(remained);
if((covered>>>i&1)==1){
if(Long.bitCount(g[i]&~covered)==0){
mds(choosed, removed|(1L<<i), covered);
return;
}else if(Long.bitCount(g[i]&~covered)==1
&&(g[i]&~covered&~removed)!=0){
mds(choosed, removed|(1L<<i), covered);
return;
}
}else{
if(Long.bitCount(g[i]&~removed)==0){
mds(choosed|(1L<<i), removed|(1L<<i), covered|(1L<<i)|g[i]);
return;
}else if(Long.bitCount(g[i]&~removed)==1
&&((g[i]&~removed)|(g[i]&~covered))==(g[i]&~removed)){
int j=Long.numberOfTrailingZeros(g[i]&~removed);
mds(choosed|(1L<<j), removed|(1L<<i)|(1L<<j), covered
|(1L<<j)|g[j]);
return;
}
}
if(k==-1||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered))
k=i;
}
if(k==-1)
return;
mds(choosed|(1L<<k), removed|(1L<<k), covered|(1L<<k)|g[k]);
mds(choosed, removed|(1L<<k), covered);
}
void println(String s){
System.out.println(s);
}
void print(String s){
System.out.print(s);
}
void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args){
Locale.setDefault(Locale.US);
new P111C().run();
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.io.*;
import java.text.*;
import java.util.*;
public class CottageVillage {
static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static String LINE() throws Exception { return stdin.readLine(); }
static String TOKEN() throws Exception {
while (st == null || !st.hasMoreTokens())st = new StringTokenizer(LINE());
return st.nextToken();
}
static int INT() throws Exception {return Integer.parseInt(TOKEN());}
static long LONG() throws Exception {return Long.parseLong(TOKEN());}
static double DOUBLE() throws Exception {return Double.parseDouble(TOKEN());}
static DecimalFormat DF = new DecimalFormat("0.000",new DecimalFormatSymbols(Locale.ENGLISH));
public static final double EPSILON = 1E-9;
public static void main(String[] args) throws Exception {
int N = INT(), T = INT();
House[] list = new House[N];
for(int i = 0;i<N;i++) {
list[i] = new House(INT(),INT());
}
Arrays.sort(list);
int cnt = 2;
for(int i = 1;i<N;i++) {
int room = list[i].center-list[i-1].center;
if(2*T<2*room-list[i].side-list[i-1].side)cnt += 2;
else if(2*T==2*room-list[i].side-list[i-1].side)cnt++;
}
System.out.println(cnt);
}
private static class House implements Comparable<House> {
int center, side;
House(int c, int s) {
this.center = c;
this.side = s;
}
public int compareTo(House h) {
return this.center-h.center;
}
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.lang.Character.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class B {
static final int[] num = new int[7];
static {
for(int i = 1, c = 1; i <= 6; i++, c *= 26)
num[i] = num[i-1] + c;
}
public void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while(n-- > 0) {
String s = sc.next();
System.out.println(s.matches("R[0-9]+C[0-9]+") ? toABdd(s) : toRC(s));
}
}
String toRC(String s) {
String ss = s.split("[0-9]+")[0];
String sn = s.split("[A-Z]+")[1];
int r = 0;
for(char c : ss.toCharArray())
r = r * 26 + c - 'A';
r += num[ss.length()];
int c = Integer.parseInt(sn);
return "R" + c + "C" + r;
}
String toABdd(String s) {
String[] ss = s.split("[RC]");
int c = Integer.parseInt(ss[1]);
int r = Integer.parseInt(ss[2]);
int a = 0;
while(r > num[++a]);
a--;
r -= num[a];
char[] cs = new char[a];
for(int i = 0; i < a; i++, r /= 26)
cs[a-i-1] = (char) (r % 26 + 'A');
return new String(cs) + c;
}
void debug(Object... os) {
System.err.println(Arrays.deepToString(os));
}
public static void main(String...args) {
new B().run();
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.util.*;
public class D
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner (System.in);
n= in.nextInt();
if (n%4==0 || n%7==0 || n%44==0 || n%47==0 || n%444==0 || n%447==0 ||
n%474==0 || n%477==0 || n%744==0 || n%747==0 || n%774==0 || n%777==0)
System.out.println("YES"); else System.out.println("NO");
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class p7{
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader sc = new FastReader();
//PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int k = sc.nextInt();
long one = (long)Math.pow(2, k) - 1;
long[] arr = new long[n+1];
arr[0] = 0;
for(int i=1;i<=n;i++){
arr[i] = sc.nextLong();
arr[i] ^= arr[i-1];
}
Map<Long, Long> count = new HashMap<>();
for(int i=0;i<=n;i++){
Long key = Math.min(arr[i], (arr[i]^one));
Long val = count.get(key);
if(val==null) val = 0L;
count.put(key, val+1);
}
long num = n;
long ans = num*(num+1)/2;
for(Map.Entry<Long, Long> ent: count.entrySet()){
Long cnt = ent.getValue();
long num1 = cnt/2;
long num2 = (cnt+1)/2;
ans -= ( (num1*(num1-1))/2 );
ans -= ( (num2*(num2-1))/2 );
}
System.out.println(ans);
}
}
|
nlogn
|
1054_D. Changing Array
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Anirudh Rayabharam (anirudhrb@yandex.com)
*/
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();
if (n % 2 == 0) {
out.println("4 " + (n - 4));
} else {
out.println("9 " + (n - 9));
}
}
}
class InputReader {
public BufferedReader reader;
private int tokenCount, nextTokenIndex;
private String[] tokens;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenCount = nextTokenIndex = 0;
}
public String next() {
String nextLine;
if (nextTokenIndex == tokenCount) {
try {
nextLine = reader.readLine();
nextTokenIndex = 0;
tokens = nextLine.split("\\s");
tokenCount = tokens.length;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokens[nextTokenIndex++];
}
public int nextInt() {
return Integer.parseInt(next());
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
List<Long> fi = new ArrayList<Long>();
fi.add((long) 0);
fi.add((long) 1);
while (fi.get(fi.size()-1)<n) {
fi.add(fi.get(fi.size()-1)+fi.get(fi.size()-2));
}
int last = fi.size()-1;
long z = last-1>=0 ? fi.get(last-1) : 0;
long y = last-3>=0 ? fi.get(last-3) : 0;
long x = last-4>=0 ? fi.get(last-4) : 0;
if (x+y+z<n)
x=1;
System.out.println(x+" "+y+" "+z);
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author zodiacLeo
*/
public class Main
{
public static void main(String[] args)
{
InputStream inputStream;
try
{
inputStream = new FileInputStream("input.txt");
} catch (IOException e)
{
throw new RuntimeException(e);
}
OutputStream outputStream;
try
{
outputStream = new FileOutputStream("output.txt");
} catch (IOException e)
{
throw new RuntimeException(e);
}
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC
{
public void solve(int testNumber, FastScanner in, FastPrinter out)
{
int n = in.nextInt();
int m = in.nextInt();
int p = in.nextInt();
int[] x = new int[p];
int[] y = new int[p];
for (int i = 0; i < p; i++)
{
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int X = x[0];
int Y = y[0];
int D = -1;
for (int dx = 1; dx <= n; dx++)
{
int x1 = dx;
int y1 = 1;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int dx = 1; dx <= n; dx++)
{
int x1 = dx;
int y1 = m;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int dy = 1; dy <= m; dy++)
{
int x1 = 1;
int y1 = dy;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int dy = 1; dy <= m; dy++)
{
int x1 = n;
int y1 = dy;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int i = 1; i <= Math.min(m, n); i++)
{
int x1 = i;
int y1 = i;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int i = 1, ii = m; i <= n && ii >= 1; i++, ii--)
{
int x1 = i;
int y1 = ii;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
out.println(X + " " + Y);
}
}
static class FastScanner
{
public BufferedReader br;
public StringTokenizer st;
public FastScanner(InputStream is)
{
br = new BufferedReader(new InputStreamReader(is));
}
public FastScanner(File f)
{
try
{
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public String next()
{
while (st == null || !st.hasMoreElements())
{
String s = null;
try
{
s = br.readLine();
} catch (IOException e)
{
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
static class FastPrinter extends PrintWriter
{
public FastPrinter(OutputStream out)
{
super(out);
}
public FastPrinter(Writer out)
{
super(out);
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class A {
public static void main(String[] args) throws IOException {
new A().run();
}
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
private void run() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
int n = nextInt();
Set<Integer> set = new TreeSet<Integer>();
for (int i = 0; i < n; i++) {
set.add(nextInt());
}
set.remove(set.iterator().next());
PrintWriter pw = new PrintWriter(System.out);
if (set.isEmpty()) {
pw.println("NO");
} else {
pw.println(set.iterator().next());
}
pw.close();
}
int nextInt() throws IOException {
while (!st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return Integer.parseInt(st.nextToken());
}
}
|
nlogn
|
22_A. Second Order Statistics
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author bdepwgjqet
*/
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);
A solver = new A();
solver.solve(1, in, out);
out.close();
}
}
class A {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int number = in.nextInt();
if((number & 1) == 0) {
out.println(4+" "+(number-4));
} else {
out.println(9+" "+(number-9));
}
}
}
class InputReader {
private final BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
public InputReader(InputStream in) {
bufferedReader = new BufferedReader(new InputStreamReader(in));
stringTokenizer = null;
}
public String nextLine() {
try {
return bufferedReader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public String nextBlock() {
while(stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(nextLine());
}
return stringTokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextBlock());
}
public double nextDouble() {
return Double.parseDouble(nextBlock());
}
public long nextLong() {
return Long.parseLong(nextBlock());
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import static java.lang.Math.*;
public class Main {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
public static void main(String[] args) {
new Main().run();
// Sworn to fight and die
}
public static void mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int levtIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (levtIndex < rightIndex) {
if (rightIndex - levtIndex <= MAGIC_VALUE) {
insertionSort(a, levtIndex, rightIndex);
} else {
int middleIndex = (levtIndex + rightIndex) / 2;
mergeSort(a, levtIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, levtIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int levtIndex, int middleIndex,
int rightIndex) {
int length1 = middleIndex - levtIndex + 1;
int length2 = rightIndex - middleIndex;
int[] levtArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, levtIndex, levtArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = levtIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = levtArray[i++];
} else {
a[k] = levtArray[i] <= rightArray[j] ? levtArray[i++]
: rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int levtIndex, int rightIndex) {
for (int i = levtIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= levtIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
class LOL implements Comparable<LOL> {
int x;
int y;
public LOL(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(LOL o) {
return (x - o.x); // ---->
//return o.x * o.y - x * y; // <----
}
}
class LOL2 implements Comparable<LOL2> {
int x;
int y;
int z;
public LOL2(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int compareTo(LOL2 o) {
return (z - o.z); // ---->
//return o.x * o.y - x * y; // <----
}
}
class test implements Comparable<test> {
long x;
long y;
public test(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(test o) {
//int compareResult = Long.compare(y, o.y); // ---->
//if (compareResult != 0) {
// return -compareResult;
//}
int compareResult = Long.compare(x, o.x);
if (compareResult != 0) {
return compareResult;
}
return Long.compare(y, o.y);
//return o.x * o.y - x * y; // <----
}
}
class data {
String name;
String city;
data(String name, String city) {
this.city = city;
this.name = name;
}
}
class Point {
double x;
double y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
double distance(Point temp) {
return Math.sqrt((x - temp.x) * (x - temp.x) + (y - temp.y) * (y - temp.y));
}
double sqrDist(Point temp) {
return ((x - temp.x) * (x - temp.x) + (y - temp.y) * (y - temp.y));
}
Point rotate(double alpha) {
return new Point(x * cos(alpha) - y * sin(alpha), x * sin(alpha) + y * cos(alpha));
}
void sum(Point o) {
x += o.x;
y += o.y;
}
void scalarProduct(int alpha) {
x *= alpha;
y *= alpha;
}
}
class Line {
double a;
double b;
double c;
Line(Point A, Point B) {
a = B.y - A.y;
b = A.x - B.x;
c = -A.x * a - A.y * b;
}
Line(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
Point intersection(Line o) {
double det = a * o.b - b * o.a;
double det1 = -c * o.b + b * o.c;
double det2 = -a * o.c + c * o.a;
return new Point(det1 / det, det2 / det);
}
}
/* class Plane {
double a;
double b;
double c;
double d;
Plane (Point fir, Point sec, Point thi) {
double del1 = (sec.y - fir.y) * (thi.z - fir.z) - (thi.y - fir.y) * (sec.z - fir.z);
double del2 = (thi.x - fir.x) * (sec.z - fir.z) - (thi.z - fir.z) * (sec.x - fir.x);
double del3 = (thi.y - fir.y) * (sec.x - fir.x) - (thi.x - fir.x) * (sec.y - fir.y);
a = del1;
b = del2;
c = del3;
d = -fir.x * del1 - fir.y * del2 - fir.z * del3;
}
double distance(Point point) {
return abs(a * point.x + b * point.y + c * point.z + d) / sqrt(a * a + b * b + c * c);
}
} */
class record implements Comparable<record> {
String city;
Long score;
public record(String name, Long score) {
this.city = name;
this.score = score;
}
@Override
public int compareTo(record o) {
if (o.city.equals(city)) {
return 0;
}
if (score.equals(o.score)) {
return 1;
}
if (score > o.score) {
return 666;
} else {
return -666;
}
//return Long.compare(score, o.score);
}
}
public long gcd(long a, long b) {
if (a == 0 || b == 0) return max(a, b);
if (a % b == 0)
return b;
else
return gcd(b, a % b);
}
boolean prime(long n) {
if (n == 1) return false;
for (int i = 2; i <= sqrt(n); i++)
if (n % i == 0)
return false;
return true;
}
public int sum(long n) {
int s = 0;
while (n > 0) {
s += (n % 10);
n /= 10;
}
return s;
}
/* public void simulation(int k) {
long ans = 0;
int start = 1;
for (int i = 0; i < k; i++) {
start *= 10;
}
for (int i = start/10; i < start; i++) {
int locAns = 0;
for (int j = start/10; j < start; j++) {
if (sum(i + j) == sum(i) + sum(j) ) {
ans += 1;
locAns += 1;
} else {
//.println(i + "!!!" + j);
}
}
//out.println(i + " " + locAns);
}
out.println(ans);
}*/
ArrayList<Integer> primes;
boolean[] isPrime;
public void getPrimes (int n) {
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
primes.add(i);
if (1l * i * i <= n) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
}
}
public long binPowMod(long a, long b, long mod) {
if (b == 0) {
return 1 % mod;
}
if (b % 2 != 0) {
return ((a % mod) * (binPowMod(a, b - 1, mod) % mod)) % mod;
} else {
long temp = binPowMod(a, b / 2, mod) % mod;
long ans = (temp * temp) % mod;
return ans;
}
}
int type[];
boolean vis[];
HashMap<Integer, HashSet<Integer>> g;
int componentNum[];
/* void dfs(int u, int numOfComponent) {
vis[u] = true;
componentNum[u] = numOfComponent;
for (Integer v: g.get(u)) {
if (!vis[v]) {
dfs(v, numOfComponent);
}
}
} */
int p[];
int find(int x) {
if (x == p[x]) {
return x;
}
return p[x] = find(p[x]);
}
boolean merge(int x, int y) {
x = find(x);
y = find(y);
if (p[x] == p[y]) {
return false;
}
p[y] = x;
return true;
}
class Trajectory {
double x0;
double y0;
double vx;
double vy;
Trajectory(double vx, double vy, double x0, double y0) {
this.vx = vx;
this.vy = vy;
this.x0 = x0;
this.y0 = y0;
}
double y (double x) {
return y0 + (x - x0) * (vy / vx) - 5 * (x - x0) * (x - x0) / (vx * vx);
}
double der(double x) {
return (vy / vx) - 10 * (x - x0) / (vx * vx);
}
}
int s;
int n;
int m;
boolean isVisited[][];
char[][] maze;
int[] dx = {0, 0, -1, 1};
int[] dy = {1, -1, 0, 0};
void dfs(int x, int y) {
isVisited[x][y] = true;
for (int i = 0; i < 4; i++) {
int currX = x + dx[i];
int currY = y + dy[i];
if (maze[currX][currY] == '.' && !isVisited[currX][currY]) {
dfs(currX, currY);
}
}
}
public void solve() throws IOException {
n = readInt();
m = readInt();
maze = new char[n + 2][m + 2];
for (int i = 0; i < n + 2; i++) {
maze[i][0] = '#';
maze[i][m + 1] = '#';
}
for (int j = 0; j < m + 2; j++) {
maze[0][j] = '#';
maze[n + 1][j] = '#';
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
maze[i][j] = '.';
}
}
int[][] dist = new int[n + 2][m + 2];
for (int i = 0; i < n + 2; i++) {
for (int j = 0; j < m + 2; j++) {
dist[i][j] = Integer.MAX_VALUE;
}
}
ArrayDeque<Integer> xValues = new ArrayDeque<Integer>();
ArrayDeque<Integer> yValues = new ArrayDeque<Integer>();
int k = readInt();
for (int i = 0; i < k; i++) {
int currX = readInt();
int currY = readInt();
xValues.add(currX);
yValues.add(currY);
dist[currX][currY] = 0;
}
while(!xValues.isEmpty()) {
int x = xValues.poll();
int y = yValues.poll();
for (int i = 0; i < 4; i++) {
int currX = x + dx[i];
int currY = y + dy[i];
if (maze[currX][currY] == '.' && dist[currX][currY] > dist[x][y] + 1) {
dist[currX][currY] = dist[x][y] + 1;
xValues.add(currX);
yValues.add(currY);
}
}
}
int maxDist = 0;
int indexX = 0;
int indexY = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (dist[i][j] >= maxDist) {
maxDist = dist[i][j];
indexX = i;
indexY = j;
}
}
}
out.print(indexX + " " + indexY);
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.concurrent.LinkedBlockingDeque;
import javax.swing.border.Border;
public class a {
public static long mod = (long) Math.pow(10, 9) + 7;
public static int k = 0;
private static class node implements Comparable<node> {
int l;
int r;
int index;
int index2;
int buffer;
node(int l, int r, int i, int b, int i2) {
this.l = l;
this.r = r;
index = i;
buffer = b;
index2 = i2;
}
@Override
public int compareTo(node o) {
if (k == 0) {
if (o.l < l)
return 1;
else if (o.l > l)
return -1;
else if (o.buffer != -1) {
return 1;
} else
return -1;
} else if (k == 1) {
if (r != o.r)
return r - o.r;
return o.index - index;
} else if (k == 2) {
return r - o.r;
} else {
if (o.index < index)
return 1;
else
return -1;
}
}
}
// private static class point implements Comparable<point> {
// int l;
// int r;
// int index;
// int buffer;
//
// point(int l, int r, int i, int b) {
// this.l = l;
// this.r = r;
// index = i;
// buffer = b;
//
// }
//
// @Override
// public int compareTo(point o) {
// if (o.l < l)
// return 1;
// else if (o.l > l)
// return -1;
// else if (o.r < r)
// return 1;
// else if (o.r > r)
// return -1;
// return 0;
// }
//
// }
public static class point implements Comparable<point> {
long x;
long y;
point(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(point o) {
return (int) (x - o.x);
}
}
public static int ch(long y) {
int r = Long.bitCount(y);
return r;
}
public static int gcd(int x, int y) {
if (y == 0)
return x;
return gcd(y, x % y);
}
public static int min[];
public static int max[];
public static void build(int s, int e, int p, int a[]) {
if (s == e) {
min[p] = a[s];
max[p] = a[s];
return;
}
int mid = (s + e) / 2;
build(s, mid, p * 2, a);
build(mid + 1, e, p * 2 + 1, a);
min[p] = Math.min(min[p * 2], min[p * 2 + 1]);
max[p] = Math.max(max[p * 2], max[p * 2 + 1]);
}
public static int getMin(int s, int e, int p, int from, int to) {
if (s > to || e < from)
return Integer.MAX_VALUE;
if (s >= from && e <= to)
return min[p];
int mid = (s + e) / 2;
int a = getMin(s, mid, p * 2, from, to);
int b = getMin(mid + 1, e, p * 2 + 1, from, to);
return Math.min(a, b);
}
public static int getMax(int s, int e, int p, int from, int to) {
if (s > to || e < from)
return Integer.MIN_VALUE;
if (s >= from && e <= to)
return max[p];
int mid = (s + e) / 2;
int a = getMax(s, mid, p * 2, from, to);
int b = getMax(mid + 1, e, p * 2 + 1, from, to);
return Math.max(a, b);
}
public static boolean ch[];
public static ArrayList<Integer> prime;
public static Queue<Integer> pp;
public static void sieve(int k) {
ch[0] = ch[1] = true;
for (int i = 2; i <= k; i++) {
if (!ch[i]) {
prime.add(i);
pp.add(i);
for (int j = i + i; j <= k; j += i) {
ch[j] = true;
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder qq = new StringBuilder();
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
String y[] = in.readLine().split(" ");
int n = Integer.parseInt(y[0]);
int a = Integer.parseInt(y[1]);
int b = Integer.parseInt(y[2]);
int arr[] = new int[n];
HashMap<Integer, Integer> mp = new HashMap();
y = in.readLine().split(" ");
boolean flag = true;
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(y[i]);
if (arr[i] >= a && arr[i] >= b) {
flag = false;
}
mp.put(arr[i], i);
}
if (!flag) {
System.out.println("NO");
return;
}
boolean ch[] = new boolean[n];
int ans[] = new int[n];
for (int i = 0; i < n; i++) {
int k = i;
while (true&&!ch[k]) {
if (mp.containsKey(a - arr[k]) && !ch[mp.get(a - arr[k])]
&& mp.containsKey(b - arr[k])
&& !ch[mp.get(b - arr[k])]) {
break;
} else if (mp.containsKey(a - arr[k])
&& !ch[mp.get(a - arr[k])]) {
//System.out.println(arr[k]);
ch[k] = true;
ans[k] = 0;
ch[mp.get(a - arr[k])] = true;
ans[mp.get(a - arr[k])] = 0;
int s = b - (a - arr[k]);
if (mp.containsKey(s)) {
k = mp.get(s);
} else
break;
} else if (mp.containsKey(b - arr[k])
&& !ch[mp.get(b - arr[k])]) {
ans[k] = 1;
ans[mp.get(b - arr[k])] = 1;
ch[k] = true;
ch[mp.get(b - arr[k])] = true;
int s = a - (b - arr[k]);
if (mp.containsKey(s)) {
k = mp.get(s);
} else
break;
} else {
// System.out.println(arr[i] + " " + i);
System.out.println("NO");
return;
}
}
}
qq.append("YES\n");
for (int i = 0; i < ans.length; i++) {
qq.append(ans[i] + " ");
}
System.out.println(qq);
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main implements Runnable {
class Segment {
int l, r;
Segment(int l, int r) {
this.l = l;
this.r = r;
}
@Override
public boolean equals(Object obj) {
Segment o = (Segment)obj;
return l == o.l && r == o.r;
}
@Override
public int hashCode() {
return 1000 * l + r;
}
}
public void _main() throws IOException {
int n = nextInt();
int t = nextInt();
int[] x = new int[n];
int[] a = new int[n];
for (int i = 0; i < n; i++) {
x[i] = nextInt();
a[i] = nextInt();
}
Set<Segment> set = new HashSet<Segment>();
for (int i = 0; i < n; i++) {
int l = 2 * x[i] + a[i];
int r = 2 * x[i] + a[i] + 2 * t;
boolean ok = true;
for (int j = 0; j < n; j++) {
if (i == j) continue;
int L = Math.max(l, 2 * x[j] - a[j]);
int R = Math.min(r, 2 * x[j] + a[j]);
if (L < R) {
ok = false;
break;
}
}
if (ok)
set.add(new Segment(l, r));
l = 2 * x[i] - a[i] - 2 * t;
r = 2 * x[i] - a[i];
ok = true;
for (int j = 0; j < n; j++) {
if (i == j) continue;
int L = Math.max(l, 2 * x[j] - a[j]);
int R = Math.min(r, 2 * x[j] + a[j]);
if (L < R) {
ok = false;
break;
}
}
if (ok)
set.add(new Segment(l, r));
}
out.print(set.size());
}
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) {
new Thread(new Main()).start();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
_main();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(202);
}
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, Scanner in, PrintWriter out) {
String[] str = in.nextLine().split(" ");
int a = Integer.parseInt(str[0]);
int v = Integer.parseInt(str[1]);
str = in.nextLine().split(" ");
int l = Integer.parseInt(str[0]);
int d = Integer.parseInt(str[1]);
int w = Integer.parseInt(str[2]);
double minTime = 0.;
if (w >= v) {
minTime = getTimeAfterSign(0, v, l, a);
out.format(Locale.US, "%.6f", minTime);
return;
}
double whenGetSpeedWPath = (w * w) / (2. * a);
if (whenGetSpeedWPath >= d) {
double time = Math.sqrt((2.0 * d) / a);
minTime = time + getTimeAfterSign(a * time, v, l - d, a);
} else {
double stopPath = (v * v - w * w) / (2. * a);
double vMaxPath = (v * v) / (2. * a);
if (stopPath + vMaxPath > d) {
// double topSpeed = (Math.sqrt(2. * a * d) + w) / 2;
// minTime = (topSpeed / a) + (topSpeed - w) / a + getTimeAfterSign(w, v, l - d, a);
double topSpeed = Math.sqrt((2. * a * d + w * w) / 2);
minTime = (2. * topSpeed - w) / a + getTimeAfterSign(w, v, l - d, a);
} else {
double stopTime = (v - w) / (a + 0.);
double getMaxTime = v / (a + 0.);
double maxTime = (d - (stopPath + vMaxPath)) / v;
minTime = stopTime + getMaxTime + maxTime + getTimeAfterSign(w, v, l - d, a);
}
}
out.format(Locale.US, "%.6f", minTime);
}
double getTimeAfterSign(double startSpeed, double maxSpeed, double path, int a) {
double maxSpeedTime = (maxSpeed - startSpeed) / a;
double maxSpeedPath = startSpeed * maxSpeedTime + (a * maxSpeedTime * maxSpeedTime) / 2;
if (maxSpeedPath > path) {
return (-startSpeed + Math.sqrt(startSpeed * startSpeed + 2 * a * path)) / a;
} else {
return maxSpeedTime + (path - maxSpeedPath) / maxSpeed;
}
}
}
|
constant
|
5_D. Follow Traffic Rules
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
public static void main(String args[]) {
FastScanner scn = new FastScanner();
int n = scn.nextInt();
int s = scn.nextInt();
if (s <= n) {
System.out.println(1);
} else if (s > n) {
if(s%n == 0){
System.out.println(s/n);
} else {
System.out.println(s/n + 1);
}
}
}
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();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
|
constant
|
1061_A. Coins
|
CODEFORCES
|
//package educational.round67;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
public class G {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni(), K = ni(), C = ni(), D = ni();
int[] a = na(K);
int[] from = new int[m];
int[] to = new int[m];
for (int i = 0; i < m; i++) {
from[i] = ni() - 1;
to[i] = ni() - 1;
}
int[][] g = packU(n, from, to);
List<Edge> es = new ArrayList<>();
int time = 100;
for(int i = 0;i < n;i++){
for(int j = 0;j < time-1;j++){
es.add(new Edge(i*time+j, i*time+j+1, 99, C));
}
}
for(int i = 0;i < n;i++){
for(int e : g[i]){
for(int j = 0;j < time-1;j++){
for(int k = 0;k < n;k++){
es.add(new Edge(i*time+j, e*time+j+1, 1, C+D*(2*k+1)));
}
}
}
}
int src = time*n, sink = src+1;
for(int i = 0;i < K;i++){
es.add(new Edge(src, (a[i]-1)*time+0, 1, 0));
}
for(int i = 0;i < time;i++){
es.add(new Edge(0*time+i, sink, 99, 0));
}
out.println(solveMinCostFlowWithSPFA(compileWD(sink+1, es), src, sink, 99));
}
public static class Edge
{
public int from, to;
public int capacity;
public int cost;
public int flow;
public Edge complement;
// public int iniflow;
public Edge(int from, int to, int capacity, int cost) {
this.from = from;
this.to = to;
this.capacity = capacity;
this.cost = cost;
}
}
public static Edge[][] compileWD(int n, List<Edge> edges)
{
Edge[][] g = new Edge[n][];
// cloning
for(int i = edges.size()-1;i >= 0;i--){
Edge origin = edges.get(i);
Edge clone = new Edge(origin.to, origin.from, origin.capacity, -origin.cost);
clone.flow = origin.capacity;
clone.complement = origin;
origin.complement = clone;
edges.add(clone);
}
int[] p = new int[n];
for(Edge e : edges)p[e.from]++;
for(int i = 0;i < n;i++)g[i] = new Edge[p[i]];
for(Edge e : edges)g[e.from][--p[e.from]] = e;
return g;
}
// NOT VERIFIED
public static Edge[][] compileWU(int n, List<Edge> edges)
{
Edge[][] g = new Edge[n][];
// cloning
for(int i = edges.size()-1;i >= 0;i--){
Edge origin = edges.get(i);
Edge back = new Edge(origin.to, origin.from, origin.capacity, origin.cost);
edges.add(back);
}
for(int i = edges.size()-1;i >= 0;i--){
Edge origin = edges.get(i);
Edge clone = new Edge(origin.to, origin.from, origin.capacity, -origin.cost);
clone.flow = origin.capacity;
clone.complement = origin;
origin.complement = clone;
edges.add(clone);
}
int[] p = new int[n];
for(Edge e : edges)p[e.from]++;
for(int i = 0;i < n;i++)g[i] = new Edge[p[i]];
for(Edge e : edges)g[e.from][--p[e.from]] = e;
return g;
}
public static class DQ {
public int[] q;
public int n;
protected int pt, ph;
public DQ(int n){ this.n = Integer.highestOneBit(n)<<1; q = new int[this.n]; pt = ph = 0; }
public void addLast(int x){ q[ph] = x; ph = ph+1&n-1; }
public void addFirst(int x){ pt = pt+n-1&n-1; q[pt] = x; }
public int pollFirst(){ int ret = q[pt]; pt = pt+1&n-1; return ret; }
public int pollLast(){ ph = ph+n-1&n-1; int ret = q[ph]; return ret; }
public int getFirst(){ return q[pt]; }
public int getFirst(int k){ return q[pt+k&n-1]; }
public int getLast(){ return q[ph+n-1&n-1]; }
public int getLast(int k){ return q[ph+n-k-1&n-1]; }
public void clear(){ pt = ph = 0; }
public int size(){ return ph-pt+n&n-1; }
public boolean isEmpty(){ return ph==pt; }
}
public static long solveMinCostFlowWithSPFA(Edge[][] g, int source, int sink, long all)
{
int n = g.length;
long mincost = 0;
final int[] d = new int[n];
DQ q = new DQ(n);
boolean[] inq = new boolean[n];
while(all > 0){
// shortest path src->sink
Edge[] inedge = new Edge[n];
Arrays.fill(d, Integer.MAX_VALUE / 2);
d[source] = 0;
q.addLast(source);
while(!q.isEmpty()){
int cur = q.pollFirst();
inq[cur] = false;
for(Edge ne : g[cur]){
if(ne.capacity - ne.flow > 0){
int nd = d[cur] + ne.cost;
if(d[ne.to] > nd){
inedge[ne.to] = ne;
d[ne.to] = nd;
if(!inq[ne.to]){
q.addLast(ne.to);
inq[ne.to] = true;
}
}
}
}
}
if(inedge[sink] == null)break;
long minflow = all;
long sumcost = 0;
for(Edge e = inedge[sink];e != null;e = inedge[e.from]){
if(e.capacity - e.flow < minflow)minflow = e.capacity - e.flow;
sumcost += e.cost;
}
mincost += minflow * sumcost;
for(Edge e = inedge[sink];e != null;e = inedge[e.from]){
e.flow += minflow;
e.complement.flow -= minflow;
}
all -= minflow;
}
return mincost;
}
static int[][] packU(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int t : to)
p[t]++;
for (int i = 0; i < n; i++)
g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) {
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new G().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
cubic
|
1187_G. Gang Up
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
public class ProblemC {
static int[] dx = {1, 0, 0, -1};
static int[] dy = {0, 1, -1, 0};
public static void main(String[] args) throws IOException {
BufferedReader s = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
// BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
// PrintWriter out = new PrintWriter(System.out);
String[] nm = s.readLine().split(" ");
int n = Integer.valueOf(nm[0]);
int m = Integer.valueOf(nm[1]);
int k = Integer.valueOf(s.readLine());
int[][] dp = new int[n][m];
for (int i = 0 ; i < n ; i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE);
}
String[] st = s.readLine().split(" ");
int[][] trees = new int[k][2];
for (int l = 0 ; l < k ; l++) {
trees[l][0] = Integer.valueOf(st[l*2])-1;
trees[l][1] = Integer.valueOf(st[l*2+1])-1;
}
int maxtime = -1;
int max_x = -1;
int max_y = -1;
for (int i = 0 ; i < n ; i++) {
for (int j = 0 ; j < m ; j++) {
int minDist = n+m;
for (int l = 0 ; l < k ; l++) {
minDist = Math.min(minDist, Math.abs(i - trees[l][0]) + Math.abs(j - trees[l][1]));
}
if (maxtime < minDist) {
maxtime = minDist;
max_x = i+1;
max_y = j+1;
}
}
}
out.println(max_x + " " + max_y);
out.flush();
}
public static void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author codeKNIGHT
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n=in.nextInt(),a=in.nextInt(),b=in.nextInt(),i,c=0;
int ar[]=new int[n];
for(i=0;i<n;i++)
ar[i]=in.nextInt();
Arrays.sort(ar);
out.println(ar[b]-ar[b-1]);
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
PrintWriter out = new PrintWriter(System.out);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer("");
String next() throws IOException {
if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }
return tok.nextToken();
}
int ni() throws IOException { return Integer.parseInt(next()); }
long nl() throws IOException { return Long.parseLong(next()); }
void solve() throws IOException {
int n=ni(),k=ni();
int puts=(int)Math.sqrt(2*k);
int t=(puts*(puts+1))/2;
puts++;
while (t<k) { t+=puts; puts++; }
int turns=puts-1;
while (t-k!=n-turns) {
t+=puts;
puts++;
turns++;
}
System.out.println(t-k);
}
public static void main(String[] args) throws IOException {
new Main().solve();
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class LookingForOrder {
static int[][] pos;
static int[] dp;
static int[] nextstate;
static int[][] dist;
static int r;
static int v;
static void print(int mask) {
if (mask < v) {
int c = 0;
int x = mask ^ nextstate[mask];
for (int i = 0; i < dist.length - 1; i++) {
if((x & (1<<i))>0) {
System.out.print(i+1 + " ");
c++;
}
}
System.out.print("0 ");
print(nextstate[mask]);
}
}
static int distace(int x1, int x2, int y1, int y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
static int solve(int mask) {
if (mask == v) {
nextstate[mask] = r;
return 0;
}
if (nextstate[mask] != 0) {
return dp[mask];
}
dp[mask] = (int) 1e9;
for (int i = 1; i < pos.length; i++) {
int u = (1 << (i - 1));
int z = mask | u;
if ((mask & u) == 0) {
int x = 2 * dist[i][0] + solve(z);
if (dp[mask] > x) {
dp[mask] = x;
nextstate[mask] = z;
}
for (int j = 1; j < pos.length; j++) {
int m = (1 << j - 1);
int y = z | m;
if ((z & m) == 0) {
x = dist[i][0] + solve(y) + dist[i][j] + dist[j][0];
if (dp[mask] > x) {
dp[mask] = x;
nextstate[mask]= y;
}
}
}
break;
}
}
return dp[mask];
}
public static void main(String[] args) {
InputReader0 in = new InputReader0(System.in);
int x = in.nextInt(), y = in.nextInt();
int n = in.nextInt();
r = 1 << n;
v = r - 1;
dp = new int[r];
nextstate = new int[r];
pos = new int[n + 1][2];
pos[0][0] = x;
pos[0][1] = y;
for (int i = 1; i < pos.length; i++) {
pos[i][0] = in.nextInt();
pos[i][1] = in.nextInt();
}
dist = new int[n + 1][n + 1];
for (int i = 0; i < dist.length; i++) {
for (int j = i + 1; j < dist.length; j++) {
dist[i][j] = dist[j][i] = distace(pos[i][0], pos[j][0], pos[i][1], pos[j][1]);
}
}
System.out.println(solve(0));
System.out.print("0 ");
print(0);
}
}
class InputReader0 {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader0(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 long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class C994{
static double area(double x1,double y1,double x2,double y2,double x3,double y3){
return Math.abs((x1 * (y2 - y3) +
x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
}
public static void main(String args[])throws IOException{
Scanner sc=new Scanner(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter pw=new PrintWriter(System.out);
int x11=sc.nextInt();
int y11=sc.nextInt();
int x12=sc.nextInt();
int y12=sc.nextInt();
int x13=sc.nextInt();
int y13=sc.nextInt();
int x14=sc.nextInt();
int y14=sc.nextInt();
double x1c=(x11+x12+x13+x14)/4.0;
double y1c=(y11+y12+y13+y14)/4.0;
int x21=sc.nextInt();
int y21=sc.nextInt();
int x22=sc.nextInt();
int y22=sc.nextInt();
int x23=sc.nextInt();
int y23=sc.nextInt();
int x24=sc.nextInt();
int y24=sc.nextInt();
double x2c=(x21+x22+x23+x24)/4.0;
double y2c=(y21+y22+y23+y24)/4.0;
double a1=area(x11,y11,x12,y12,x13,y13)+area(x11,y11,x13,y13,x14,y14);
double a2=area(x21,y21,x22,y22,x23,y23)+area(x21,y21,x23,y23,x24,y24);
if(a1==area(x11,y11,x12,y12,x21,y21)+area(x11,y11,x21,y21,x14,y14)+area(x21,y21,x12,y12,x13,y13)+area(x21,y21,x14,y14,x13,y13)){
pw.println("YES");
pw.close();
return;
}
if(a1==area(x11,y11,x12,y12,x22,y22)+area(x11,y11,x22,y22,x14,y14)+area(x22,y22,x12,y12,x13,y13)+area(x22,y22,x14,y14,x13,y13)){
pw.println("YES");
pw.close();
return;
}
if(a1==area(x11,y11,x12,y12,x23,y23)+area(x11,y11,x23,y23,x14,y14)+area(x23,y23,x12,y12,x13,y13)+area(x23,y23,x14,y14,x13,y13)){
pw.println("YES");
pw.close();
return;
}
if(a1==area(x11,y11,x12,y12,x24,y24)+area(x11,y11,x24,y24,x14,y14)+area(x24,y24,x12,y12,x13,y13)+area(x24,y24,x14,y14,x13,y13)){
pw.println("YES");
pw.close();
return;
}
if(a1==area(x11,y11,x12,y12,x2c,y2c)+area(x11,y11,x2c,y2c,x14,y14)+area(x2c,y2c,x12,y12,x13,y13)+area(x2c,y2c,x14,y14,x13,y13)){
pw.println("YES");
pw.close();
return;
}
if(a2==area(x21,y21,x22,y22,x11,y11)+area(x21,y21,x11,y11,x24,y24)+area(x11,y11,x22,y22,x23,y23)+area(x11,y11,x24,y24,x23,y23)){
pw.println("YES");
pw.close();
return;
}
if(a2==area(x21,y21,x22,y22,x12,y12)+area(x21,y21,x12,y12,x24,y24)+area(x12,y12,x22,y22,x23,y23)+area(x12,y12,x24,y24,x23,y23)){
pw.println("YES");
pw.close();
return;
}
if(a2==area(x21,y21,x22,y22,x13,y13)+area(x21,y21,x13,y13,x24,y24)+area(x13,y13,x22,y22,x23,y23)+area(x13,y13,x24,y24,x23,y23)){
pw.println("YES");
pw.close();
return;
}
if(a2==area(x21,y21,x22,y22,x14,y14)+area(x21,y21,x14,y14,x24,y24)+area(x14,y14,x22,y22,x23,y23)+area(x14,y14,x24,y24,x23,y23)){
pw.println("YES");
pw.close();
return;
}
if(a2==area(x21,y21,x22,y22,x1c,y1c)+area(x21,y21,x14,y14,x2c,y2c)+area(x1c,y1c,x22,y22,x23,y23)+area(x1c,y1c,x24,y24,x23,y23)){
pw.println("YES");
pw.close();
return;
}
pw.println("NO");
pw.close();
}
}
|
constant
|
994_C. Two Squares
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
public class Cycles
{
public static FastInputStream fis;
public static void main(String[] args) throws IOException
{
fis = new FastInputStream(System.in);
System.out.println(solve(fis.nextInt(), fis.nextInt()));
fis.close();
}
public static long solve(int n, int m) throws IOException
{
boolean[][] graph = new boolean[n][];
long[][] state = new long[1 << n][n];
for (int i = 0; i < n; i++)
graph[i] = new boolean[n - i];
for (int i = 0; i < m; i++)
{
int a = fis.nextInt() - 1;
int b = fis.nextInt() - 1;
setConnected(graph, a, b);
state[(1 << a) | (1 << b)][a > b ? a : b] = 1;
}
long res = 0;
for (int i = 2; i < n; i++)
{
int baseCombination = (2 << i) - 1;
while (baseCombination < (1 << n))
{
int min = getFirstOne(baseCombination);
int bits = baseCombination;
while (bits != 0)
{
int firstBit = bits & (-bits);
int firstBitPos = getFirstOne(firstBit);
bits &= bits - 1;
if (firstBitPos == min)
continue;
int leftOverBits = baseCombination - firstBit;
int nextBits = leftOverBits;
while (nextBits != 0)
{
int nextBit = nextBits & (-nextBits);
int nextBitPos = getFirstOne(nextBit);
nextBits &= nextBits - 1;
if (nextBitPos == min)
continue;
if (!isConnected(graph, firstBitPos, nextBitPos))
continue;
/*System.out.println("Comb: " + Integer.toBinaryString(baseCombination));
System.out.println("Bit: " + Integer.toBinaryString(firstBit));
System.out.println("(pos): " + firstBitPos);
System.out.println("Left over: " + Integer.toBinaryString(leftOverBits));
System.out.println("Next bit: " + Integer.toBinaryString(nextBit));
System.out.println("(pos): " + nextBitPos);
System.out.println();*/
state[baseCombination][firstBitPos] += state[leftOverBits][nextBitPos];
}
if (isConnected(graph, firstBitPos, min))
res += state[baseCombination][firstBitPos];
}
baseCombination = nextCombination(baseCombination);
}
}
/*for (int i = 0; i < state.length; i++)
{
if ((i & (i - 1)) == 0)
continue;
System.out.print(String.format("%4s:", Integer.toBinaryString(i)).replace(' ', '0') + " ");
for (int j = 0; j < state[i].length; j++)
System.out.print(state[i][j] + " ");
System.out.println();
}*/
return res >> 1;
}
public static boolean isConnected(boolean[][] graph, int a, int b)
{
if (b < a || graph[a].length <= (b - a))
return graph[b][a - b];
return graph[a][b - a];
}
public static void setConnected(boolean[][] graph, int a, int b)
{
if (b < a || graph[a].length <= (b - a))
graph[b][a - b] = true;
else
graph[a][b - a] = true;
}
public static int nextCombination(int x)
{
int smallest = x & -x;
int ripple = x + smallest;
int ones = ((x ^ ripple) >> 2) / smallest;
return ripple | ones;
}
public static boolean on(int bitmask, int pos)
{
return ((bitmask >> pos) & 1) == 1;
}
public static int setOn(int bitmask, int pos)
{
return bitmask | (1 << pos);
}
public static int setOff(int bitmask, int pos)
{
return bitmask & ~(1 << pos);
}
public static int getOns(int bitmask)
{
int amt = 0;
while (bitmask != 0)
{
bitmask &= bitmask - 1;
amt++;
}
return amt;
}
public static int getFirstOne(int bitmask)
{
if (bitmask == 0)
return -1;
int first = 0;
while ((bitmask & 1) != 1)
{
first++;
bitmask = bitmask >> 1;
}
return first;
}
public static class FastInputStream extends InputStream
{
private InputStream in;
private byte[] buffer = new byte[512];
private int loaded = 0;
private int pointer = 0;
public FastInputStream(InputStream in)
{
this.in = in;
}
@Override
public int read() throws IOException
{
if (hasNext())
return buffer[pointer++];
else
return -1;
}
public void skipWhitespace() throws IOException
{
while (hasNext())
{
char c = (char) buffer[pointer];
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') pointer++;
else return;
}
}
public Integer nextInt() throws IOException
{
skipWhitespace();
if (!hasNext()) return null;
byte multiplier = 1;
int number = 0;
if (buffer[pointer] == '-')
{
multiplier = -1;
pointer++;
}
while (hasNext())
{
char c = (char) buffer[pointer];
if (c >= '0' && c <= '9')
{
number = (number << 3) + (number << 1) + c - '0';
pointer++;
} else break;
}
return number * multiplier;
}
public void close() throws IOException
{
in.close();
}
public boolean hasNext() throws IOException
{
while (pointer == loaded)
{
loaded = in.read(buffer);
pointer = 0;
if (loaded == -1) return false;
}
return loaded != -1;
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.Scanner;
public class A_Toy_Army {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner entrada = new Scanner(System.in);
while(entrada.hasNextInt())
{
int n = entrada.nextInt();
System.out.println(n+(n/2));
}
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.*;
import java.util.Scanner;
import java.lang.String;
public class A23 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
int i=0,j=0,n=0,t=0,count=0;
n=s.length();
String s1="y",s2="yu6j";
for(t=1;t<n;t++)
{
for(i=0;i<t;i++)
{
s1=s.substring(i,i+n-t);
for(j=i+1;j<=t;j++)
{
s2=s.substring(j,j+n-t);
if(s1.equalsIgnoreCase(s2))
{
count++;break;
}
if(count==1) break;
}
if(count==1) break;
}
if(count==1) break;
}
if(n==0)
{
System.out.println("0");
}
else
{
if(count==1)
{
System.out.println(s1.length());
}
else System.out.println("0");
}
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class C{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n=in.nextInt(),key=in.nextInt(),ans=0;
int[] a = new int[101], b = new int[101];
for (int i=1;i<=n;i++) {a[i]=in.nextInt();b[i]=in.nextInt();}
for (int i=1;i<n;i++)
for (int j=i+1;j<=n;j++)
if (a[i]<a[j] || (a[i]==a[j] && b[i]>b[j])) {
int yed = a[i];a[i]=a[j]; a[j]=yed;
yed = b[i];b[i]=b[j];b[j]=yed;
}
int k=0;
for (int i=1;i<=n;i++) {
if (a[i]==a[i-1] && b[i]==b[i-1]) k++; else
{if (i>key && ans==0) ans = k;k=1;}
}
if (ans == 0) ans = k;
System.out.println(ans);
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.util.Scanner;
public class B1177 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long N = in.nextLong();
long answer = solve(N, 0, 1, 1);
System.out.println(answer);
}
static long solve(long N, long offset, long start, int digits) {
long thisSection = digits*start*9;
long fromOffset = N-offset;
if (fromOffset > thisSection) {
return solve(N, offset+thisSection, 10*start, digits+1);
}
long number = start + (fromOffset-1)/digits;
long posInNumber = digits - 1 - (fromOffset-1)%digits;
while (posInNumber > 0) {
posInNumber--;
number /= 10;
}
return number%10;
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.util.Scanner;
public class A {
static Scanner scanner = new Scanner(System.in);
static int s;
public static void main(String[] args) {
s = scanner.nextInt();
if (s >= 0) {
System.out.println(s);
}
else {
if (s >= -10) {
System.out.println(0);
}
else {
int ss = -s;
int a, b;
a = ss % 10;
b = (ss % 100) / 10;
if (a > b) {
ss = ss / 10;
}
else {
ss = (ss / 100) * 10 + a;
}
if (ss == 0) {
System.out.println(0);
}
else {
System.out.println("-" + ss);
}
}
}
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
// upsolve with rainboy
import java.io.*;
import java.util.*;
public class CF1187G extends PrintWriter {
CF1187G() { super(System.out, true); }
static class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
int k, l; byte[] bb = new byte[1 << 15];
byte getc() {
if (k >= l) {
k = 0;
try { l = in.read(bb); } catch (IOException e) { l = 0; }
if (l <= 0) return -1;
}
return bb[k++];
}
int nextInt() {
byte c = 0; while (c <= 32) c = getc();
int a = 0;
while (c > 32) { a = a * 10 + c - '0'; c = getc(); }
return a;
}
}
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1187G o = new CF1187G(); o.main(); o.flush();
}
static final int INF = 0x3f3f3f3f;
ArrayList[] aa_;
int n_, m_;
int[] pi, kk;
int[] uu, vv, uv, cost, cost_;
int[] cc;
void init() {
aa_ = new ArrayList[n_];
for (int u = 0; u < n_; u++)
aa_[u] = new ArrayList<Integer>();
pi = new int[n_];
kk = new int[n_];
uu = new int[m_];
vv = new int[m_];
uv = new int[m_];
cost = new int[m_];
cc = new int[m_ * 2];
m_ = 0;
}
void link(int u, int v, int cap, int cos) {
int h = m_++;
uu[h] = u;
vv[h] = v;
uv[h] = u ^ v;
cost[h] = cos;
cc[h << 1 ^ 0] = cap;
aa_[u].add(h << 1 ^ 0);
aa_[v].add(h << 1 ^ 1);
}
boolean dijkstra(int s, int t) {
Arrays.fill(pi, INF);
pi[s] = 0;
TreeSet<Integer> pq = new TreeSet<>((u, v) -> pi[u] != pi[v] ? pi[u] - pi[v] : kk[u] != kk[v] ? kk[u] - kk[v] : u - v);
pq.add(s);
Integer first;
while ((first = pq.pollFirst()) != null) {
int u = first;
int k = kk[u] + 1;
ArrayList<Integer> adj = aa_[u];
for (int h_ : adj)
if (cc[h_] > 0) {
int h = h_ >> 1;
int p = pi[u] + ((h_ & 1) == 0 ? cost_[h] : -cost_[h]);
int v = u ^ uv[h];
if (pi[v] > p || pi[v] == p && kk[v] > k) {
if (pi[v] != INF)
pq.remove(v);
pi[v] = p;
kk[v] = k;
pq.add(v);
}
}
}
return pi[t] != INF;
}
int dfs(int u, int t, int c) {
if (u == t || c == 0)
return c;
int k = kk[u] + 1;
ArrayList<Integer> adj = aa_[u];
for (int h_ : adj) {
int h = h_ >> 1;
int v = u ^ uv[h];
if (kk[v] != k)
continue;
int p = pi[u] + ((h_ & 1) == 0 ? cost_[h] : -cost_[h]), f;
if (pi[v] == p && (f = dfs(v, t, Math.min(c, cc[h_]))) != 0) {
cc[h_] -= f; cc[h_ ^ 1] += f;
return f;
}
}
kk[u] = INF;
return 0;
}
int edmonds_karp(int s, int t) {
cost_ = Arrays.copyOf(cost, m_);
while (dijkstra(s, t)) {
while (dfs(s, t, INF) > 0)
;
for (int h = 0; h < m_; h++) {
int u = uu[h], v = vv[h];
if (pi[u] != INF && pi[v] != INF)
cost_[h] += pi[u] - pi[v];
}
}
int c = 0;
for (int h = 0; h < m_; h++)
c += cost[h] * cc[h << 1 ^ 1];
return c;
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int[] ii = new int[k];
for (int h = 0; h < k; h++)
ii[h] = sc.nextInt() - 1;
ArrayList[] aa = new ArrayList[n];
for (int i = 0; i < n; i++)
aa[i] = new ArrayList<Integer>();
for (int h = 0; h < m; h++) {
int i = sc.nextInt() - 1;
int j = sc.nextInt() - 1;
aa[i].add(j);
aa[j].add(i);
}
int t = n + k + 1;
n_ = n * t + 1;
m_ = k + (m * 2 * k + n) * (t - 1);
init();
for (int i = 0; i < n; i++) {
ArrayList<Integer> adj = aa[i];
for (int s = 0; s < t - 1; s++) {
int u = i * t + s;
for (int j : adj) {
int v = j * t + s + 1;
for (int x = 1; x <= k; x++)
link(u, v, 1, c + (x * 2 - 1) * d);
}
}
}
for (int i = 0; i < n; i++)
for (int s = 0; s < t - 1; s++) {
int u = i * t + s, v = u + 1;
link(u, v, k, i == 0 ? 0 : c);
}
for (int h = 0; h < k; h++)
link(n_ - 1, ii[h] * t + 0, 1, 0);
println(edmonds_karp(n_ - 1, 0 * t + t - 1));
}
}
|
cubic
|
1187_G. Gang Up
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class problemA {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] numbs = new int[n];
int[] smallest_color = new int[n];
for(int i = 0; i < n;i++){
numbs[i] = scan.nextInt();
}
Arrays.sort(numbs);
int count = 0;
for(int i =0; i < n; i++){
for(int j=0; j <n;j++ ){
if(smallest_color[j] == 0){
count++;
smallest_color[j] = numbs[i];
break;
}
if(numbs[i] % smallest_color[j] == 0){
break;
}
}
}
System.out.println(count);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class A {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
long f(int x, int y) {
if (x == 0 || y == 0)
return 0;
if (x >= y) {
return x / y + f(y, x % y);
} else {
return y / x + f(x, y % x);
}
}
A() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int t = nextInt();
while (t-- > 0) {
int a = nextInt();
int b = nextInt();
out.println(f(a, b));
}
out.close();
}
public static void main(String[] args) throws IOException {
new A();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
|
constant
|
267_A. Subtractions
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int numbers[] = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
scanner.close();
Arrays.sort(numbers);
boolean[] colored = new boolean[n];
int res = 0;
for (int i = 0; i < n; i++) {
if (!colored[i]) {
res += 1;
}
for (int j = i; j < n; j++) {
if (numbers[j] % numbers[i] == 0) {
colored[j] = true;
}
}
}
System.out.println(res);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class round111A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [] coins = new int [n];
for(int i = 0 ; i < n ; ++i)
coins[i] = sc.nextInt();
Arrays.sort(coins);
int ans = (int)1e9;
for(int i = 1 ; i <= n ; ++i){
int sum1 = 0;
int c = 0;
int j = n - 1;
for(j = n - 1 ; j >= 0 && c < i ; --j, ++c){
sum1 += coins[j];
}
int sum2 = 0;
for(int k = 0 ; k <= j ; ++k)
sum2 += coins[k];
if(sum1 > sum2){
System.out.println(i);
return;
}
}
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.IntStream;
public class Test {
static PrintWriter writer =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
static long readLong() {
long ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
static String readLine() {
StringBuilder b = new StringBuilder();
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (Character.isLetterOrDigit(c)) {
start = true;
b.append((char) c);
} else if (start) break;
}
} catch (IOException e) {
}
return b.toString();
}
public static void main(String[] args) {
Test te = new Test();
te.start();
writer.flush();
}
void start() {
int t = readInt();
while (t-- > 0) {
int n = readInt(), m = readInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = readInt();
int[] dp = new int[1<<n];
Arrays.fill(dp, -1);
dp[0] = 0;
for (int c = 0; c < m; c++) {
for (int i = (1 << n) - 1; i >= 0; i--) {
int u = (1 << n) - 1 - i;
int p = u;
if (dp[i] >= 0)
while (p > 0) {
for (int r = 0; r < n; r++) {
int sum = 0;
for (int j = 0; j < n; j++) if (((p >> j) & 1) != 0) sum += a[(j + r) % n][c];
dp[i | p] = Math.max(dp[i | p], dp[i] + sum);
}
p = (p - 1) & u;
}
}
}
writer.println(dp[(1<<n) - 1]);
}
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.util.Locale;
import java.util.Scanner;
public class E {
public static void main(String[] args) {
new E().run();
}
private void run() {
Locale.setDefault(Locale.US);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double[][] p = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
p[i][j] = sc.nextDouble();
}
sc.close();
double[] w = new double[1 << n];
int max = (1 << n) - 1;
w[max] = 1;
for (int mask = max; mask > 0; mask--) {
int count = 0;
for (int i = 0; i < n; i++)
if (((mask >> i) & 1) > 0)
for (int j = i + 1; j < n; j++)
if (((mask >> j) & 1) > 0) {
count++;
}
if (count > 0)
for (int i = 0; i < n; i++)
if (((mask >> i) & 1) > 0)
for (int j = i + 1; j < n; j++)
if (((mask >> j) & 1) > 0) {
w[mask ^ (1 << j)] += w[mask] * p[i][j] / count;
w[mask ^ (1 << i)] += w[mask] * (1 - p[i][j])
/ count;
}
}
for (int i = 0; i < n; i++) {
if (i != 0)
System.out.print(' ');
System.out.printf("%.6f", w[1 << i]);
}
System.out.println();
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
TaskC.InputReader in = new TaskC.InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.Solve(in, out);
out.close();
}
static class TaskC {
void Solve(InputReader in, PrintWriter out) {
int n = in.NextInt();
double r = in.NextInt();
double[] x = new double[n];
for (int i = 0; i < n; i++) x[i] = in.NextInt();
double[] y = new double[n];
for (int i = 0; i < n; i++) {
double maxY = r;
for (int j = 0; j < i; j++) {
if (Math.abs(x[i] - x[j]) <= 2 * r) {
double currentY = Math.sqrt((2 * r) * (2 * r) - (x[i] - x[j]) * (x[i] - x[j])) + y[j];
maxY = Math.max(maxY, currentY);
}
}
y[i] = maxY;
}
out.print(y[0]);
for (int i = 1; i < n; i++) {
out.print(" " + y[i]);
}
out.println();
}
static int GetMax(int[] ar) {
int max = Integer.MIN_VALUE;
for (int a : ar) {
max = Math.max(max, a);
}
return max;
}
static int GetMin(int[] ar) {
int min = Integer.MAX_VALUE;
for (int a : ar) {
min = Math.min(min, a);
}
return min;
}
static long GetSum(int[] ar) {
long s = 0;
for (int a : ar) s += a;
return s;
}
static int[] GetCount(int[] ar) {
return GetCount(ar, GetMax(ar));
}
static int[] GetCount(int[] ar, int maxValue) {
int[] dp = new int[maxValue + 1];
for (int a : ar) {
dp[a]++;
}
return dp;
}
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(), " \t\n\r\f,");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
int NextInt() {
return Integer.parseInt(Next());
}
long NextLong() {
return Long.parseLong(Next());
}
double NextDouble() {
return Double.parseDouble(Next());
}
int[] NextIntArray(int n) {
return NextIntArray(n, 0);
}
int[] NextIntArray(int n, int offset) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = NextInt() - offset;
}
return a;
}
int[][] NextIntMatrix(int n, int m) {
return NextIntMatrix(n, m, 0);
}
int[][] NextIntMatrix(int n, int m, int offset) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = NextInt() - offset;
}
}
return a;
}
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class SimpleTask {
public static void main(String[] args) throws Exception {
InputReader in = new InputReader(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[] g = new int[n];
long[][] dp = new long[1 << n][n];
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1, b = in.nextInt() - 1;
g[a] |= (1 << b);
g[b] |= (1 << a);
}
int all = (1 << n) - 1;
for (int i = 0; i < n; i++) {
int l = (1 << i);
int left = all ^ (l - 1) ^ l;
for (int j = left; j > 0; j = (j - 1) & left)
if ((j & (j - 1)) != 0) {
dp[j | l][i] = 1;
}
}
for (int i = (1 << n) - 1; i > 0; i--) {
int last = i & -i;
for (int j = 0; j < n; j++) {
if (((1 << j) == last && (i & (i - 1)) != 0)
|| ((1 << j) & i) == 0)
continue;
for (int k = 0; k < n; k++) {
if ((1 << k) >= last && ((1 << k) & g[j]) != 0
&& ((1 << k) == last || ((1 << k) & i) == 0)) {
dp[i][j] += dp[i | (1 << k)][k];
}
}
}
}
long res = 0;
for (int i = 0; i < n; i++)
res += dp[(1 << i)][i];
System.out.println(res / 2);
}
static 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());
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main {
static int n;
static long TotalTime;
static Problem[] problems;
static StringBuilder sb;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
sb = new StringBuilder();
n = sc.nextInt();
TotalTime = sc.nextLong();
problems = new Problem[n];
for (int i = 0; i < n; i++) {
problems[i] = new Problem (sc.nextInt(), sc.nextLong(), i);
}
Arrays.sort(problems);
long num = -1;
long high = n;
long low = 0;
int iter = 0;
while (high - low > 1) {
num = (high + low) / 2;
if (test(num, false)) {
low = num;
}
else {
high = num;
}
}
if (test(high, false))
num = high;
else
num = low;
test(num, true);
System.out.print(sb);
}
public static boolean test (long num, boolean print) {
int count = 0;
long sum = 0L;
if (print) sb.append(num + "\n" + num + "\n");
for (int i = 0; i < n && count < num; i++) {
if (problems[i].a >= num) {
count++;
sum += problems[i].t;
if (print) sb.append((problems[i].index + 1) + " ");
}
}
return (count == num) && (sum <= TotalTime);
}
public static class Problem implements Comparable<Problem> {
int a;
long t;
int index;
public int compareTo(Problem o) {
return Long.compare(t, o.t);
}
public Problem (int a, long t, int index) {
this.a = a;
this.t = t;
this.index = index;
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextLong();
}
return a;
}
}
}
|
nlogn
|
913_D. Too Easy Problems
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class Main {
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tok;
static boolean hasNext()
{
while(tok==null||!tok.hasMoreTokens())
try{
tok=new StringTokenizer(in.readLine());
}
catch(Exception e){
return false;
}
return true;
}
static String next()
{
hasNext();
return tok.nextToken();
}
static long nextLong()
{
return Long.parseLong(next());
}
static int nextInt()
{
return Integer.parseInt(next());
}
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) {
Map<Integer,Integer> map = new HashMap();
map.put(0,1);
int n = nextInt();
int m = nextInt();
int index = -1;
int a[] = new int[n];
for(int i=0;i<n;i++){
a[i]=nextInt();
if(a[i]==m)
index=i;
}
int sum = 0;
for(int i=0;i<index;i++){
if (a[i]<m)
sum--;
else
sum++;
if (map.containsKey(sum)){
map.put(sum,map.get(sum)+1);
}else {
map.put(sum,1);
}
}
long ans = 0;
for(int i=index;i<n;i++){
if (a[i]<m)
sum--;
else if(a[i]>m)
sum++;
if (map.containsKey(sum))
ans+=map.get(sum);
if (map.containsKey(sum-1))
ans+=map.get(sum-1);
}
out.print(ans);
out.flush();
}
}
|
nlogn
|
1005_E1. Median on Segments (Permutations Edition)
|
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.util.ArrayList;
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);
TaskG2 solver = new TaskG2();
solver.solve(1, in, out);
out.close();
}
static class TaskG2 {
static final int MOD = 1000000000 + 7;
static final int MAXN = 51;
int getWays(int i, int j, int k, int l, int[][][][] ways, boolean[][][][] cached) {
if (i + j + k == 0) return l == -1 ? 1 : 0;
if (l < 0) return 0;
if (cached[i][j][k][l]) return ways[i][j][k][l];
int s = i + j + k;
long value = 0;
if (l == 0 && i != 0) {
for (int x = -1; x < 3; x++)
if (x != l) {
value += getWays(i - 1, j, k, x, ways, cached);
}
}
if (l == 1 && j != 0) {
for (int x = -1; x < 3; x++)
if (x != l) {
value += getWays(i, j - 1, k, x, ways, cached);
}
}
if (l == 2 && k != 0) {
for (int x = -1; x < 3; x++)
if (x != l) {
value += getWays(i, j, k - 1, x, ways, cached);
}
}
ways[i][j][k][l] = (int) (value % MOD);
cached[i][j][k][l] = true;
return ways[i][j][k][l];
}
int totalWays(int i, int j, int k, int[][][][] ways, boolean[][][][] cached, int[] factorial) {
long ret = 0;
for (int l = 0; l < 3; l++) ret += getWays(i, j, k, l, ways, cached);
ret *= factorial[i];
ret %= MOD;
ret *= factorial[j];
ret %= MOD;
ret *= factorial[k];
ret %= MOD;
return (int) ret;
}
int add(int type, int value, int[] sizes, int sum, int[][][][] dp) {
sizes[type]++;
if (type == 0) {
for (int s = sum + value; s >= value; s--) {
for (int i = 1; i <= sizes[0]; i++)
for (int j = 0; j <= sizes[1]; j++)
for (int k = 0; k <= sizes[2]; k++) {
dp[i][j][k][s] += dp[i - 1][j][k][s - value];
if (dp[i][j][k][s] >= MOD)
dp[i][j][k][s] -= MOD;
}
}
}
if (type == 1) {
for (int s = sum + value; s >= value; s--) {
for (int i = 0; i <= sizes[0]; i++)
for (int j = 1; j <= sizes[1]; j++)
for (int k = 0; k <= sizes[2]; k++) {
// System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length);
dp[i][j][k][s] += dp[i][j - 1][k][s - value];
if (dp[i][j][k][s] >= MOD)
dp[i][j][k][s] -= MOD;
}
}
}
if (type == 2) {
for (int s = sum + value; s >= value; s--) {
for (int i = 0; i <= sizes[0]; i++)
for (int j = 0; j <= sizes[1]; j++)
for (int k = 1; k <= sizes[2]; k++) {
// System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length);
dp[i][j][k][s] += dp[i][j][k - 1][s - value];
if (dp[i][j][k][s] >= MOD)
dp[i][j][k][s] -= MOD;
}
}
}
return sum + value;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int[][][][] ways = new int[MAXN][MAXN][MAXN][3];
boolean[][][][] cached = new boolean[MAXN][MAXN][MAXN][3];
// Arrays.fill(ways, -1);
int n = in.nextInt(), T = in.nextInt();
ArrayList<Integer>[] ar = new ArrayList[3];
for (int i = 0; i < 3; i++) ar[i] = new ArrayList<Integer>();
int total_sum = 0;
for (int i = 0; i < n; i++) {
int t = in.nextInt(), g = in.nextInt();
ar[g - 1].add(t);
total_sum += t;
}
if (T > total_sum) {
out.println(0);
return;
}
int min_index = 0, mn = 0;
for (int i = 0; i < 3; i++) {
if (ar[i].size() > mn) {
mn = ar[i].size();
min_index = i;
}
}
int[][][][] dp = new int[ar[(1 + min_index) % 3].size() + 1][ar[(2 + min_index) % 3].size() + 1][1][total_sum + 1];
int[][][][] dp2 = new int[1][1][mn + 1][total_sum + 1];
dp[0][0][0][0] = dp2[0][0][0][0] = 1;
int[] sizes = {0, 0, 0};
int sum = 0;
int[] order = {(min_index + 1) % 3, (min_index + 2) % 3};
int type = 0;
for (int i : order) {
for (int v : ar[i])
sum = add(type, v, sizes, sum, dp);
type++;
}
sum = 0;
sizes[0] = sizes[1] = sizes[2] = 0;
for (int i : ar[min_index])
sum = add(2, i, sizes, sum, dp2);
int[] factorial = new int[MAXN];
factorial[0] = 1;
for (int i = 1; i < MAXN; i++)
factorial[i] = (int) ((factorial[i - 1] * 1L * i) % MOD);
long answer = 0;
for (int i = 0; i < dp.length; i++)
for (int j = 0; j < dp[0].length; j++)
for (int k = 0; k <= mn; k++)
for (int s = 0; s <= T; s++) {
long x = (dp[i][j][0][s] * 1L * totalWays(i, j, k, ways, cached, factorial)) % MOD;
x *= dp2[0][0][k][T - s];
x %= MOD;
answer += x;
}
out.println(answer % MOD);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public 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);
}
}
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 println(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
writer.print('\n');
}
public void close() {
writer.close();
}
}
}
|
cubic
|
1185_G2. Playlist for Polycarp (hard version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
private void solve() throws IOException {
out.println(solve(nl()));
out.close();
}
private long solve(long n) throws IOException {
if (n > 0) {
n <<= 1;
long k = nl();
n--;
int M = 1000000007;
long p = power(2, k, M);
// Helper.tr(n * p + 1);
n = (n % M * p + 1) % M;
}
return n;
}
long power(long a, long b, long mod) {
long x = 1, y = a;
while (b > 0) {
if (b % 2 != 0) {
x = (x * y) % mod;
}
y = (y * y) % mod;
b /= 2;
}
return x % mod;
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
private int[][] na(int n) throws IOException {
int[][] a = new int[n][2];
for (int i = 0; i < n; i++) {
a[i][0] = ni();
a[i][1] = i;
}
return a;
}
String ns() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine(), " ");
}
return tok.nextToken();
}
int ni() throws IOException {
return Integer.parseInt(ns());
}
long nl() throws IOException {
return Long.parseLong(ns());
}
double nd() throws IOException {
return Double.parseDouble(ns());
}
String[] nsa(int n) throws IOException {
String[] res = new String[n];
for (int i = 0; i < n; i++) {
res[i] = ns();
}
return res;
}
int[] nia(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = ni();
}
return res;
}
long[] nla(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nl();
}
return res;
}
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = new StringTokenizer("");
Main main = new Main();
main.solve();
out.close();
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Cf1017A {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int result = 1;
int thomasSum = 0;
StringTokenizer stk;
stk = new StringTokenizer(br.readLine());
int first = Integer.parseInt(stk.nextToken());
int second = Integer.parseInt(stk.nextToken());
int third = Integer.parseInt(stk.nextToken());
int fourth = Integer.parseInt(stk.nextToken());
thomasSum = first + second + third + fourth;
int tmp;
for (int i = 1; i < n; i++) {
stk = new StringTokenizer(br.readLine());
first = Integer.parseInt(stk.nextToken());
second = Integer.parseInt(stk.nextToken());
third = Integer.parseInt(stk.nextToken());
fourth = Integer.parseInt(stk.nextToken());
tmp = first + second + third + fourth;
if (tmp > thomasSum)
result++;
}
System.out.println(result);
}
}
|
linear
|
1017_A. The Rank
|
CODEFORCES
|
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
long n=sc.nextLong();
long x=1;
long ar=0;
tag:for(long i=1;;i++)
{
ar+=9*i*x;
if(ar>=n)
{
long d = n - (ar-9*i*x);
long ans = x+d/i;
long p=d%i;
if(p==0)
{
p=i;
ans--;
}
p=i-p;
p++;
long fns=0;
//System.out.println(ans);
while(p!=0)
{
fns=ans%10;
ans/=10;
p--;
}
System.out.println(fns);
break tag;
}
x*=10;
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int N = r.nextInt();
int K = r.nextInt() - 1;
T[] a = new T[N];
for(int i = 0; i < N; i++)
a[i] = new T(r.nextInt(), r.nextInt());
Arrays.sort(a, new Comparator<T>() {
@Override
public int compare(T x, T y) {
if(x.p > y.p)return -1;
else if(x.p == y.p){
if(x.t < y.t)return -1;
else if(x.t == y.t)return 0;
else return 1;
}else return 1;
}
});
int ret = 0;
for(int i = 0; i < N; i++)
if(a[i].p == a[K].p && a[i].t == a[K].t)ret++;
System.out.println(ret);
}
}
class T{
int p, t;
public T(int pi, int ti){
p = pi;
t = ti;
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger l = sc.nextBigInteger();
BigInteger r = sc.nextBigInteger();
BigInteger a = l.add(BigInteger.ZERO);
while (a.compareTo(r) < 0) {
BigInteger b = a.add(BigInteger.ONE);
while (b.compareTo(r) < 0) {
try {
a.modInverse(b);
} catch (ArithmeticException e) {
b = b.add(BigInteger.ONE);
continue;
}
BigInteger c = b.add(BigInteger.ONE);
while (c.compareTo(r) <= 0) {
try {
b.modInverse(c);
try {
a.modInverse(c);
} catch (ArithmeticException e) {
System.out.printf("%s %s %s\n", a.toString(), b.toString(), c.toString());
return;
}
} catch (ArithmeticException e) {
}
c = c.add(BigInteger.ONE);
}
b = b.add(BigInteger.ONE);
}
a = a.add(BigInteger.ONE);
}
System.out.println("-1");
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class Codeforces
{
public StreamTokenizer st;
public PrintWriter pw;
public static final int modulo = 1000000009;
static class Point
{
public int x, y;
Point(int _x, int _y)
{
x = _x;
y = _y;
}
}
void init(String in, String out)
{
if (in.isEmpty())
st = new StreamTokenizer(System.in);
else
{
try
{
st = new StreamTokenizer(new BufferedReader(new FileReader(in)));
}
catch(FileNotFoundException e)
{
}
}
if (out.isEmpty())
pw = new PrintWriter(System.out);
else
{
try
{
pw = new PrintWriter(new FileWriter(out));
}
catch(IOException e)
{
}
}
}
private void close()
{
pw.close();
}
private int nI()
{
try{
st.nextToken();
}
catch(IOException e)
{
}
return (int)st.nval;
}
private double nD()
{
try{
st.nextToken();
}
catch(IOException e)
{
}
return st.nval;
}
private String nS()
{
try{
st.nextToken();
}
catch(IOException e)
{
}
return st.sval;
}
private long nL()
{
try{
st.nextToken();
}
catch(IOException e)
{
}
return (long)st.nval;
}
public static void qSort(int[] A, int low, int high) {
int i = low;
int j = high;
int x = A[(low+high)/2];
do {
while(A[i] < x) ++i;
while(A[j] > x) --j;
if(i <= j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
i++; j--;
}
} while(i < j);
if(low < j)
qSort(A, low, j);
if(i < high)
qSort(A, i, high);
}
public static void main(String[] aslkdjlkgja) throws IOException
{
Codeforces z = new Codeforces();
z.init("", "");
long l = z.nL();
long r = z.nL();
if ( l == r)
{
System.out.println(0);
z.close();
return;
}
List<Boolean> R = new ArrayList<Boolean>();
List<Boolean> L = new ArrayList<Boolean>();
long temp = r;
while (temp != 0)
{
if (temp % 2 == 1)
R.add(true);
else
R.add(false);
temp /= 2;
}
Collections.reverse(R);
temp = l;
while (temp != 0)
{
if (temp % 2 == 1)
L.add(true);
else
L.add(false);
temp /= 2;
}
int n = R.size() - L.size();
while (n!=0)
{
L.add(false);
--n;
}
Collections.reverse(L);
List<Boolean> res = new ArrayList<Boolean>();
// for (int i = 0 ; i < R.size(); ++i)
// res.add(false);
int it = 0;
while (R.get(0) == L.get(0))
{
res.add(false);
R.remove(0);
L.remove(0);
}
for (int i = 0; i< R.size(); ++i)
res.add(true);
long out = 0;
it = 0;
long add = 1;
Collections.reverse(res);
while (it < res.size())
{
if (res.get(it))
out += add;
add *= 2;
++it;
}
System.out.println(out);
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class z3 {
public static boolean divch(int i,int a)
{ if (a>1000) return false; if ((a>0)&&(i%a==0)) return true; return (divch(i,a*10+4)||divch(i,a*10+7)); }
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println(divch(in.nextInt(),0)?"YES":"NO");
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.util.Scanner;
public class Round8_C {
/**
* @param args
*/
int n ;
int[] X, Y ;
public Round8_C() {
info_in() ;
process() ;
}
void info_in()
{
Scanner input = new Scanner(System.in) ;
int dx = input.nextInt() ;
int dy = input.nextInt() ;
n = input.nextInt() ;
X = new int[n] ;
Y = new int[n] ;
for( int i=0;i<n;i++) {
X[i] = input.nextInt() - dx ;
Y[i] = input.nextInt() - dy ;
}
}
int[] d ;
int[] trace ;
public static int distance( int x1, int y1, int x2, int y2 )
{
return (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) ;
}
void process()
{
int gh = 1<<n ;
d = new int[gh] ;
trace = new int[gh] ;
d[0] = 0 ;
for( int i=1;i<gh;i++) {
d[i] = Integer.MAX_VALUE ;
for( int j=0;j<n;j++)
if ( (i & (1<<j)) > 0 ) {
int val = d[i^(1<<j)] + ( distance( X[j], Y[j], 0, 0 ) << 1 ) ;
if ( val < d[i] ) {
d[i] = val ;
trace[i] = j+1 ;
}
int state = i ^ (1<<j) ;
for( int p=j+1;p<n;p++)
if ( (i & (1<<p)) > 0) {
val = d[state^(1<<p)] + distance( X[j], Y[j], 0, 0 ) + distance( X[j], Y[j], X[p], Y[p] ) + distance( X[p], Y[p], 0, 0 ) ;
if ( val < d[i] ) {
d[i] = val ;
trace[i] = (j+1) * 100 + (p+1) ;
}
}
break ;
}
}
System.out.println( d[gh-1] ) ;
gh-- ;
while ( gh > 0 ) {
int v1 = trace[gh] / 100 - 1 ;
int v2 = trace[gh] % 100 - 1 ;
System.out.print(0 + " ") ;
if ( v1 != -1 ) {
System.out.print((v1+1) + " " ) ;
gh -= 1 << v1 ;
}
System.out.print( (v2+1) + " " ) ;
gh -= 1 << v2 ;
}
System.out.println(0) ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Round8_C() ;
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class zz{
static int mod=(int)1e9+7;
public static void main(String[] args) throws Exception{
//MScanner sc = new MScanner("chess.in");
MScanner sc = new MScanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
//int[]in=new int[n];for(int i=0;i<n;i++)in[i]=sc.nextInt();
int k=sc.nextInt();
int x=(-3+(int)Math.sqrt(9+4*1.0*(2*k*1.0+2*n*1.0)))/2;
pw.println(n-x);
pw.flush();
}
static class pair implements Comparable<pair>{
String t;int d;int idx;
pair(String x,int y,int i){
t=x;d=y;idx=i;
}
@Override
public int compareTo(pair o) {
if(t.compareTo(o.t)!=0) {
return t.compareTo(o.t);
}
return o.d-d;
}
public boolean equals(pair o) {
if(this.compareTo(o)==0)return true;
return false;
}
public String toString() {
return "("+t+" "+d+")";
}
}
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
public class Main implements Runnable {
/**
* @param args
*/
public static void main(String[] args) {
new Thread(new Main()).start();
}
public void run() {
Locale.setDefault(Locale.US);
try {
run1();
} catch (IOException e) {
throw new RuntimeException();
}
}
int nextInt(StreamTokenizer st) throws IOException {
st.nextToken();
return (int) st.nval;
}
private List<Integer> kmp(String x, String a) {
String s = a + "$" + x;
int[] oppa = new int[s.length()];
oppa[0] = 0;
int tmp = 0;
List<Integer> res = new ArrayList<Integer>();
for (int i = 1; i < s.length(); i++) {
while (tmp != 0 && s.charAt(tmp) != s.charAt(i)) {
// System.out.println(i + " " + tmp);
tmp = oppa[tmp - 1];
}
if (s.charAt(tmp) == s.charAt(i))
tmp++;
oppa[i] = tmp;
if (tmp == a.length()) {
res.add(i - a.length() - a.length());
}
}
return res;
}
double nextDouble(StreamTokenizer st) throws IOException {
st.nextToken();
return st.nval;
}
String nextLine(StreamTokenizer st) throws IOException {
st.nextToken();
return st.sval;
}
int cnt = 0;
int[] col;
void unite(int a, int b) {
if (cnt % 2 == 0)
col[getCol(a)] = getCol(b);
else
col[getCol(b)] = getCol(a);
cnt++;
}
int getCol(int a) {
return a == col[a] ? a : (col[a] = getCol(col[a]));
}
public void run1() throws IOException {
// Scanner sc = new Scanner(new FileReader("input.txt"));
Scanner sc = new Scanner(new InputStreamReader(System.in));
// BufferedReader br = new BufferedReader(new
// InputStreamReader(System.in));
// PrintWriter pw = new PrintWriter(new FileWriter("output.txt"));
String s= sc.next();
int res = 0;
int n = s.length();
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++) {
int k = 0;
while(j + k < n && s.charAt(i + k) == s.charAt(j + k))
k++;
res = Math.max(res, k);
}
System.out.println(res);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class _1036_B_DiagonalWalkingV2 {
public static void main(String[] args) throws IOException {
int Q = readInt();
while(Q-- > 0) {
long n = readLong(), m = readLong(), k = readLong();
if(Math.max(n, m) > k) println(-1);
else {
long ans = k;
if(n%2 != k%2) ans--;
if(m%2 != k%2) ans--;
println(ans);
}
}
exit();
}
final private static int BUFFER_SIZE = 1 << 16;
private static DataInputStream din = new DataInputStream(System.in);
private static byte[] buffer = new byte[BUFFER_SIZE];
private static int bufferPointer = 0, bytesRead = 0;
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = Read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public static String read() throws IOException {
byte[] ret = new byte[1024];
int idx = 0;
byte c = Read();
while (c <= ' ') {
c = Read();
}
do {
ret[idx++] = c;
c = Read();
} while (c != -1 && c != ' ' && c != '\n' && c != '\r');
return new String(ret, 0, idx);
}
public static int readInt() 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 static long readLong() 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 static double readDouble() 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 static void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private static byte Read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
static void print(Object o) {
pr.print(o);
}
static void println(Object o) {
pr.println(o);
}
static void flush() {
pr.flush();
}
static void println() {
pr.println();
}
static void exit() throws IOException {
din.close();
pr.close();
System.exit(0);
}
}
|
linear
|
1036_B. Diagonal Walking v.2
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class pr1073B {
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[] a = new int[n];
int[] b = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
b[i] = Integer.parseInt(st.nextToken());
}
solve(n, a, b, out);
out.flush();
out.close();
}
private static void solve(int n, int[] a, int[] b, PrintWriter out) {
boolean[] book = new boolean[n+1];
boolean f;
int j1 = 0, j2 = 0;
for (int i = 0; i < n; i++) {
f = false;
int num = b[i];
if(!book[num]) {
f = true;
j1 = j2;
for (;j2 < n; j2++) {
book[a[j2]] = true;
if (a[j2] == num) {
j2++;
break;
}
}
}
out.print(f ? j2-j1 + " ": 0 + " ");
}
}
}
|
linear
|
1073_B. Vasya and Books
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class Codeforce {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++) {
arr[i] = sc.nextInt();
}
int color = 0;
Arrays.sort(arr);
for(int i=0; i<n; i++) {
if(arr[i]!=0) {
int col = arr[i];
color++;
for(int j=i; j<n; j++) {
if(arr[j]%col==0) arr[j]=0;
}
}
}
System.out.println(color);
sc.close();
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
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();
int m = sc.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = sc.nextInt();
val = new int[n][n];
for (int i = 0; i < n; i++)
Arrays.fill(val[i], Integer.MAX_VALUE);
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++) {
for (int k = 0; k < m; k++)
val[i][j] = val[j][i] = Math.min(val[i][j], Math.abs(a[i][k] - a[j][k]));
}
val2 = new int[n][n];
for (int i = 0; i < n; i++)
Arrays.fill(val2[i], Integer.MAX_VALUE);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
for (int k = 0; k < m - 1; k++)
val2[i][j] = Math.min(val2[i][j], Math.abs(a[i][k] - a[j][k + 1]));
}
mem = new Long[n][n][1 << n];
long ans = 0;
for (int i = 0; i < n; i++) {
ans = Math.max(ans, dp(i, i, 1 << i));
}
if (n == 1)
pw.println(val2[0][0]);
else
pw.println(ans);
pw.flush();
pw.close();
}
static int n;
static int[][] val, val2;
static Long[][][] mem;
static long dp(int st, int lst, int msk) {
int bits = Integer.bitCount(msk);
if (mem[st][lst][msk] != null)
return mem[st][lst][msk];
long ans = 0;
for (int i = 0; i < n; i++)
if ((msk & (1 << i)) == 0) {
int newMsk = (msk | (1 << i));
if (bits < n - 1)
ans = Math.max(ans, Math.min(val[lst][i], dp(st, i, newMsk)));
else
ans = Math.max(ans, Math.min(val[lst][i], val2[i][st]));
}
return mem[st][lst][msk] = ans;
}
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;
}
}
}
|
np
|
1102_F. Elongated Matrix
|
CODEFORCES
|
import java.util.Scanner;
public class A {
public static void main(String[] args) {
new A().run();
}
private void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int ce = 0;
int co = 0;
int le = 0;
int lo = 0;
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
if (x % 2 == 0) {
ce++;
le = i + 1;
} else {
co++;
lo = i + 1;
}
}
System.out.println(ce == 1 ? le : lo);
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.util.Scanner;
public class b817 {
public static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
long n = scn.nextLong();
long s = scn.nextLong();
long lo = 0;
long hi = n ;
while(lo<=hi)
{
long mid=(lo+hi)/2;
if(check(mid, s))// no's greater thn this grtr
{
hi=mid-1;
}
else
{
lo=mid+1;
}
}
if(check(lo, s))
{
System.out.println(n-lo+1);
}
else // could check initially too
{
System.out.println("0");
}
}
public static boolean check(long n, long s) {
long sum=0;
long a=n;
while(n>0)
{
sum=sum+(n%10);
n=n/10;
}
if(a-sum>=s)
{
return true;
}
return false;
}
}
|
logn
|
817_C. Really Big Numbers
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class G {
static final int P = 1_000_000_007;
int[][] ways;
int[][] pow;
void preCalc(int sz) {
ways = new int[sz][];
for (int i = 0; i < ways.length; i++) {
ways[i] = new int[i + 1];
ways[i][0] = ways[i][i] = 1;
for (int j = 1; j < i; j++) {
ways[i][j] = (ways[i - 1][j] + ways[i - 1][j - 1]) % P;
}
}
pow = new int[10][sz];
pow[0] = null;
for (int i = 1; i <= 9; i++) {
pow[i][0] = 1;
for (int j = 1; j < sz; j++) {
pow[i][j] = (int) ((long) pow[i][j - 1] * i % P);
}
}
}
int solve(String ss) {
int n = ss.length();
int[] s = new int[n];
for (int i = 0; i < n; i++) {
s[i] = ss.charAt(i) - '0';
}
preCalc(n + 10);
int[] ans = new int[n + 1];
int[] cnt = new int[10];
for (int i = 0; i < n; i++) {
int rest = n - i - 1;
int dig = s[i];
for (int j = 0; j <= (i == n - 1 ? dig : dig - 1); j++) {
cnt[j]++; // now we have one more digit >= j
for (int use = 1; use < 10; use++) {
// use digits are bad, 10 - use are good
for (int cntGood = 0; cntGood <= rest; cntGood++) {
int delta = (int) ((long) ways[rest][cntGood]
* pow[use][rest - cntGood] % P
* pow[10 - use][cntGood] % P);
int idx = cnt[use] + cntGood;
ans[idx] += delta;
if (ans[idx] >= P) {
ans[idx] -= P;
}
}
}
// System.err.println(Arrays.toString(ans));
}
cnt[dig]++;
}
int ret = 0;
long mult = 0;
for (int i = 1; i < ans.length; i++) {
mult = (10L * mult + 1) % P;
ret += (int)(mult * ans[i] % P);
if (ret >= P) {
ret -= P;
}
}
return ret;
}
void submit() {
out.println(solve(nextToken()));
}
void stress() {
}
void test() {
StringBuilder sb = new StringBuilder("1");
for (int i = 0; i < 700; i++) {
sb.append('0');
}
solve(sb.toString());
}
G() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
submit();
// stress();
// test();
out.close();
}
static final Random rng = new Random();
static int rand(int l, int r) {
return l + rng.nextInt(r - l + 1);
}
public static void main(String[] args) throws IOException {
new G();
}
BufferedReader br;
PrintWriter out;
StringTokenizer st;
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
|
quadratic
|
908_G. New Year and Original Order
|
CODEFORCES
|
/*Author: Satyajeet Singh, Delhi Technological University*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
public class Main {
/*********************************************Constants******************************************/
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static long mod=(long)1e9+7;
static long mod1=998244353;
static boolean sieve[];
static ArrayList<Integer> primes;
static ArrayList<Long> factorial;
static HashSet<Integer> graph[];
/****************************************Solutions Begins*****************************************/
public static void main (String[] args) throws Exception {
String st[]=br.readLine().split(" ");
int n=Integer.parseInt(st[0]);
long input[]=new long[n];
st=br.readLine().split(" ");
for(int i=0;i<n;i++){
input[i]=Long.parseLong(st[i]);
}
HashMap<Long,ArrayList<Pair>> map=new HashMap<>();
long pref[]=new long[n+1];
pref[1]=input[0];
for(int i=1;i<n;i++){
pref[i+1]=pref[i]+input[i];
}
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
long sum=pref[j+1]-pref[i];
if(!map.containsKey(sum)){
ArrayList<Pair> list=new ArrayList<>();
list.add(new Pair(i,j));
map.put(sum,list);
}
else{
ArrayList<Pair> list=map.get(sum);
list.add(new Pair(i,j));
}
}
}
ArrayList<Pair> ans=new ArrayList<>();
// debug(map);
for(long keys:map.keySet()){
ArrayList<Pair> list=map.get(keys);
Collections.sort(list,new PairComp());
int nn=list.size();
for(int j=0;j<=0;j++){
ArrayList<Pair> cur=new ArrayList<>();
cur.add(list.get(j));
int lim=list.get(j).v;
int i=j;
while(i<nn){
if(list.get(i).u<=lim){
i++;
}
else{
cur.add(list.get(i));
lim=list.get(i).v;
i++;
}
}
if(ans.size()<cur.size()){
ans=cur;
}
}
}
out.println(ans.size());
for(Pair p:ans){
out.println(++p.u+" "+ ++p.v);
}
/****************************************Solutions Ends**************************************************/
out.flush();
out.close();
}
/****************************************Template Begins************************************************/
/***************************************Precision Printing**********************************************/
static void printPrecision(double d){
DecimalFormat ft = new DecimalFormat("0.00000000000000000");
out.println(ft.format(d));
}
/******************************************Graph*********************************************************/
static void Makegraph(int n){
graph=new HashSet[n];
for(int i=0;i<n;i++){
graph[i]=new HashSet<>();
}
}
static void addEdge(int a,int b){
graph[a].add(b);
}
/*********************************************PAIR********************************************************/
static class PairComp implements Comparator<Pair>{
public int compare(Pair p1,Pair p2){
if(p1.v>p2.v){
return 1;
}
else if(p1.v<p2.v){
return -1;
}
else{
return p1.u-p2.u;
}
}
}
static class Pair implements Comparable<Pair> {
int u;
int v;
int index=-1;
public Pair(int u, int v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
static class PairCompL implements Comparator<Pairl>{
public int compare(Pairl p1,Pairl p2){
if(p1.v>p2.v){
return -1;
}
else if(p1.v<p2.v){
return 1;
}
else{
return 0;
}
}
}
static class Pairl implements Comparable<Pair> {
long u;
long v;
int index=-1;
public Pairl(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/*****************************************DEBUG***********************************************************/
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
/************************************MODULAR EXPONENTIATION***********************************************/
static long modulo(long a,long b,long c) {
long x=1;
long y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
/********************************************GCD**********************************************************/
static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
/******************************************SIEVE**********************************************************/
static void sieveMake(int n){
sieve=new boolean[n];
Arrays.fill(sieve,true);
sieve[0]=false;
sieve[1]=false;
for(int i=2;i*i<n;i++){
if(sieve[i]){
for(int j=i*i;j<n;j+=i){
sieve[j]=false;
}
}
}
primes=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(sieve[i]){
primes.add(i);
}
}
}
/********************************************End***********************************************************/
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Solution{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] a = new int[n];
for(int i=0;i<n;i++) a[i] = Integer.parseInt(st.nextToken());
int ind = 0;
for(int i=0;i<n;i++){
if(a[i]==n){
ind = i;
break;
}
}
boolean ok = true;
for(int i=ind+1;i<n;i++) if(a[i]>a[i-1]) ok = false;
for(int i=ind-1;i>=0;i--) if(a[i]>a[i+1]) ok = false;
if(ok) System.out.println("YES");
else System.out.println("NO");
}
}
|
linear
|
1197_B. Pillars
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Cf270a {
public static void main(String[] args) throws IOException {
InputStreamReader fin = new InputStreamReader(System.in);
Scanner scr = new Scanner(fin);
int n = scr.nextInt();
int x = 0;
int y = 0;
if (n%2 == 0) {
x = 4;
y = n - x;
} else {
x = 9;
y = n - x;
}
PrintWriter fout = new PrintWriter(System.out);
fout.print(x+" "+y);
fout.flush();
fout.close();
}
}
|
constant
|
472_A. Design Tutorial: Learn from Math
|
CODEFORCES
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
/**
* Created by hama_du on 2014/09/21.
*/
public class ProblemB {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
long a = in.nextLong();
long b = in.nextLong();
long[] x = new long[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextLong();
}
Map<Long,Integer> idxmap = new HashMap<>();
for (int i = 0; i < n; i++) {
idxmap.put(x[i], i);
}
if (a == b) {
solve1(x, a, idxmap, out);
return;
}
int[] mark = new int[n];
Arrays.fill(mark, -1);
boolean isok = true;
for (int i = 0 ; i < n ; i++) {
if (mark[i] != -1) {
continue;
}
long w = x[i];
long aw = a - w;
long bw = b - w;
if (idxmap.containsKey(aw) && idxmap.containsKey(bw)) {
continue;
} else if (idxmap.containsKey(bw)) {
long w1 = w;
long w2 = bw;
while (true) {
if (!idxmap.containsKey(w1) || !idxmap.containsKey(w2)) {
break;
}
int i1 = idxmap.get(w1);
int i2 = idxmap.get(w2);
if (mark[i1] == 0 || mark[i2] == 0) {
isok = false;
}
mark[i1] = 1;
mark[i2] = 1;
if (w1 + a - b == w2) {
break;
}
w1 += (a - b);
w2 += (b - a);
}
} else if (idxmap.containsKey(aw)){
long w1 = w;
long w2 = aw;
while (true) {
if (!idxmap.containsKey(w1) || !idxmap.containsKey(w2)) {
break;
}
int i1 = idxmap.get(w1);
int i2 = idxmap.get(w2);
if (mark[i1] == 1 || mark[i2] == 1) {
isok = false;
}
mark[i1] = 0;
mark[i2] = 0;
if (w1 + b - a == w2) {
break;
}
w1 += (b - a);
w2 += (a - b);
}
}
}
for (int i = 0 ; i < n ; i++) {
if (mark[i] == -1) {
isok = false;
break;
}
}
if (isok) {
printAnswer(mark, out);
} else {
out.println("NO");
}
out.flush();
}
private static void printAnswer(int[] mark, PrintWriter out) {
out.println("YES");
StringBuilder ln = new StringBuilder();
for (int m : mark) {
ln.append(' ').append(m);
}
out.println(ln.substring(1));
}
private static void solve1(long[] x, long a, Map<Long, Integer> idxmap, PrintWriter out) {
int[] mark = new int[x.length];
for (int i = 0 ; i < x.length ; i++) {
if (mark[i] == 1) {
continue;
}
long w = x[i];
long wp = a - w;
if (idxmap.containsKey(wp)) {
mark[i] = mark[idxmap.get(wp)] = 1;
}
}
boolean isok = true;
for (int i = 0 ; i < x.length ; i++) {
if (mark[i] == 0) {
isok = false;
break;
}
}
if (isok) {
printAnswer(mark, out);
} else {
out.println("NO");
}
out.flush();
}
public static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int next() {
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 = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = next();
while (isSpaceChar(c))
c = next();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
linear
|
468_B. Two Sets
|
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 A {
public static void main(String[] args) throws Exception {
FastScanner sc = new FastScanner(System.in);
FastPrinter out = new FastPrinter(System.out);
new A().run(sc, out);
out.close();
}
public void run(FastScanner sc, FastPrinter out) throws Exception {
int N = sc.nextInt();
int[] arr = sc.nextIntArray(N);
Arrays.sort(arr);
boolean[] done = new boolean[N];
int ans = 0;
for (int i = 0; i < N; i++) {
if (done[i]) continue;
ans++;
for (int j = i; j < N; j++) {
if (arr[j] % arr[i] == 0) {
done[j] = true;
}
}
}
out.println(ans);
}
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);
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class A {
BufferedReader in;
StringTokenizer st;
PrintWriter out;
void solve() throws IOException {
int n = nextInt();
int k = nextInt();
boolean[] sieve = new boolean[n + 1];
List<Integer> primes = new ArrayList<Integer>();
for (int i = 2; i <= n; ++i) {
if (!sieve[i]) {
primes.add(i);
for (int j = 2 * i; j <= n; j += i) {
sieve[j] = true;
}
}
}
int count = 0;
for (int i = 0; i + 1 < primes.size(); ++i) {
int v = primes.get(i) + primes.get(i + 1) + 1;
if (v <= n && !sieve[v]) {
++count;
}
}
// System.err.println(count);
out.println(count >= k ? "YES" : "NO");
}
public void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
eat("");
solve();
out.close();
in.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 {
new A().run();
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.HashSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Lokesh Khandelwal aka (codeKNIGHT | phantom11)
*/
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(),k=in.nextInt();
int a[]=new int[n];
int i;
for(i=0;i<n;i++)
a[i]=in.nextInt();
HashSet<Integer> hs=new HashSet<Integer>();
boolean status=false;
int index=-1;
for(i=0;i<n;i++)
{
hs.add(a[i]);
if(hs.size()==k)
{
index=i;
status=true;
break;
}
}
if(!status)
{
out.println(-1+" "+ -1);
return;
}
HashSet<Integer> hash=new HashSet<Integer>();
for(i=index;i>=0;i--)
{
hash.add(a[i]);
if(hash.size()==k)
{
break;
}
}
out.println((i+1)+" "+(index+1));
}
}
class InputReader
{
BufferedReader in;
StringTokenizer tokenizer=null;
public InputReader(InputStream inputStream)
{
in=new BufferedReader(new InputStreamReader(inputStream));
}
public String next()
{
try{
while (tokenizer==null||!tokenizer.hasMoreTokens())
{
tokenizer=new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
catch (IOException e)
{
return null;
}
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
|
linear
|
224_B. Array
|
CODEFORCES
|
//package codeforces.br17;
import java.io.*;
import java.text.DecimalFormat;
public class ProblemA {
public void solve() {
boolean oj = true;
try {
Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("A.in");
Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("A.out");
BufferedReader br = new BufferedReader(reader);
PrintWriter out = new PrintWriter(writer);
MyTokenizer tok = new MyTokenizer(br.readLine());
int n = (int)tok.getNum();
int k = (int)tok.getNum();
boolean[] isPrime = new boolean[n + 1];
for(int i=1;i<=n;i++)
isPrime[i] = true;
isPrime[1] = false;
isPrime[2] = true;
for(int i=2;i*i<=n;i++)
for(int j=2*i;j<=n;j+=i)
isPrime[j] = false;
int[] primes = new int[n];
int cur = 0;
for(int i=2;i<=n;i++)
if (isPrime[i]) {
primes[cur] = i;
cur++;
}
int count = 0;
for(int i=0;i<cur-1;i++) {
if (primes[i] + primes[i+1] + 1 <= n && isPrime[primes[i] + primes[i+1] + 1])
count++;
}
if (count >= k)
out.printf("YES");
else
out.printf("NO");
br.close();
out.close();
reader.close();
writer.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
}
}
public static void main(String[] args) {
ProblemA f = new ProblemA();
f.solve();
}
private class MyTokenizer {
private String s;
private int cur;
public MyTokenizer(String s) {
this.s = s;
cur = 0;
}
public void skip() {
while (cur < s.length() && (s.charAt(cur) == ' ' || s.charAt(cur) == '\n')) {
cur++;
}
}
public double getNum() {
skip();
String snum = "";
while (cur < s.length() && (s.charAt(cur) >= '0' && s.charAt(cur) <= '9' || s.charAt(cur) == '.')) {
snum += s.charAt(cur);
cur++;
}
return Double.valueOf(snum);
}
public String getString() {
skip();
String s2 = "";
while (cur < s.length() && (s.charAt(cur) >= 'a' && s.charAt(cur) <= 'z')) {
s2 += s.charAt(cur);
cur++;
}
return s2;
}
public char getCurrentChar() throws Exception {
if (cur < s.length())
return s.charAt(cur);
else
throw new Exception("Current character out of string length");
}
public void moveNextChar() {
if (cur < s.length())
cur++;
}
public boolean isFinished() {
return cur >= s.length();
}
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.util.*;
public class Quiz{
static int MOD = (int)1e9 + 9;
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
long n = reader.nextInt();
long m = reader.nextInt();
long k = reader.nextInt();
long r = (n + k - 1)/k;
long longDrops = n%k;
if(longDrops == 0){
long d = m - (r * (k-1));
if(d <= 0){
System.out.println(m);
return;
}
long sum = (fastExpo(2,d+1)-2) * k + (m - d*k);
System.out.println((sum+MOD)%MOD);
}else{
long d = (m-longDrops*r) - (r-1)*(k-longDrops-1);
if(d <= 0){
System.out.println(m);
return;
}
long sum = (fastExpo(2,d+1)-2) * k + (m - d*k);
System.out.println((sum+MOD)%MOD);
}
}
public static long fastExpo(long b, long p){
if(p == 0)
return 1;
if(p % 2 == 1)
return (b * fastExpo(b, p-1))%MOD;
long x = fastExpo(b, p/2);
return (x * x)%MOD;
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeSet;
public final class CF_599_D1_C
{
static boolean verb=true;
static void log(Object X){if (verb) System.err.println(X);}
static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(Object X){if (verb) System.err.print(X);}
static void info(Object o){ System.out.println(o);}
static void output(Object o){outputWln(""+o+"\n"); }
static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}}
static long mod=1000000007;
// Global vars
static BufferedWriter out;
static InputReader reader;
static class Composite implements Comparable<Composite>{
int idx;
int v;
public int compareTo(Composite X) {
if (v!=X.v)
return v-X.v;
return idx-X.idx;
}
public Composite(int idx, int v) {
this.idx = idx;
this.v = v;
}
}
static void test() {
log("testing");
log("done");
}
static void explore(ArrayList<Integer>[] components,ArrayList<Integer> bob,int[][] move,ArrayList<int[]>[] howto,int[][] list) {
for (int x:bob) {
if (components[x].size()==1) {
int tm[]=howto[x].get(0);
int L=howto[x].size();
howto[x].add(tm);
for (int i=0;i<L;i++) {
int[] cur=howto[x].get(i);
int[] nx=howto[x].get(i+1);
int a=cur[0];
int a2=nx[0];
int b2=nx[1];
move[a2][0]=list[a2][b2];
move[a2][1]=a;
}
} else {
explore(components,components[x],move,howto,list);
}
}
}
static void process() throws Exception {
//arrayTest();
out = new BufferedWriter(new OutputStreamWriter(System.out));
reader = new InputReader(System.in);
int k=reader.readInt();
int[][] list=new int[k][];
long[] sum=new long[k];
int[] L=new int[k];
HashMap<Integer,int[]> target=new HashMap<Integer,int[]>();
long tot=0;
for (int i=0;i<k;i++) {
L[i]=reader.readInt();
list[i]=new int[L[i]];
for (int j=0;j<L[i];j++) {
list[i][j]=reader.readInt();
sum[i]+=list[i][j];
target.put(list[i][j],new int[] {i,j});
}
tot+=sum[i];
}
int MX=1<<k;
int AX=1000000001;
ArrayList<int[]>[] howto=new ArrayList[MX];
log("ok with the data");
if (tot%k!=0) {
output("No");
} else {
tot/=k;
for (int i=0;i<k;i++) {
if (sum[i]==tot) {
//log("nothing to do for i:"+i);
// nothing to do
int mask=1<<i;
ArrayList<int[]> cand=new ArrayList<int[]>();
cand.add(new int[] {i,0});
howto[mask]=cand;
} else
for (int j=0;j<L[i];j++) {
int u=i;
int v=j;
boolean ok=true;
int src_u=u;
int src_v=v;
int mask=0;
boolean goon=true;
ArrayList<int[]> cand=new ArrayList<int[]>();
//log("start loop");
while (goon) {
cand.add(new int[] {u,v});
//log("u:"+u+" v:"+v);
ok=false;
goon=false;
long need=tot-((long)sum[u]-(long)list[u][v]);
if (Math.abs(need)<=AX) {
//log("need:"+need);
int nd=(int)need;
int[] tm=target.get(nd);
//log("tm:"+tm);
if (tm!=null) {
//log("can find successor");
int nxu=tm[0];
int nxv=tm[1];
if ((mask&(1<<nxu))==0) {
mask|=1<<nxu;
if (nxu==src_u) {
// looping back to source
if (nxv==src_v)
ok=true;
} else {
u=nxu;
v=nxv;
ok=true;
goon=true;
}
}
}
}
}
if (ok) {
if (howto[mask]==null) {
howto[mask]=cand;
}
}
}
}
log("step 1 done");
// now mask
ArrayList[] components=new ArrayList[MX];
for (int m=0;m<MX;m++) {
if (howto[m]!=null) {
//String s=Integer.toBinaryString(m);
//while (s.length()<k)
// s="0"+s;
//log("found mask:"+s);
components[m]=new ArrayList<Integer>();
components[m].add(m);
}
}
int[] msk=new int[MX];
int w=0;
for (int a=0;a<MX;a++) {
if (howto[a]!=null) {
ArrayList<Integer> add=new ArrayList<Integer>();
int ww=w;
for (int i=0;i<ww;i++) {
int b=msk[i];
if ((b&a)==0) {
int c=b|a;
//log("creating c:"+c+" ");
if (components[c]==null ) {
components[c]=new ArrayList<Integer>();
components[c].add(a);
components[c].add(b);
msk[w++]=c;
}
}
}
msk[w++]=a;
}
}
//log("msk:"+msk);
//log(components[MX-1]);
if (components[MX-1]!=null) {
output("Yes");
int[][] move=new int[k][2];
explore(components,components[MX-1],move,howto,list);
for (int i=0;i<k;i++) {
output(move[i][0]+" "+(move[i][1]+1));
}
} else {
output("No");
}
}
try {
out.close();
} catch (Exception e) {
}
}
public static void main(String[] args) throws Exception {
process();
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final int readInt() throws IOException {
int c = read();
boolean neg = false;
while (isSpaceChar(c)) {
c = read();
}
char d = (char) c;
// log("d:"+d);
if (d == '-') {
neg = true;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
// log("res:"+res);
if (neg)
return -res;
return res;
}
public final long readLong() throws IOException {
int c = read();
boolean neg = false;
while (isSpaceChar(c)) {
c = read();
}
char d = (char) c;
// log("d:"+d);
if (d == '-') {
neg = true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
// log("res:"+res);
if (neg)
return -res;
return res;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
np
|
1242_C. Sum Balance
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main {
static FastScanner sc = new FastScanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder();
static long mod = (long) 1e9 + 7;
public static void main(String[] args) throws Exception {
solve();
pw.flush();
}
static ArrayList<ArrayList<ArrayList<int[]>>> kruscal = new ArrayList<>();
static long ans = Integer.MAX_VALUE;
static int[][][] map;
public static void solve() {
int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt();
for(int i = 0; i < n; i++){
kruscal.add(new ArrayList<>());
for(int j = 0; j < m; j++){
kruscal.get(i).add(new ArrayList<>());
}
}
map = new int[n][m][k+1];
for(int i = 0; i < n; i++){
for(int j = 0; j < m-1; j++){
//int now = (int)(Math.random()*1000000)*2;
int now = sc.nextInt();
kruscal.get(i).get(j).add(new int[]{now,i,j+1});
kruscal.get(i).get(j+1).add(new int[]{now,i,j});
}
}
for(int i = 0; i < n-1; i++){
for(int j = 0; j < m; j++){
//int now = (int)(Math.random()*1000000)*2;
int now = sc.nextInt();
kruscal.get(i).get(j).add(new int[]{now,i+1,j});
kruscal.get(i+1).get(j).add(new int[]{now,i,j});
}
}
if(k % 2 != 0){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
sb.append(-1).append(" ");
}
pw.println(sb.toString().trim());
sb.setLength(0);
}
return;
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
Arrays.fill(map[i][j],Integer.MAX_VALUE/2);
map[i][j][k/2] = 0;
}
}
for(int kk = k/2; kk > 0; kk--){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
for(int[] next : kruscal.get(i).get(j)){
int d = next[0], i2 = next[1], j2 = next[2];
map[i2][j2][kk-1] = Math.min(map[i2][j2][kk-1],map[i][j][kk]+d);
}
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
sb.append(map[i][j][0]*2).append(" ");
}
pw.println(sb.toString().trim());
sb.setLength(0);
}
}
static void dfs(Stack<Integer> st, int y, int x, int cnt, long total){
if(st.size() == cnt){
ans = Math.min(total,ans);
}
for(int[] next : kruscal.get(y).get(x)){
int d = next[0], i = next[1], j = next[2];
if(Math.abs(i-y)+Math.abs(j-x)-st.size() < 0){
continue;
}
Stack<Integer> stk = (Stack<Integer>)st.clone();
stk.push(d);
dfs(stk,i,j,cnt,total + d);
}
int rem = cnt - st.size();
long tmp = 0;
int c = 0;
while(st.size() > 0){
tmp += st.pop();
c++;
if(rem % c == 0){
ans = Math.min(ans,total + tmp * (rem/c));
}
}
}
static class ArrayComparator implements Comparator<int[]> {
@Override
public int compare(int[] a1, int[] a2) {
for (int i = 0; i < a1.length; i++) {
if (a1[i] < a2[i]) {
return -1;
} else if (a1[i] > a2[i]) {
return 1;
}
}
if (a1.length < a2.length) {
return -1;
} else if (a1.length > a2.length) {
return 1;
} else {
return 0;
}
}
}
private static String ArraysToString(int[] arr){
String s = Arrays.toString(arr);
s = s.replaceAll(",","");
s = s.substring(1,s.length()-1);
return s;
}
static class GeekInteger {
public static void save_sort(int[] array) {
shuffle(array);
Arrays.sort(array);
}
public static int[] shuffle(int[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
int randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
public static void save_sort(long[] array) {
shuffle(array);
Arrays.sort(array);
}
public static long[] shuffle(long[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
long randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
}
}
class DSU {
private int n;
private int[] parentOrSize;
private java.util.ArrayList<java.util.ArrayList<Integer>> map;
public DSU(int n) {
this.n = n;
this.map = new java.util.ArrayList<java.util.ArrayList<Integer>>();
for (int i = 0; i < n; i++) {
this.map.add(new java.util.ArrayList<Integer>());
this.map.get(i).add(i);
}
this.parentOrSize = new int[n];
java.util.Arrays.fill(parentOrSize, -1);
}
int merge(int a, int b) {
if (!(0 <= a && a < n))
throw new IndexOutOfBoundsException("a=" + a);
if (!(0 <= b && b < n))
throw new IndexOutOfBoundsException("b=" + b);
int x = leader(a);
int y = leader(b);
if (x == y)
return x;
if (-parentOrSize[x] < -parentOrSize[y]) {
int tmp = x;
x = y;
y = tmp;
}
parentOrSize[x] += parentOrSize[y];
parentOrSize[y] = x;
this.map.get(x).addAll(this.map.get(y));
return x;
}
boolean same(int a, int b) {
if (!(0 <= a && a < n))
throw new IndexOutOfBoundsException("a=" + a);
if (!(0 <= b && b < n))
throw new IndexOutOfBoundsException("b=" + b);
return leader(a) == leader(b);
}
int leader(int a) {
if (parentOrSize[a] < 0) {
return a;
} else {
parentOrSize[a] = leader(parentOrSize[a]);
return parentOrSize[a];
}
}
int size(int a) {
if (!(0 <= a && a < n))
throw new IndexOutOfBoundsException("" + a);
return -parentOrSize[leader(a)];
}
java.util.ArrayList<java.util.ArrayList<Integer>> groups() {
int[] leaderBuf = new int[n];
int[] groupSize = new int[n];
for (int i = 0; i < n; i++) {
leaderBuf[i] = leader(i);
groupSize[leaderBuf[i]]++;
}
java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n);
for (int i = 0; i < n; i++) {
result.add(new java.util.ArrayList<>(groupSize[i]));
}
for (int i = 0; i < n; i++) {
result.get(leaderBuf[i]).add(i);
}
result.removeIf(java.util.ArrayList::isEmpty);
return result;
}
java.util.ArrayList<Integer> getArray(int n) {
return this.map.get(n);
}
}
class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public FastScanner(FileReader in) {
reader = new BufferedReader(in);
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String[] nextArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = next();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
744444444747477777774
44444447474747777777
*/
/**
*
* @author Andy Phan
*/
public class b {
public static void main(String[] args) {
FS in = new FS(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
Integer[] arr = new Integer[n];
int numZ = 0;
for(int i = 0; i < n; i++) {
arr[i] = in.nextInt();
if(arr[i] == 0) numZ++;
}
Arrays.sort(arr);
if(numZ > 1) {
System.out.println("cslnb");
return;
}
int numDup = 0;
int[] arr2 = new int[n];
for(int i = 0; i < n; i++) {
arr2[i] = arr[i];
if(i != 0) {
if(arr2[i] == arr2[i-1]) {
arr2[i-1]--;
numDup++;
}
}
}
if(numDup > 1) {
System.out.println("cslnb");
return;
}
for(int i = 0; i < n; i++) {
if(i != 0) {
if(arr2[i] == arr2[i-1]) {
System.out.println("cslnb");
return;
}
}
}
long num = 0;
if(numDup == 1) num++;
for(int i = 0; i < n; i++) {
num += arr2[i]-i;
}
if(num%2 == 0) {
System.out.println("cslnb");
} else {
System.out.println("sjfnb");
}
out.close();
}
static class FS {
BufferedReader in;
StringTokenizer token;
public FS(InputStream str) {
in = new BufferedReader(new InputStreamReader(str));
}
public String next() {
if (token == null || !token.hasMoreElements()) {
try {
token = new StringTokenizer(in.readLine());
} catch (IOException ex) {
}
return next();
}
return token.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
linear
|
1191_D. Tokitsukaze, CSL and Stone Game
|
CODEFORCES
|
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.atomic.AtomicIntegerArray;
public class Solution {
public static void main(String[] args) throws Exception {
MyReader reader = new MyReader(System.in);
// MyReader reader = new MyReader(new FileInputStream("input.txt"));
MyWriter writer = new MyWriter(System.out);
new Solution().run(reader, writer);
writer.close();
}
private void run(MyReader reader, MyWriter writer) throws Exception {
char[] c = reader.nextCharArray();
int n = c.length;
int[] x = new int[n];
for (int i = 0; i < n; i++) {
x[i] = c[i] - '0';
}
long mod = 1_000_000_007;
long[] p = new long[n + 1];
long[] s = new long[n + 1];
p[0] = 1;
for (int i = 1; i <= n; i++) {
p[i] = p[i - 1] * 10 % mod;
}
s[n] = 1;
for (int i = n - 1; i >= 0; i--) {
s[i] = (p[n - i - 1] * x[i] + s[i + 1]) % mod;
}
long[][][] d = new long[n + 1][n + 1][2];
long ans = 0;
for (int i = 1; i < 10; i++) {
for (long[][] q : d) {
for (long[] w : q) {
Arrays.fill(w, 0);
}
}
for (int j = 0; j <= n; j++) {
d[j][0][0] = s[j];
d[j][0][1] = p[n - j];
}
for (int j = n - 1; j >= 0; j--) {
for (int k = 1; k <= n; k++) {
for (int l = 1; l >= 0; l--) {
int lim = l == 1 ? 10 : x[j] + 1;
for (int m = 0; m < lim; m++) {
d[j][k][l] += d[j + 1][k - (m >= i ? 1 : 0)][l == 1 || m < x[j] ? 1 : 0];
d[j][k][l] %= mod;
}
}
if (j == 0) {
ans = (ans + p[k - 1] * d[0][k][0]) % mod;
}
}
}
}
System.out.println(ans);
}
static class MyReader {
final BufferedInputStream in;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = bufSize;
int k = bufSize;
boolean end = false;
final StringBuilder str = new StringBuilder();
MyReader(InputStream in) {
this.in = new BufferedInputStream(in, bufSize);
}
int nextInt() throws IOException {
return (int) nextLong();
}
int[] nextIntArray(int n) throws IOException {
int[] m = new int[n];
for (int i = 0; i < n; i++) {
m[i] = nextInt();
}
return m;
}
int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] a = new int[n][0];
for (int j = 0; j < n; j++) {
a[j] = nextIntArray(m);
}
return a;
}
long nextLong() throws IOException {
int c;
long x = 0;
boolean sign = true;
while ((c = nextChar()) <= 32) ;
if (c == '-') {
sign = false;
c = nextChar();
}
if (c == '+') {
c = nextChar();
}
while (c >= '0') {
x = x * 10 + (c - '0');
c = nextChar();
}
return sign ? x : -x;
}
long[] nextLongArray(int n) throws IOException {
long[] m = new long[n];
for (int i = 0; i < n; i++) {
m[i] = nextLong();
}
return m;
}
int nextChar() throws IOException {
if (i == k) {
k = in.read(buf, 0, bufSize);
i = 0;
}
return i >= k ? -1 : buf[i++];
}
String nextString() throws IOException {
if (end) {
return null;
}
str.setLength(0);
int c;
while ((c = nextChar()) <= 32 && c != -1) ;
if (c == -1) {
end = true;
return null;
}
while (c > 32) {
str.append((char) c);
c = nextChar();
}
return str.toString();
}
String nextLine() throws IOException {
if (end) {
return null;
}
str.setLength(0);
int c = nextChar();
while (c != '\n' && c != '\r' && c != -1) {
str.append((char) c);
c = nextChar();
}
if (c == -1) {
end = true;
if (str.length() == 0) {
return null;
}
}
if (c == '\r') {
nextChar();
}
return str.toString();
}
char[] nextCharArray() throws IOException {
return nextString().toCharArray();
}
char[][] nextCharMatrix(int n) throws IOException {
char[][] a = new char[n][0];
for (int i = 0; i < n; i++) {
a[i] = nextCharArray();
}
return a;
}
}
static class MyWriter {
final BufferedOutputStream out;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = 0;
final byte c[] = new byte[30];
static final String newLine = System.getProperty("line.separator");
MyWriter(OutputStream out) {
this.out = new BufferedOutputStream(out, bufSize);
}
void print(long x) throws IOException {
int j = 0;
if (i + 30 >= bufSize) {
flush();
}
if (x < 0) {
buf[i++] = (byte) ('-');
x = -x;
}
while (j == 0 || x != 0) {
c[j++] = (byte) (x % 10 + '0');
x /= 10;
}
while (j-- > 0)
buf[i++] = c[j];
}
void print(int[] m) throws IOException {
for (int a : m) {
print(a);
print(' ');
}
}
void print(long[] m) throws IOException {
for (long a : m) {
print(a);
print(' ');
}
}
void print(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
print(s.charAt(i));
}
}
void print(char x) throws IOException {
if (i == bufSize) {
flush();
}
buf[i++] = (byte) x;
}
void print(char[] m) throws IOException {
for (char c : m) {
print(c);
}
}
void println(String s) throws IOException {
print(s);
println();
}
void println() throws IOException {
print(newLine);
}
void flush() throws IOException {
out.write(buf, 0, i);
out.flush();
i = 0;
}
void close() throws IOException {
flush();
out.close();
}
}
}
|
quadratic
|
908_G. New Year and Original Order
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String str=sc.next();
sc.close();
int maxm=0;
int ind1,ind2;
for(int i=0;i<str.length();i++){
for(int j=i+1;j<str.length();j++){
int len=0;
ind1=i;ind2=j;
while(ind2<str.length() && str.charAt(ind1)==str.charAt(ind2)){
ind1++;
ind2++;
len++;
}
maxm=Math.max(maxm,len);
}
}
System.out.println(maxm);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.