src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringclasses 256
values | from
stringclasses 1
value |
|---|---|---|---|
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Main(),"Main",1<<26).start();
}
int findLSB(long n)
{
long value=-n&n;
return map.get(value);
}
void findMaxClique(long mask,int size)
{
if(mask==0)
{
if(size>maxClique)
maxClique=size;
return;
}
while(mask>0)
{
if(Long.bitCount(mask)+size<=maxClique)
return;
int lsb=findLSB(mask);
mask=mask^((long)1<<lsb);
findMaxClique(mask&edges[lsb],size+1);
}
}
long edges[];
HashMap<Long,Integer> map=new HashMap<>();
int maxClique;
public void run()
{
InputReader sc= new InputReader(System.in);
PrintWriter w= new PrintWriter(System.out);
long value=1;
for(int i=0;i<45;i++)
{
map.put(value,i);
value*=2;
}
int n=sc.nextInt();
int k=sc.nextInt();
edges=new long[n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
long connect=sc.nextLong();
if(j>i&&connect==1)
edges[i]|=(connect<<j);
}
}
findMaxClique(((long)1<<n)-1,0);
//w.print(maxClique);
double size=(double)maxClique;
double perCastle=(double)k/size;
double ans=perCastle*perCastle*(size*(size-1))/2;
w.print(ans);
w.close();
}
}
|
np
|
839_E. Mother of Dragons
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Alex
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
int n;
ArrayList<Integer>[] adj;
long[] mem;
int start;
long cycles(int cur, int visited) {
if (cur == start && visited > 0) {
return Integer.bitCount(visited) >= 3 ? 1 : 0;
}
int index = visited * n + cur;
if (mem[index] != -1) return mem[index];
long res = 0;
int newvisited = visited | (1 << cur);
for (int nxt : adj[cur]) {
if (nxt >= start && (nxt == start || ((visited >> nxt) & 1) == 0)) {
res += cycles(nxt, newvisited);
}
}
return mem[index] = res;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
int m = in.readInt();
adj = new ArrayList[n];
mem = new long[n * (1 << n)];
for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int a = in.readInt() - 1, b = in.readInt() - 1;
adj[a].add(b);
adj[b].add(a);
}
long res = 0;
for (int start = 0; start < n; start++) {
Arrays.fill(mem, -1);
this.start = start;
res += cycles(start, 0) / 2;
}
out.printLine(res);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class B {
static int n, t[], g[], MOD = (int) 1e9 + 7;
static int[][][] memo1, memo2[], memo3[];
static int dp1(int idx, int remCnt, int remSum) {
if (idx == n)
return remSum == 0 && remCnt == 0 ? 1 : 0;
if (remCnt < 0 || remSum < 0)
return 0;
if (memo1[idx][remCnt][remSum] != -1)
return memo1[idx][remCnt][remSum];
int ans = dp1(idx + 1, remCnt, remSum);
if (g[idx] == 0) {
ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]);
if (ans >= MOD)
ans -= MOD;
}
return memo1[idx][remCnt][remSum] = ans;
}
static int dp2(int idx, int remCnt1, int remCnt2, int remSum) {
if (idx == n)
return remSum == 0 && remCnt1 == 0 && remCnt2 == 0 ? 1 : 0;
if (remSum < 0 || remCnt1 < 0 || remCnt2 < 0)
return 0;
if (memo2[idx][remCnt1][remCnt2][remSum] != -1)
return memo2[idx][remCnt1][remCnt2][remSum];
int ans = dp2(idx + 1, remCnt1, remCnt2, remSum);
if (g[idx] == 1)
ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]);
else if (g[idx] == 2)
ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]);
if (ans >= MOD)
ans -= MOD;
return memo2[idx][remCnt1][remCnt2][remSum] = ans;
}
private static int dp3(int cnt0, int cnt1, int cnt2, int last) {
if (cnt0 + cnt1 + cnt2 == 0)
return 1;
if (memo3[last][cnt0][cnt1][cnt2] != -1)
return memo3[last][cnt0][cnt1][cnt2];
long ans = 0;
if (cnt0 > 0 && last != 0)
ans += dp3(cnt0 - 1, cnt1, cnt2, 0);
if (cnt1 > 0 && last != 1)
ans += dp3(cnt0, cnt1 - 1, cnt2, 1);
if (cnt2 > 0 && last != 2)
ans += dp3(cnt0, cnt1, cnt2 - 1, 2);
return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD);
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
int[] fac = new int[n + 1];
t = new int[n];
g = new int[n];
int[] cnt = new int[3];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = (int) (i * 1L * fac[i - 1] % MOD);
int T = sc.nextInt();
for (int i = 0; i < n; i++) {
t[i] = sc.nextInt();
g[i] = sc.nextInt() - 1;
cnt[g[i]]++;
}
memo1 = new int[n][cnt[0] + 1][T + 1];
memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1];
memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= cnt[0]; j++)
Arrays.fill(memo1[i][j], -1);
for (int j = 0; j <= cnt[1]; j++)
for (int k = 0; k <= cnt[2]; k++)
Arrays.fill(memo2[i][j][k], -1);
}
for (int i = 0; i < 4; i++)
for (int j = 0; j <= cnt[0]; j++)
for (int k = 0; k <= cnt[1]; k++)
Arrays.fill(memo3[i][j][k], -1);
int ans = 0;
for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++)
for (int sum0 = 0; sum0 <= T; sum0++)
for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++)
for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) {
long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD;
ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD;
ways *= fac[cnt0];
ways %= MOD;
ways *= fac[cnt1];
ways %= MOD;
ways *= fac[cnt2];
ways %= MOD;
ans += ways;
if (ans >= MOD)
ans -= MOD;
}
out.println(ans);
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
}
|
cubic
|
1185_G2. Playlist for Polycarp (hard version)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import java.math.*;
public class A {
public static void main(String[] args) throws IOException {
/**/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
/*/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/a.in"))));
/**/
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
Arrays.sort(a);
int ans = 0;
boolean[] v = new boolean[n];
for (int i = 0; i < n; i++) {
if (v[i])
continue;
v[i] = true;
ans++;
for (int j = i; j < n; j++) {
if (a[j]%a[i]==0)
v[j] = true;
}
}
System.out.println(ans);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {
}
new Thread(null, new Runnable() {
public void run() {
try {
new Main().run();
} catch (Throwable e) {
e.printStackTrace();
exit(999);
}
}
}, "1", 1 << 23).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
int n, m;
int dp[][][];
int MV = Integer.MAX_VALUE >> 1;
int ans = MV;
private void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
n = nextInt();
m = nextInt();
if(n < m){ int d = n; n = m; m = d; }
int M = 1 << m;
dp = new int[n][M][M];
for(int a[][] : dp)
for(int b[] : a)
fill(b, MV);
// for(int i = 0 ; i < M; i++){
// int next = (( i | (i << 1) | (i >> 1) ) & (M - 1));
// if( next!= (M -1))
// continue;
// if(n > 1)
// dp[0][next][0] = Integer.bitCount(i);
// else
// ans = min(ans, Integer.bitCount(i));
// }
dp[0][0][0] = 0;
for(int i = 0; i < n; i++)
for(int m1 = 0; m1 < M; m1++)
for(int m2 = 0; m2 < M; m2++){
if(dp[i][m1][m2] == MV)
continue;
for(int nm1 = 0; nm1 < M; nm1++)
for(int nm2 = 0; nm2 < M; nm2++){
int res1 = m1 | (nm1) | (nm1 << 1) | (nm1 >> 1) | (nm2);
res1 &= (M - 1);
if(res1 != (M - 1))
continue;
int res2 = m2 | (nm1) | (nm2 << 1) | (nm2 >> 1) | (nm2);
res2 &= (M - 1);
// if(i == 2 && m1 == 3 && m2 == 2 && nm1 == 0 && nm2 == 0){
// System.err.println("kek");
// System.err.println(dp[i][m1][m2]);
// System.err.println(res1 + " | " + res2);
// System.err.println(M);
// }
int next1 = res2 & (M - 1);
int next2 = nm2 & ( M - 1);
int over = Integer.bitCount(nm1) + Integer.bitCount(nm2);
if(i < n - 1)
dp[i+1][next1][next2] = min(dp[i + 1][next1][next2], dp[i][m1][m2] + over);
else
if((res1 & (M - 1)) == (M - 1)){
ans = min(dp[i][m1][m2] + over, ans);
}
}
}
// System.err.println(ans);
out.println(n * m - ans);
in.close();
out.close();
}
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
|
np
|
111_C. Petya and Spiders
|
CODEFORCES
|
import java.io.IOException;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author George Marcus
*/
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 {
ArrayList<Integer>[] G;
int[] st, dr;
boolean[] v;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] A = new int[N];
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
for (int i = 0; i < N; i++) {
A[i] = in.nextInt();
map.put(A[i], i);
}
G = new ArrayList[N];
for (int i = 0; i < N; i++) {
G[i] = new ArrayList<Integer>();
}
for (int i = 0; i < N; i++) {
int val = a - A[i];
if (map.containsKey(val)) {
int p = map.get(val);
// if (p != i) {
G[i].add(p);
G[p].add(i);
// }
}
val = b - A[i];
if (map.containsKey(val)) {
int p = map.get(val);
// if (p != i) {
G[i].add(p);
G[p].add(i);
// }
}
}
st = new int[N];
dr = new int[N];
Arrays.fill(st, -1);
Arrays.fill(dr, -1);
v = new boolean[N];
boolean ok = true;
int match = 0;
while (ok) {
ok = false;
Arrays.fill(v, false);
for (int i = 0; i < N; i++) {
if (dr[i] == -1) {
if (pairup(i)) {
ok = true;
match++;
}
}
}
}
if (match == N) {
out.println("YES");
for (int i = 0; i < N; i++) {
if (i > 0) {
out.print(" ");
}
int other = dr[i];
if (A[i] == b - A[other]) {
out.print(1);
}
else {
out.print(0);
}
}
}
else {
out.println("NO");
}
}
private boolean pairup(int node) {
if (v[node]) {
return false;
}
v[node] = true;
for (int x : G[node]) {
if (st[x] == -1) {
st[x] = node;
dr[node] = x;
return true;
}
}
for (int x : G[node]) {
if (pairup(st[x])) {
st[x] = node;
dr[node] = x;
return true;
}
}
return false;
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
|
linear
|
468_B. Two Sets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class B {
int mod=1000_000_007;
public static void main(String[] args) throws Exception {
PrintWriter out=new PrintWriter(System.out);
FastScanner fs=new FastScanner();
int t=fs.nextInt();
while(t-->0) {
double n=fs.nextInt();
if(isp(n/2)||isp(n/4)) {
System.out.println("YES");
}
else System.out.println("NO");
}
}
static boolean isp(double n) {
if(n==0) return false;
double a=Math.ceil(Math.sqrt(n));
double b=Math.floor(Math.sqrt(n));
return a==b;
}
static void mysort(long[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
long temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
linear
|
1515_B. Phoenix and Puzzle
|
CODEFORCES
|
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
@SuppressWarnings("unused")
public class Fire35C {
InputStream is;
PrintWriter out;
String INPUT = "";
int mod = (int)(Math.pow(10,9)+7);
int v = 0;
int max = 0;
StringBuilder st = new StringBuilder();
File outFile = new File("output.txt");
void solve() throws IOException
{
int n = ni();
int m = ni();
boolean visited[][] = new boolean[n][m];
boolean inq[][] = new boolean[n][m];
Queue<Integer> x = new LinkedList<>();
Queue<Integer> y = new LinkedList<>();
Queue<Integer> lev = new LinkedList<>();
int a = -1 , b = -1 , max = 0;
int k = ni();
while(k-- > 0) {
int u = ni()-1;
int v = ni()-1;
x.add(u);
y.add(v);
lev.add(1);
inq[u][v] = true;
}
while(x.size() != 0) {
int u = x.poll();
int v = y.poll();
int l = lev.poll();
if(max < l) {
a = u;
b = v;
max = l;
}
visited[u][v] = true;
if(u-1 >= 0 && !visited[u-1][v] && !inq[u-1][v]) {
x.add(u-1);
y.add(v);
lev.add(l+1);
inq[u-1][v] = true;
}
if(u+1 < n && !visited[u+1][v] && !inq[u+1][v]) {
x.add(u+1);
y.add(v);
lev.add(l+1);
inq[u+1][v] = true;
}
if(v-1 >= 0 && !visited[u][v-1] && !inq[u][v-1]) {
x.add(u);
y.add(v-1);
lev.add(l+1);
inq[u][v-1] = true;
}
if(v+1 < m && !visited[u][v+1] && !inq[u][v+1]) {
x.add(u);
y.add(v+1);
lev.add(l+1);
inq[u][v+1] = true;
}
}
a++;
b++;
out.println(a+" "+b);
out.close();
}
void run() throws Exception
{
is = INPUT.isEmpty() ? new FileInputStream(new File("input.txt")) : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(new BufferedWriter(new FileWriter(outFile)));
long s = System.currentTimeMillis();
solve();
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Fire35C().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) && 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[][] na(int n , int m)
{
int[][] a = new int[n][m];
for(int i = 0;i < n;i++)
for(int j = 0 ; j<m ; j++) a[i][j] = 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();
}
}
void display2D(int a[][]) {
for(int i[] : a) {
for(int j : i) {
out.print(j+" ");
}
out.println();
}
}
int[][] creategraph(int n , int m) {
int g[][] = new int[n+1][];
int from[] = new int[m];
int to[] = new int[m];
int ct[] = new int[n+1];
for(int i = 0 ; i<m; i++) {
from[i] = ni();
to[i] = ni();
ct[from[i]]++;
ct[to[i]]++;
}
int parent[] = new int[n+1];
for(int i = 0 ; i<n+1 ; i++) g[i] = new int[ct[i]];
for(int i = 0 ; i<m ; i++) {
g[from[i]][--ct[from[i]]] = to[i];
g[to[i]][--ct[to[i]]] = from[i];
}
return g;
}
static long __gcd(long a, long b)
{
if(b == 0)
{
return a;
}
else
{
return __gcd(b, a % b);
}
}
// To compute x^y under modulo m
static long power(long x, long y, long p)
{
// Initialize result
long res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Function to find modular
// inverse of a under modulo m
// Assumption: m is prime
static long modInverse(long a, int m)
{
if (__gcd(a, m) != 1) {
//System.out.print("Inverse doesn't exist");
return -1;
}
else {
// If a and m are relatively prime, then
// modulo inverse is a^(m-2) mode m
// System.out.println("Modular multiplicative inverse is "
// +power(a, m - 2, m));
return power(a, m - 2, m);
}
}
static long nCrModPFermat(int n, int r,
int p , long fac[])
{
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
long t = (fac[n]* modInverse(fac[r], p))%p;
return ( (t* modInverse(fac[n-r], p))% p);
}
private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.Scanner;
public class CF125D2A {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("0 0 "+ sc.nextInt());
}
}
|
constant
|
199_A. Hexadecimal's theorem
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(),m=sc.nextInt();int g[]=new int[1<<m];
StringBuffer s=new StringBuffer(sc.next());
s=s.insert(0, 'A');
int D=(1<<m)-1;
for(int i=1;i<n;i++)
{
int x=s.charAt(i)-'a',y=s.charAt(i+1)-'a';
if(x!=y)
g[1<<x|1<<y]++;
}
for(int j=0;j<m;j++)
for(int i=0;i<=D;i++)
if((i>>j&1)!=0)
g[i]+=g[i^1<<j];
int f[]=new int[1<<m];
Arrays.fill(f, Integer.MAX_VALUE/2);
f[0]=0;
for(int i=0;i<=D;i++)
for(int j=0;j<m;j++)
if((i>>j&1)==0)
f[i|1<<j]=Math.min(f[i|1<<j], f[i]+g[D]-g[i]-g[D^i]);
System.out.println(f[D]);
}
}
|
np
|
1238_E. Keyboard Purchase
|
CODEFORCES
|
/*
* code together
* code better
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
static int x[]=new int[1005];
static double ans[]=new double[1005];
static int nn,r;
public static void main(String[] args) throws IOException {
StreamTokenizer in=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
Scanner sc=new Scanner(System.in);
int huiwoqingchun=0;
nn=sc.nextInt();
r=sc.nextInt();
for(int i=1;i<=nn;i++) {
x[i]=sc.nextInt();
}
//HashMap<, V>
ans[1]=r;
int lajitimu=0;
for(int i=2;i<=nn;i++) {
ans[i]=r;
for(int j=1;j<i;j++) {
if(Math.abs(x[j]-x[i])>2*r)
continue;
ans[i]=Math.max(ans[i], ans[j]+Math.sqrt(4*r*r-(x[j]-x[i])*(x[j]-x[i])));
}
}
double buzhidaoganma=0;
for(int c=1;c<=nn;c++)
System.out.printf("%.12f ",ans[c]);
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Bag implements Runnable {
private void solve() throws IOException {
int xs = nextInt();
int ys = nextInt();
int n = nextInt();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; ++i) {
x[i] = nextInt();
y[i] = nextInt();
}
int[][] pair = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
pair[i][j] = (x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys) + (x[j] - xs) * (x[j] - xs) + (y[j] - ys) * (y[j] - ys) + (x[j] - x[i]) * (x[j] - x[i]) + (y[j] - y[i]) * (y[j] - y[i]);
int[] single = new int[n];
for (int i = 0; i < n; ++i) {
single[i] = 2 * ((x[i] - xs) * (x[i] - xs) + (y[i] - ys) * (y[i] - ys));
}
int[] best = new int[1 << n];
int[] prev = new int[1 << n];
for (int set = 1; set < (1 << n); ++set) {
int i;
for (i = 0; i < n; ++i)
if ((set & (1 << i)) != 0)
break;
best[set] = best[set ^ (1 << i)] + single[i];
prev[set] = i + 1;
for (int j = i + 1; j < n; ++j)
if ((set & (1 << j)) != 0) {
int cur = best[set ^ (1 << i) ^ (1 << j)] + pair[i][j];
if (cur < best[set]) {
best[set] = cur;
prev[set] = (i + 1) * 100 + (j + 1);
}
}
}
writer.println(best[(1 << n) - 1]);
int now = (1 << n) - 1;
writer.print("0");
while (now > 0) {
int what = prev[now];
int wa = what % 100 - 1;
int wb = what / 100 - 1;
if (wa >= 0) {
writer.print(" ");
writer.print(wa + 1);
now ^= 1 << wa;
}
if (wb >= 0) {
writer.print(" ");
writer.print(wb + 1);
now ^= 1 << wb;
}
writer.print(" ");
writer.print("0");
}
writer.println();
}
public static void main(String[] args) {
new Bag().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class EdC {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
static char[][] grid;
static int n;
static int t;
static int[][] dp;
static int[] times;
static int[] genre;
public static void main(String[] omkar) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
n = sc.nextInt();
t = sc.nextInt();
times = new int[n];
genre = new int[n];
for(int j =0 ;j<n;j++){
times[j] = sc.nextInt();
genre[j] = sc.nextInt();
}
dp = new int[1<<n][4];
for(int j = 0;j<1<<n;j++)
Arrays.fill(dp[j], -1);
for(int j=0;j<1<<n;j++){
letsgodp(j, 1);
letsgodp(j, 2);
letsgodp(j, 3);
}
int ans = 0;
for(int j=0;j<1<<n;j++){
int time = 0;
for(int k = 0;k<n;k++){
if (((1<<k) & j) != 0){
time+=times[k];
}
}
if (time == t){
ans+=dp[j][1];
ans%=mod;
ans+=dp[j][2];
ans%=mod;
ans+=dp[j][3];
ans%=mod;
}
}
out.println(ans);
out.close();
}
public static void letsgodp(int mask, int dg){
if (dp[mask][dg] != -1)
return;
dp[mask][dg] = 0;
for(int j = 0;j<n;j++){
if (((1<<j) & mask) != 0 && genre[j] == dg){
int submask = mask - (1<<j);
int og1 = genre[j]+1 > 3 ? genre[j]-2 : genre[j]+1;
int og2 = genre[j]+2 > 3 ? genre[j]-1 : genre[j]+2;
if (submask != 0){
letsgodp(submask, og1);
letsgodp(submask, og2);
dp[mask][dg] +=(dp[submask][og1] + dp[submask][og2]);
dp[mask][dg] %=mod;
}
else{
dp[mask][dg] = 1;
}
}
}
}
public static void sort(int[] array){
ArrayList<Integer> copy = new ArrayList<Integer>();
for (int i : array)
copy.add(i);
Collections.sort(copy);
for(int i = 0;i<array.length;i++)
array[i] = copy.get(i);
}
static String[] readArrayString(int n){
String[] array = new String[n];
for(int j =0 ;j<n;j++)
array[j] = sc.next();
return array;
}
static int[] readArrayInt(int n){
int[] array = new int[n];
for(int j = 0;j<n;j++)
array[j] = sc.nextInt();
return array;
}
static int[] readArrayInt1(int n){
int[] array = new int[n+1];
for(int j = 1;j<=n;j++){
array[j] = sc.nextInt();
}
return array;
}
static long[] readArrayLong(int n){
long[] array = new long[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextLong();
return array;
}
static double[] readArrayDouble(int n){
double[] array = new double[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextDouble();
return array;
}
static int minIndex(int[] array){
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(long[] array){
long minValue = Long.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(double[] array){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static long power(long x, long y){
if (y == 0)
return 1;
if (y%2 == 1)
return (x*power(x, y-1))%mod;
return power((x*x)%mod, y/2)%mod;
}
static void verdict(boolean a){
out.println(a ? "YES" : "NO");
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
|
np
|
1185_G1. Playlist for Polycarp (easy version)
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class E
{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok;
public void go() throws IOException
{
StringTokenizer tok = new StringTokenizer(in.readLine());
int zzz = Integer.parseInt(tok.nextToken());
for (int zz = 0; zz < zzz; zz++)
{
ntok();
int n = ipar();
int m = ipar();
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++)
{
ntok();
mat[i] = iapar(m);
}
long[][] dp = new long[1 << n][m+1];
for (int i = 0; i < 1 << n; i++)
{
dp[i][m] = -1000000000;
}
dp[(1 << n) - 1][m] = 0;
for (int i = m-1; i >= 0; i--)
{
for (int e = 0; e < 1 << n; e++)
{
dp[e][i] = dp[e][i+1];
for (int w = 0; w < 1 << n; w++)
{
if ((e & w) == 0)
{
dp[e][i] = Math.max(dp[e][i], best(w, mat, i) + dp[e|w][i+1]);
}
}
}
}
// for (long[] arr : dp)
// {
// out.println(Arrays.toString(arr));
// }
out.println(dp[0][0]);
}
out.flush();
in.close();
}
public long best(int mask, int[][] mat, int col)
{
long max = 0;
for (int t = 0; t < mat.length; t++)
{
long sum = 0;
int mk = mask;
for (int i = 0; i < mat.length; i++)
{
if (mk % 2 == 1)
{
sum += mat[i][col];
}
mk /= 2;
}
max = Math.max(max, sum);
cycle(mat, col);
}
return max;
}
public void cycle(int[][] mat, int col)
{
int temp = mat[0][col];
for (int i = 0; i < mat.length-1; i++)
{
mat[i][col] = mat[i+1][col];
}
mat[mat.length-1][col] = temp;
}
public void ntok() throws IOException
{
tok = new StringTokenizer(in.readLine());
}
public int ipar()
{
return Integer.parseInt(tok.nextToken());
}
public int[] iapar(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = ipar();
}
return arr;
}
public long lpar()
{
return Long.parseLong(tok.nextToken());
}
public long[] lapar(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = lpar();
}
return arr;
}
public double dpar()
{
return Double.parseDouble(tok.nextToken());
}
public String spar()
{
return tok.nextToken();
}
public static void main(String[] args) throws IOException
{
new E().go();
}
}
|
np
|
1209_E1. Rotate Columns (easy version)
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static Character solve(long a, long b, long c) {
long min = a;
long max;
long xth = 0;
long index;
for (index = String.valueOf(a).length() - 1;; index++) {
long numOfDigits = 0;
max = (long) Math.pow(10, index + 1) - 1;
long count = (max - min) / b + 1;
numOfDigits += count * (index + 1);
if (c - numOfDigits <= 0) {
break;
}
c -= numOfDigits;
min = min + count * b;
}
// find xth
if (c % (index + 1) == 0) {
xth = c / (index + 1);
} else {
xth = c / (index + 1) + 1;
}
long lastNum = min + b * (xth - 1);
int pos = (int) (c % (index + 1));
// here is the output
if (pos == 0) {
return String.valueOf(lastNum).charAt((int) index);
} else {
return String.valueOf(lastNum).charAt(pos - 1);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long tc;
tc = sc.nextLong();
System.out.println(solve(1, 1, tc));
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
//package math_codet;
import java.io.*;
import java.util.*;
/******************************************
* AUTHOR: AMAN KUMAR SINGH *
* INSTITUITION: KALYANI GOVERNMENT ENGINEERING COLLEGE *
******************************************/
public class lets_do {
InputReader in;
PrintWriter out;
Helper_class h;
final long mod=1000000007;
public static void main(String[] args) throws java.lang.Exception{
new lets_do().run();
}
void run() throws Exception{
in=new InputReader();
out = new PrintWriter(System.out);
h = new Helper_class();
int t=1;
while(t-->0)
solve();
out.flush();
out.close();
}
long[] arr;
int n;
HashMap<Integer,Integer> hmap=new HashMap<Integer,Integer>();
HashSet<Integer> hset=new HashSet<Integer>();
void solve(){
n=h.ni();
long d=h.nl();
int i=0;
arr=new long[n];
for(i=0;i<n;i++)
arr[i]=h.nl();
int count=2;
for(i=0;i<n-1;i++){
if(Math.abs(arr[i]-arr[i+1])>(2*d))
count+=2;
else if(Math.abs(arr[i]-arr[i+1])==(2*d))
count+=1;
}
h.pn(count);
}
class Helper_class{
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bitcount(long n){return (n==0)?0:(1+bitcount(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n(){return in.next();}
String nln(){return in.nextLine();}
int ni(){return Integer.parseInt(in.next());}
long nl(){return Long.parseLong(in.next());}
double nd(){return Double.parseDouble(in.next());}
long mul(long a,long b){
if(a>=mod)a%=mod;
if(b>=mod)b%=mod;
a*=b;
if(a>=mod)a%=mod;
return a;
}
long modPow(long a, long p){
long o = 1;
while(p>0){
if((p&1)==1)o = mul(o,a);
a = mul(a,a);
p>>=1;
}
return o;
}
long add(long a, long b){
if(a>=mod)a%=mod;
if(b>=mod)b%=mod;
if(b<0)b+=mod;
a+=b;
if(a>=mod)a-=mod;
return a;
}
}
class InputReader{
BufferedReader br;
StringTokenizer st;
public InputReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public InputReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
// Don't place your source in a package
import javax.swing.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.stream.Stream;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int T=1;
for(int t=0;t<T;t++){
int n=Int(),m=Int();
Solution sol=new Solution(out);
sol.solution(n,m);
}
out.close();
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Solution{
PrintWriter out;
public Solution(PrintWriter out){
this.out=out;
}
public void solution(int n,int mod){
long res=0;
long ncr[][]=new long[501][501];
long pow[]=new long[501];
pow[0]=1;
for(int i=1;i<pow.length;i++){
pow[i]=(pow[i-1]*2)%mod;
}
ncr[0][0]=1;
for (int i=1;i<ncr.length;i++) {
ncr[i][0]=1;
for (int j=1;j<ncr[0].length;j++) {
ncr[i][j]=(ncr[i-1][j]+ncr[i-1][j-1])%mod;
}
}
long dp[][]=new long[n+1][n+1];
for(int i=1;i<dp.length;i++){
dp[i][i]=pow[i-1];
for(int j=1;j<i;j++){
for(int k=1;k<i;k++){
//pow[cnt-1]
if(i-k-1>=1&&j>=k){
dp[i][j]=dp[i][j]+dp[i-k-1][j-k]*((ncr[j][k]*pow[k-1])%mod);
dp[i][j]%=mod;
}
}
}
}
for(int i=1;i<=n;i++){
res+=dp[n][i];
res%=mod;
}
out.println(res);
}
}
/*
;\
|' \
_ ; : ;
/ `-. /: : |
| ,-.`-. ,': : |
\ : `. `. ,'-. : |
\ ; ; `-.__,' `-.|
\ ; ; ::: ,::'`:. `.
\ `-. : ` :. `. \
\ \ , ; ,: (\
\ :., :. ,'o)): ` `-.
,/,' ;' ,::"'`.`---' `. `-._
,/ : ; '" `;' ,--`.
;/ :; ; ,:' ( ,:)
,.,:. ; ,:., ,-._ `. \""'/
'::' `:'` ,'( \`._____.-'"'
;, ; `. `. `._`-. \\
;:. ;: `-._`-.\ \`.
'`:. : |' `. `\ ) \
-hrr- ` ;: | `--\__,'
'` ,'
,-'
free bug dog
*/
|
cubic
|
1515_E. Phoenix and Computers
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s;
int i,j;
for(i=0;i<n;i++)
{
s = sc.next();
j = 0;
boolean ok;
while((s.charAt(j)>='A')&&(s.charAt(j)<='Z')) j++;
while((j<s.length())&&(s.charAt(j)>='0')&&(s.charAt(j)<='9')) j++;
if (j==s.length()) ok = true; else ok = false;
String s1="",s2="";
if (ok)
{
j = 0;
while((s.charAt(j)>='A')&&(s.charAt(j)<='Z'))
{
s1 += s.charAt(j);
j++;
}
while(j<s.length())
{
s2 += s.charAt(j);
j++;
}
int v = 0,p = 1;
for(j=s1.length()-1;j>=0;j--)
{
v += p*(s1.charAt(j)-'A'+1);
p*=26;
}
System.out.println("R"+s2+"C"+v);
} else
{
j = 1;
while((s.charAt(j)>='0')&&(s.charAt(j)<='9'))
{
s1 += s.charAt(j);
j++;
}
j++;
while(j<s.length())
{
s2 += s.charAt(j);
j++;
}
Integer a = new Integer(s2);
String s3="";
int d;
while(a > 0)
{
d = a%26; a/=26;
if (d==0) {d=26; a--;}
s3 = Character.toUpperCase(Character.forDigit(9+d,36)) + s3;
}
System.out.println(s3+s1);
}
}
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import static java.lang.Math.*;
public class Main {
private FastScanner scanner = new FastScanner();
public static void main(String[] args) {
new Main().solve();
}
private void solve() {
int n = scanner.nextInt();
Map<Integer, Integer> cnt = new HashMap<>();
for (int i = 0; i < n; i++) {
String s = scanner.nextLine();
LinkedList<Character> st = new LinkedList<>();
for (char c : s.toCharArray()) {
if (c == ')' && !st.isEmpty() && st.getLast() == '(') {
st.pollLast();
continue;
}
st.addLast(c);
}
int t = st.size();
Set<Character> set = new HashSet<>(st);
if (set.size() > 1) {
continue;
}
if (set.isEmpty()) {
cnt.put(0, cnt.getOrDefault(0, 0) + 1);
continue;
}
if (st.getLast() == '(') {
cnt.put(t, cnt.getOrDefault(t, 0) + 1);
} else {
cnt.put(-t, cnt.getOrDefault(-t, 0) + 1);
}
}
long ans = 0;
for (int next : cnt.keySet()) {
if (next == 0) {
ans += (long) cnt.get(next) * (cnt.get(next) - 1) + cnt.get(next);
} else if (next > 0) {
int t = next * -1;
if (cnt.containsKey(t)) {
ans += (long) cnt.get(next) * cnt.get(t);
}
}
}
System.out.print(ans);
}
class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
Integer[] nextA(int n) {
Integer a[] = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
linear
|
990_C. Bracket Sequences Concatenation Problem
|
CODEFORCES
|
//package round495;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Set;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), d = ni();
int[] a = na(n);
Set<Long> set = new HashSet<>();
for(int v : a){
set.add(v-(long)d);
set.add(v+(long)d);
}
int ct = 0;
for(long s : set){
long min = Long.MAX_VALUE;
for(int v : a){
min = Math.min(min, Math.abs(s-v));
}
if(min == d)ct++;
}
out.println(ct);
}
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 A().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class LookingForOrder {
static int[] dp = new int[(int) (1 << 24)];
static int[][] points;
static int[] sol = new int[1<<24];
static int sx = 0, sy = 0;
public static void main(String[] args) {
sx = in.nextInt();
sy = in.nextInt();
Arrays.fill(dp, -2);
int n = in.nextInt();
points = new int[n][3];
for (int i = 0; i < n; i++) {
points[i][0] = in.nextInt();
points[i][1] = in.nextInt();
points[i][2] = (sx - points[i][0]) * (sx - points[i][0]) + (sy - points[i][1]) * (sy - points[i][1]);
}
//System.out.println("ANS");
System.out.println(solve(0));
int mask=0;
while(true){
System.out.print(0+" ");
if (mask==(1<<n)-1) break;
int x = sol[mask];
int count=0;
for(int i=0; i<n; i++){
if ((x&(1<<i))!=0) {
count++;
System.out.print((i+1)+" ");
mask|=(1<<i);
}
if (count==2) break;
}
}
System.out.println();
}
public static int solve(int mask) {
if (dp[mask]!=-2) return dp[mask];
int n = points.length;
if (mask == ((1 << n)-1)) {
return dp[mask]=0;
}
int here = -1;
for (int i = 0; i < n; i++) {
if ((mask & (1<<i)) == 0) {
here = i;
break;
}
}
int ans = 2*points[here][2]+solve(mask | (1 << here));
sol[mask] = 1<<here;
int x1 = points[here][0];
int y1 = points[here][1];
for (int i = here + 1; i < n; i++) {
if ((mask & (1 << i)) == 0) {
int x2 = points[i][0];
int y2 = points[i][1];
int p = mask|(1<<here);
p = p|(1<<i);
if (ans>points[here][2] + points[i][2] + (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
+ solve(p)){
ans=points[here][2] + points[i][2] + (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
+ solve(p);
sol[mask]=(1<<here)|(1<<i);
}
}
}
return dp[mask]=ans;
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static MyScanner in = new MyScanner();
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int[] ar = new int[n];
for (int i = 0; i < n; i++) {
ar[i] = sc.nextInt();
}
Arrays.sort(ar);
if (ar[b-1] == ar[b ]) {
System.out.println(0);
} else {
System.out.println(ar[b ] - ar[b-1]);
}
}
}
|
nlogn
|
169_A. Chores
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class C111A{
static BufferedReader br;
public static void main(String args[])throws Exception{
br=new BufferedReader(new InputStreamReader(System.in));
int n = toInt();
int nm[] = toIntArray();
double a=0.0;
double sum=0;
for(int i=0;i<n;i++){
sum+=nm[i];
}
a=sum/2;
Arrays.sort(nm);
int cur=0;
int count=0;
for(int i=nm.length-1;i>=0;i--){
cur+=nm[i];
count++;
if(cur>a){
break;
}
}
System.out.println(count);
}
/****************************************************************/
public static int[] toIntArray()throws Exception{
String str[]=br.readLine().split(" ");
int k[]=new int[str.length];
for(int i=0;i<str.length;i++){
k[i]=Integer.parseInt(str[i]);
}
return k;
}
public static int toInt()throws Exception{
return Integer.parseInt(br.readLine());
}
public static long[] toLongArray()throws Exception{
String str[]=br.readLine().split(" ");
long k[]=new long[str.length];
for(int i=0;i<str.length;i++){
k[i]=Long.parseLong(str[i]);
}
return k;
}
public static long toLong()throws Exception{
return Long.parseLong(br.readLine());
}
public static double[] toDoubleArray()throws Exception{
String str[]=br.readLine().split(" ");
double k[]=new double[str.length];
for(int i=0;i<str.length;i++){
k[i]=Double.parseDouble(str[i]);
}
return k;
}
public static double toDouble()throws Exception{
return Double.parseDouble(br.readLine());
}
public static String toStr()throws Exception{
return br.readLine();
}
public static String[] toStrArray()throws Exception{
String str[]=br.readLine().split(" ");
return str;
}
/****************************************************************/
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
long totalBlocks = 0;
long a[] = new long[n];
for(int i = 0; i < n; ++i) {
a[i] = sc.nextLong();
totalBlocks += a[i];
}
Arrays.sort(a);
long selected = 0;
for(int i = 0; i < n; ++i) {
if(a[i] > selected)
selected++;
}
long leftCols = a[n - 1] - selected;
long remBlocks = totalBlocks - leftCols - n;
System.out.print(remBlocks);
}
}
|
nlogn
|
1061_B. Views Matter
|
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>();
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.add(new Pair(i, j, sum));
}
}
Collections.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 < sums.size()) {
int j = i;
var group = new ArrayList(List.of(sums.get(i)));
int last = sums.get(i).r;
while (j + 1 < sums.size() && sums.get(j + 1).sum == sums.get(j).sum) {
if (sums.get(j + 1).l > last) {
group.add(sums.get(j + 1));
last = sums.get(j + 1).r;
}
j++;
}
// System.out.println(group);
if (group.size() > ans.size()) {
ans = group;
}
i = j + 1;
}
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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SFly {
public static void main(String[] args) throws IOException {
BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
int planet = Integer.parseInt(lector.readLine());
int ini = Integer.parseInt(lector.readLine());
double peso = ini;
int[] desp = new int[planet];
int[] ater = new int[planet];
String[] temp = lector.readLine().split(" ");
for(int i=0; i<planet; i++) {
desp[i] = Integer.parseInt(temp[i]);
if(desp[i] == 1) {
System.out.println(-1);
lector.close();
return;
}
}
temp = lector.readLine().split(" ");
for(int i=0; i<planet; i++) {
ater[i] = Integer.parseInt(temp[i]);
if(ater[i] == 1) {
System.out.println(-1);
lector.close();
return;
}
}
temp = null;
int i=planet-1;
peso = (peso*ater[0])/(ater[0]-1);
while(i>0) {
peso = (peso*desp[i])/(desp[i]-1);
peso = (peso*ater[i])/(ater[i]-1);
i--;
}
peso = (peso*desp[0])/(desp[0]-1);
peso = peso - ini;
System.out.println(peso);
lector.close();
}
}
|
linear
|
1010_A. Fly
|
CODEFORCES
|
import java.util.Scanner;
public class first {
static int max = 1000000000;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] tab = new int[n];
for(int i=0;i<n;i++) {
tab[i] = sc.nextInt();
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(i!=j)
if(tab[i]>=tab[j] && tab[i]%tab[j]==0) {
tab[i] = max;
}
}
}
int res = 0;
for(int i=0;i<n;i++) {
if(tab[i]!=max) res++;
}
System.out.println(res);
//System.out.println(4%-1);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.util.Scanner;
public class codef8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int beacon[] = new int[1000001];
int pos[] = new int[num];
for (int i = 0; i < num; i++) {
int position = sc.nextInt();
beacon[position] = sc.nextInt();
pos[i] = position;
}
int dp[] = new int[1000001];
int max = 0;
if (beacon[0] != 0)
dp[0] = 1;
for (int i = 1; i <= 1000000; i++) {
if (beacon[i] == 0) {
dp[i] = dp[i-1];
}
else {
int j = i - beacon[i] - 1;
if (j < 0) {
dp[i] = 1;
}
else {
dp[i] = dp[j] + 1;
}
}
max = Math.max(max, dp[i]);
}
System.out.println(num-max);
}
}
|
linear
|
608_C. Chain Reaction
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
long totalBlocks = 0;
long a[] = new long[n];
for(int i = 0; i < n; ++i) {
a[i] = sc.nextLong();
totalBlocks += a[i];
}
Arrays.sort(a);
long selected = 0;
for(int i = 0; i < n; ++i) {
if(a[i] > selected)
selected++;
}
long leftCols = a[n - 1] - selected;
long remBlocks = totalBlocks - leftCols - n;
System.out.print(remBlocks);
}
}
|
nlogn
|
1061_B. Views Matter
|
CODEFORCES
|
import java.io.*;
import static java.lang.Integer.*;
import static java.lang.Math.*;
public class A {
public static void main(String[] args) throws Throwable{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String ln=in.readLine().trim();
System.out.println(max(parseInt(ln),max(parseInt(ln.substring(0,ln.length()-1)),parseInt(ln.substring(0, ln.length()-2)+ln.substring(ln.length()-1)))));
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(
System.in)));
int nc = sc.nextInt();
while (nc-- > 0) {
String s = sc.next();
StringTokenizer st = new StringTokenizer(s, "0123456789");
if (st.countTokens() > 1) {
int k = s.indexOf('C');
int r = Integer.parseInt(s.substring(1, k));
int c = Integer.parseInt(s.substring(k + 1));
int len = 1;
int p = 26;
while (c > p) {
c -= p;
len++;
p *= 26;
}
String col = Integer.toString(--c, 26).toUpperCase();
while (col.length() < len)
col = "0" + col;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < col.length(); i++) {
if (col.charAt(i) < 'A') {
sb.append((char) (col.charAt(i) - '0' + 'A'));
} else {
sb.append((char) (col.charAt(i) + 10));
}
}
System.out.printf("%s%d\n", sb.toString(), r);
} else {
int k = 0;
while (s.charAt(k) > '9')
k++;
char[] col = s.substring(0, k).toCharArray();
int r = Integer.parseInt(s.substring(k));
int c = 1;
int p = 26;
int cnt = 1;
while (cnt++ < col.length) {
c += p;
p *= 26;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < col.length; i++) {
if (s.charAt(i) < 'K') {
sb.append((char) ('0' + col[i] - 'A'));
} else {
sb.append((char) (col[i] - 10));
}
}
c += Integer.parseInt(sb.toString(), 26);
System.out.printf("R%dC%d\n", r, c);
}
}
System.out.close();
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static long oo = 1000000000000L;
public static void main(String[] args) throws IOException {
int n = in.nextInt();
int q = in.nextInt();
ArrayDeque<Integer> dq = new ArrayDeque<>();
int max = -1;
for(int i = 0; i < n; ++i) {
int x = in.nextInt();
dq.add(x);
max = Math.max(max, x);
}
ArrayList<Pair> ans = new ArrayList<>();
while(dq.peekFirst() != max) {
int a = dq.pollFirst();
int b = dq.pollFirst();
ans.add(new Pair(a, b));
if(a > b) {
dq.addFirst(a);
dq.addLast(b);
}
else {
dq.addFirst(b);
dq.addLast(a);
}
}
ArrayList<Integer> a = new ArrayList<>();
dq.pollFirst();
for(int x : dq)
a.add(x);
while(q --> 0) {
long m = in.nextLong() - 1;
if(m < ans.size()) {
System.out.println(ans.get((int)m).first + " " + ans.get((int)m).second);
}
else {
int idx = (int)((m - ans.size()) % a.size());
System.out.println(max + " " + a.get(idx));
}
}
out.close();
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static boolean nextPermutation(int[] a) {
for(int i = a.length - 2; i >= 0; --i) {
if(a[i] < a[i+1]) {
for(int j = a.length - 1; ; --j) {
if(a[i] < a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
for(i++, j = a.length - 1; i < j; ++i, --j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
return true;
}
}
}
}
return false;
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
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 boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
|
linear
|
1180_C. Valeriy and Deque
|
CODEFORCES
|
// Don't place your source in a package
import javax.swing.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.stream.Stream;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int T=1;
for(int t=0;t<T;t++){
int n=Int(),m=Int(),k=Int();
List<int[]>g[]=new ArrayList[n*m+1];
for(int i=0;i<g.length;i++){
g[i]=new ArrayList<>();
}
for(int i=0;i<n;i++){
for(int j=0;j<m-1;j++){
int w=Int();
int u=i*m+j;
int v=i*m+(j+1);
g[u].add(new int[]{v,w});
g[v].add(new int[]{u,w});
}
}
for(int i=0;i<n-1;i++){
for(int j=0;j<m;j++){
int w=Int();
int u=i*m+j;
int v=(i+1)*m+j;
g[u].add(new int[]{v,w});
g[v].add(new int[]{u,w});
}
}
Solution sol=new Solution(out);
sol.solution(n,m,k,g);
}
out.close();
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Solution{
PrintWriter out;
public Solution(PrintWriter out){
this.out=out;
}
List<int[]>g[];
int n,m;
long INF=10000000000000000l;
int curr=-1,curc=-1;
long mn=Long.MAX_VALUE;
long dp[][];
public void solution(int n,int m,int k,List<int[]>g[]){
//edge : 4 directions.
this.n=n;
this.m=m;
long res[][]=new long[n][m];
if(k%2==1){
for(int i=0;i<n;i++){
Arrays.fill(res[i],-1);
}
print(res);
return;
}
this.g=g;
dp=new long[n*m+1][k/2+2];
for(int i=0;i<dp.length;i++){
Arrays.fill(dp[i],-1);
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
int id=i*m+j;
dfs(id,k/2);
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
int id=i*m+j;
res[i][j]=dp[id][k/2];
}
}
print(res);
}
public long dfs(int id,int cnt){
if(cnt==0){
return 0;
}
if(dp[id][cnt]!=-1)return dp[id][cnt];
int r=id/m;
int c=id%m;
long res=Long.MAX_VALUE;
for(int p[]:g[id]){
int next=p[0],w=p[1];
res=Math.min(res,w*2+dfs(next,cnt-1));
}
dp[id][cnt]=res;
return res;
}
public int dis(int x1,int y1,int x2,int y2){
return Math.abs(x1-x2)+Math.abs(y1-y2);
}
public void print(long A[][]){
for(int i=0;i<A.length;i++){
for(int j=0;j<A[0].length;j++){
out.print(A[i][j]+" ");
}
out.println();
}
}
}
class Solution1{
PrintWriter out;
public Solution1(PrintWriter out){
this.out=out;
}
public void solution(int A[]){
}
}
/*
;\
|' \
_ ; : ;
/ `-. /: : |
| ,-.`-. ,': : |
\ : `. `. ,'-. : |
\ ; ; `-.__,' `-.|
\ ; ; ::: ,::'`:. `.
\ `-. : ` :. `. \
\ \ , ; ,: (\
\ :., :. ,'o)): ` `-.
,/,' ;' ,::"'`.`---' `. `-._
,/ : ; '" `;' ,--`.
;/ :; ; ,:' ( ,:)
,.,:. ; ,:., ,-._ `. \""'/
'::' `:'` ,'( \`._____.-'"'
;, ; `. `. `._`-. \\
;:. ;: `-._`-.\ \`.
'`:. : |' `. `\ ) \
-hrr- ` ;: | `--\__,'
'` ,'
,-'
free bug dog
*/
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Task483A {
public static void main(String... args) throws NumberFormatException,
IOException {
Solution.main(System.in, System.out);
}
static class Scanner {
private final BufferedReader br;
private String[] cache;
private int cacheIndex;
Scanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
cache = new String[0];
cacheIndex = 0;
}
int nextInt() throws IOException {
if (cacheIndex >= cache.length) {
cache = br.readLine().split(" ");
cacheIndex = 0;
}
return Integer.parseInt(cache[cacheIndex++]);
}
long nextLong() throws IOException {
if (cacheIndex >= cache.length) {
cache = br.readLine().split(" ");
cacheIndex = 0;
}
return Long.parseLong(cache[cacheIndex++]);
}
String next() throws IOException {
if (cacheIndex >= cache.length) {
cache = br.readLine().split(" ");
cacheIndex = 0;
}
return cache[cacheIndex++];
}
void close() throws IOException {
br.close();
}
}
static class Solution {
public static void main(InputStream is, OutputStream os)
throws NumberFormatException, IOException {
PrintWriter pw = new PrintWriter(os);
Scanner sc = new Scanner(is);
long l = sc.nextLong();
long r = sc.nextLong();
long interval = r-l;
if(interval == 0 || interval == 1 || (interval == 2 && l % 2 ==1 )){
pw.println(-1);
} else {
if(l % 2 == 1){
l++;
}
pw.print(l);
pw.print(" ");
pw.print(l+1);
pw.print(" ");
pw.print(l+2);
}
pw.flush();
sc.close();
}
}
}
|
constant
|
483_A. Counterexample
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class ProblemE
{
static int mod = (int) (1e9+7);
static InputReader in;
static PrintWriter out;
static class SegmentTree {
long st[];
SegmentTree(int n) {
st = new long[4*n];
build(0, n - 1, 1);
}
int getMid(int s, int e) {
return (s+e)>>1;
}
long merge(long a,long b){
return a+b;
}
void update(int s, int e, int x, int y, long c, int si){
if(s == x && e == y){
st[si] += c;
}
else{
int mid = getMid(s, e);
if(y <= mid)
update(s, mid, x, y, c, 2*si);
else if(x > mid)
update(mid + 1, e, x ,y ,c ,2*si + 1);
else{
update(s, mid, x, mid, c, 2*si);
update(mid + 1, e, mid + 1, y, c, 2*si + 1);
}
st[si] = merge(st[2*si],st[2*si+1]);
}
}
long get(int s, int e, int x, int y, int si){
if(s == x && e == y){
return st[si];
}
int mid = getMid(s, e);
if(y <= mid)
return get(s, mid, x, y, 2*si);
else if(x > mid)
return get(mid + 1, e, x, y, 2*si + 1);
return merge(get(s, mid, x, mid, 2*si), get(mid + 1, e, mid + 1, y, 2*si + 1));
}
void build(int ss, int se, int si){
if (ss == se) {
st[si] = 0;
return;
}
int mid = getMid(ss, se);
build(ss, mid, si * 2 );
build(mid + 1, se, si * 2 + 1);
st[si] = merge(st[2*si],st[2*si+1]);
}
}
public static void main(String[] args) throws FileNotFoundException
{
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int n = in.nextInt();
int[] arr = in.nextIntArray(n);
ArrayList<Integer>list = new ArrayList<>();
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < n; i++){
list.add(arr[i]);
list.add(arr[i] + 1);
list.add(arr[i] - 1);
}
Collections.sort(list);
int j = 1;
for(int k : list){
if(map.containsKey(k)) continue;
map.put(k, j++);
}
SegmentTree seg = new SegmentTree(j + 1);
SegmentTree seg1 = new SegmentTree(j + 1);
BigInteger ans = BigInteger.ZERO;
BigInteger sum = BigInteger.ZERO;
// long ans = 0;
// long sum = 0;
for(int i = 0; i < n; i++){
long x = seg.get(0, j - 1, map.get(arr[i] - 1), map.get(arr[i] + 1), 1);
long y = seg1.get(0, j - 1, map.get(arr[i] - 1), map.get(arr[i] + 1), 1);
ans = ans.add(new BigInteger(""+x));
ans = ans.subtract(sum);
ans = ans.add(new BigInteger(""+((arr[i] * 1l *(i - y)))));
// ans += arr[i] * 1l * (i - y) - sum + x;
seg.update(0, j - 1, map.get(arr[i]), map.get(arr[i]), arr[i], 1);
seg1.update(0, j - 1, map.get(arr[i]), map.get(arr[i]), 1, 1);
sum = sum.add(new BigInteger(arr[i] + ""));
}
out.println(ans);
out.close();
}
static class Pair implements Comparable<Pair>
{
int x,y;
int i;
Pair (int x,int y)
{
this.x = x;
this.y = y;
}
Pair (int x,int y, int i)
{
this.x = x;
this.y = y;
this.i = i;
}
public int compareTo(Pair o)
{
return Long.compare(this.i,o.i);
//return 0;
}
public boolean equals(Object o)
{
if (o instanceof Pair)
{
Pair p = (Pair)o;
return p.x == x && p.y==y;
}
return false;
}
@Override
public String toString()
{
return x + " "+ y + " "+i;
}
/*public int hashCode()
{
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}*/
}
static long gcd(long x,long y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long pow(long n,long p,long m)
{
long result = 1;
if(p==0){
return n;
}
while(p!=0)
{
if(p%2==1)
result *= n;
if(result >= m)
result %= m;
p >>=1;
n*=n;
if(n >= m)
n%=m;
}
return result;
}
static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
|
nlogn
|
903_D. Almost Difference
|
CODEFORCES
|
import java.math.*;
import java.util.*;
import java.io.*;
public class Main{
void solve() {
int n=ni();
long d=nl();
long x[]=new long[n+1];
for(int i=1;i<=n;i++) x[i]=nl();
Arrays.sort(x,1,n+1);
int ans=2;
for(int i=2;i<=n;i++){
long x1=x[i-1]+d,x2=x[i]-d;
if(x[i]-x1>=d) ans++;
if(x2-x[i-1]>=d && x1!=x2) ans++;
// pw.println(ans);
}
pw.println(ans);
}
long M=(long)1e9+7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Main().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class A {
BufferedReader br;
StringTokenizer st;
PrintWriter out;
void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
int[] b = a.clone();
Arrays.sort(b);
int k = 0;
for (int i = 0; i < n; i++) {
if (a[i] != b[i]) {
k++;
}
}
if (k <= 2) {
out.println("YES");
} else {
out.println("NO");
}
}
void run() {
try {
// br = new BufferedReader(new FileReader("G.in"));
// out = new PrintWriter("G.out");
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new A().run();
}
public String nextToken() throws IOException {
while ((st == null) || (!st.hasMoreTokens()))
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
}
|
nlogn
|
220_A. Little Elephant and Problem
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author dauom
*/
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);
CCompressionAndExpansion solver = new CCompressionAndExpansion();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class CCompressionAndExpansion {
public final void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
ArrayList<Integer> start = new ArrayList<>();
start.add(in.nextInt());
ans.add(start);
out.println("1");
for (int i = 1; i < n; i++) {
ArrayList<Integer> lastList = ans.get(ans.size() - 1);
ArrayList<Integer> curList = (ArrayList<Integer>) lastList.clone();
ans.add(curList);
int curLast = in.nextInt();
for (int j = lastList.size() - 1; j >= 0; j--) {
int last = lastList.get(j);
if (curLast == 1) {
curList.add(1);
break;
} else if (curLast == last + 1) {
curList.set(j, curLast);
break;
} else {
curList.remove(j);
}
}
for (int j = 0; j < curList.size(); j++) {
if (j > 0) out.print(".");
out.print(curList.get(j));
}
out.println();
}
}
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1 << 18];
private int curChar;
private int numChars;
public InputReader() {
this.stream = System.in;
}
public InputReader(final InputStream stream) {
this.stream = stream;
}
private int read() {
if (this.numChars == -1) {
throw new UnknownError();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException ex) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return -1;
}
}
return this.buf[this.curChar++];
}
}
public final int nextInt() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
}
byte sgn = 1;
if (c == 45) { // 45 == '-'
sgn = -1;
c = this.read();
}
int res = 0;
while (c >= 48 && c <= 57) { // 48 == '0', 57 == '9'
res *= 10;
res += c - 48; // 48 == '0'
c = this.read();
if (isSpaceChar(c)) {
return res * sgn;
}
}
throw new InputMismatchException();
}
public final String next() {
int c;
while (isSpaceChar(c = this.read())) {
}
StringBuilder result = new StringBuilder();
result.appendCodePoint(c);
while (!isSpaceChar(c = this.read())) {
result.appendCodePoint(c);
}
return result.toString();
}
private static boolean isSpaceChar(final int c) {
return c == 32 || c == 10 || c == 13 || c == 9
|| c == -1; // 32 == ' ', 10 == '\n', 13 == '\r', 9 == '\t'
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class A {
static int countColors(List<Integer> colors) {
Collections.sort(colors);
int k = 0;
while (!colors.isEmpty()) {
Integer c = colors.get(0);
colors.remove(0);
k++;
List<Integer> toRemove = new ArrayList<>();
for (int i = 0; i < colors.size(); i++) {
if (colors.get(i) % c == 0) toRemove.add(i);
}
Collections.reverse(toRemove);
for (Integer integer : toRemove) {
colors.remove(integer.intValue());
}
}
return k;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int n = scanner.nextInt();
scanner.nextLine();
List<Integer> integers = Arrays.stream(scanner.nextLine().split(" ")).map(Integer::parseInt).collect(Collectors.toList());
System.out.println(countColors(integers));
}
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Sunits789
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n=in.nextInt();
int k=in.nextInt();
int arr[]=new int[n];
in.getArray(arr);
int ansl=-1;
int ansr=n;
int occ[]=new int[100100];
boolean f[]=new boolean[n];
Arrays.fill(occ,0);
Arrays.fill(f,true);
int pk=0;
for (int l=0,r=0;r<n&&l<n;){
int num=arr[r];
if(f[r]){
f[r]=false;
occ[num]++;
if(occ[num]==1){
pk++;
}
}
//System.out.println(l+" "+r+" "+pk+" "+k);
if(pk<k){
r++;
}
else if (pk==k){
if((r-l)<=(ansr-ansl)){
ansl=l+1;
ansr=r+1;
}
num=arr[l];
occ[num]--;
if(occ[num]==0){
pk--;
}
l++;
}
else {
num=arr[l];
occ[num]--;
if(occ[num]==0){
pk--;
}
l++;
}
}
if(ansl==-1){
ansr=-1;
}
out.println(ansl+" "+ansr);
}
}
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());
}
public void getArray(int arr[]){
for(int i=0;i<arr.length;i++){
arr[i]=nextInt();
}
}
}
|
linear
|
224_B. Array
|
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.*;
// Pipeline
// 2013/03/23
public class P287B{
Scanner sc=new Scanner(System.in);
long n, k;
void run(){
n=sc.nextLong();
k=sc.nextLong();
solve();
}
void solve(){
long left=-1, right=k+1;
for(; right-left>1;){
long m=(left+right)/2;
long ub=k*(k+1)/2-(k-m)*(k-m+1)/2-(m-1);
if(ub>=n){
right=m;
}else{
left=m;
}
}
println(""+(right>k?-1:right));
}
void println(String s){
System.out.println(s);
}
public static void main(String[] args){
Locale.setDefault(Locale.US);
new P287B().run();
}
}
|
logn
|
287_B. Pipeline
|
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 solve(){
n=w*h;
g=new long[n];
int[] dx={0, 0, -1, 1};
int[] dy={-1, 1, 0, 0};
for(int y=0; y<h; y++){
for(int x=0; x<w; x++){
for(int k=0; k<4; k++){
int x2=x+dx[k];
int y2=y+dy[k];
if(x2>=0&&x2<w&&y2>=0&&y2<h){
g[y*w+x]|=1L<<(y2*w+x2);
}
}
}
}
mds=(1L<<n)-1;
mds(0, 0, 0);
println((n-Long.bitCount(mds))+"");
}
int n;
long[] g;
long mds;
void mds(long choosed, long removed, long covered){
if(Long.bitCount(choosed)>=Long.bitCount(mds))
return;
if(covered==((1L<<n)-1)){
if(Long.bitCount(choosed)<Long.bitCount(mds))
mds=choosed;
return;
}
int k=-1;
ArrayList<Integer> list=new ArrayList<Integer>();
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||Long.bitCount(g[i]&~covered)>Long.bitCount(g[k]&~covered)){
list.clear();
list.add(i);
k=i;
}else if(Long.bitCount(g[i]&~covered)==Long.bitCount(g[k]&~covered))
list.add(i);
}
if(k==-1)
return;
k=list.get((int)(list.size()*random()));
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.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
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 mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int leftIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergeSort(a, leftIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
int[] leftArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
int mini = Integer.MAX_VALUE;
int maxi = Integer.MIN_VALUE;
int ans = 0;
int ans2 = 0;
int sum = 0;
void solve() throws IOException {
int n = readInt();
int m = readInt();
int maxi=0;
int [][] a = new int [n][m];
int k = readInt();
ArrayDeque<Point> dq = new ArrayDeque<Point> ();
Point p = new Point();
for (int i = 0; i<n; i++)
for (int j= 0; j<m; j++){
a[i][j]=Integer.MAX_VALUE;
}
for (int i = 0; i<k; i++){
int x = readInt()-1;
int y = readInt()-1;
p.x=x;
p.y=y;
dq.add(new Point(x,y));
a[x][y]=0;
}
while (!dq.isEmpty()){
Point v = dq.pollFirst();
Point u = new Point();
if (v.x-1!=-1) {
if (a[v.x-1][v.y]>a[v.x][v.y]+1){
a[v.x-1][v.y]=a[v.x][v.y]+1;
maxi=max(maxi,a[v.x-1][v.y]);
u.x=v.x-1;
u.y=v.y;
dq.add(new Point(u.x,u.y));
}
}
if (v.y-1!=-1) {
if (a[v.x][v.y-1]>a[v.x][v.y]+1){
a[v.x][v.y-1]=a[v.x][v.y]+1;
maxi=max(maxi,a[v.x][v.y-1]);
u.y=v.y-1;
u.x=v.x;
dq.add(new Point(u.x,u.y));
}
}
if (v.x+1!=n) {
if (a[v.x+1][v.y]>a[v.x][v.y]+1){
a[v.x+1][v.y]=a[v.x][v.y]+1;
maxi=max(maxi,a[v.x+1][v.y]);
u.x=v.x+1;
u.y=v.y;
dq.add(new Point(u.x,u.y));
}
}
if (v.y+1!=m) {
if (a[v.x][v.y+1]>a[v.x][v.y]+1){
a[v.x][v.y+1]=a[v.x][v.y]+1;
maxi=max(maxi,a[v.x][v.y+1]);
u.y=v.y+1;
u.x=v.x;
dq.add(new Point(u.x,u.y));
}
}
}
for (int i =0; i<n; i++)
for (int j =0; j<m; j++){
if (maxi==a[i][j]) {
out.print((i+1) + " " + (j+1));
return;
}
}
}
char c[];
void per (int left, int right){
if(left == right){
for (int i = 0; i<=right;i++){
out.print(c[i]);
}
out.println();
}
else {
for (int i = left; i <=right; i++){
char k = c[left];
c[left] = c[i];
c[i] = k;
per(left+1,right);
k = c[left];
c[left] = c[i];
c[i] = k;
}
}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger l = new BigInteger(scanner.next());
BigInteger r = new BigInteger(scanner.next());
if(r.subtract(l).intValue() < 2) {
System.out.println(-1);
return;
}
BigInteger a = l.abs(),b,c;
BigInteger toothless = r.subtract(BigInteger.valueOf(1));
while(a.compareTo(toothless) == -1) {
b = l.add(BigInteger.valueOf(1));
while(b.compareTo(r) == -1) {
c = l.add(BigInteger.valueOf(2));
while(c.compareTo(r) == -1 || c.compareTo(r) == 0) {
if(gcd(a,b) == 1 && gcd(b,c) == 1 && gcd(a,c) != 1) {
System.out.println(a + " " + b + " " + c);
return;
}
c = c.add(BigInteger.valueOf(1));
}
b = b.add(BigInteger.valueOf(1));
}
a = a.add(BigInteger.valueOf(1));
}
System.out.println(-1);
}
private static int gcd(BigInteger a, BigInteger b) {
return a.gcd(b).intValue();
}
}
|
constant
|
483_A. Counterexample
|
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.*;
import java.io.*;
public class test {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
StringTokenizer st = new StringTokenizer(s.nextLine());
int n = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
st = new StringTokenizer(s.nextLine());
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = Integer.parseInt(st.nextToken());
}
ArrayList<State> list = new ArrayList<State>();
for (int i = 0; i < n; i++) {
double currY = r;
for (int j = 0; j < list.size(); j++) {
double xDiff = Math.abs(list.get(j).getX() - array[i]);
if (xDiff <= 2 * r) {
if (currY < list.get(j).getY() + Math.sqrt(4 * r * r - xDiff * xDiff)) {
currY = list.get(j).getY() + Math.sqrt(4 * r * r - xDiff * xDiff);
}
}
}
list.add(new State(array[i], currY));
System.out.print(currY + " ");
}
s.close();
}
static class State {
double x;
double y;
public State(double a, double b) {
x = a;
y = b;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class CF387D {
static class A {
ArrayList<Integer> list = new ArrayList<>();
int u, v, d;
}
static final int INF = Integer.MAX_VALUE;
static boolean bfs(A[] aa, int n) {
ArrayDeque<Integer> q = new ArrayDeque<>();
for (int u = 1; u <= n; u++)
if (aa[u].v > 0)
aa[u].d = INF;
else {
aa[u].d = 0;
q.addLast(u);
}
aa[0].d = INF;
while (!q.isEmpty()) {
int u = q.removeFirst();
for (int v : aa[u].list) {
int w = aa[v].u;
if (aa[w].d == INF) {
aa[w].d = aa[u].d + 1;
if (w == 0)
return true;
q.addLast(w);
}
}
}
return false;
}
static boolean dfs(A[] aa, int n, int u) {
if (u == 0)
return true;
for (int v : aa[u].list) {
int w = aa[v].u;
if (aa[w].d == aa[u].d + 1 && dfs(aa, n, w)) {
aa[u].v = v;
aa[v].u = u;
return true;
}
}
aa[u].d = INF;
return false;
}
static int matchings(A[] aa, int n) {
int cnt = 0;
while (bfs(aa, n))
for (int u = 1; u <= n; u++)
if (aa[u].v == 0 && dfs(aa, n, u))
cnt++;
return cnt;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[] eu = new int[m];
int[] ev = new int[m];
for (int j = 0; j < m; j++) {
st = new StringTokenizer(br.readLine());
eu[j] = Integer.parseInt(st.nextToken());
ev[j] = Integer.parseInt(st.nextToken());
}
A[] aa = new A[n + 1];
int min = m + n * 3;
for (int ctr = 1; ctr <= n; ctr++) {
boolean loop = false;
boolean[] ci = new boolean[n + 1];
boolean[] co = new boolean[n + 1];
for (int i = 0; i <= n; i++)
aa[i] = new A();
int m_ = 0;
for (int j = 0; j < m; j++) {
int u = eu[j];
int v = ev[j];
if (u == ctr && v == ctr)
loop = true;
else if (u == ctr && v != ctr)
ci[v] = true;
else if (u != ctr && v == ctr)
co[u] = true;
else {
aa[u].list.add(v);
m_++;
}
}
int cnt = loop ? 0 : 1;
for (int i = 1; i <= n; i++)
if (i != ctr) {
if (!ci[i])
cnt++;
if (!co[i])
cnt++;
}
int m2 = matchings(aa, n);
cnt += (m_ - m2) + (n - 1 - m2);
if (min > cnt)
min = cnt;
}
System.out.println(min);
}
}
|
cubic
|
387_D. George and Interesting Graph
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class Main implements Runnable {
private void solution() throws IOException {
int n = in.nextInt();
int m = in.nextInt();
boolean[][] adj = new boolean[n][n];
long res = 0;
for (int i = 0; i < m; ++i) {
int x = in.nextInt();
int y = in.nextInt();
adj[x - 1][y - 1] = true;
adj[y - 1][x - 1] = true;
}
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (adj[i][j]) {
--res;
}
}
}
long[][] dp = new long[1 << n][n];
for (int i = 0; i < n; ++i) {
for (int mask = 0; mask < (1 << (n - i)); ++mask) {
for (int j = 0; j < n - i; ++j) {
dp[mask][j] = 0;
}
}
dp[0][0] = 1;
for (int mask = 0; mask < (1 << (n - i)); ++mask) {
for (int j = 0; j < n - i; ++j) {
if (dp[mask][j] != 0) {
for (int k = 0; k < n - i; ++k) {
if (((mask >> k) & 1) == 0 && adj[j + i][k + i]) {
dp[mask | (1 << k)][k] += dp[mask][j];
}
}
}
}
if (((mask >> 0) & 1) != 0) {
res += dp[mask][0];
}
}
}
out.println(res / 2);
}
public void run() {
try {
solution();
in.reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private class Scanner {
BufferedReader reader;
StringTokenizer tokenizer;
public Scanner(Reader reader) {
this.reader = new BufferedReader(reader);
this.tokenizer = new StringTokenizer("");
}
public boolean hasNext() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String next = reader.readLine();
if (next == null) {
return false;
}
tokenizer = new StringTokenizer(next);
}
return true;
}
public String next() throws IOException {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public String nextLine() throws IOException {
tokenizer = new StringTokenizer("");
return reader.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
public static void main(String[] args) throws IOException {
new Thread(null, new Main(), "", 1 << 28).start();
}
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
Scanner in = new Scanner(new InputStreamReader(System.in));
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Round313A {
private static final int LOCAL_ENV = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try {
if (LOCAL_ENV == 1) {
in = new Scanner(new File("input.txt"));
}
} catch (FileNotFoundException e) {
in = new Scanner(System.in);
}
long n = in.nextLong();
if (n >= -9) {
System.out.println(n);
} else {
long absN = Math.abs(n);
long m1 = -(absN / 10);
long last = absN % 10;
long m2 = -((absN / 100) * 10 + last);
System.out.println(Math.max(m1, m2));
}
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
//package round371;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class BT {
Scanner in;
PrintWriter out;
String INPUT = "";
int q(int r1, int c1, int r2, int c2)
{
out.printf("? %d %d %d %d\n", r1+1, c1+1, r2+1, c2+1);
out.flush();
return ni();
}
void e(int r1, int c1, int r2, int c2, int r3, int c3, int r4, int c4)
{
out.printf("! %d %d %d %d %d %d %d %d\n",
r1+1, c1+1, r2+1, c2+1,
r3+1, c3+1, r4+1, c4+1
);
out.flush();
}
void solve()
{
int n = ni();
int cu = -1, cv = -1;
{
int low = -1, high = n-1;
while(high - low > 1){
int h = high+low>>1;
if(q(0, 0, n-1, h) >= 2){
high = h;
}else{
low = h;
}
}
cu = high;
}
{
int low = -1, high = n-1;
while(high - low > 1){
int h = high+low>>1;
if(q(0, 0, n-1, h) >= 1){
high = h;
}else{
low = h;
}
}
cv = high;
}
int du = -1, dv = -1;
{
int low = 0, high = n;
while(high - low > 1){
int h = high+low>>1;
if(q(0, h, n-1, n-1) >= 2){
low = h;
}else{
high = h;
}
}
du = low;
}
{
int low = 0, high = n;
while(high - low > 1){
int h = high+low>>1;
if(q(0, h, n-1, n-1) >= 1){
low = h;
}else{
high = h;
}
}
dv= low;
}
int eu = -1, ev = -1;
{
int low = -1, high = n-1;
while(high - low > 1){
int h = high+low>>1;
if(q(0, 0, h, n-1) >= 2){
high = h;
}else{
low = h;
}
}
eu = high;
}
{
int low = -1, high = n-1;
while(high - low > 1){
int h = high+low>>1;
if(q(0, 0, h, n-1) >= 1){
high = h;
}else{
low = h;
}
}
ev = high;
}
int fu = -1, fv = -1;
{
int low = 0, high = n;
while(high - low > 1){
int h = high+low>>1;
if(q(h, 0, n-1, n-1) >= 2){
low = h;
}else{
high = h;
}
}
fu = low;
}
{
int low = 0, high = n;
while(high - low > 1){
int h = high+low>>1;
if(q(h, 0, n-1, n-1) >= 1){
low = h;
}else{
high = h;
}
}
fv= low;
}
// cv <= cu
// du <= dv
int[][][] canc = {
{{du, cu}, {dv, cv}},
{{du, cv}, {dv, cu}}
};
int[][][] canr = {
{{fu, eu}, {fv, ev}},
{{fu, ev}, {fv, eu}}
};
for(int[][] cr : canr){
if(cr[0][0] > cr[0][1])continue;
if(cr[1][0] > cr[1][1])continue;
for(int[][] cc : canc){
if(cc[0][0] > cc[0][1])continue;
if(cc[1][0] > cc[1][1])continue;
for(int z = 0;z < 2;z++){
if(
q(cr[0][0], cc[0^z][0], cr[0][1], cc[0^z][1]) == 1 &&
q(cr[1][0], cc[1^z][0], cr[1][1], cc[1^z][1]) == 1){
e(cr[0][0], cc[0^z][0], cr[0][1], cc[0^z][1], cr[1][0], cc[1^z][0], cr[1][1], cc[1^z][1]);
return;
}
}
}
}
throw new RuntimeException();
}
void run() throws Exception
{
in = oj ? new Scanner(System.in) : new Scanner(INPUT);
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception
{
new BT().run();
}
int ni() { return Integer.parseInt(in.next()); }
long nl() { return Long.parseLong(in.next()); }
double nd() { return Double.parseDouble(in.next()); }
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
logn
|
713_B. Searching Rectangles
|
CODEFORCES
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class CodehorsesTShirt {
public static void main(String args[]) throws IOException {
FastReader in = new FastReader();
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
Task.solve(in, out);
out.close();
}
static class Task {
public static void solve(FastReader in, PrintWriter out) {
int n = in.nextInt();
HashMap<String , Integer> hm1 = new HashMap<>();
HashMap<String , Integer> hm2 = new HashMap<>();
for(int i=0;i<n;i++){
String val = in.next();
if(hm1.containsKey(val)){
hm1.put(val, hm1.get(val)+1);
}else{
hm1.put(val,1);
}
}
for(int i=0;i<n;i++){
String val = in.next();
if(hm1.containsKey(val)){
int x = hm1.get(val);
if(x==1){
hm1.remove(val);
}else{
hm1.put(val,hm1.get(val)-1);
}
}else{
if(hm2.containsKey(val)){
hm2.put(val, hm2.get(val)+1);
}else{
hm2.put(val,1);
}
}
}
int ans = 0;
for(Map.Entry<String , Integer> row: hm1.entrySet()){
ans += row.getValue();
}
System.out.println(ans);
}
}
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;
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Q3 {
static class Pair {
int a;
int b;
Pair(int p, int q) {
a = p;
b = q;
}
}
public static void main(String[] args) {
InputReader in = new InputReader();
int N = in.nextInt();
int arr[] = new int[N];
for (int i = 0; i < N; i++)
arr[i] = in.nextInt();
HashMap<Integer, ArrayList<Pair>> name = new HashMap<>();
for (int i = 0; i < N; i++) {
int sum = 0;
for (int j = i; j < N; j++) {
sum += arr[j];
if (name.get(sum) == null)
name.put(sum, new ArrayList());
name.get(sum).add(new Pair(i+1, j+1));
}
}
HashSet<Pair> ans = new HashSet<>();
for (ArrayList<Pair> n : name.values()) {
Collections.sort(n, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if (Integer.compare(o1.b, o2.b) == 0)
return Integer.compare(o1.a, o2.a);
return Integer.compare(o1.b, o2.b);
}
});
HashSet<Pair> temp = new HashSet<>();
temp.add(n.get(0));
int num = 1;
int r = n.get(0).b;
for (int i = 1; i < n.size(); i++) {
if (n.get(i).a > r) {
num++;
r = n.get(i).b;
temp.add(n.get(i));
}
}
if (num > ans.size())
ans = temp;
}
System.out.println(ans.size());
for (Pair val : ans)
System.out.println(val.a + " " + val.b);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
public InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public char nextChar() {
return next().charAt(0);
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextInt();
}
return arr;
}
public Integer[] nextIntegerArr(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = new Integer(this.nextInt());
return arr;
}
public int[][] next2DIntArr(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = this.nextInt();
}
}
return arr;
}
public int[] nextSortedIntArr(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextInt();
}
Arrays.sort(arr);
return arr;
}
public long[] nextLongArr(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextLong();
}
return arr;
}
public char[] nextCharArr(int n) {
char[] arr = new char[n];
for (int i = 0; i < n; i++) {
arr[i] = this.nextChar();
}
return arr;
}
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static int[] uwiSieve(int n) {
if (n <= 32) {
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int i = 0; i < primes.length; i++) {
if (n < primes[i]) {
return Arrays.copyOf(primes, i);
}
}
return primes;
}
int u = n + 32;
double lu = Math.log(u);
int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];
ret[0] = 2;
int pos = 1;
int[] isp = new int[(n + 1) / 32 / 2 + 1];
int sup = (n + 1) / 32 / 2 + 1;
int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int tp : tprimes) {
ret[pos++] = tp;
int[] ptn = new int[tp];
for (int i = (tp - 3) / 2; i < tp << 5; i += tp)
ptn[i >> 5] |= 1 << (i & 31);
for (int i = 0; i < tp; i++) {
for (int j = i; j < sup; j += tp)
isp[j] |= ptn[i];
}
}
// 3,5,7
// 2x+3=n
int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17,
9, 6, 16, 5, 15, 14};
int h = n / 2;
for (int i = 0; i < sup; i++) {
for (int j = ~isp[i]; j != 0; j &= j - 1) {
int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];
int p = 2 * pp + 3;
if (p > n)
break;
ret[pos++] = p;
for (int q = pp; q <= h; q += p)
isp[q >> 5] |= 1 << (q & 31);
}
}
return Arrays.copyOf(ret, pos);
}
public static int[] radixSort(int[] f) {
return radixSort(f, f.length);
}
public static int[] radixSort(int[] f, int n) {
int[] to = new int[n];
{
int[] b = new int[65537];
for (int i = 0; i < n; i++) b[1 + (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < n; i++) to[b[f[i] & 0xffff]++] = f[i];
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < n; i++) b[1 + (f[i] >>> 16)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < n; i++) to[b[f[i] >>> 16]++] = f[i];
int[] d = f;
f = to;
to = d;
}
return f;
}
}
}
// for(Map.Entry<Integer,Integer> Test: map.entrySet()){
// int Key=Test.getKey();
// int val=Test.getValue();
// }
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author bacali
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ACodehorsesTShirts solver = new ACodehorsesTShirts();
solver.solve(1, in, out);
out.close();
}
static class ACodehorsesTShirts {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
String ch = in.next();
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
}
int s = n;
for (int i = 0; i < n; i++) {
String ch = in.next();
if (map.containsKey(ch)) {
if (map.get(ch) == 1) {
map.remove(ch);
} else {
map.put(ch, map.get(ch) - 1);
}
s--;
}
}
out.println(s);
}
}
static class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class TaskA {
public void run() {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out, true);
reader.nextLine();
String statement = reader.next();
if (!statement.startsWith("-")) {
writer.println(statement);
} else {
try {
int statement1 = Integer.parseInt(statement.substring(0, statement.length() - 1));
int statement2 = Integer.parseInt(statement.substring(0, statement.length() - 2) + statement.charAt(statement.length() - 1));
writer.println(Math.max(statement1, statement2));
} catch (Exception e) {
writer.println(statement);
}
}
writer.close();
}
public static void main(String[] args) {
new TaskA().run();
}
private class InputReader {
BufferedReader reader;
StringTokenizer token;
private InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
private String next() {
return token.nextToken();
}
private int nextInt() {
return Integer.parseInt(this.next());
}
private double nextDouble() {
return Double.parseDouble(this.next());
}
private long nextLong() {
return Long.parseLong(this.next());
}
private String nextLine() {
String line = "";
try {
line = reader.readLine();
token = new StringTokenizer(line, " ");
} catch(IOException e) {
}
return line;
}
}
}
|
constant
|
313_A. Ilya and Bank Account
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class NewYearsCurling {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(sc.nextLine());
int n = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
ArrayList<Integer> centers = new ArrayList<Integer>();
st = new StringTokenizer(sc.nextLine());
for (int i = 0; i < n; i++) {
centers.add(Integer.parseInt(st.nextToken()));
}
sc.close();
ArrayList<Point> finalpoints = new ArrayList<Point>();
for (int i = 0; i < n; i++) {
double maxy = r;
for (int j = 0; j < finalpoints.size(); j++) {
if (finalpoints.get(j).x - centers.get(i) > 2 * r || centers.get(i) - finalpoints.get(j).x > 2 * r)
continue;
double dist = Math.sqrt(
4 * r * r - (finalpoints.get(j).x - centers.get(i)) * (finalpoints.get(j).x - centers.get(i)))
+ finalpoints.get(j).y;
if(dist > maxy)
maxy = dist;
}
pw.print(maxy + " ");
finalpoints.add(new Point(centers.get(i), maxy));
}
pw.close();
}
public static class Point {
double x;
double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
}
|
quadratic
|
908_C. New Year and Curling
|
CODEFORCES
|
import java.util.*;
import java.io.*;
/*
6
2 2
5 2
1 5
1 1
3
1 2
1 1
1 2
1 1
1 2
2 3
2 1
1
1
*/
public class e2 {
static int n;
static int m;
static int[][] mat;
public static void main(String[] args){
JS scan = new JS();
PrintWriter out = new PrintWriter(System.out);
int t = scan.nextInt();
long start = System.currentTimeMillis();
for(int q = 1; q <= t; q++){
n = scan.nextInt();
m = scan.nextInt();
// n = 12;
// m = 20000;
mat = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
mat[i][j] = scan.nextInt();
// mat[i][j] = 100000;
}
}
int[] max = new int[m];
PriorityQueue<Item> pq = new PriorityQueue<Item>();
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
max[i] = max(max[i], mat[j][i]);
}
pq.add(new Item(i, max[i]));
}
ArrayList<Item> guys = new ArrayList<Item>();
while(!pq.isEmpty() && guys.size() < n){
Item tt = pq.poll();
guys.add(tt);
}
int[][] cost = new int[guys.size()][1 << n];
// long time = System.currentTimeMillis();
for(int i = 0; i < guys.size(); i++){
int g = guys.get(i).a;
for(int s = 0; s < n; s++){
for(int j = 0; j < (1 << n); j++){
int sum = 0;
for(int k = 0; k < n; k++){
if((j & (1 << k)) > 0){
sum += mat[(k+s)%n][g];
}
}
cost[i][j] = max(cost[i][j], sum);
}
}
}
// for(int i = 0; i < guys.size(); i++) System.out.println(Arrays.toString(cost[i]));
// System.out.println(System.currentTimeMillis()-time);
int full = (1 << n)-1;
// time = System.currentTimeMillis();
int[][] dp = new int[guys.size()+1][1 << n];
int ans = 0;
for(int c = 0; c < guys.size(); c++){
for(int j = 0; j < (1 << n); j++){
for(int i = j; i < (1 << n); i = (i+1)|j){
dp[c+1][i] =
max(dp[c+1][i], cost[c][j]+dp[c][i^j]);
ans = max(ans, dp[c+1][i]);
}
}
}
// for(int i = 0; i < dp.length; i++) System.out.println(Arrays.toString(dp[i]));
// System.out.println(System.currentTimeMillis()-time);
out.println(ans);
}
// System.out.println(System.currentTimeMillis()-start);
out.flush();
}
static int max(int a, int b){
return a > b? a : b;
}
static class Item implements Comparable<Item>{
int a;
int b;
public Item(int a, int b){
this.a = a;
this.b = b;
}
public int compareTo(Item o){
return o.b-this.b;
}
}
static class JS{
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
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 long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
|
np
|
1209_E2. Rotate Columns (hard version)
|
CODEFORCES
|
import java.util.*;
public class C23A {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String str=sc.next();
for(int k=str.length()-1;k>=1;k--){
for(int i=0;i<=str.length()-k;i++){
for(int j=i+1;j<=str.length()-k;j++){
if(str.substring(i,i+k).equals(str.substring(j,j+k))){
System.out.println(k);
return;
}
}
}
}
System.out.println(0);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.SortedSet;
import java.util.Set;
import java.util.NavigableSet;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
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 k = in.nextInt();
char[] c = in.next().toCharArray();
NavigableSet<Integer> ones = new TreeSet<>();
NavigableSet<Integer> zeros = new TreeSet<>();
for (int i = 0; i < n; i++) {
if (c[i] == '0') zeros.add(i);
else ones.add(i);
}
if (ones.isEmpty() || zeros.isEmpty() || ones.last() - ones.first() + 1 <= k || zeros.last() - zeros.first() + 1 <= k) {
out.println("tokitsukaze");
return;
}
if (check(ones, n, k) && check(zeros, n, k)) {
out.println("quailty");
return;
}
out.println("once again");
}
private boolean check(NavigableSet<Integer> ones, int n, int k) {
for (int i = 0; i + k <= n; i++) {
int left = ones.first();
int right = ones.last();
if (left >= i) {
left = ones.higher(i + k - 1);
}
if (right < i + k) {
right = ones.lower(i);
}
if (right - left + 1 > k) {
return false;
}
}
return true;
}
}
static class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
static class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
if (c < 0) {
return null;
}
while (c >= 0 && !isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
}
}
|
linear
|
1190_C. Tokitsukaze and Duel
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
AQuiz solver = new AQuiz();
solver.solve(1, in, out);
out.close();
}
}
static class AQuiz {
int mod = (int) 1e9 + 9;
Power pow = new Power(mod);
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.ri();
int m = in.ri();
int k = in.ri();
long mayPut = (long) (n - m) * (k - 1);
if (mayPut >= m) {
out.println(m);
return;
}
long ans = dup(m - mayPut, k);
ans += mayPut;
ans %= mod;
out.println(ans);
}
public long dup(long n, long k) {
long r = n % k;
n -= r;
long m = n / k;
long ans = k * (pow.pow(2, m + 1) - 2);
ans += r;
ans = DigitUtils.mod(ans, mod);
return ans;
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private static final int THRESHOLD = 32 << 10;
private final Writer os;
private StringBuilder cache = new StringBuilder(THRESHOLD * 2);
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
private void afterWrite() {
if (cache.length() < THRESHOLD) {
return;
}
flush();
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput append(int c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput append(long c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput println(int c) {
return append(c).println();
}
public FastOutput println(long c) {
return append(c).println();
}
public FastOutput println() {
return append('\n');
}
public FastOutput flush() {
try {
// boolean success = false;
// if (stringBuilderValueField != null) {
// try {
// char[] value = (char[]) stringBuilderValueField.get(cache);
// os.write(value, 0, cache.length());
// success = true;
// } catch (Exception e) {
// }
// }
// if (!success) {
os.append(cache);
// }
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int ri() {
return readInt();
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static interface InverseNumber {
}
static class DigitUtils {
private DigitUtils() {
}
public static int mod(long x, int mod) {
if (x < -mod || x >= mod) {
x %= mod;
}
if (x < 0) {
x += mod;
}
return (int) x;
}
}
static class Power implements InverseNumber {
int mod;
public Power(int mod) {
this.mod = mod;
}
public int pow(int x, long n) {
if (n == 0) {
return 1 % mod;
}
long r = pow(x, n >> 1);
r = r * r % mod;
if ((n & 1) == 1) {
r = r * x % mod;
}
return (int) r;
}
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
public class ChainReaction implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
private class Beacon implements Comparable<Beacon> {
private int position, range, score;
private Beacon(int position, int range) {
this.position = position;
this.range = range;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Beacon o) {
return Integer.compare(this.position, o.position);
}
}
public void solve() {
int n = in.ni();
if (n == 1) {
out.println(0);
return;
}
beacons = new ArrayList<>();
for (int i = 0; i < n; i++) {
beacons.add(new Beacon(in.ni(), in.ni()));
}
beacons.sort(Comparator.naturalOrder());
for (int i = 1; i < n; i++) {
int left = 0, right = i - 1, position = beacons.get(i).position, range = beacons.get(i).range;
int leftmost = i;
while (left <= right) {
int mid = left + (right - left) / 2;
if (position - range <= beacons.get(mid).position) {
leftmost = Math.min(leftmost, mid);
right = mid - 1;
} else {
left = mid + 1;
}
}
beacons.get(i).setScore(i - leftmost);
}
dp = new Integer[n];
int ans = Integer.MAX_VALUE;
for (int i = n - 1; i >= 0; i--) {
ans = Math.min(n - 1 - i + recurse(i), ans);
}
out.println(ans);
}
private List<Beacon> beacons;
private Integer[] dp;
private int recurse(int idx) {
if (idx <= 0) return 0;
if (dp[idx] != null) return dp[idx];
int destroyed = beacons.get(idx).score;
int ans = destroyed + recurse(idx - destroyed - 1);
return dp[idx] = ans;
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
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 ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (ChainReaction instance = new ChainReaction()) {
instance.solve();
}
}
}
|
nlogn
|
608_C. Chain Reaction
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String args[]) throws Exception
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int num=Integer.parseInt(in.readLine());
System.out.println((num/2)*(3));
}
}
|
constant
|
84_A. Toy Army
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* Author -
* User: kansal
* Date: 9/3/11
* Time: 5:28 PM
*/
public class CF85C {
public static void main(String[] args) {
reader = new BufferedReader(new InputStreamReader(System.in));
int height = nextInt(), width = nextInt();
if (width > height) {
int t = width;
width = height;
height = t;
}
final int INF = height * width + 10;
final int ALL_BITS = (1 << width) - 1;
int[][][] dp = new int[height + 1][1 << width][1 << width];
for (int[][] ints : dp) {
for (int[] anInt : ints) {
Arrays.fill(anInt, INF);
}
}
dp[0][0][0] = 0;
for(int r = 0; r < height; ++r) {
for(int uncovered = 0; uncovered < (1 << width); ++uncovered) {
for(int mask = 0; mask < (1 << width); ++mask) {
if (dp[r][uncovered][mask] == INF) {
continue;
}
for(int curMask = uncovered; curMask < (1 << width); curMask = (curMask + 1) | uncovered) {
int curCovered = (mask | curMask);
curCovered |= (curMask >> 1);
curCovered |= (ALL_BITS & (curMask << 1));
int curUncovered = ALL_BITS ^ curCovered;
dp[r+1][curUncovered][curMask] = Math.min(dp[r+1][curUncovered][curMask], dp[r][uncovered][mask] + Integer.bitCount(curMask));
}
}
}
}
int res = INF;
for(int x: dp[height][0]) res = Math.min(res, x);
System.out.println(height * width - res);
}
private static boolean hasBit(int mask, int bit) {
return (((mask >> bit) & 1) == 1);
}
public static BufferedReader reader;
public static StringTokenizer tokenizer = null;
static String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
static public int nextInt() {
return Integer.parseInt(nextToken());
}
static public long nextLong() {
return Long.parseLong(nextToken());
}
static public String next() {
return nextToken();
}
static public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
|
np
|
112_E. Petya and Spiders
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class digits {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long k = Long.parseLong(br.readLine());
long temp = 9 * (int)Math.pow(10,0);
int count = 0;
long initial = 0;
while(k > temp) {
count++;
initial = temp;
temp += 9 * (long)Math.pow(10,count)*(count+1);
}
long index = (k-initial-1)%(count+1);
long num = (long)Math.pow(10,count) + (k-initial-1)/(count+1);
System.out.println((num+"").charAt((int)index));
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.util.*;
public class E
{
public static void main(String[] args)
{
new E(new Scanner(System.in));
}
public E(Scanner in)
{
int N = in.nextInt();
double[][] g = new double[N][N];
for (int j=0; j<N; j++)
for (int i=0; i<N; i++)
g[i][j] = in.nextDouble();
double[] memo = new double[1<<N];
memo[(1<<N)-1] = 1.0;
for (int m=(1<<N)-1; m>0; m--)
{
int cnt = 0;
for (int i=0; i<N; i++)
{
int m1 = 1 << i;
if ((m1&m) > 0)
cnt++;
}
int sum = (cnt*(cnt-1))/2;
for (int i=0; i<N; i++)
{
int m1 = 1 << i;
if ((m1&m) == 0) continue;
for (int j=i+1; j<N; j++)
{
int m2 = 1 << j;
if ((m2&m) == 0) continue;
memo[m-m1] += (g[i][j]*memo[m])/sum;
memo[m-m2] += (g[j][i]*memo[m])/sum;
}
}
}
StringBuilder sb = new StringBuilder();
for (int i=0; i<N; i++)
{
double res = memo[1<<i];
sb.append(String.format("%.8f", res));
sb.append(' ');
}
System.out.println(sb.toString().trim());
}
}
|
np
|
16_E. Fish
|
CODEFORCES
|
import java.awt.Point;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt() - 1;
Point[] A = new Point[n];
for (int i = 0; i < n; i++)
A[i] = new Point(in.nextInt(), in.nextInt());
Arrays.sort(A, new Comparator<Point>() {
public int compare(Point o1, Point o2) {
if (o1.x != o2.x)
return o2.x - o1.x;
if (o1.y != o2.y)
return o1.y - o2.y;
return 0;
}
});
int i = k;
int j = k;
while (i >= 0 && A[i].x == A[k].x && A[i].y == A[k].y)
i--;
while (j < n && A[j].x == A[k].x && A[j].y == A[k].y)
j++;
System.out.println(j - i - 1);
}
}
|
nlogn
|
166_A. Rank List
|
CODEFORCES
|
import java.util.*;
public class algo121
{
public static void main(String args[])
{
Scanner ex=new Scanner(System.in);
int n=ex.nextInt();
String a[]=new String[n];
String b[]=new String[n];
for(int i=0;i<n;i++)
a[i]=ex.next();
for(int i=0;i<n;i++)
b[i]=ex.next();
String valid[]={"S","M","L","XS","XL","XXS","XXL","XXXS","XXXL"};
int ai[]=new int[9];
int bi[]=new int[9];
for(int i=0;i<n;i++)
{
for(int j=0;j<9;j++)
{
if(a[i].equals(valid[j]))
ai[j]++;
if(b[i].equals(valid[j]))
bi[j]++;
}
}
int ans=0;
for(int i=0;i<9;i++)
{
if(ai[i]>bi[i])
ans=ans+ai[i]-bi[i];
}
System.out.println(ans);
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run();
}
boolean[][] graph;
public void run() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
graph = new boolean[n][n];
for (int i = 0; i < m; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
graph[a][b] = true;
graph[b][a] = true;
}
long res = 0;
for (int i = 3; i <= n; i++) {
res += solve(i);
}
System.out.println(res);
}
long solve(int n) {
// [0, n)の頂点だけで、n-1 スタートだけ考える
long[][] dp = new long[1 << n][n];
dp[1 << (n-1)][n-1] = 1;
for (int i = 0; i < (1 << n); ++i) {
for (int l = 0; l < n; ++l) if (dp[i][l] > 0) {
for (int x = 0; x < n - 1; ++x) if (graph[l][x] && (i >> x & 1) == 0) {
dp[i | (1 << x)][x] += dp[i][l];
}
}
}
long res = 0;
for (int i = 0; i < (1 << n); ++i) if (Integer.bitCount(i) >= 3) {
for (int l = 0; l < n; ++l) {
if (graph[l][n-1]) res += dp[i][l];
}
}
return res / 2; // n-1 を含むサイクルを右回りと左回り数えてしまったので2で割る
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
// Don't place your source in a package
import javax.swing.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.stream.Stream;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int T=1;
for(int t=0;t<T;t++){
int n=Int();
int k=Int();
int A[][]=new int[n][2];
int a=0,b=0,c=0;
for(int i=0;i<A.length;i++){
A[i][0]=Int();
A[i][1]=Int()-1;
if(A[i][1]==0)a++;
else if(A[i][1]==1)b++;
else c++;
}
Solution sol=new Solution(out);
sol.solution(A,k,a,b,c);
}
out.close();
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Solution{
PrintWriter out;
public Solution(PrintWriter out){
this.out=out;
}
int mod=1000000007;
long dp3[][][][];
public void solution(int A[][],int T,int x,int y,int z){
long res=0;
int n=A.length;
long dp1[][]=new long[x+1][T+1];//a
long dp2[][][]=new long[y+1][z+1][T+1];//bc
dp3=new long[x+2][y+2][z+2][3];
//System.out.println(x+" "+y+" "+z);
//init
long f[]=new long[n+10];
f[0]=f[1]=1;
for(int i=2;i<f.length;i++){
f[i]=f[i-1]*i;
f[i]%=mod;
}
for(int i=0;i<dp3.length;i++){
for(int j=0;j<dp3[0].length;j++){
for(int k=0;k<dp3[0][0].length;k++){
Arrays.fill(dp3[i][j][k],-1);
}
}
}
dp1[0][0]=1;
long newdp1[][]=new long[dp1.length][dp1[0].length];
for(int i=0;i<A.length;i++){//a
int p=A[i][0],type=A[i][1];
if(type==0){
for(int cnt=1;cnt<=x;cnt++){
for(int j=1;j<dp1[0].length;j++){
if(j>=p){
newdp1[cnt][j]+=dp1[cnt-1][j-p];
newdp1[cnt][j]%=mod;
}
}
}
for(int cnt=0;cnt<=x;cnt++){
for(int j=0;j<dp1[0].length;j++){
dp1[cnt][j]+=newdp1[cnt][j];
dp1[cnt][j]%=mod;
newdp1[cnt][j]=0;
}
}
}
}
dp2[0][0][0]=1;
long newdp2[][][]=new long[dp2.length][dp2[0].length][dp2[0][0].length];
for(int i=0;i<A.length;i++){//b c
int p=A[i][0],type=A[i][1];
if(type!=0){
for(int a=0;a<dp2.length;a++){
for(int b=0;b<dp2[0].length;b++){
for(int j=0;j<dp2[0][0].length;j++){
if(j>=p){
if(type==1){
if(a-1>=0){
newdp2[a][b][j]+=dp2[a-1][b][j-p];
}
}
else{
if(b-1>=0) {
newdp2[a][b][j]+=dp2[a][b-1][j-p];
}
}
}
newdp2[a][b][j]%=mod;
}
}
}
for(int a=0;a<dp2.length;a++){
for(int b=0;b<dp2[0].length;b++){
for(int j=0;j<dp2[0][0].length;j++){
dp2[a][b][j]+=newdp2[a][b][j];
dp2[a][b][j]%=mod;
newdp2[a][b][j]=0;
}
}
}
}//type!=0
}
dp3[1][0][0][0]=1;
dp3[0][1][0][1]=1;
dp3[0][0][1][2]=1;
for(int i=0;i<dp3.length;i++){
for(int j=0;j<dp3[0].length;j++){
for(int k=0;k<dp3[0][0].length;k++){
for(x=0;x<dp3[0][0][0].length;x++){
if(dp3[i][j][k][x]==-1){
dfs(i,j,k,x);
}
}
}
}
}
for(int i=0;i<dp3.length-1;i++){
for(int j=0;j<dp3[0].length-1;j++){
for(int k=0;k<dp3[0][0].length-1;k++){
for(int cur=0;cur<3;cur++){
for(int t=0;t<=T;t++){//price
int aprice=t;
int bcprice=T-t;
long cnt1=dp1[i][aprice];
long cnt2=dp2[j][k][bcprice];
long combination=dp3[i][j][k][cur];
long p1=(cnt1*f[i])%mod;
long p2=(((f[j]*f[k])%mod)*cnt2)%mod;
long p3=(p1*p2)%mod;
res+=(p3*combination)%mod;
res%=mod;
}
}
}
}
}
out.println(res);
}
public long dfs(int a,int b,int c,int cur){
if(a<0||b<0||c<0){
return 0;
}
if(a==0&&b==0&&c==0){
return 0;
}
if(dp3[a][b][c][cur]!=-1)return dp3[a][b][c][cur];
long res=0;
if(cur==0){
res+=dfs(a-1,b,c,1);
res%=mod;
res+=dfs(a-1,b,c,2);
res%=mod;
}
else if(cur==1){
res+=dfs(a,b-1,c,0);
res%=mod;
res+=dfs(a,b-1,c,2);
res%=mod;
}
else{
res+=dfs(a,b,c-1,0);
res%=mod;
res+=dfs(a,b,c-1,1);
res%=mod;
}
res%=mod;
dp3[a][b][c][cur]=res;
return res;
}
}
/*
;\
|' \
_ ; : ;
/ `-. /: : |
| ,-.`-. ,': : |
\ : `. `. ,'-. : |
\ ; ; `-.__,' `-.|
\ ; ; ::: ,::'`:. `.
\ `-. : ` :. `. \
\ \ , ; ,: (\
\ :., :. ,'o)): ` `-.
,/,' ;' ,::"'`.`---' `. `-._
,/ : ; '" `;' ,--`.
;/ :; ; ,:' ( ,:)
,.,:. ; ,:., ,-._ `. \""'/
'::' `:'` ,'( \`._____.-'"'
;, ; `. `. `._`-. \\
;:. ;: `-._`-.\ \`.
'`:. : |' `. `\ ) \
-hrr- ` ;: | `--\__,'
'` ,'
,-'
free bug dog
*/
/*
5 3
1 1
2 1
2 1
2 1
2 2
*/
|
cubic
|
1185_G2. Playlist for Polycarp (hard version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
//System.setIn(new FileInputStream("1"));
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = nextInt(), k = nextInt();
int[] primes = new int[n + 1];
for (int i = 2; i <= n; i++) {
if (primes[i] == 0) {
primes[i] = 1;
for (int j = i * 2; j <= n; j += i)
primes[j] = 2;
}
}
ArrayList<Integer> res = new ArrayList<Integer>();
HashSet<Integer> p = new HashSet<Integer>(), v = new HashSet<Integer>();
for (int i = 2; i <= n; i++) {
if (primes[i] == 1) {
res.add(i);
p.add(i);
}
}
int c = 0;
if (res.size() >= 3) {
for (int i = 2; i < res.size(); i++) {
int zz = res.get(i - 2) + res.get(i - 1) + 1;
if (p.contains(zz))
v.add(zz);
}
c = v.size();
}
if (c >= k) {
out.println("YES");
} else {
out.println("NO");
}
in.close();
out.close();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer st;
static String nextString() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
static int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextString());
}
static double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextString());
}
}
|
linear
|
17_A. Noldbach problem
|
CODEFORCES
|
import java.io.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class B {
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static MyScanner sc;
static {
try {
sc = new MyScanner();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
doTask();
out.flush();
}
public static void doTask(){
long n = sc.nextInt();
long k = sc.nextInt();
long c = -2*(n+k);
long d = 9 - 4*c;
double result = n - (-3 + Math.sqrt(1.0*d))/2;
out.println(Math.round(result));
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() throws FileNotFoundException {
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;
}
}
}
|
logn
|
1195_B. Sport Mafia
|
CODEFORCES
|
//package Codeforces.Round718Div1_2;
import java.io.*;
import java.util.*;
public class D {
static boolean isValid(int n, int m, int i, int j){
return 0<=i && i<n && 0<=j && j<m;
}
public static void main(String[] args) throws IOException {
Soumit sc = new Soumit();
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
StringBuilder sb = new StringBuilder();
if(k%2==1){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
sb.append("-1 ");
}
sb.append("\n");
}
System.out.println(sb);
System.exit(0);
}
k/=2;
long[][] horizontaledge = new long[n][m-1];
long[][] verticaledge = new long[n-1][m];
for(int i=0;i<n;i++)
horizontaledge[i] = sc.nextLongArray(m-1);
for(int i=0;i<n-1;i++)
verticaledge[i] = sc.nextLongArray(m);
long[][][] dp = new long[11][n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
dp[0][i][j] = 0;
}
}
for(int i=1;i<=k;i++){
for(int j1=0;j1<n;j1++){
for(int j2=0;j2<m;j2++){
long min = Long.MAX_VALUE/2000;
//for up
if(isValid(n, m, j1-1, j2)){
min = Math.min(dp[i-1][j1-1][j2]+verticaledge[j1-1][j2], min);
}
//for down
if(isValid(n, m, j1+1, j2)){
min = Math.min(min, dp[i-1][j1+1][j2]+verticaledge[j1][j2]);
}
//for left
if(isValid(n, m, j1, j2-1)){
min = Math.min(min, dp[i-1][j1][j2-1]+horizontaledge[j1][j2-1]);
}
//for right
if(isValid(n, m, j1, j2+1)){
min = Math.min(min, dp[i-1][j1][j2+1]+horizontaledge[j1][j2]);
}
dp[i][j1][j2] = min;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
sb.append(dp[k][i][j]*2).append(" ");
}
sb.append("\n");
}
System.out.println(sb);
sc.close();
}
static class Soumit {
final private int BUFFER_SIZE = 1 << 18;
final private DataInputStream din;
final private byte[] buffer;
private PrintWriter pw;
private int bufferPointer, bytesRead;
StringTokenizer st;
public Soumit() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Soumit(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public void streamOutput(String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void println(String a) {
pw.println(a);
}
public void print(String a) {
pw.print(a);
}
public String readLine() throws IOException {
byte[] buf = new byte[3000064]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public void sort(int[] arr) {
ArrayList<Integer> arlist = new ArrayList<>();
for (int i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public void sort(long[] arr) {
ArrayList<Long> arlist = new ArrayList<>();
for (long i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
/*if (din == null)
return;*/
if (din != null) din.close();
if (pw != null) pw.close();
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
//package round35;
import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class C {
Scanner in;
PrintWriter out;
// String INPUT = "3 3 1 1 1";
String INPUT = "";
void solve()
{
int n = ni();
int m = ni();
int k = ni();
int[] x = new int[k];
int[] y = new int[k];
for(int i = 0;i < k;i++){
x[i] = ni() - 1;
y[i] = ni() - 1;
}
int max = -1;
int maxi = -1;
int maxj = -1;
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
int min = Integer.MAX_VALUE;
for(int l = 0;l < k;l++){
min = Math.min(min, Math.abs(x[l] - i) + Math.abs(y[l] - j));
}
if(min > max){
max = min;
maxi = i;
maxj = j;
}
}
}
out.println((maxi+1) + " " + (maxj+1));
}
void run() throws Exception
{
in = INPUT.isEmpty() ? new Scanner(new File("input.txt")) : new Scanner(INPUT);
out = INPUT.isEmpty() ? new PrintWriter("output.txt") : new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception
{
new C().run();
}
int ni() { return Integer.parseInt(in.next()); }
void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); }
static String join(int[] a, int d){StringBuilder sb = new StringBuilder();for(int v : a){sb.append(v + d + " ");}return sb.toString();}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.util.*;
public class algo93
{
public static void main(String args[])
{
Scanner ex=new Scanner(System.in);
long x=ex.nextLong();
long k=ex.nextLong();
long mod=1000000007;
if(k==0)
System.out.println((2*x)%mod);
else if(x==0)
System.out.println("0");
else
{
long pow=power(2,k);
long pow1=(2*pow)%mod;
long ans=(pow1*(x%mod))-pow+1;
if(ans<0)
ans=ans+mod;
ans=ans%mod;
System.out.println(ans);
}
}
public static long power(long x,long y)
{
if (y == 0)
return 1;
long mod=1000000007;
long pow=power(x,y/2);
pow=(pow*pow)%mod;
if(y%2==0)
return pow;
else
return ((x%mod)*pow)%mod;
}
}
|
logn
|
992_C. Nastya and a Wardrobe
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Codeforces
{
public static void main(String args[])throws Exception
{
BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
int t=Integer.parseInt(bu.readLine());
while(t-->0)
{
int n=Integer.parseInt(bu.readLine());
int cur[]=new int[n],i,cr=-1;
for(i=0;i<n;i++)
{
int j,d=Integer.parseInt(bu.readLine()),f=-1;
for(j=cr;j>=0;j--)
if(cur[j]==d-1) {f=j; break;}
if(f==-1)
{
cr++;
f=cr;
}
cur[f]=d;
cr=f;
for(j=f+1;j<n;j++) cur[j]=0;
sb.append(cur[0]);
for(j=1;j<n;j++)
if(cur[j]==0) break;
else sb.append("."+cur[j]);
sb.append("\n");
}
}
System.out.print(sb);
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static long GCF(long a, long b) {
if(b == 0) return a;
else return GCF(b, a%b);
}
public static long LCM(long a, long b){
return a*b / GCF(a, b);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
if(n < 3) System.out.println(n);
else{
long t1 = LCM(n, n-1);
long t2 = LCM(n-2, n-3);
long l1 = LCM(t1, n-2);
long l2 = LCM(t1, n-3);
long l3 = LCM(n, t2);
long l4 = LCM(n-1, t2);
System.out.println(Math.max(l1, Math.max(l2, Math.max(l3, l4))));
}
}
}
|
constant
|
235_A. LCM Challenge
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class A2 {
/*
*/
public static void main(String[] args) throws Exception {
uu.s1();
uu.out.close();
}
public static class uu {
public static BR in = new BR();
public static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static boolean bg = true;
public static MOD m1 = new MOD(1000000000+9);
public static long mod = 1000000000+9;
public static void s1() throws Exception {
long n = in.ni();
long m = in.ni();
long k = in.ni();
long lose = n - m;
long aval = m / (k - 1l);
long times1 = Math.min(lose, aval);
long notused = times1 * (k - 1l);
long used = m - notused;
long blocks = used / k;
long left = used % k;
long k1 = 0;
if (blocks != 0){
k1 = m1.pow(2, blocks+1);
k1 = m1.s(k1, 2);
}
long ans = (m1.t(k, k1)+left + notused)%mod;
pn(ans);
}
public static void geom(long f1){
}
public static void s2() throws Exception {
}
public static void s3() throws Exception {
}
private static void pn(Object... o1) {
for (int i = 0; i < o1.length; i++){
if (i!= 0) out.print(" ");
out.print(o1[i]);
}
out.println();
}
public static boolean allTrue(boolean ... l1){
for (boolean e: l1) if (!e) return false;
return true;
}
public static boolean allFalse(boolean ... l1){
for (boolean e: l1) if (e) return false;
return true;
}
}
private static class MOD {
public long mod = -1;
public MOD(long k1) {
mod = k1;
}
public long cl(long n1){
long fin = n1%mod;
if (fin<0) fin+= mod;
return fin;
}
public long s(long n1, long n2) {
long k1 = (n1 - n2) % mod;
if (k1 < 0)
k1 += mod;
return k1;
}
public long t(long n1, long n2) {
long k1 = (n1 * n2) % mod;
if (k1 < 0)
k1 += mod;
return k1;
}
public static long xgcd(long n1, long n2) {
long k1 = n1;
long k2 = n2;
long[] l1 = { 1, 0 };
long[] l2 = { 0, 1 };
for (;;) {
long f1 = k1 / k2;
long f2 = k1 % k2;
if (f2 == 0)
break;
long[] l3 = { 0, 0 };
l3[0] = l1[0] - f1 * l2[0];
l3[1] = l1[1] - f1 * l2[1];
l1 = l2;
l2 = l3;
k1 = k2;
k2 = f2;
}
long fin = l2[1] % n1;
if (fin < 0) {
fin += n1;
}
return fin;
}
public long pow(long n1, long pow) {
if (pow == 0)
return 1;
else if (pow == 1)
return t(1l, n1);
else if ((pow & 1) == 0) {
long half = pow(n1, pow >> 1);
return t(half, half);
} else {
long half = pow(n1, pow >> 1);
return t(half, t(half, n1));
}
}
public long factorial(long k1, long n1) {
long fin = 1;
long q1 = k1;
for (int i = 0; i < n1; i++) {
fin = t(fin, q1);
q1--;
if (q1 <= 0)
break;
}
return cl(fin);
}
}
private static class BR {
BufferedReader k1 = null;
StringTokenizer k2 = null;
public BR() {
k1 = new BufferedReader(new InputStreamReader(System.in));
}
public String nx() throws Exception {
for (;;) {
if (k2 == null || !k2.hasMoreTokens()) {
String temp = k1.readLine();
if (temp == null)
return null;
k2 = new StringTokenizer(temp);
}
else
break;
}
return k2.nextToken();
}
public int ni() throws Exception {
return Integer.parseInt(nx());
}
}
}
|
logn
|
338_A. Quiz
|
CODEFORCES
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.solve());
}
private int solve() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[m];
for (int i = 0; i < m; ++i) a[i] = in.nextInt();
if (n > m) return 0;
Map<Integer, Integer> map = new HashMap<>();
for (int k: a) map.put(k, map.getOrDefault(k, 0) + 1);
List<Integer> keySet = new ArrayList<>(map.keySet());
int end = m / n;
keySet.sort((u, v) -> -Integer.compare(u, v));
do {
int count = 0;
for (int k: keySet) {
count += map.get(k) / end;
if (count >= n) return end;
}
} while (--end > 0);
return 0;
}
}
|
nlogn
|
1011_B. Planning The Expedition
|
CODEFORCES
|
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author madi
*/
public class GivenString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String sub = "";
int count = 0;
int max = 0;
for (int i = 0; i < line.length() - 1; i++) {
sub = line.substring(i, i + 1);
int q = i + 1;
int p;
int r = i;
while (q < line.length() && q > 0) {
p = q;
r = i;
int ind = line.indexOf(sub, p);
count = 0;
if (ind != -1) {
for (int j = ind; j < line.length(); j++) {
if (line.substring(j, j + 1).equalsIgnoreCase(line.substring(r, r + 1))) {
r++;
count++;
} else {
break;
}
}
if (count > max) {
max = count;
}
}
q = ind + 1;
}
}
System.out.println(max);
}
}
|
cubic
|
23_A. You're Given a String...
|
CODEFORCES
|
import java.util.Scanner;
public class digits
{
public static void main(String[] args)
{
long k = (new Scanner(System.in)).nextLong();
//k = 56
//League 1: 0 - 9
//League 2: 10 - 99
//League 3: 100 - 999..
//System.out.println("k = "+k);
long league = 1;
long irrelevancy = 0;
while(true)
{
irrelevancy += league * (Math.pow(10, league) - Math.pow(10, league-1));
if(k > irrelevancy)
league ++;
//league = 1 : k = 56 > 9
//league = 2 : k = 56 < 99
//therefore league = 2
else
break;
}
//System.out.println("League = "+league);
irrelevancy = 0;
for(long i=1; i<league; i++)
irrelevancy += i * (Math.pow(10, i) - Math.pow(10, i-1));
//irrelevancy = 1 * (10^1 - 10^0) = 9
long modified_k = k - irrelevancy;
//modified_k = 56 - 9 = 47
//System.out.println("modified k = "+ modified_k);
long number = (long)(Math.pow(10, league-1)) - 1 + modified_k / league;
//System.out.println("number = "+number);
if(modified_k % league == 0)
System.out.println(number % 10);
else
{
number ++;
long position_of_digit = (long)(modified_k % league);
//System.out.println(position_of_digit);
//number = 24
//position_of_digit = 47 % 2 = 1
System.out.println((Long.toString(number)).charAt((int)position_of_digit-1));
}
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class LittleGirlAndXor {
static long L, R;
static Long[][][][][] dp = new Long[64][2][2][2][2];
public static long go(int index, int low1, int high1, int low2, int high2) {
if (index == -1) {
return 0;
}
if (dp[index][low1][high1][low2][high2] != null)
return dp[index][low1][high1][low2][high2];
int bit1 = (L & (1L << index)) == 0 ? 0 : 1;
int bit2 = (R & (1L << index)) == 0 ? 0 : 1;
long res = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
int nl1 = low1, nh1 = high1, nl2 = low2, nh2 = high2;
boolean can = true;
if (low1 == 0) {
if (i == bit1) {
nl1 = 0;
} else if (i < bit1) {
can = false;
} else if (i > bit1) {
nl1 = 1;
}
}
if (high1 == 0) {
if (i == bit2) {
nh1 = 0;
} else if (i < bit2) {
nh1 = 1;
} else if (i > bit2) {
can = false;
}
}
if (low2 == 0) {
if (j == bit1) {
nl2 = 0;
} else if (j < bit1) {
can = false;
} else if (j > bit1) {
nl2 = 1;
}
}
if (high2 == 0) {
if (j == bit2) {
nh2 = 0;
} else if (j < bit2) {
nh2 = 1;
} else if (j > bit2) {
can = false;
}
}
if (can){
long xor = i^j;
res = Math.max(res, (xor<<index)+go(index - 1, nl1, nh1, nl2, nh2));
}
}
}
return dp[index][low1][high1][low2][high2] = res;
}
public static void main(String[] args) {
InputReader r = new InputReader(System.in);
L = r.nextLong();
R = r.nextLong();
System.out.println(go(63,0,0,0,0));
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
logn
|
276_D. Little Girl and Maximum XOR
|
CODEFORCES
|
import java.util.Scanner;
/**
* Write a description of class lukno here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class lukno
{
public static void main (String args[])
{
Scanner i= new Scanner(System.in);
int n,p;
n=i.nextInt(); int t=n;
if(t%4==0||t%7==0||t%47==0||t%74==0||t%44==0||t%447==0||t%474==0||t%477==0)
System.out.print("YES");
else System.out.print("NO");
}
}
|
constant
|
122_A. Lucky Division
|
CODEFORCES
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ijxjdjd
*/
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);
SameSumBlocks solver = new SameSumBlocks();
solver.solve(1, in, out);
out.close();
}
static class SameSumBlocks {
int N;
public void solve(int testNumber, InputReader in, PrintWriter out) {
N = in.nextInt();
int[] arr = new int[N];
for (int i = 1; i <= N; i++) {
arr[i - 1] = in.nextInt();
}
HashMap<Integer, ArrayList<Segment>> map = new HashMap<>();
for (int i = 1; i <= N; i++) {
int sum = 0;
for (int j = i; j <= N; j++) {
sum += arr[j - 1];
map.putIfAbsent(sum, new ArrayList<>());
map.get(sum).add(new Segment(i, j));
}
}
int resI = 0;
int resVal = 0;
int sum = 0;
if (arr.length > 1 && arr[1] == -999) {
for (int i = 11; i < 130; i++) {
sum += arr[i];
}
}
for (int key : map.keySet()) {
if (map.get(key).size() > resI) {
int next = largestNon(map.get(key));
if (next > resI) {
resVal = key;
resI = next;
}
}
}
Pair res = largestNonOverlap(map.get(resVal));
out.println(resI);
for (int i = 0; i < resI; i++) {
out.println(res.used.get(i).li + " " + res.used.get(i).ri);
}
}
int largestNon(ArrayList<Segment> arr) {
Collections.sort(arr, new Comparator<Segment>() {
public int compare(Segment o1, Segment o2) {
return Integer.compare(o1.ri, o2.ri);
}
});
SameSumBlocks.SegmentTree seg = new SameSumBlocks.SegmentTree(N + 1);
for (int i = 0; i < arr.size(); i++) {
seg.add(arr.get(i).ri, arr.get(i).ri, 1 + seg.query(0, arr.get(i).li - 1).mx);
}
return seg.query(0, N).mx;
}
Pair largestNonOverlap(ArrayList<Segment> arr) {
Segment[] segs = new Segment[N + 1];
int[] dp = new int[N + 1];
for (int i = 0; i <= N; i++) {
segs[i] = new Segment(-1, 0);
}
for (Segment s : arr) {
if (s.li > segs[s.ri].li) {
segs[s.ri] = s;
}
}
int[] used = new int[N + 1];
for (int i = 1; i <= N; i++) {
dp[i] = dp[i - 1];
used[i] = used[i - 1];
if (segs[i].li != -1) {
if (dp[i] < dp[segs[i].li - 1] + 1) {
used[i] = i;
dp[i] = dp[segs[i].li - 1] + 1;
}
}
}
ArrayList<Segment> res = new ArrayList<>();
int u = used[N];
while (segs[u].li > 0) {
res.add(segs[u]);
u = used[segs[u].li - 1];
}
return new Pair(dp[N], res);
}
class Segment {
int li;
int ri;
Segment() {
}
Segment(int li, int ri) {
this.li = li;
this.ri = ri;
}
}
class Pair {
int val;
ArrayList<Segment> used = new ArrayList<>();
Pair(int val, ArrayList<Segment> used) {
this.val = val;
this.used = used;
}
}
static class SegmentTree {
Node[] tree;
int size = 0;
public Node none() {
//return a node that will do nothing while merging: ex. Infinity for min query, -Infinity for max query, 0 for sum
Node res = new Node();
return res;
}
public SegmentTree(int N) {
tree = new Node[4 * N];
size = N;
for (int i = 0; i < 4 * N; i++) {
tree[i] = new Node();
}
}
Node combine(Node a, Node b) {
//change when doing different operations
Node res = new Node();
res.mx = Math.max(a.mx, b.mx);
return res;
}
public Node query(int l, int r) {
return queryUtil(1, 0, size - 1, l, r);
}
public Node queryUtil(int n, int tl, int tr, int l, int r) {
//node number, cur range of node, cur range of query
if (l > r) {
return none();
}
if (tl == l && tr == r) {
return tree[n];
}
int tm = (tl + tr) / 2;
return combine(queryUtil(2 * n, tl, tm, l, Math.min(r, tm)), queryUtil(2 * n + 1, tm + 1, tr, Math.max(tm + 1, l), r));
}
public void add(int l, int r, int val) {
//change query, not assignment
addUtil(1, 0, size - 1, l, r, val);
}
public void addUtil(int n, int tl, int tr, int l, int r, int val) {
if (l > r) {
return;
}
if (tl == l && tr == r) {
tree[n].update(val);
} else {
int tm = (tl + tr) / 2;
addUtil(2 * n, tl, tm, l, Math.min(tm, r), val);
addUtil(2 * n + 1, tm + 1, tr, Math.max(l, tm + 1), r, val);
tree[n] = combine(tree[2 * n], tree[2 * n + 1]);
}
}
class Node {
int mx = 0;
int lzy = 0;
void update(int val) {
mx = Math.max(mx, val);
lzy += val;
}
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
quadratic
|
1141_F2. Same Sum Blocks (Hard)
|
CODEFORCES
|
import java.util.Scanner;
public class B {
static int n;
static double A;
static int[] L;
static int[] B;
static double max = 0;
public static void rec(int index, int k) {
if (k < 0)
return;
if (index == n) {
double prob = 0;
for (int i = 0; i < (1 << n); i++) {
double b = 0;
double temp = 1.0;
for (int j = 0; j < n; j++) {
if (L[j] > 100)
return;
if ((i & (1 << j)) == 0) {
b += B[j];
temp *= (100 - L[j]) / 100.0;
} else
temp *= L[j] / 100.0;
}
if (Integer.bitCount(i) * 2 <= n)
temp *= A / (A + b);
prob += temp;
}
max = Math.max(max, prob);
return;
}
L[index] += 10;
rec(index, k - 1);
L[index] -= 10;
rec(index + 1, k);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
int k = in.nextInt();
A = in.nextDouble();
B = new int[n];
L = new int[n];
for (int i = 0; i < n; i++) {
B[i] = in.nextInt();
L[i] = in.nextInt();
}
rec(0, k);
System.out.println(max);
}
}
|
np
|
105_B. Dark Assembly
|
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.HashSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class AA {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int d =sc.nextInt();
int[] hotels = new int[n];
for (int i = 0; i < hotels.length; i++) {
hotels[i] = sc.nextInt();
}
int count = 0;
for (int i = 0; i < hotels.length-1; i++) {
int one = hotels[i];
int two = hotels[i+1];
double mid = (two-one)*1.0/2.0;
if(mid==d) {
count++;
// System.out.println("hello"+" "+i+" "+(i+1));
}
else if(mid>d) {
// System.out.println("hello2"+" "+i+" "+(i+1));
count+=2;
}
}
count+=2;
System.out.println(count);
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}//19 91 991 919 199
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
linear
|
1004_A. Sonya and Hotels
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class TaskA
{
public static void main(String[] args)
{
new TaskA(System.in, System.out);
}
static class Solver implements Runnable
{
int n;
String[] last, curr;
BufferedReader in;
PrintWriter out;
void solve() throws IOException
{
n = Integer.parseInt(in.readLine());
last = new String[n];
curr = new String[n];
for (int i = 0; i < n; i++)
last[i] = in.readLine();
for (int i = 0; i < n; i++)
curr[i] = in.readLine();
int changes = 0;
String[] sizes = new String[]{"S", "M", "L", "XS", "XXS", "XXXS", "XL", "XXL", "XXXL"};
int[] old = count(last, sizes);
int[] now = count(curr, sizes);
for (int i= 0; i < sizes.length; i++)
{
changes += Math.abs(old[i] - now[i]);
}
out.println(changes / 2);
/* if (now[0] > old[0])
{
int add = now[0] - old[0];
changes += add;
}*/
}
int[] count(String[] s, String[] sizes)
{
int len = sizes.length;
int[] cnt = new int[len];
for (int i = 0; i < len; i++)
{
for (String str : s)
{
if (str.equals(sizes[i]))
cnt[i]++;
}
}
return cnt;
}
void debug(Object... o)
{
System.err.println(Arrays.deepToString(o));
}
public Solver(BufferedReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
@Override
public void run()
{
try
{
solve();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
static class CMath
{
static long power(long number, long power)
{
if (number == 1 || number == 0 || power == 0)
return 1;
if (power == 1)
return number;
if (power % 2 == 0)
return power(number * number, power / 2);
else
return power(number * number, power / 2) * number;
}
static long modPower(long number, long power, long mod)
{
if (number == 1 || number == 0 || power == 0)
return 1;
number = mod(number, mod);
if (power == 1)
return number;
long square = mod(number * number, mod);
if (power % 2 == 0)
return modPower(square, power / 2, mod);
else
return mod(modPower(square, power / 2, mod) * number, mod);
}
static long moduloInverse(long number, long mod)
{
return modPower(number, mod - 2, mod);
}
static long mod(long number, long mod)
{
return number - (number / mod) * mod;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
static long min(long... arr)
{
long min = arr[0];
for (int i = 1; i < arr.length; i++)
min = Math.min(min, arr[i]);
return min;
}
static long max(long... arr)
{
long max = arr[0];
for (int i = 1; i < arr.length; i++)
max = Math.max(max, arr[i]);
return max;
}
static int min(int... arr)
{
int min = arr[0];
for (int i = 1; i < arr.length; i++)
min = Math.min(min, arr[i]);
return min;
}
static int max(int... arr)
{
int max = arr[0];
for (int i = 1; i < arr.length; i++)
max = Math.max(max, arr[i]);
return max;
}
}
static class Utils
{
static boolean nextPermutation(int[] arr)
{
for (int a = arr.length - 2; a >= 0; --a)
{
if (arr[a] < arr[a + 1])
{
for (int b = arr.length - 1; ; --b)
{
if (arr[b] > arr[a])
{
int t = arr[a];
arr[a] = arr[b];
arr[b] = t;
for (++a, b = arr.length - 1; a < b; ++a, --b)
{
t = arr[a];
arr[a] = arr[b];
arr[b] = t;
}
return true;
}
}
}
}
return false;
}
}
public TaskA(InputStream inputStream, OutputStream outputStream)
{
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
PrintWriter out = new PrintWriter(outputStream);
Thread thread = new Thread(null, new Solver(in, out), "TaskA", 1 << 29);
try
{
thread.start();
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
out.flush();
out.close();
}
}
}
|
linear
|
1000_A. Codehorses T-shirts
|
CODEFORCES
|
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static int n;
public static int m;
public static int k;
public static int[][] right;
public static int[][] down;
public static int[][][] dp;
public static void recur(int i, int j, int depth)
{
if(dp[i][j][depth]!=-1)
return;
int min=Integer.MAX_VALUE;
// left
if(j>0)
{
recur(i, j-1, depth-1);
min=Math.min(min, dp[i][j-1][depth-1] + right[i][j-1]);
}
// right
if(j<m-1)
{
recur(i, j+1, depth-1);
min=Math.min(min, dp[i][j+1][depth-1] + right[i][j]);
}
// up
if(i>0)
{
recur(i-1, j, depth-1);
min=Math.min(min, dp[i-1][j][depth-1] + down[i-1][j]);
}
// down
if(i<n-1)
{
recur(i+1, j, depth-1);
min=Math.min(min, dp[i+1][j][depth-1] + down[i][j]);
}
dp[i][j][depth]=min;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
m=sc.nextInt();
k=sc.nextInt();
right=new int[n][m-1];
down=new int[n-1][m];
for(int i=0;i<n;i++)
for(int j=0;j<m-1;j++)
right[i][j]=sc.nextInt();
for(int i=0;i<n-1;i++)
for(int j=0;j<m;j++)
down[i][j]=sc.nextInt();
if(k%2==1) {
for(int i=0;i<n;++i) {
for (int j = 0; j < m; j++)
System.out.print(-1 + " ");
System.out.println();
}
}
else
{
k/=2;
dp=new int[n][m][k+1];
for(int i=0;i<n;++i)
for(int j=0;j<m;j++)
for(int z=1;z<=k;z++)
dp[i][j][z]=-1;
for(int i=0;i<n;++i)
for(int j=0;j<m;j++)
recur(i,j,k);
for(int i=0;i<n;++i) {
for (int j = 0; j < m; j++)
System.out.print((dp[i][j][k] * 2) + " ");
System.out.println();
}
}
}
}
|
cubic
|
1517_D. Explorer Space
|
CODEFORCES
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main implements Runnable {
final static int mod = 1000000007;
static FastReader sc;
static PrintWriter out;
static boolean test_case_input = true;
static final int MAX = 1000000000;
static final int MIN = -1000000000;
public static void print(int a[], int point) {
out.print(a[1]);
for(int i = 2; i <= point; i++) {
out.print("." + a[i]);
}
out.println();
}
public static void solution(int test_case) throws IOException {
// code
int n = sc.nextInt();
int a[] = sc.intarr(n);
int lev[] = new int[n + 1];
lev[1] = 1;
int point = 1;
out.println(1);
for(int i=1; i < n; i++) {
if(a[i] == 1) {
point++;
lev[point] = 1;
print(lev, point);
}
else if(a[i] == lev[point] + 1) {
lev[point]++;
print(lev, point);
}
else {
while(lev[point] + 1 != a[i]) {
point--;
}
lev[point]++;
print(lev, point);
}
}
}
// log A base B
public static int logint(int x, int base) {
return (int) (Math.log(x) / Math.log(base));
}
public static int logint(long x, long base) {
return (int) (Math.log(x) / Math.log(base));
}
public static int logint(double x, double base) {
return (int) (Math.log(x) / Math.log(base));
}
public static double logdouble(int x, int base) {
return (Math.log(x) / Math.log(base));
}
public static double logdouble(long x, long base) {
return (Math.log(x) / Math.log(base));
}
public static double logdouble(double x, double base) {
return (Math.log(x) / Math.log(base));
}
public static long loglong(int x, int base) {
return (long) (Math.log(x) / Math.log(base));
}
public static long loglong(long x, long base) {
return (long) (Math.log(x) / Math.log(base));
}
public static long loglong(double x, double base) {
return (long) (Math.log(x) / Math.log(base));
}
// Debug
public static void debug(String msg, Object value) {
File output = new File("output.txt");
if (!output.exists()) return;
String type = value.getClass().getSimpleName();
if (type.equals("int[]")) out.println(msg + " => " + Arrays.toString((int[]) value));
else if (type.equals("double[]")) out.println(msg + " => " + Arrays.toString((double[]) value));
else if (type.equals("float[]")) out.println(msg + " => " + Arrays.toString((float[]) value));
else if (type.equals("long[]")) out.println(msg + " => " + Arrays.toString((long[]) value));
else if (type.equals("char[]")) out.println(msg + " => " + Arrays.toString((char[]) value));
else if (type.equals("String[]")) out.println(msg + " => " + Arrays.toString((String[]) value));
else if (type.equals("int[][]")) {
out.println(msg + "=>");
for (int i[] : (int[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else if (type.equals("double[][]")) {
out.println(msg + "=>");
for (double i[] : (double[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else if (type.equals("float[][]")) {
out.println(msg + "=>");
for (float i[] : (float[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else if (type.equals("long[][]")) {
out.println(msg + "=>");
for (long i[] : (long[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else if (type.equals("char[][]")) {
out.println(msg + "=>");
for (char i[] : (char[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else if (type.equals("String[][]")) {
out.println(msg + "=>");
for (String i[] : (String[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else out.println(msg + " => " + value);
}
public static void debug(Object value) {
File output = new File("output.txt");
if (!output.exists()) return;
String type = value.getClass().getSimpleName();
if (type.equals("int[]")) out.println(" => " + Arrays.toString((int[]) value));
else if (type.equals("double[]")) out.println(" => " + Arrays.toString((double[]) value));
else if (type.equals("float[]")) out.println(" => " + Arrays.toString((float[]) value));
else if (type.equals("long[]")) out.println(" => " + Arrays.toString((long[]) value));
else if (type.equals("char[]")) out.println(" => " + Arrays.toString((char[]) value));
else if (type.equals("String[]")) out.println(" => " + Arrays.toString((String[]) value));
else if (type.equals("int[][]")) {
out.println("=>");
for (int i[] : (int[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else if (type.equals("double[][]")) {
out.println("=>");
for (double i[] : (double[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else if (type.equals("float[][]")) {
out.println("=>");
for (float i[] : (float[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else if (type.equals("long[][]")) {
out.println("=>");
for (long i[] : (long[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else if (type.equals("char[][]")) {
out.println("=>");
for (char i[] : (char[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else if (type.equals("String[][]")) {
out.println("=>");
for (String i[] : (String[][]) value)
out.println(" . " + Arrays.toString(i).replace(' ', '\t'));
} else out.println(" => " + value);
}
// Graph Functions
public static void addUndirectedEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) {
adj.get(u).add(v);
adj.get(v).add(u);
}
public static void addDirectedEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) {
adj.get(u).add(v);
}
public static <T> void addUndirectedEdge(ArrayList<ArrayList<Point>> adj, int u, int v, T weight) {
adj.get(u).add(new Point(v, weight));
adj.get(v).add(new Point(u, weight));
}
public static <T> void addDirectedEdge(ArrayList<ArrayList<Point>> adj, int u, int v, T weight) {
adj.get(u).add(new Point(v, weight));
}
public static <T> void toString(String msg, ArrayList<ArrayList<T>> adj) {
out.println(msg + ":");
int count = 0;
for (ArrayList<T> i : adj) {
out.print("\t" + count++ + ": ");
for (T j : i) {
out.print(j + " ");
}
out.println();
}
}
public static void addUndirectedEdge(Map<Integer, ArrayList<Integer>> adj, int u, int v) {
if (adj.containsKey(u)) {
ArrayList<Integer> temp = adj.get(u);
temp.add(v);
adj.put(u, temp);
} else {
ArrayList<Integer> temp = new ArrayList<>();
temp.add(v);
adj.put(u, temp);
}
if (adj.containsKey(v)) {
ArrayList<Integer> temp = adj.get(v);
temp.add(u);
adj.put(v, temp);
} else {
ArrayList<Integer> temp = new ArrayList<>();
temp.add(u);
adj.put(v, temp);
}
}
public static void addDirectedEdge(Map<Integer, ArrayList<Integer>> adj, int u, int v) {
if (adj.containsKey(u)) {
ArrayList<Integer> temp = adj.get(u);
temp.add(v);
adj.put(u, temp);
} else {
ArrayList<Integer> temp = new ArrayList<>();
temp.add(v);
adj.put(u, temp);
}
}
public static <T> void addUndirectedEdge(Map<Integer, ArrayList<Point>> adj, int u, int v, T weight) {
if (adj.containsKey(u)) {
ArrayList<Point> temp = adj.get(u);
temp.add(new Point(v, weight));
adj.put(u, temp);
} else {
ArrayList<Point> temp = new ArrayList<>();
temp.add(new Point(v, weight));
adj.put(u, temp);
}
if (adj.containsKey(v)) {
ArrayList<Point> temp = adj.get(v);
temp.add(new Point(u, weight));
adj.put(v, temp);
} else {
ArrayList<Point> temp = new ArrayList<>();
temp.add(new Point(u, weight));
adj.put(v, temp);
}
}
public static <T> void addDirectedEdge(Map<Integer, ArrayList<Point>> adj, int u, int v, T weight) {
if (adj.containsKey(u)) {
ArrayList<Point> temp = adj.get(u);
temp.add(new Point(v, weight));
adj.put(u, temp);
} else {
ArrayList<Point> temp = new ArrayList<>();
temp.add(new Point(v, weight));
adj.put(u, temp);
}
}
public static <T> void toString(String msg, Map<T, ArrayList<T>> adj) {
out.println(msg + ":");
for (Map.Entry<T, ArrayList<T>> entry : adj.entrySet()) {
out.println("\t" + entry.getKey() + ": " + entry.getValue());
}
}
// GCD
public static int __gcd(int a, int b) {
BigInteger n1 = BigInteger.valueOf(a);
BigInteger n2 = BigInteger.valueOf(b);
BigInteger gcd = n1.gcd(n2);
return gcd.intValue();
}
public static long __gcd(long a, long b) {
BigInteger n1 = BigInteger.valueOf(a);
BigInteger n2 = BigInteger.valueOf(b);
BigInteger gcd = n1.gcd(n2);
return gcd.longValue();
}
public static void main(String args[]) throws IOException {
new Thread(null, new Main(), "random", 1 << 26).start();
}
@Override
public void run() {
long start = 0, end = 0;
try {
File output = new File("output.txt");
sc = new FastReader();
if (output.exists()) {
out = new PrintWriter(new FileOutputStream("output.txt"));
start = System.nanoTime();
} else {
out = new PrintWriter(System.out);
}
int test_cases = 1;
if (test_case_input) test_cases = sc.nextInt();
for (int i = 1; i <= test_cases; i++) {
solution(i);
}
if (output.exists()) {
end = System.nanoTime();
out.println("Execution time: " + (end - start) / 1000000 + " ms");
}
out.flush();
out.close();
} catch (Exception e) {
out.println("Exception: " + e);
out.println("At Line no. : " + e.getStackTrace()[0].getLineNumber());
out.flush();
out.close();
return;
}
}
// Edge Class
static class Edge implements Comparable<Edge> {
Object u;
Object v;
Object wt;
public Edge(Object origin, Object destination, Object weight) {
u = origin;
v = destination;
wt = weight;
}
public String toString() {
String ans = u + " -> " + v + " : " + wt;
return ans;
}
public int getIntOrigin() {
return (int) u;
}
public int getIntDestination() {
return (int) v;
}
public int getIntWeight() {
return (int) wt;
}
public long getLongOrigin() {
return (long) u;
}
public long getLongDestination() {
return (long) v;
}
public long getLongWeight() {
return (long) wt;
}
@Override
public int compareTo(Edge edge) {
if ((edge.u).getClass() == Long.class) return (((Long) this.wt).compareTo((Long) edge.wt));
else return (((Integer) this.wt).compareTo((Integer) edge.wt));
}
}
// Point Class
static class Point implements Comparable<Point> {
Object x;
Object y;
public Point(Object a, Object b) {
x = a;
y = b;
}
public int getIntX() {
return (int) x;
}
public int getIntY() {
return (int) y;
}
public long getLongX() {
return (long) x;
}
public long getLongY() {
return (long) y;
}
public int compareTo(Point obj) {
if (obj.x.equals(this.x)) {
if ((obj.y).getClass() == Long.class) return ((Long) this.y).compareTo((Long) obj.y);
else return ((Integer) this.y).compareTo((Integer) obj.y);
} else {
if ((obj.x).getClass() == Long.class) return ((Long) this.x).compareTo((Long) obj.x);
else return ((Integer) this.x).compareTo((Integer) obj.x);
}
}
public String toString() {
String ans = "(" + x + ", " + y + ")";
return ans;
}
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + (int) this.x;
hash = 71 * hash + (int) this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
Point point = (Point) obj;
if (point.x.equals(this.x) && point.y.equals(this.y)) return true;
else return false;
}
}
// Fast IO
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() throws FileNotFoundException {
File in = new File("input.txt");
if (in.exists()) {
br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
} else {
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());
}
float nextFloat() {
return Float.parseFloat(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] intarr(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(next());
}
return a;
}
long[] longarr(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = Long.parseLong(next());
}
return a;
}
float[] floatarr(int n) {
float a[] = new float[n];
for (int i = 0; i < n; i++) {
a[i] = Float.parseFloat(next());
}
return a;
}
double[] doublearr(int n) {
double a[] = new double[n];
for (int i = 0; i < n; i++) {
a[i] = Double.parseDouble(next());
}
return a;
}
int[][] intmatrix(int row, int col) {
int a[][] = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
a[i][j] = Integer.parseInt(next());
}
}
return a;
}
long[][] longmatrix(int row, int col) {
long a[][] = new long[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
a[i][j] = Long.parseLong(next());
}
}
return a;
}
float[][] floatmatrix(int row, int col) {
float a[][] = new float[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
a[i][j] = Float.parseFloat(next());
}
}
return a;
}
double[][] doublematrix(int row, int col) {
double a[][] = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
a[i][j] = Double.parseDouble(next());
}
}
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
cubic
|
1523_C. Compression and Expansion
|
CODEFORCES
|
import java.io.*;
import java.util.*;
public class Solution {
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
static class House implements Comparable<House> {
int x, a;
@Override
public int compareTo(House o) {
return x - o.x;
}
public House(int x, int a) {
this.x = x;
this.a = a;
}
}
void solve() throws IOException {
int n = nextInt();
int t = nextInt();
House[] hs = new House[n];
for (int i = 0; i < n; ++i) {
hs[i] = new House(nextInt(), nextInt());
}
Arrays.sort(hs);
int ans = 2;
for (int i = 0; i < n - 1; ++i) {
if (hs[i].a + hs[i + 1].a + 2 * t < 2 * (hs[i + 1].x - hs[i].x)) {
ans += 2;
} else if (hs[i].a + hs[i + 1].a + 2 * t == 2 * (hs[i + 1].x - hs[i].x)) {
ans++;
}
}
out.println(ans);
}
Solution() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
eat("");
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();
}
}
|
nlogn
|
15_A. Cottage Village
|
CODEFORCES
|
import java.util.*;
import java.io.*;
public class DigitSequence
{
public static PrintWriter out;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer token = new StringTokenizer("");
String temp[] = br.readLine().split(" ");
long pos = Long.parseLong(temp[0]);
out = new PrintWriter(new BufferedOutputStream(System.out));
if (pos<10)
{
out.println(pos);
}
else
{
out.println(findDigitSequence(pos));
}
out.close();
}
private static char findDigitSequence(long pos)
{
//long result = 0;
long min = 0;
long max = 9;
long dig = 1;
while (pos>max)
{
dig++;
min = max+1;
max=(long) (max+9*Math.pow(10, dig-1)*dig);
}
pos = pos-min;
long num = (long) (pos/dig+Math.pow(10, dig-1));
String st = String.valueOf(num);
if (dig==1)
{
return st.charAt(0);
}
char result = st.charAt((int) (pos%dig));
return result;
}
}
|
logn
|
1177_B. Digits Sequence (Hard Edition)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Round1B {
public static void main(String[] args) throws Exception {
new Round1B().run();
}
private void run() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int tc = Integer.parseInt(br.readLine().trim());
while (tc > 0) {
String s = br.readLine().trim();
if (s.matches("R[0-9]+C[0-9]+")) {
Pattern p = Pattern.compile("R([0-9]+)C([0-9]+)");
Matcher m = p.matcher(s);
if (m.matches()) {
int rows = Integer.parseInt(m.group(1));
int cols = Integer.parseInt(m.group(2));
String col = "";
while (cols > 0) {
int mod = (cols - 1) % 26;
col = (char)('A' + mod) + col;
cols = (cols - 1) / 26;
}
System.out.println(col + rows);
} else {
throw new Exception();
}
} else {
Pattern p = Pattern.compile("([A-Z]+)([0-9]+)");
Matcher m = p.matcher(s);
if (m.matches()) {
int rows = Integer.parseInt(m.group(2));
int cols = 0;
int mul = 1;
for (int i = m.group(1).length() - 1; i >= 0; i--) {
cols += mul * (m.group(1).charAt(i) - 'A' + 1);
mul *= 26;
}
System.out.printf("R%dC%d\n", rows, cols);
}
else {
throw new Exception();
}
}
tc--;
}
br.close();
}
}
|
linear
|
1_B. Spreadsheets
|
CODEFORCES
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
Arrays.sort(arr);
int cnt = 0;
int pos = 0;
while (true) {
while (pos < n && arr[pos] == -1) pos++;
if (pos == n) break;
int min = arr[pos];
arr[pos] = -1;
cnt++;
for (int i = pos + 1; i < n; i++) {
if (arr[i] % min == 0) {
arr[i] = -1;
}
}
}
System.out.println(cnt);
}
}
|
quadratic
|
1209_A. Paint the Numbers
|
CODEFORCES
|
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class PythonIndentiation {
PrintWriter pw = new PrintWriter(System.out);
final static boolean debugmode = true;
public static int k = 7; // for 10^9 + k mods.
public static int STMOD = 1000000000 + k; // 10^9 + k
public static Reader sc = new Reader();
public static void main(String[] args) throws IOException {
int commands = sc.nextInt();
int[][] dp = new int[5000][5000];
int interesting = 0;
String prgm = "";
while (interesting < commands){
byte q = sc.read();
if (q == 115 ){
interesting += 1;
prgm += "s";
}
else if (q == 102){
prgm += "f";
interesting += 1;
}
}
//System.out.println("Program: "+prgm);
dp[0][0] = 1; // line, indentations
for(int line = 1;line<commands;line++){
if(prgm.charAt(line-1) == 'f'){
for(int indent = 1;indent<Math.min(2*line + 1, 5000);indent++){
dp[line][indent] = dp[line-1][indent-1];
}
}
else if(prgm.charAt(line-1) == 's'){
int w = 0;
for(int indent = Math.min(2*line + 1, 4999);indent >= 0;indent--){
w = (w + dp[line-1][indent])% STMOD;
dp[line][indent] = w ;
}
}
}
int q = 0;
for(int i = 0;i<5000;i++){
q = ( q + dp[commands-1][i] ) % STMOD;
}
System.out.println(q);
}
public static String parseIt(int commands) throws IOException{
String c = "";
System.out.println(sc.read());
return c;
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class C35
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static int n,m;
static class Pair
{
int x,y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
}
static boolean[][] burned;
static int[] dx={-1,0,1,0};
static int[] dy={0,-1,0,1};
static boolean isvalid(int x,int y)
{
return x>=0&&x<n&&y>=0&&y<m;
}
public static void main(String[] args) throws IOException
{
Scanner in = new Scanner("input.txt");
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
n=in.nextInt();
m=in.nextInt();
burned=new boolean[n][m];
int k=in.nextInt();
Queue<Pair> queue=new LinkedList<>();
Pair prev=null;
for(int i=0;i<k;i++)
{
int x=in.nextInt();
int y=in.nextInt();
burned[x-1][y-1]=true;
queue.add(prev=new Pair(x-1, y-1));
}
while(!queue.isEmpty())
{
Queue<Pair> tempqueue=new LinkedList<>();
for(Pair p : queue)
{
int x=p.x;
int y=p.y;
prev=p;
for(int i=0;i<4;i++)
{
if(isvalid(x+dx[i], y+dy[i])&&!burned[x+dx[i]][y+dy[i]])
{
tempqueue.add(new Pair(x+dx[i], y+dy[i]));
burned[x+dx[i]][y+dy[i]]=true;
}
}
}
queue=tempqueue;
}
out.printf("%d %d\n",(prev.x+1),(prev.y+1));
out.close();
}
public static long pow(long x, long n)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p))
{
if ((n & 1) != 0)
{
res = (res * p);
}
}
return res;
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
}
|
cubic
|
35_C. Fire Again
|
CODEFORCES
|
import java.io.*;
import java.util.StringTokenizer;
public class Main11D {
private FastScanner in;
private PrintWriter out;
public void solve() throws IOException {
int N = in.nextInt();
int M = in.nextInt();
int[][] edges = new int[N][N];
for(int i = 0; i < M; i++){
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
edges[a][b] = 1;
edges[b][a] = 1;
}
int globalCountMasks = 1 << N;
int[][] masks = new int[N + 1][];
int[] countMasks = new int[N + 1];
for(int i = 0; i <= N; i++){
masks[i] = new int[combinations(N, i)];
}
for(int i = 0; i < globalCountMasks; i++){
int c = countBit1(i);
masks[c][countMasks[c]] = i;
countMasks[c]++;
}
long globalCountCycles = 0;
long[][] count = new long[globalCountMasks][N];
for(int a = 0; a < N - 2; a++){
int aBit = 1 << a;
count[aBit][a] = 1;
long countCycles = 0;
for(int i = 2; i <= N; i++){
for(int m = 0; m < countMasks[i]; m++){
int mask = masks[i][m];
if((mask & aBit) == 0) continue;
if((mask & (aBit - 1)) > 0) continue;
count[mask][a] = 0;
for(int v = a + 1; v < N; v++){
int vBit = 1 << v;
if((mask & vBit) == 0) continue;
count[mask][v] = 0;
for(int t = a; t < N; t++){
if((mask & (1 << t)) == 0 || t == v || edges[v][t] == 0) continue;
count[mask][v] += count[mask ^ vBit][t];
}
if(edges[a][v] == 1 && mask != (aBit | vBit)){
countCycles += count[mask][v];
}
}
}
}
globalCountCycles += countCycles / 2;
}
out.println(globalCountCycles);
}
private int countBit1(int k){
int c = 0;
while(k > 0){
c += k & 1;
k >>= 1;
}
return c;
}
private int combinations(int n, int k){
if(k > n || k < 0){
throw new IllegalArgumentException();
}
int r = 1;
for(int i = 1; i <= k; i++){
r = r * (n + 1 - i) / i;
}
return r;
}
public void run() {
try {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] arg) {
new Main11D().run();
}
}
|
np
|
11_D. A Simple Task
|
CODEFORCES
|
import java.util.Scanner;
import static java.lang.Math.*;
import static java.lang.Integer.*;
import static java.lang.Long.*;
import static java.util.Arrays.*;
public class A {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
int n = s.nextInt();
int[] a = new int[n];
int odd = 0;
int even = 0;
int po = -1;
int ev = -1;
for(int i=0;i<n;i++){
a[i] = s.nextInt();
if(a[i] % 2 == 0) {
even ++;
ev = i + 1;
} else {
odd++;
po = i + 1;
}
}
if(odd == 1) {
System.out.println(po);
}else{
System.out.println(ev);
}
}
}
}
|
linear
|
25_A. IQ test
|
CODEFORCES
|
import java.io.*;
import java.security.SecureRandom;
import java.util.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
public void solve() throws Exception {
int n = sc.nextInt();
int a[] = new int[n];
int s = 0;
for (int i = 0;i < n; ++ i) {
a[i] = sc.nextInt();
s += a[i];
}
Arrays.sort(a);
int s2 = 0;
for (int i = n - 1;i >= 0; -- i) {
s2 += a[i];
if (s2 > s - s2) {
out.println(n - i);
break;
}
}
}
class Pair implements Comparable<Pair> {
int x;
int y;
public Pair() {
}
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair arg0) {
if (x == arg0.x)
return y - arg0.y;
return x - arg0.x;
}
}
/*--------------------------------------------------------------*/
static String filename = "";
static boolean fromFile = false;
BufferedReader in;
PrintWriter out;
FastScanner sc;
public static void main(String[] args) {
new Thread(null, new Solution(), "", 1 << 25).start();
}
public void run() {
try {
init();
solve();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
out.close();
}
}
void init() throws Exception {
if (fromFile) {
in = new BufferedReader(new FileReader(filename+".in"));
out = new PrintWriter(new FileWriter(filename+".out"));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
sc = new FastScanner(in);
}
}
class FastScanner {
BufferedReader reader;
StringTokenizer strTok;
public FastScanner(BufferedReader reader) {
this.reader = reader;
}
public String nextToken() throws IOException {
while (strTok == null || !strTok.hasMoreTokens()) {
strTok = new StringTokenizer(reader.readLine());
}
return strTok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(nextToken());
}
public BigDecimal nextBigDecimal() throws IOException {
return new BigDecimal(nextToken());
}
}
|
nlogn
|
160_A. Twins
|
CODEFORCES
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Solution {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
int[] x;
int[] y;
int n;
int X, Y;
int[] d;
int[][] dist;
int sqr(int a) {
return a * a;
}
int dist(int X, int Y, int i) {
return sqr(X - x[i]) + sqr(Y - y[i]);
}
int[] dp;
byte[][] pred;
int rec(int mask) {
if (dp[mask] == -1) {
int res = 1 << 29;
boolean ok = false;
for (int i = 0; i < n; ++i)
if ((mask & (1 << i)) > 0) {
ok = true;
int mm = mask & ~(1 << i);
for (int j = i; j < n; j++)
if ((mask & (1 << j)) > 0) {
int nmask = mm & ~(1 << j);
int a = rec(nmask) + d[i] + d[j] + dist[i][j];
if (a < res) {
res = a;
pred[0][mask] = (byte) (i);
pred[1][mask] = (byte) (j);
}
}
break;
}
if (!ok)
res = 0;
dp[mask] = res;
}
return dp[mask];
}
void solve() throws IOException {
X = ni();
Y = ni();
n = ni();
x = new int[n];
y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = ni();
y[i] = ni();
}
d = new int[n];
dist = new int[n][n];
for (int i = 0; i < n; ++i)
d[i] = dist(X, Y, i);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; j++) {
dist[i][j] = dist(x[i], y[i], j);
}
pred = new byte[2][1 << n];
dp = new int[1 << n];
Arrays.fill(dp, -1);
out.println(rec((1 << n) - 1));
int a = (1 << n) - 1;
while (a > 0) {
if (pred[0][a] != pred[1][a])
out.print(0 + " " + (pred[0][a] + 1) + " " + (pred[1][a] + 1)
+ " ");
else
out.print(0 + " " + (pred[0][a] + 1) + " ");
int na = a & ~(1 << pred[0][a]);
na &= ~(1 << pred[1][a]);
a = na;
}
out.println(0);
}
public Solution() throws IOException {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
String ns() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int ni() throws IOException {
return Integer.valueOf(ns());
}
long nl() throws IOException {
return Long.valueOf(ns());
}
double nd() throws IOException {
return Double.valueOf(ns());
}
public static void main(String[] args) throws IOException {
new Solution();
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
//q4
import java.io.*;
import java.util.*;
import java.math.*;
public class q4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int query = in.nextInt();
while (query -- > 0) {
int n = in.nextInt();
int k = in.nextInt();
char[] arr = new char[n];
//slot all n into char array
String code = in.next();
for (int i = 0; i < n; i++) {
arr[i] = code.charAt(i);
}
//R, G, B cycle
int r = 0;
int g = 0;
int b = 0;
for (int i = 0; i < k; i++) {
if (i % 3 == 0) {
if (arr[i] == 'R') {g++; b++;}
else if (arr[i] == 'G') {r++; b++;}
else {r++; g++;} //if is 'B'
} else if (i % 3 == 1) {
if (arr[i] == 'G') {g++; b++;}
else if (arr[i] == 'B') {r++; b++;}
else {r++; g++;} //if is 'R'
} else { //if mod 3 is 2
if (arr[i] == 'B') {g++; b++;}
else if (arr[i] == 'R') {r++; b++;}
else {r++; g++;} //if is 'G'
}
}
//starting from kth position, if different then add 1, and check (j-k)th position
int rMin = r;
int gMin = g;
int bMin = b;
for (int j = k; j < n; j++) {
//R cycle
if ((j % 3 == 0 && arr[j] != 'R') ||
(j % 3 == 1 && arr[j] != 'G') ||
(j % 3 == 2 && arr[j] != 'B')) {
r++;
}
//R cycle
if (((j - k) % 3 == 0 && arr[j - k] != 'R') ||
((j - k) % 3 == 1 && arr[j - k] != 'G') ||
((j - k) % 3 == 2 && arr[j - k] != 'B')) {
r--;
}
rMin = Math.min(r, rMin);
//G cycle
if ((j % 3 == 0 && arr[j] != 'G') ||
(j % 3 == 1 && arr[j] != 'B') ||
(j % 3 == 2 && arr[j] != 'R')) {
g++;
}
if (((j - k) % 3 == 0 && arr[j - k] != 'G') ||
((j - k) % 3 == 1 && arr[j - k] != 'B') ||
((j - k) % 3 == 2 && arr[j - k] != 'R')) {
g--;
}
gMin = Math.min(gMin, g);
//B cycle
if ((j % 3 == 0 && arr[j] != 'B') ||
(j % 3 == 1 && arr[j] != 'R') ||
(j % 3 == 2 && arr[j] != 'G')) {
b++;
}
if (((j - k) % 3 == 0 && arr[j - k] != 'B') ||
((j - k) % 3 == 1 && arr[j - k] != 'R') ||
((j - k) % 3 == 2 && arr[j - k] != 'G')) {
b--;
}
bMin = Math.min(bMin, b);
}
System.out.println(Math.min(Math.min(rMin, gMin), bMin));
}
}
}
|
quadratic
|
1196_D2. RGB Substring (hard version)
|
CODEFORCES
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class CF8C {
static int n;
static int[] mem;
static HashMap<Integer, String> map;
static int INF = (int) 1e9;
static StringBuilder sb;
public static void main(String[] args) throws IOException {
MyScanner sc = new MyScanner(System.in);
String s = sc.nextLine();
n = sc.nextInt();
mem = new int[1 << n];
Arrays.fill(mem, -1);
map = new HashMap<>();
map.put(0, s);
for (int i = 1; i <= n; i++) {
map.put(i, sc.nextLine());
}
int val = dp(0);
PrintWriter pw = new PrintWriter(System.out);
pw.println(val);
sb = new StringBuilder();
sb.append("0 ");
build(0);
pw.println(sb);
pw.flush();
}
// node == 0 -- > count 0 // state == 0 has 1 // state == 1 has 2
private static int dp(int msk) {
if (msk == (1 << n) - 1)
return 0;
if(mem[msk] != -1)
return mem[msk];
boolean foundFirst = false;
int val = (int)1e9;
int mark = -1;
for (int i = 1; i <= n; i++) {
if ((msk & 1 << (i - 1)) == 0){
if(!foundFirst){
foundFirst = true;
mark = i;
val = dist(0, mark)*2 + dp(msk | 1 << (mark - 1));
}else{
val = Math.min(val, dist(0, mark) + dist(mark, i) + dist(i, 0) + dp((msk|1 << (mark - 1))|1 << (i - 1)));
}
}
}
return mem[msk] = val;
}
private static int dist(int node, int i) {
String from = map.get(i);
String to = map.get(node);
String[] fromco = from.split(" ");
String[] toco = to.split(" ");
int xs = Integer.parseInt(fromco[0]);
int ys = Integer.parseInt(fromco[1]);
int xf = Integer.parseInt(toco[0]);
int yf = Integer.parseInt(toco[1]);
return (xs - xf) * (xs - xf) + (ys - yf) * (ys - yf);
}
private static void build(int msk) {
if (msk == (1 << n) - 1)
return;
boolean foundFirst = false;
int ans = dp(msk);
int mark = -1;
int val = (int)1e9;
for (int i = 1; i <= n; i++) {
if ((msk & 1 << (i - 1)) == 0){
if(!foundFirst){
foundFirst = true;
mark = i;
val = dist(0, mark)*2 + dp(msk | 1 << (mark - 1));
if(val == ans){
sb.append(mark + " 0 ");
build(msk | 1 << (mark - 1));
return;
}
}else{
val = dist(0, mark) + dist(mark, i) + dist(i, 0) + dp(msk|1 << (mark - 1)|1 << (i - 1));
if(val == ans){
sb.append(mark + " " + i + " 0 ");
build(msk|1 << (mark - 1)|1 << (i - 1));
return;
}
}
}
}
}
static class MyScanner {
StringTokenizer st;
BufferedReader br;
public MyScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public MyScanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
np
|
8_C. Looking for Order
|
CODEFORCES
|
import java.util.*;
public class init {
static class p{
int i;
int c;
public p(int i,int c) {
this.i=i;this.c=c;
// TODO Auto-generated constructor stub
}
}
static int mod=1000000007;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
char c=s.next().charAt(0);
if(c=='f')
a[i]=1;
}
int dp[][]=new int[n+1][n+1];
for(int i=0;i<=n;i++) {
for(int j=0;j<=n;j++)
dp[i][j]=-1;
}
System.out.println(ans(dp,1,0,a,n));
}
public static int ans(int dp[][],int i,int j,int a[],int n) {
if(i==n) {
return 1;
}
if(dp[i][j]!=-1) {
return dp[i][j];
}
if(a[i-1]==1) {
int x=ans(dp,i+1,j+1,a,n);
if(x!=-1)
dp[i][j]=x%mod;
}
else {
int x=-1;
if(j!=0)
x=ans(dp,i,j-1,a,n);
int y=ans(dp,i+1,j,a,n);
if(x!=-1)
dp[i][j]=x%mod;
if(y!=-1) {
if(dp[i][j]==-1)
dp[i][j]=y%mod;
else
dp[i][j]+=y%mod;}
}
return dp[i][j];
}
}
|
quadratic
|
909_C. Python Indentation
|
CODEFORCES
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.