contest_id
stringclasses 33
values | problem_id
stringclasses 14
values | statement
stringclasses 181
values | tags
listlengths 1
8
| code
stringlengths 21
64.5k
| language
stringclasses 3
values |
---|---|---|---|---|---|
1296
|
C
|
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
|
[
"data structures",
"implementation"
] |
//package com.rajan.codeforces.level_1500;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class YetAnotherWalkingRobot {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
int tt = Integer.parseInt(reader.readLine());
while (tt-- > 0) {
int n = Integer.parseInt(reader.readLine());
String s = reader.readLine();
int[] ans = null;
Map<List<Integer>, Integer> positionToIndex = new HashMap<>();
int x = 0, y = 0;
for (int i = 0; i < n; i++) {
List<Integer> pos = List.of(x, y);
if (positionToIndex.containsKey(pos)) {
int lastIdx = positionToIndex.get(pos);
if (ans == null || (i - lastIdx) < (ans[1] - ans[0])) {
ans = new int[]{lastIdx, i};
}
}
positionToIndex.put(pos, i);
if (s.charAt(i) == 'L') {
x--;
} else if (s.charAt(i) == 'R')
x++;
else if (s.charAt(i) == 'U')
y++;
else
y--;
}
List<Integer> pos = List.of(x, y);
if (positionToIndex.containsKey(pos)) {
int lastIdx = positionToIndex.get(pos);
if (ans == null || (n - lastIdx) < (ans[1] - ans[0])) {
ans = new int[]{lastIdx, n};
}
}
if (ans == null)
writer.write("-1\n");
else
writer.write(String.format("%d %d\n", ans[0] + 1, ans[1]));
}
writer.flush();
}
}
|
java
|
1293
|
B
|
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.
|
[
"combinatorics",
"greedy",
"math"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
public class Main {
static BiFunction<Integer, Integer, Integer> ADD = (x, y) -> (x + y);
static BiFunction<ArrayList<Integer>, ArrayList<Integer>, ArrayList<Integer>> ADD_ARRAY_LIST = (x, y) -> {
x.addAll(y);
return x;
};
static Function<Pair<Integer, Integer>, Integer> GET_FIRST = (x) -> (x.first);
static Function<Pair<Integer, Integer>, Integer> GET_SECOND = (x) -> (x.second);
static Comparator<Pair<Integer, Integer>> C = Comparator.comparing(x -> x.first + x.second);
static long MOD = 1_000_000_000 + 7;
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
int t = 1;
while (t-- > 0) {
solve();
}
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms");
exit(0);
}
static void solve() {
double n = in.nextInt();
double ans = 1;
while (n > 1) {
ans += 1 / n;
n--;
}
out.println(ans);
}
static void debug(Object... args) {
for (Object a : args) {
out.println(a);
}
}
static int dist(Pair<Integer, Integer> a, Pair<Integer, Integer> b) {
return Math.abs(a.first - b.first) + Math.abs(a.second - b.second);
}
static void y() {
out.println("YES");
}
static void n() {
out.println("NO");
}
static int[] stringToArray(String s) {
return s.chars().map(x -> Character.getNumericValue(x)).toArray();
}
static <T> T min(T a, T b, Comparator<T> C) {
if (C.compare(a, b) <= 0) {
return a;
}
return b;
}
static <T> T max(T a, T b, Comparator<T> C) {
if (C.compare(a, b) >= 0) {
return a;
}
return b;
}
static void fail() {
out.println("-1");
}
static class Pair<T, R> {
public T first;
public R second;
public Pair(T first, R second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Pair<?, ?> pair = (Pair<?, ?>) o;
return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "Pair{" + "a=" + first + ", b=" + second + '}';
}
public T getFirst() {
return first;
}
public R getSecond() {
return second;
}
}
static <T, R> Pair<T, R> make_pair(T a, R b) {
return new Pair<>(a, b);
}
static long mod_inverse(long a, long m) {
Number x = new Number(0);
Number y = new Number(0);
extended_gcd(a, m, x, y);
return (m + x.v % m) % m;
}
static long extended_gcd(long a, long b, Number x, Number y) {
long d = a;
if (b != 0) {
d = extended_gcd(b, a % b, y, x);
y.v -= (a / b) * x.v;
} else {
x.v = 1;
y.v = 0;
}
return d;
}
static class Number {
long v = 0;
public Number(long v) {
this.v = v;
}
}
static long lcm(long a, long b, long c) {
return lcm(a, lcm(b, c));
}
static long lcm(long a, long b) {
long p = 1L * a * b;
return p / gcd(a, b);
}
static long gcd(long a, long b) {
while (b != 0) {
long t = b;
b = a % b;
a = t;
}
return a;
}
static long gcd(long a, long b, long c) {
return gcd(a, gcd(b, c));
}
static class ArrayUtils {
static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(char[] a, int i, int j) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void print(char[] a) {
for (char c : a) {
out.print(c);
}
out.println("");
}
static int[] reverse(int[] data) {
int[] p = new int[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static void prefixSum(long[] data) {
for (int i = 1; i < data.length; i++) {
data[i] += data[i - 1];
}
}
static void prefixSum(int[] data) {
for (int i = 1; i < data.length; i++) {
data[i] += data[i - 1];
}
}
static long[] reverse(long[] data) {
long[] p = new long[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static char[] reverse(char[] data) {
char[] p = new char[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static int[] MergeSort(int[] A) {
if (A.length > 1) {
int q = A.length / 2;
int[] left = new int[q];
int[] right = new int[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
int[] left_sorted = MergeSort(left);
int[] right_sorted = MergeSort(right);
return Merge(left_sorted, right_sorted);
} else {
return A;
}
}
static int[] Merge(int[] left, int[] right) {
int[] A = new int[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
static long[] MergeSort(long[] A) {
if (A.length > 1) {
int q = A.length / 2;
long[] left = new long[q];
long[] right = new long[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
long[] left_sorted = MergeSort(left);
long[] right_sorted = MergeSort(right);
return Merge(left_sorted, right_sorted);
} else {
return A;
}
}
static long[] Merge(long[] left, long[] right) {
long[] A = new long[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
static int upper_bound(long[] data, long num, int start) {
int low = start;
int high = data.length - 1;
int mid = 0;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (data[mid] < num) {
low = mid + 1;
} else if (data[mid] >= num) {
high = mid - 1;
ans = mid;
}
}
if (ans == -1) {
return 100000000;
}
return ans;
}
static int lower_bound(int[] data, int num, int start) {
int low = start;
int high = data.length - 1;
int mid = 0;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (data[mid] <= num) {
low = mid + 1;
ans = mid;
} else if (data[mid] > num) {
high = mid - 1;
}
}
if (ans == -1) {
return 100000000;
}
return ans;
}
}
static boolean[] primeSieve(int n) {
boolean[] primes = new boolean[n + 1];
Arrays.fill(primes, true);
primes[0] = false;
primes[1] = false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (primes[i]) {
for (int j = i * i; j <= n; j += i) {
primes[j] = false;
}
}
}
return primes;
}
// Iterative Version
static HashMap<Integer, Boolean> subsets_sum_iter(int[] data) {
HashMap<Integer, Boolean> temp = new HashMap<Integer, Boolean>();
temp.put(data[0], true);
for (int i = 1; i < data.length; i++) {
HashMap<Integer, Boolean> t1 = new HashMap<Integer, Boolean>(temp);
t1.put(data[i], true);
for (int j : temp.keySet()) {
t1.put(j + data[i], true);
}
temp = t1;
}
return temp;
}
static HashMap<Integer, Integer> subsets_sum_count(int[] data) {
HashMap<Integer, Integer> temp = new HashMap<>();
temp.put(data[0], 1);
for (int i = 1; i < data.length; i++) {
HashMap<Integer, Integer> t1 = new HashMap<>(temp);
t1.merge(data[i], 1, ADD);
for (int j : temp.keySet()) {
t1.merge(j + data[i], temp.get(j) + 1, ADD);
}
temp = t1;
}
return temp;
}
static class Graph {
ArrayList<Integer>[] g;
boolean[] visited;
ArrayList<Integer>[] graph(int n) {
g = new ArrayList[n];
visited = new boolean[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
return g;
}
void BFS(int s) {
Queue<Integer> Q = new ArrayDeque<>();
visited[s] = true;
Q.add(s);
while (!Q.isEmpty()) {
int v = Q.poll();
for (int a : g[v]) {
if (!visited[a]) {
visited[a] = true;
Q.add(a);
}
}
}
}
}
static class SparseTable {
int[] log;
int[][] st;
public SparseTable(int n, int k, int[] data, BiFunction<Integer, Integer, Integer> f) {
log = new int[n + 1];
st = new int[n][k + 1];
log[1] = 0;
for (int i = 2; i <= n; i++) {
log[i] = log[i / 2] + 1;
}
for (int i = 0; i < data.length; i++) {
st[i][0] = data[i];
}
for (int j = 1; j <= k; j++)
for (int i = 0; i + (1 << j) <= data.length; i++)
st[i][j] = f.apply(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
}
public int query(int L, int R, BiFunction<Integer, Integer, Integer> f) {
int j = log[R - L + 1];
return f.apply(st[L][j], st[R - (1 << j) + 1][j]);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 2048);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readAllInts(int n) {
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextInt();
}
return p;
}
public int[] readAllInts(int n, int s) {
int[] p = new int[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextInt();
}
return p;
}
public long[] readAllLongs(int n) {
long[] p = new long[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextLong();
}
return p;
}
public long[] readAllLongs(int n, int s) {
long[] p = new long[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextLong();
}
return p;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static void exit(int a) {
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
|
java
|
1304
|
B
|
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0
InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
|
[
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"strings"
] |
import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextInt();
String[] strings = new String[n];
for (int i = 0; i < strings.length; ++i) {
strings[i] = sc.next();
}
System.out.println(solve(strings));
sc.close();
}
static String solve(String[] strings) {
StringBuilder left = new StringBuilder();
String center = "";
Set<String> rest = Arrays.stream(strings).collect(Collectors.toSet());
while (!rest.isEmpty()) {
String s = rest.iterator().next();
rest.remove(s);
String reversed = new StringBuilder(s).reverse().toString();
if (rest.contains(reversed)) {
left.append(s);
} else if (reversed.equals(s)) {
center = s;
}
}
return String.format("%d\n%s%s%s", left.length() * 2 + center.length(), left, center,
new StringBuilder(left).reverse().toString());
}
}
|
java
|
1316
|
D
|
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters — UU, DD, LL, RR or XX — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103) — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :
|
[
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] |
import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
static int n,arrx[][],arry[][];
static char path[][];
static boolean vis[][];
public static void main(String args[]) throws IOException {
Scan input=new Scan();
StringBuilder ans=new StringBuilder("VALID\n");
n=input.scanInt();
arrx=new int[n][n];
arry=new int[n][n];
path=new char[n][n];
vis=new boolean[n][n];
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
arrx[i][j]=Math.max(-1,input.scanInt()-1);
arry[i][j]=Math.max(-1,input.scanInt()-1);
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(arrx[i][j]==i && arry[i][j]==j) {
DFS(i,j,'X');
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(arrx[i][j]==-1 && arry[i][j]==-1) {
continue;
}
if(!vis[i][j]) {
System.out.println("INVALID");
return;
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(vis[i][j]) {
continue;
}
char chr=get_nei(i,j);
if(chr=='0') {
System.out.println("INVALID");
return;
}
DFS(i,j,chr);
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
ans.append(path[i][j]);
}
ans.append("\n");
}
System.out.print(ans);
}
public static void DFS(int x,int y,char chr) {
vis[x][y]=true;
path[x][y]=chr;
if(x!=0 && !vis[x-1][y] && arrx[x-1][y]==arrx[x][y] && arry[x-1][y]==arry[x][y]) {
DFS(x-1,y,'D');
}
if(x!=n-1 && !vis[x+1][y] && arrx[x+1][y]==arrx[x][y] && arry[x+1][y]==arry[x][y]) {
DFS(x+1,y,'U');
}
if(y!=0 && !vis[x][y-1] && arrx[x][y-1]==arrx[x][y] && arry[x][y-1]==arry[x][y]) {
DFS(x,y-1,'R');
}
if(y!=n-1 && !vis[x][y+1] && arrx[x][y+1]==arrx[x][y] && arry[x][y+1]==arry[x][y]) {
DFS(x,y+1,'L');
}
}
public static char get_nei(int x,int y) {
if(x!=0 && arrx[x-1][y]==arrx[x][y] && arry[x-1][y]==arry[x][y]) {
return 'U';
}
if(x!=n-1 && arrx[x+1][y]==arrx[x][y] && arry[x+1][y]==arry[x][y]) {
return 'D';
}
if(y!=0 && arrx[x][y-1]==arrx[x][y] && arry[x][y-1]==arry[x][y]) {
return 'L';
}
if(y!=n-1 && arrx[x][y+1]==arrx[x][y] && arry[x][y+1]==arry[x][y]) {
return 'R';
}
return '0';
}
}
|
java
|
1284
|
B
|
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
|
[
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class NewYearAndAscentSequence {
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 nextFloat() { return Float.parseFloat(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n)
{
int[] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
long[] nextArrayLong(int n)
{
long[] a = new long[n];
for (int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
}
public static void solve(int n, int[][] s) {
long aCount = 0;
boolean[] isAscent = new boolean[n];
long buf[] = new long[1000007];
for (int i=0; i<n; i++) {
for (int j=1; j<s[i].length; j++) {
if (s[i][j] > s[i][j-1]) {
isAscent[i] = true;
aCount++;
break;
}
}
}
for (int i=0; i<n; i++) {
if (!isAscent[i]) {
buf[s[i][0]]++;
}
}
for (int i=buf.length-2; i>=0; i--) {
buf[i] += buf[i+1];
}
long ans = aCount * n;
for (int i=0; i<n; i++) {
if (!isAscent[i]) {
ans += (aCount + buf[s[i][s[i].length-1]+1]);
}
}
System.out.println(ans);
}
public static void main(String[] args) {
FastReader in = new FastReader();
int n = in.nextInt();
int[][] s = new int[n][];
for (int i=0; i<n; i++) {
int l = in.nextInt();
s[i] = in.nextArray(l);
}
solve(n, s);
}
}
|
java
|
1313
|
C1
|
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
|
[
"brute force",
"data structures",
"dp",
"greedy"
] |
import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static int mod = (int) (1e9 + 7);
static void solve() {
int n=i();
int[]arr=new int[n];
for(int i=0;i<n;i++)arr[i]=i();
int[]ans=new int[n];
long sum=0;
int idx=0;
for(int i=0;i<n;i++){
int []temp=new int[n];
long ts=0;
int v=arr[i];
temp[i]=v;
ts=v;
for(int j=i+1;j<n;j++){
v=Math.min(v,arr[j]);
temp[i]=v;
ts+=v;
}
v=arr[i];
for(int j=i-1;j>=0;j--){
v=Math.min(v,arr[j]);
temp[i]=v;
ts+=v;
}
if(ts>sum){
idx=i;
sum=ts;
}
}
int v1=arr[idx];
// ans[]
for(int j=idx;j<n;j++){
v1=Math.min(v1,arr[j]);
ans[j]=v1;
}
v1=arr[idx];
for(int j=idx-1;j>=0;j--){
v1=Math.min(v1,arr[j]);
ans[j]=v1;
}
for(int i=0;i<n;i++){
sb.append(ans[i]+" ");
}
}
public static void main(String[] args) {
sb = new StringBuilder();
int test = 1;
while (test-- > 0) {
solve();
}
System.out.println(sb);
}
/*
* fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++)
* { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; }
*/
//**************NCR%P******************
static long ncr(int n, int r) {
if (r > n)
return (long) 0;
long res = fact[n] % mod;
// System.out.println(res);
res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;
res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;
// System.out.println(res);
return res;
}
static long p(long x, long y)// POWER FXN //
{
if (y == 0)
return 1;
long res = 1;
while (y > 0) {
if (y % 2 == 1) {
res = (res * x) % mod;
y--;
}
x = (x * x) % mod;
y = y / 2;
}
return res;
}
//**************END******************
// *************Disjoint set
// union*********//
static class dsu {
int parent[];
dsu(int n) {
parent = new int[n];
for (int i = 0; i < n; i++)
parent[i] = -1;
}
int find(int a) {
if (parent[a] < 0)
return a;
else {
int x = find(parent[a]);
parent[a] = x;
return x;
}
}
void merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
parent[b] = a;
}
}
//**************PRIME FACTORIZE **********************************//
static TreeMap<Integer, Integer> prime(long n) {
TreeMap<Integer, Integer> h = new TreeMap<>();
long num = n;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (n % i == 0) {
int nt = 0;
while (n % i == 0) {
n = n / i;
nt++;
}
h.put(i, nt);
}
}
if (n != 1)
h.put((int) n, 1);
return h;
}
//****CLASS PAIR ************************************************
static class Pair implements Comparable<Pair> {
int x;
long y;
Pair(int x, long y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
return (int) (this.y - o.y);
}
}
//****CLASS PAIR **************************************************
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
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 String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
public static long[] sort(long[] a2) {
int n = a2.length;
ArrayList<Long> l = new ArrayList<>();
for (long i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static char[] sort(char[] a2) {
int n = a2.length;
ArrayList<Character> l = new ArrayList<>();
for (char i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static long pow(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 != 0) {
res = (res * x);// % modulus;
y--;
}
x = (x * x);// % modulus;
y = y / 2;
}
return res;
}
//GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public static long gcd(long x, long y) {
if (x == 0)
return y;
else
return gcd(y % x, x);
}
// ******LOWEST COMMON MULTIPLE
// *********************************************
public static long lcm(long x, long y) {
return (x * (y / gcd(x, y)));
}
//INPUT PATTERN********************************************************
public static int i() {
return in.Int();
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static String s() {
return in.String();
}
public static int[] readArrayi(int n) {
int A[] = new int[n];
for (int i = 0; i < n; i++) {
A[i] = i();
}
return A;
}
public static long[] readArray(long n) {
long A[] = new long[(int) n];
for (int i = 0; i < n; i++) {
A[i] = l();
}
return A;
}
}
|
java
|
1324
|
A
|
A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.
|
[
"implementation",
"number theory"
] |
/*package whatever //do not write package name here */
import java.util.Scanner;
public class code{
/* public static boolean perfect(int n){
double d1 = Math.sqrt(n);
if(d1==(int)d1){
return true;
}
return false;
}*/
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int t1 = s.nextInt();
while(t1-->0){
int n = s.nextInt();
int[] arr = new int[n];
int count_odd = 0;
int count_even = 0;
for(int i = 0;i<n;i++){
arr[i] = s.nextInt();
if(arr[i]%2==0){
count_even+=1;
}else{
count_odd+=1;
}
}
if(count_even==0 && count_odd!=0){
System.out.println("YES");
}else if (count_even!=0 && count_odd==0){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
}
|
java
|
1286
|
B
|
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2
|
[
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] |
import java.io.*;
import java.util.*;
// #FullSolution
public class new1{
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
//static int max = -1;
public static ArrayList<Integer> dfs(int[] parent, int[] gret, int x){
//System.out.println(x);
int n = parent.length - 1;
ArrayList<Integer> aList = new ArrayList<Integer>();
for(int i = 1; i <= n; i++) {
if(parent[i] == x) {
ArrayList<Integer> a1 = dfs(parent, gret, i);
if(a1 == null) return null;
for(int j = 0; j < a1.size(); j++) aList.add(a1.get(j));
}
}
int pos = gret[x];
if(aList.size() < pos) return null;
aList.add(pos, x);
return aList;
}
public static void main(String[] args) throws IOException{
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
FastReader s = new FastReader();
int t = 1;//s.nextInt();
for(int z = 0; z < t; z++) {
int n = s.nextInt();
int[] parent = new int[n + 1];
int[] gret = new int[n + 1];
int root = -1;
for(int i = 0; i < n; i++) {
int pa = s.nextInt();
if(pa == 0) root = i + 1;
int gr = s.nextInt();
parent[i + 1] = pa;
gret[i + 1] = gr;
}
// System.out.println(root);
// System.out.println(Arrays.toString(parent));
// System.out.println(Arrays.toString(gret));
ArrayList<Integer> ans = dfs(parent, gret, root);
if(ans == null) System.out.println("NO");
else {
System.out.println("YES");
int[] ans1 = new int[n + 1];
for(int i = 1; i <= n; i++) {
int val = ans.get(i - 1);
ans1[val] = i;
}
for(int i = 1; i <= n; i ++) System.out.print(ans1[i] + " ");
}
//System.out.println(ans.toString());
}
//output.flush();
}
}
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();
}
public 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;
}}
|
java
|
1288
|
C
|
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
|
[
"combinatorics",
"dp"
] |
import java.util.*;
public class Main{
public static void main(String[]args) {
final int mx = 1010;
final int mod = 1000000007;
long [][] dp = new long [30][mx];
long sum = 0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
m*=2;
for(int i=1;i<=n;i++)//初始化
dp[1][i]=1;
for(int i=2;i<=m;i++)//长度
{
for(int j=1;j<=n;j++)//结尾
{
for(int k=1;k<=j;k++)
dp[i][j]=(dp[i][j]+dp[i-1][k])%mod;
}
}
for(int i = 1 ; i<=n ; i++)
sum = (sum + dp[m][i])%mod;
System.out.println(sum);
}
}
|
java
|
1303
|
D
|
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
|
[
"bitmasks",
"greedy"
] |
import java.io.*;
import java.util.*;
//import javafx.util.*;
import java.math.*;
//import java.lang.*;
public class Main
{
// static int n;
static HashSet<Integer> adj[];
static boolean vis[];
// static long ans[];
static int arr[];
static long mod=1000000007;
static final long oo=(long)1e18;
// static int n;
public static void main(String[] args) throws IOException {
// Scanner sc=new Scanner(System.in);
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
br = new BufferedReader(new InputStreamReader(System.in));
int test=nextInt();
// int test=1;
outer: while(test--!=0){
int a[]=new int[64];
long n=nextLong();
int m=nextInt();
Long arr[]=new Long[m];
for(int i=0;i<m;i++){
arr[i]=nextLong();
a[(int)(Math.log(arr[i])/Math.log(2))]++;
}
int ans=0;
for(int i=0;i<62;i++){
if((n&(1l<<i))!=0){
// pw.println(i);
boolean yes=false;
int j=i;
for(j=i;j<62;j++){
if(a[j]>0){
yes=true;
break;
}
}
if(yes){
while(j!=i){
a[j]--;
a[j-1]+=2;
ans++;
j--;
}
a[j]--;
}
else{
pw.println("-1");
continue outer;
}
}
a[i+1]+=a[i]/2;
}
pw.println(ans);
// Arrays.sort(arr,Collections.reverseOrder());
}
pw.close();
}
static boolean dfs(int v,int parent){
// System.out.println(v);
vis[v]=true;
for(int a:adj[v]){
if(!vis[a]){
if(dfs(a,v)){
return true;
}
}
else if(a!=parent){
return true;
}
}
return false;
}
static ArrayList<ArrayList<Integer>> permutation2(int[] a, int n) {
ArrayList<ArrayList<Integer>> gen = new ArrayList<>();
if(n == 1) {
ArrayList<Integer> new_permutation = new ArrayList<>();
new_permutation.add(a[n-1]);
gen.add(new_permutation);
} else {
Iterator<ArrayList<Integer>> itr = permutation2(a, n-1).iterator();
while(itr.hasNext()) {
ArrayList<Integer> permutation = itr.next();
// (create new permutation with this element in every position)
for(int i = 0;i <= permutation.size();i++) {
ArrayList<Integer> new_permutation = new ArrayList<>(permutation);
new_permutation.add(i, a[n-1]);
gen.add(new_permutation);
}
}
}
return gen;
}
static void decToBinary(int n)
{
// array to store binary number
int[] binaryNum = new int[1000];
// counter for binary array
int i = 0;
while (n > 0)
{
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
System.out.print(binaryNum[j]);
System.out.println();
}
static long ncr(long n,long r){
if(r==0)
return 1;
long val=ncr(n-1,r-1);
val=(n*val)%mod;
val=(val*modInverse(r,mod))%mod;
return val;
}
static int find(ArrayList<Integer> a,int i){
if(a.size()==0||i<0)return 0;
ArrayList<Integer> l=new ArrayList<Integer>();
ArrayList<Integer> r=new ArrayList<Integer>();
for(int v:a){
if((v&(1<<i))!=0)l.add(v);
else r.add(v);
}
if(l.size()==0)return find(r,i-1);
if(r.size()==0)return find(l,i-1);
return Math.min(find(l,i-1),find(r,i-1))+(1<<i);
}
public static BufferedReader br;
public static StringTokenizer st;
public static String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public static Integer nextInt() {
return Integer.parseInt(next());
}
public static Long nextLong() {
return Long.parseLong(next());
}
public static Double nextDouble() {
return Double.parseDouble(next());
}
// static class Pair{
// int x;int y;
// Pair(int x,int y,int z){
// this.x=x;
// this.y=y;
// // this.z=z;
// // this.z=z;
// // this.i=i;
// }
// }
// static class sorting implements Comparator<Pair>{
// public int compare(Pair a,Pair b){
// //return (a.y)-(b.y);
// if(a.y==b.y){
// return -1*(a.z-b.z);
// }
// return (a.y-b.y);
// }
// }
public static int[] na(int n)throws IOException{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = nextInt();
return a;
}
static class query implements Comparable<query>{
int l,r,idx,block;
static int len;
query(int l,int r,int i){
this.l=l;
this.r=r;
this.idx=i;
this.block=l/len;
}
public int compareTo(query a){
return block==a.block?r-a.r:block-a.block;
}
}
static class Pair implements Comparable<Pair>{
int x;int y;
Pair(int x,int y){
this.x=x;
this.y=y;
//this.z=z;
}
public int compareTo(Pair p){
//return (x-p.x);
if(x>p.x)
return 1;
if(x<p.x)
return -1;
return y-p.y;
//return (x-a.x)>0?1:-1;
}
}
// static class sorting implements Comparator<Pair>{
// public int compare(Pair a1,Pair a2){
// if(o1.a==o2.a)
// return (o1.b>o2.b)?1:-1;
// else if(o1.a>o2.a)
// return 1;
// else
// return -1;
// }
// }
static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 ||
n % 3 == 0)
return false;
for (int i = 5;
i * i <= n; i = i + 6)
if (n % i == 0 ||
n % (i + 2) == 0)
return false;
return true;
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// To compute x^y under modulo m
static long power(long x, long y, long m){
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (p * p) % m;
if (y % 2 == 0)
return p;
else
return (x * p) % m;
}
static long fast_pow(long base,long n,long M){
if(n==0)
return 1;
if(n==1)
return base;
long halfn=fast_pow(base,n/2,M);
if(n%2==0)
return ( halfn * halfn ) % M;
else
return ( ( ( halfn * halfn ) % M ) * base ) % M;
}
static long modInverse(long n,long M){
return fast_pow(n,M-2,M);
}
// (1,1)
// (3,2) (3,5)
}
|
java
|
1321
|
A
|
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
|
[
"greedy"
] |
//package currentContest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
import java.util.StringTokenizer;
public class P1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader sc=new FastReader();
int t=1;
StringBuilder st=new StringBuilder();
while(t--!=0) {
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
int b[]=new int[n];
for(int i=0;i<n;i++) {
b[i]=sc.nextInt();
}
int count1=0;
int count2=0;
int ca=0;
int cb=0;
for(int i=0;i<n;i++) {
if(a[i]==b[i]) {
continue;
}else if(a[i]==1) {
count1++;
count2--;
}else if(b[i]==1){
count2++;
}
}
if(count2<0) {
st.append("1\n");
}else if(count1==0) {
st.append("-1\n");
}else {
st.append((int)Math.ceil(((double)count1+count2+1)/count1)+"\n");
}
}
System.out.println(st);
}
static FastReader sc = new FastReader();
public static void solvegraph() {
int n = sc.nextInt();
int edge[][] = new int[n - 1][2];
for (int i = 0; i < n - 1; i++) {
edge[i][0] = sc.nextInt() - 1;
edge[i][1] = sc.nextInt() - 1;
}
ArrayList<ArrayList<Integer>> ad = new ArrayList<>();
for (int i = 0; i < n; i++) {
ad.add(new ArrayList<Integer>());
}
for (int i = 0; i < n - 1; i++) {
ad.get(edge[i][0]).add(edge[i][1]);
ad.get(edge[i][1]).add(edge[i][0]);
}
int parent[] = new int[n];
Arrays.fill(parent, -1);
parent[0] = n;
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(0);
int child[] = new int[n];
Arrays.fill(child, 0);
ArrayList<Integer> lv = new ArrayList<Integer>();
while (!queue.isEmpty()) {
int toget = queue.getFirst();
queue.removeFirst();
child[toget] = ad.get(toget).size() - 1;
for (int i = 0; i < ad.get(toget).size(); i++) {
if (parent[ad.get(toget).get(i)] == -1) {
parent[ad.get(toget).get(i)] = toget;
queue.addLast(ad.get(toget).get(i));
}
}
lv.add(toget);
}
child[0]++;
}
static void sort(int[] A) {
int n = A.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
int tmp = A[i];
int randomPos = i + rnd.nextInt(n - i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static void sort(long[] A) {
int n = A.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
long tmp = A[i];
int randomPos = i + rnd.nextInt(n - i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static String sort(String s) {
Character ch[] = new Character[s.length()];
for (int i = 0; i < s.length(); i++) {
ch[i] = s.charAt(i);
}
Arrays.sort(ch);
StringBuffer st = new StringBuffer("");
for (int i = 0; i < s.length(); i++) {
st.append(ch[i]);
}
return st.toString();
}
public static long gcd(long a, long b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
java
|
1286
|
B
|
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2
|
[
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] |
/*
TASK: template
LANG: JAVA
*/
import java.io.*;
import java.lang.*;
import java.util.*;
public class B1286 {
static HashMap<Integer, ArrayList<Integer>> hash = new HashMap<>();;
static int[] c;
static int[] val;
static int[] parent;
static boolean broken = false;
static int[] value;
public static void main(String[] args) throws IOException {
StringBuffer ans = new StringBuffer();
StringTokenizer st;
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
c = new int[n];
val = new int[n];
parent = new int[n];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(f.readLine());
int ft = Integer.parseInt(st.nextToken()) - 1;
int sc = Integer.parseInt(st.nextToken());
c[i] = sc;
if (!hash.containsKey(ft))
hash.put(ft, new ArrayList<>());
parent[i] = ft;
hash.get(ft).add(i);
}
ArrayList<Integer> arrl = new ArrayList<>();
//System.out.println(hash);
for(int i = 0; i < n; i++){
if(parent[i] == -1){
arrl = dfs(i);
}
}
f.close();
value = new int[n];
int val = 1;
for(int i : arrl){
value[i] = val;
val++;
}
for(int i = 0; i < n; i++){
//System.out.println(check(i, value[i]) + " " + c[i]);
if(check(i, value[i]) != c[i])
broken = true;
}
if(broken){
System.out.println("NO");
System.exit(0);
}
System.out.println("YES");
for(int i : value)
ans.append(i).append(" ");
System.out.println(ans);
}
public static ArrayList<Integer> dfs(int node){
ArrayList<Integer> arrl = new ArrayList<>();
if(hash.containsKey(node) && hash.get(node).size() != 0){
for(int i : hash.get(node)){
arrl.addAll(dfs(i));
}
}
if(c[node] > arrl.size())
broken = true;
else
arrl.add(c[node], node);
//System.out.println(arrl);
return arrl;
}
public static int check(int node, int val){
int add = 0;
if(value[node] < val){
add++;
}
if(hash.containsKey(node))
for(int i : hash.get(node)){
add+=check(i, val);
}
return add;
}
public static class point implements Comparable<point>{
int x;
int y;
public point(int x,int y){
this.x = x;
this.y = y;
}
public String toString(){
return(x + " " + y);
}
public int compareTo(point other){
if(this.x > other.x || (this.x == other.x && this.y > other.y)){
return 1;
}else if(this.x == other.x && other.y == this.y){
return 0;
}
return -1;
}
}
}
|
java
|
1290
|
B
|
B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105) — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.
|
[
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] |
import java.io.*;
import java.util.*;
// #FullSolution
public class new1{
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static FastReader s = new FastReader();
public static void main(String[] args) throws IOException{
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int t = 1;//s.nextInt();
for(int z = 0; z < t; z++) {
String str = s.next();
int n = str.length();
int[][] freq = new int[n + 1][26];
for(int i = 0; i < n; i++) {
for(int j = 0; j < 26; j++) {
if(str.charAt(i) - 'a' == j) {
freq[i + 1][j] = freq[i][j] + 1;
}
else freq[i + 1][j] = freq[i][j];
}
}
int q = s.nextInt();
for(int i = 0; i < q; i++) {
int st = s.nextInt() - 1; int en = s.nextInt() - 1;
if(st == en) {
System.out.println("YES"); continue;
}
int count = 0;
boolean pos = false;
if(str.charAt(st) != str.charAt(en)) pos = true;
for(int j = 0; j < 26; j++) {
if(str.charAt(st) - 'a' == j) continue;
if(freq[en + 1][j] - freq[st][j] > 0) count++;
}
if(count >= 2)pos = true;
//if(i == 12) System.out.println(str.substring(st, en + 1));
if(pos)System.out.println("YES");
else System.out.println("NO");
}
}
output.flush();
}
}
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();
}
public 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;
}}
|
java
|
1286
|
A
|
A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.
|
[
"dp",
"greedy",
"sortings"
] |
import java.util.Arrays;
import java.util.Map;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
int[] a = new int[n + 1];
int[][][][][] f = new int[n + 1][n + 1][n / 2 + 1][3][3];//f[i][j][k]: 表示 [i, j] 取了 k 个2的最小答案数
for (int i = 0; i < f.length; i++) {
for (int j = 0; j < f[i].length; j++) {
for (int k = 0; k < f[i][j].length; k++) {
for (int l = 0; l < f[i][j][k].length; l++) {
Arrays.fill(f[i][j][k][l], Integer.MAX_VALUE / 2);
}
}
}
}
for(int i = 1; i <= n; i++) {
int x = scanner.nextInt();
if (x == 0) {
f[i][i][0][1][1] = 0;
if (1 < f[i][i].length)
f[i][i][1][2][2] = 0;
continue;
}
if (x % 2 == 0) {
a[i] = 2;
f[i][i][1][2][2] = 0;
}else {
a[i] = 1;
f[i][i][0][1][1] = 0;
}
}
//(n / 2) 个 2
//(n - n / 2) 个 1
for (int len = 2; len <= n; len++) {
for (int i = 1, j = i + len - 1; j <= n; i++, j++) {
for (int k = 0; k <= Math.min(n / 2, len); k++) {
for (int l = 1; l <= 2; l++) {
if (a[i] != 0 && a[i] != l) continue;
for (int m = 1; m <= 2; m++) {
if (a[j] != 0 && a[j] != m) continue;
for (int o = 1; o <= 2; o++) {
if (a[i + 1] != 0 && a[i + 1] != o) {
continue;
}
if (l != 2 || k - 1 >= 0)
f[i][j][k][l][m] = Math.min(f[i + 1][j][l == 2 ? k - 1 : k][o][m] + (o != l ? 1 : 0), f[i][j][k][l][m]);
}
for (int o = 1; o <= 2; o++) {
if (a[j - 1] != 0 && a[j - 1] != o) {
continue;
}
if (m != 2 || k - 1 >= 0)
f[i][j][k][l][m] = Math.min(f[i][j - 1][m == 2 ? k - 1 : k][l][o] + (o != m ? 1 : 0), f[i][j][k][l][m]);
}
}
}
}
}
}
int res = Integer.MAX_VALUE;
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 2; j++) {
res = Math.min(res, f[1][n][n / 2][i][j]);
}
}
System.out.println(res);
}
}
|
java
|
1296
|
E2
|
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1
|
[
"data structures",
"dp"
] |
/*
Author: Anthony Ngene
Created: 04/09/2020 - 07:07
*/
import java.io.*;
import java.util.*;
public class E2 {
// We must learn to live together as brothers or perish together as fools. - Martin Luther King, Jr.
int[] colors;
void solver() throws IOException {
// O(nlogn) time | O(n) space
int n = in.intNext();
String seq = in.next();
colors = new int[n];
TreeSet<Tuple> seen = new TreeSet<>();
for (int i = 0; i < n; i++) {
int num = seq.charAt(i) - 'a';
if (seen.isEmpty() || seen.first().a > num) {
int color = seen.size() + 1;
colors[i] = color;
seen.add(new Tuple(num, color));
} else {
Tuple lowestPossible = seen.lower(new Tuple(num, seen.size() + 1));
seen.remove(lowestPossible);
colors[i] = (int) lowestPossible.b;
seen.add(new Tuple(num, colors[i]));
}
}
out.println(seen.size());
out.println(colors);
}
// checks: 1. edge cases 2. overflow 3. possible errors (e.g 1/0, arr[out]) 4. time/space complexity
// Generated Code Below:
private static final FastWriter out = new FastWriter();
private static FastScanner in;
static ArrayList<Integer>[] adj;
private static long e97 = (long)1e9 + 7;
public static void main(String[] args) throws IOException {
in = new FastScanner();
new E2().solver();
out.close();
}
static class FastWriter {
private static final int IO_BUFFERS = 128 * 1024;
private final StringBuilder out;
public FastWriter() { out = new StringBuilder(IO_BUFFERS); }
public FastWriter p(Object object) { out.append(object); return this; }
public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; }
public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(int[] args) { for (int ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(long[] args) { for (long ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(char[] args) { for (char ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public void println(long[] arr) { for(long e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(int[] arr) { for(int e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(char[] arr) { for(char e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(double[] arr) { for(double e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(boolean[] arr) { for(boolean e: arr) out.append(e).append(" "); out.append("\n"); }
public <T>void println(T[] arr) { for(T e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(long[][] arr) { for (long[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(int[][] arr) { for (int[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(char[][] arr) { for (char[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(double[][] arr) { for (double[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public <T>void println(T[][] arr) { for (T[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public FastWriter println(Object object) { out.append(object).append("\n"); return this; }
public void toFile(String fileName) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(out.toString());
writer.close();
}
public void close() throws IOException { System.out.print(out); }
}
static class FastScanner {
private InputStream sin = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
public FastScanner(){}
public FastScanner(String filename) throws FileNotFoundException {
File file = new File(filename);
sin = new FileInputStream(file);
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = sin.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long longNext() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while(true){
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
}else if(b == -1 || !isPrintableChar(b) || b == ':'){
return minus ? -n : n;
}else{
throw new NumberFormatException();
}
b = readByte();
}
}
public int intNext() {
long nl = longNext();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double doubleNext() { return Double.parseDouble(next());}
public long[] nextLongArray(final int n){
final long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = longNext();
return a;
}
public int[] nextIntArray(final int n){
final int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = intNext();
return a;
}
public double[] nextDoubleArray(final int n){
final double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = doubleNext();
return a;
}
public ArrayList<Integer>[] getAdj(int n) {
ArrayList<Integer>[] adj = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();
return adj;
}
public ArrayList<Integer>[] adjacencyList(int nodes, int edges) throws IOException {
return adjacencyList(nodes, edges, false);
}
public ArrayList<Integer>[] adjacencyList(int nodes, int edges, boolean isDirected) throws IOException {
adj = getAdj(nodes);
for (int i = 0; i < edges; i++) {
int a = intNext(), b = intNext();
adj[a].add(b);
if (!isDirected) adj[b].add(a);
}
return adj;
}
}
static class u {
public static int upperBound(long[] array, long obj) {
int l = 0, r = array.length - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj < array[c]) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int upperBound(ArrayList<Long> array, long obj) {
int l = 0, r = array.size() - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj < array.get(c)) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int lowerBound(long[] array, long obj) {
int l = 0, r = array.length - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj <= array[c]) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int lowerBound(ArrayList<Long> array, long obj) {
int l = 0, r = array.size() - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj <= array.get(c)) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
static <T> T[][] deepCopy(T[][] matrix) { return Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone()); }
static int[][] deepCopy(int[][] matrix) { return Arrays.stream(matrix).map(int[]::clone).toArray($ -> matrix.clone()); }
static long[][] deepCopy(long[][] matrix) { return Arrays.stream(matrix).map(long[]::clone).toArray($ -> matrix.clone()); }
private static void sort(int[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
private static void sort(long[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
private static <T>void rSort(T[] arr) { Arrays.sort(arr, Collections.reverseOrder()); }
private static void customSort(int[][] arr) {
Arrays.sort(arr, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a[0] == b[0]) return Integer.compare(a[1], b[1]);
return Integer.compare(a[0], b[0]);
}
});
}
public static char[] swap(char[] arr, int left, int right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
return arr;
}
public static boolean[] swap(boolean[] arr, int left, int right) {
boolean temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
return arr;
}
public static int[] reverse(int[] arr, int left, int right) {
while (left < right) {
int temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return arr;
}
// public static boolean findNextPermutation(int[] data) {
// if (data.length <= 1) return false;
// int last = data.length - 2;
// while (last >= 0) {
// if (data[last] < data[last + 1]) break;
// last--;
// }
// if (last < 0) return false;
// int nextGreater = data.length - 1;
// for (int i = data.length - 1; i > last; i--) {
// if (data[i] > data[last]) {
// nextGreater = i;
// break;
// }
// }
// data = swap(data, nextGreater, last);
// data = reverse(data, last + 1, data.length - 1);
// return true;
// }
public static int biSearch(int[] dt, int target){
int left=0, right=dt.length-1;
int mid=-1;
while(left<=right){
mid = (right+left)/2;
if(dt[mid] == target) return mid;
if(dt[mid] < target) left=mid+1;
else right=mid-1;
}
return -1;
}
public static int biSearchMax(long[] dt, long target){
int left=-1, right=dt.length;
int mid=-1;
while((right-left)>1){
mid = left + (right-left)/2;
if(dt[mid] <= target) left=mid;
else right=mid;
}
return left;
}
public static int biSearchMaxAL(ArrayList<Integer> dt, long target){
int left=-1, right=dt.size();
int mid=-1;
while((right-left)>1){
mid = left + (right-left)/2;
if(dt.get(mid) <= target) left=mid;
else right=mid;
}
return left;
}
private static <T>void fill(T[][] ob, T res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(boolean[][] ob,boolean res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(int[][] ob, int res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(long[][] ob, long res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(char[][] ob, char res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(double[][] ob, double res){for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(int[][][] ob,int res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static void fill(long[][][] ob,long res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static <T>void fill(T[][][] ob,T res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static void fill_parent(int[] ob){ for(int i=0; i<ob.length; i++) ob[i]=i; }
private static boolean same3(long a, long b, long c){
if(a!=b) return false;
if(b!=c) return false;
if(c!=a) return false;
return true;
}
private static boolean dif3(long a, long b, long c){
if(a==b) return false;
if(b==c) return false;
if(c==a) return false;
return true;
}
private static double hypotenuse(double a, double b){
return Math.sqrt(a*a+b*b);
}
private static long factorial(int n) {
long ans=1;
for(long i=n; i>0; i--){ ans*=i; }
return ans;
}
private static long facMod(int n, long mod) {
long ans=1;
for(long i=n; i>0; i--) ans = (ans * i) % mod;
return ans;
}
private static long lcm(long m, long n){
long ans = m/gcd(m,n);
ans *= n;
return ans;
}
private static long gcd(long m, long n) {
if(m < n) return gcd(n, m);
if(n == 0) return m;
return gcd(n, m % n);
}
private static boolean isPrime(long a){
if(a==1) return false;
for(int i=2; i<=Math.sqrt(a); i++){ if(a%i == 0) return false; }
return true;
}
static long modInverse(long a, long mod) {
/* Fermat's little theorem: a^(MOD-1) => 1
Therefore (divide both sides by a): a^(MOD-2) => a^(-1) */
return binpowMod(a, mod - 2, mod);
}
static long binpowMod(long a, long b, long mod) {
long res = 1;
while (b > 0) {
if (b % 2 == 1) res = (res * a) % mod;
a = (a * a) % mod;
b /= 2;
}
return res;
}
private static int getDigit2(long num){
long cf = 1; int d=0;
while(num >= cf){ d++; cf = 1<<d; }
return d;
}
private static int getDigit10(long num){
long cf = 1; int d=0;
while(num >= cf){ d++; cf*=10; }
return d;
}
private static boolean isInArea(int y, int x, int h, int w){
if(y<0) return false;
if(x<0) return false;
if(y>=h) return false;
if(x>=w) return false;
return true;
}
private static ArrayList<Integer> generatePrimes(int n) {
int[] lp = new int[n + 1];
ArrayList<Integer> pr = new ArrayList<>();
for (int i = 2; i <= n; ++i) {
if (lp[i] == 0) {
lp[i] = i;
pr.add(i);
}
for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n; ++j) {
lp[i * pr.get(j)] = pr.get(j);
}
}
return pr;
}
static long nPrMod(int n, int r, long MOD) {
long res = 1;
for (int i = (n - r + 1); i <= n; i++) {
res = (res * i) % MOD;
}
return res;
}
static long nCr(int n, int r) {
if (r > (n - r))
r = n - r;
long ans = 1;
for (int i = 1; i <= r; i++) {
ans *= n;
ans /= i;
n--;
}
return ans;
}
static long nCrMod(int n, int r, long MOD) {
long rFactorial = nPrMod(r, r, MOD);
long first = nPrMod(n, r, MOD);
long second = binpowMod(rFactorial, MOD-2, MOD);
return (first * second) % MOD;
}
static void printBitRepr(int n) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < 32; i++) {
int mask = (1 << i);
res.append((mask & n) == 0 ? "0" : "1");
}
out.println(res);
}
static String bitString(int n) {return Integer.toString(n);}
static int setKthBitToOne(int n, int k) { return (n | (1 << k)); } // zero indexed
static int setKthBitToZero(int n, int k) { return (n & ~(1 << k)); }
static int invertKthBit(int n, int k) { return (n ^ (1 << k)); }
static boolean isPowerOfTwo(int n) { return (n & (n - 1)) == 0; }
static HashMap<Character, Integer> counts(String word) {
HashMap<Character, Integer> counts = new HashMap<>();
for (int i = 0; i < word.length(); i++) counts.merge(word.charAt(i), 1, Integer::sum);
return counts;
}
static HashMap<Integer, Integer> counts(int[] arr) {
HashMap<Integer, Integer> counts = new HashMap<>();
for (int value : arr) counts.merge(value, 1, Integer::sum);
return counts;
}
static HashMap<Long, Integer> counts(long[] arr) {
HashMap<Long, Integer> counts = new HashMap<>();
for (long l : arr) counts.merge(l, 1, Integer::sum);
return counts;
}
static HashMap<Character, Integer> counts(char[] arr) {
HashMap<Character, Integer> counts = new HashMap<>();
for (char c : arr) counts.merge(c, 1, Integer::sum);
return counts;
}
static long hash(int x, int y) {
return x* 1_000_000_000L +y;
}
static final Random random = new Random();
static void sort(int[] a) {
int n = a.length;// shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void sort(long[] arr) {
shuffleArray(arr);
Arrays.sort(arr);
}
static void shuffleArray(long[] arr) {
int n = arr.length;
for(int i=0; i<n; ++i){
long tmp = arr[i];
int randomPos = i + random.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
}
static class Tuple implements Comparable<Tuple> {
long a;
long b;
long c;
public Tuple(long a, long b) {
this.a = a;
this.b = b;
this.c = 0;
}
public Tuple(long a, long b, long c) {
this.a = a;
this.b = b;
this.c = c;
}
public long getA() { return a; }
public long getB() { return b; }
public long getC() { return c; }
public int compareTo(Tuple other) {
if (this.a == other.a) {
if (this.b == other.b) return Long.compare(this.c, other.c);
return Long.compare(this.b, other.b);
}
return Long.compare(this.a, other.a);
}
@Override
public int hashCode() { return Arrays.deepHashCode(new Long[]{a, b, c}); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Tuple)) return false;
Tuple pairo = (Tuple) o;
return (this.a == pairo.a && this.b == pairo.b && this.c == pairo.c);
}
@Override
public String toString() { return String.format("(%d %d %d) ", this.a, this.b, this.c); }
}
private static int abs(int a){ return (a>=0) ? a: -a; }
private static int min(int... ins){ int min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static int max(int... ins){ int max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static int sum(int... ins){ int total = 0; for (int v : ins) { total += v; } return total; }
private static long abs(long a){ return (a>=0) ? a: -a; }
private static long min(long... ins){ long min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static long max(long... ins){ long max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static long sum(long... ins){ long total = 0; for (long v : ins) { total += v; } return total; }
private static double abs(double a){ return (a>=0) ? a: -a; }
private static double min(double... ins){ double min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static double max(double... ins){ double max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static double sum(double... ins){ double total = 0; for (double v : ins) { total += v; } return total; }
}
|
java
|
1294
|
B
|
B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
|
[
"implementation",
"sortings"
] |
import java.util.Arrays;
import java.util.Scanner;
public class sol {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[][] arr = new int[n][2];
for (int i = 0; i < n; i++) {
arr[i][0] = sc.nextInt();
arr[i][1] = sc.nextInt();
}
Arrays.sort(arr, (a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]));
StringBuilder sb = new StringBuilder();
boolean ok = true;
int x = 0, y = 0;
for (int i = 0; i < n; i++) {
if (arr[i][1] < y) {
ok = false;
break;
}
while (x < arr[i][0]) {
sb.append("R");
x++;
}
while (y < arr[i][1]) {
sb.append("U");
y++;
}
}
if (ok) {
System.out.println("YES");
System.out.println(sb);
} else {
System.out.println("NO");
}
}
}
}
|
java
|
1312
|
C
|
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.
|
[
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] |
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static final int INF = 0x3f3f3f3f;
static final long LNF = 0x3f3f3f3f3f3f3f3fL;
public static void main(String[] args) throws IOException {
initReader();
int t=nextInt();
while (t--!=0){
int n=nextInt();
int k=nextInt();
long[]a=new long[n+1];
for(int i=1;i<=n;i++){
a[i]=nextLong();
}
int[]K=new int[101];
boolean ans=true;
for(int i=1;i<=n;i++) {
long p = a[i];
if (a[i] == 0) continue;
ArrayList<Integer> arr = new ArrayList<>();
for (int j = 100; j >= 0; j--) {
if (K[j] == 1) continue;
if ((long)Math.pow(k, j) <= p) {
p-= (long) Math.pow(k, j);
arr.add(j);
}
}
if (p == 0) {
for (int j = 0; j < arr.size(); j++) {
K[arr.get(j)] = 1;
}
} else {
ans = false;
break;
}
}
if(ans)pw.println("YES");
else pw.println("NO");
}
pw.close();
}
/***************************************************************************************/
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter pw;
public static void initReader() throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer("");
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
// 从文件读写
// reader = new BufferedReader(new FileReader("test.in"));
// tokenizer = new StringTokenizer("");
// pw = new PrintWriter(new BufferedWriter(new FileWriter("test1.out")));
}
public static boolean hasNext() {
try {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
public static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static char nextChar() throws IOException {
return next().charAt(0);
}
}
|
java
|
1285
|
D
|
D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.
|
[
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] |
/*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 0; t < test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
Set<Long> set = new HashSet<>();
for (int i = 0; i < n; i++) {
long val = sc.nextLong();
set.add(val);
}
out.println(drEvilUnderscores(set, 30));
}
private static long drEvilUnderscores(Set<Long> set, int bitPosition) {
if (bitPosition == 0) {
return 0;
}
Set<Long> set0 = new HashSet<>();
Set<Long> set1 = new HashSet<>();
long currMask = (1 << (bitPosition - 1));
for (long val : set) {
if ((currMask & val) == 0) {
set0.add(val);
}else {
set1.add(val);
}
}
if (set0.size() == 0) {
return drEvilUnderscores(set1, bitPosition - 1);
}
if (set1.size() == 0) {
return drEvilUnderscores(set0, bitPosition - 1);
}
return (1 << (bitPosition - 1)) + Math.min(drEvilUnderscores(set0, bitPosition - 1), drEvilUnderscores(set1, bitPosition - 1));
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException end)
{
end.printStackTrace();
}
}
return str.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 end)
{
end.printStackTrace();
}
return str;
}
}
}
|
java
|
1141
|
A
|
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.
|
[
"implementation",
"math"
] |
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// PrintWriter out=new PrintWriter(System.out);
Scanner sc=new Scanner(System.in);
// String testcases[]=br.readLine().split(" ");
// int t=Integer.parseInt(testcases[0]);
int n=sc.nextInt();
int m=sc.nextInt();
if(m%n==0)
{
int req=m/n;
int two=0;
while(req%2==0)
{
two++;
req/=2;
}
int three=0;
while(req%3==0)
{
three++;
req/=3;
}
if(req!=1)
System.out.println("-1");
else
System.out.println(two+three);
}
else
System.out.println("-1");
}
// static ArrayList<Integer> getFactors(int n)
// {
// ArrayList<Integer> al=new ArrayList<>();
// for(int i=1;i<=Math.sqrt(n);i++)
// {
// if(n%i==0)
// {
// al.add(i);
// if(n/i!=i)
// al.add(n/i);
// }
// }
// return al;
// }
// static void sort(long[] a) {
// ArrayList<Long> l=new ArrayList<>();
// for (long i:a) l.add(i);
// Collections.sort(l);
// for (int i=0; i<a.length; i++) a[i]=l.get(i);
// }
// static int gcd(int a, int b) {
// return b==0?a:gcd(b, a%b);
// }
// static int lcm(int a, int b){
// return ((a/gcd(a,b))*b);
// }
// static boolean coprime(int a, int b) {
// if(a==1||b==1)
// return true;
// if ( __gcd(a, b) == 1)
// return true;
// else
// return false;
// }
// private static boolean checkSquare(long n)
// {
// if (Math.ceil((double)Math.sqrt(n)) ==
// Math.floor((double)Math.sqrt(n)))
// return true;
// else
// return false;
// }
// private static long floorSqrt(long x)
// {
// if (x == 0 || x == 1)
// return x;
// long start = 1, end = x / 2, ans = 0;
// while (start <= end) {
// long mid = (start + end) / 2;
// if (mid * mid == x)
// return (int)mid;
// if (mid * mid < x) {
// start = mid + 1;
// ans = mid;
// }
// else
// end = mid - 1;
// }
// return (long)ans;
// }
}
// class Pair{
// int a=0;
// int b=0;
// Pair(int x, int y)
// {
// this.a=x;
// this.b=y;
// }
// }
|
java
|
1304
|
E
|
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
|
[
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] |
import java.io.*;
import java.util.*;
public class Main {
static int[] depth;
static int[][] table;
static ArrayList<Integer>[] tree;
static void dfs(int curr,int p) {
table[curr][0]=p;
for (int i=1;i<18;i++) {
table[curr][i]=table[table[curr][i-1]][i-1];
}
for(int child:tree[curr]) {
if(child!=p) {
depth[child]=1+depth[curr];
dfs(child,curr);
}
}
}
static int lca(int u, int v)
{
if(depth[u]<depth[v]) {
int temp=u;
u=v;
v=temp;
}
for (int i=17;i>-1;i--) {
if ((depth[u]-(int)Math.pow(2, i))>=depth[v]) {
u=table[u][i];
}
}
if (u==v) {
return u;
}
for(int i=17;i>-1;i--) {
if (table[u][i]!=table[v][i]) {
u=table[u][i];
v=table[v][i];
}
}
return table[u][0];
}
static int dist(int a, int b) {
int c = lca(a, b);
int ans = depth[a] + depth[b] - 2*depth[c];
return ans;
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int ttt=1;
// ttt=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
for(int tt=0;tt<ttt;tt++) {
int n=f.nextInt();
tree=new ArrayList[n];
depth=new int[n];
table=new int[n][19];
for(int i=0;i<n;i++) tree[i]=new ArrayList<>();
for(int i=0;i<n-1;i++) {
int u=f.nextInt()-1;
int v=f.nextInt()-1;
tree[u].add(v);
tree[v].add(u);
}
dfs(0,0);
int q=f.nextInt();
for(int i=0;i<q;i++) {
int x=f.nextInt()-1;
int y=f.nextInt()-1;
int a=f.nextInt()-1;
int b=f.nextInt()-1;
int k=f.nextInt();
int d1 = dist(a, b);
int d2 = dist(a, x) + 1 + dist(y, b);
int d3 = dist(a, y) + 1 + dist(x, b);
boolean w1 = d1 <= k && (k-d1)%2==0;
boolean w2 = d2 <= k && (k-d2)%2==0;
boolean w3 = d3 <= k && (k-d3)%2==0;
if (w1 || w2 || w3) {
out.println("YES");
} else {
out.println("NO");
}
}
}
out.close();
}
static void sort(int[] p) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: p) q.add( i);
Collections.sort(q);
for (int i = 0; i < p.length; i++) p[i] = q.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
}
|
java
|
1311
|
E
|
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example:
|
[
"brute force",
"constructive algorithms",
"trees"
] |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jaynil
*/
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);
EConstructTheBinaryTree solver = new EConstructTheBinaryTree();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class EConstructTheBinaryTree {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int d = in.nextInt();
int tot = (n * (n - 1)) / 2;
PriorityQueue<int[]> highest = new PriorityQueue<>((x, y) -> x[1] - y[1]);
PriorityQueue<int[]> lowest = new PriorityQueue<>((x, y) -> y[1] - x[1]);
if (d > tot) {
out.println("NO");
return;
}
//p d c
int a[][] = new int[n][4];
for (int i = 0; i < n; i++) {
a[i][0] = i - 1;
a[i][1] = i;
a[i][2] = 1;
a[i][3] = i;
highest.add(a[i]);
lowest.add(a[i]);
}
a[n - 1][2] = 0;
while (highest.size() > 0 && lowest.size() > 0 && tot - d > 0) {
int[] h = highest.poll();
if (h[2] == 2) continue;
int[] l = lowest.poll();
if (l[2] > 0) {
highest.add(h);
continue;
}
if (tot - l[1] + 1 + h[1] >= d) {
tot = tot - l[1] + 1 + h[1];
h[2]++;
a[l[0]][2]--;
l[1] = h[1] + 1;
l[0] = h[3];
highest.add(l);
highest.add(h);
} else {
lowest.add(l);
}
}
if (tot == d) {
out.println("YES");
for (int i = 1; i < n; i++) {
out.print((a[i][0] + 1) + " ");
}
out.println();
} else {
out.println("NO");
// out.println(tot);
// out.println(highest.size());
// out.println(lowest.size());
// for(int i=1;i<n;i++){
// out.print((a[i][0]+1) + " ");
// }
out.println();
}
}
}
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());
}
}
}
|
java
|
1296
|
A
|
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
|
[
"math"
] |
import java.util.Scanner;
public class hello
{
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
for(int i=0;i<n1;i++){
int n = sc.nextInt();
boolean odd = false;
boolean even = false;
int sum = 0;
for(int m=0;m<n;m++){
int t = sc.nextInt();
sum += t;
if(t%2 == 0){
even = true;
}else{
odd = true;
}
}
if(sum%2 != 0){
System.out.println("YES");
}else{
if(odd == true && even == true){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
}
}
|
java
|
1316
|
A
|
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.
|
[
"implementation"
] |
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
int t = kb.nextInt();
while(t-- > 0)
{
int n = kb.nextInt();
int x = kb.nextInt();
// int[ ] arr1 = new int[n];
int sum=0;
for(int i=0;i<n;i++)
{
sum += kb.nextInt();
}
System.out.println(Math.min(sum , x));
}
}
}
|
java
|
1288
|
E
|
E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3]
|
[
"data structures"
] |
import java.io.*;
public class Main {
static class BIT{
int[] t;
int N;
public BIT(int n) {
N = n;
t = new int[N+1];
}
void add(int i, int dx) {
while(i <= N) {
t[i] += dx;
i += i&-i;
}
}
int sum(int i) {
int s = 0;
while(i > 0) {
s += t[i];
i -= i&-i;
}
return s;
}
int sum(int l, int r) {
return sum(r) - sum(l-1);
}
}
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
public static int nextInt()throws IOException { in.nextToken(); return (int)in.nval; }
public static String next()throws IOException { in.nextToken(); return (String)in.sval; }
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static int MN = (int)3e5 + 5;
static int[] lst = new int[MN];
static int[] mn = new int[MN];
static int[] mx = new int[MN];
public static void main(String[] args) throws IOException {
int n = nextInt();
int m = nextInt();
BIT bit = new BIT(n+m);
for(int i=1; i<=n; ++i) {
lst[i] = n+1-i;
mn[i] = i;
mx[i] = i;
bit.add(lst[i], 1);
}
for(int i=1; i<=m; ++i) {
int t = nextInt();
mn[t] = 1;
mx[t] = Math.max(mx[t], bit.sum(lst[t], n+m));
bit.add(lst[t], -1);
lst[t] = n+i;
bit.add(lst[t], 1);
}
for(int i=1; i<=n; ++i)
mx[i] = Math.max(mx[i], bit.sum(lst[i], n+m));
for(int i=1; i<=n; ++i)
out.printf("%d %d\n", mn[i], mx[i]);
out.flush();
out.close();
}
}
|
java
|
1288
|
D
|
D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
|
[
"binary search",
"bitmasks",
"dp"
] |
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
//BufferedReader f = new BufferedReader(new FileReader("uva.in"));
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[][] a = new int[n][m];
for(int i = 0; i < n; i++) {
st = new StringTokenizer(f.readLine());
for(int j = 0; j < m; j++) {
a[i][j] = Integer.parseInt(st.nextToken());
}
}
int L = 1 << m;
int low = 0;
int high = 1000000000;
int x = 0;
int y = 0;
while(low <= high) {
int mid = (low+high)/2;
int[] idx = new int[L];
for(int i = 0; i < n; i++) {
int temp = 0;
for(int j = 0; j < m; j++) {
temp <<= 1;
if(a[i][j] >= mid) {
temp |= 1;
}
}
idx[temp] = i+1;
}
boolean flag = false;
for(int i = 0; i < L; i++) {
for(int j = 0; j < L; j++) {
if(idx[i] > 0 && idx[j] > 0 && (i|j) == L-1) {
flag = true;
x = idx[i];
y = idx[j];
break;
}
}
if(flag) {
break;
}
}
if(flag) {
low = mid+1;
} else {
high = mid-1;
}
}
out.println(x + " " + y);
f.close();
out.close();
}
}
|
java
|
1321
|
A
|
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
|
[
"greedy"
] |
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class A_Contest_for_Robots {
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = 1;
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
int n = f.nextInt();
int r[] = f.nextArray(n);
int b[] = f.nextArray(n);
int onlyR = 0;
int onlyB = 0;
for(int i = 0; i < n; i++) {
if(r[i] == 1 && b[i] == 0) {
onlyR++;
}
if(r[i] == 0 && b[i] == 1) {
onlyB++;
}
}
if(onlyR == 0) {
out.println(-1);
return;
}
int ans = onlyB/onlyR + 1;
out.println(ans);
// int countr = 0;
// int countb = 0;
// int count = 0;
// for(int i = 0; i < n; i++) {
// if(r[i] == 1) {
// countr++;
// }
// if(b[i] == 1) {
// countb++;
// }
// if(r[i] == 1 && b[i] == 0) {
// count++;
// }
// }
// if(count == 0) {
// out.println(-1);
// return;
// }
// if(countr > countb) {
// out.println(1);
// return;
// }
// int x = (countb-(countr-count));
// int ans = x/count + 1;
// out.println(ans);
}
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
public static int gcd(int a, int b) {
int dividend = a > b ? a : b;
int divisor = a < b ? a : b;
while(divisor > 0) {
int reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
public static int lcm(int a, int b) {
int lcm = gcd(a, b);
int hcf = (a * b) / lcm;
return hcf;
}
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
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());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
|
java
|
1141
|
B
|
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
|
[
"implementation"
] |
import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.text.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner scn = new Scanner(System.in);
// int t = scn.nextInt();
// while (t-- > 0) {
// }
int n = scn.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=scn.nextInt();
}
// int c1=0;
// for(int i=0;i<n;i++){
// if(arr[i]==1){
// c1++;
// }
// }
// if(c1==0){
// System.out.println(0);
// return;
// }
// int curr=0;
// int max=0;
// for(int i=1; i<n; i++){
// if(arr[i-1]==1 && arr[i]==1){
// curr++;
// }
// if(curr>=max){
// max=curr;
// }
// }
// if(max==0 && arr[0]==1 && arr[n-1]==1){
// max=2;
// System.out.println(max);
// return;
// }
// System.out.println(max+1);
int res=0;
int fans=0;
for (int i = 0; i < n * 2; i++) {
if (arr[i % n] == 1) {
res++;
fans = Math.max(res, fans);
} else {
res = 0;
}
}
System.out.println(fans);
}
}
|
java
|
1295
|
E
|
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2
|
[
"data structures",
"divide and conquer"
] |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import javax.transaction.xa.Xid;
public class Main {
static final long MOD1=1000000007;
//static final long MOD=998244353;
static final long MOD = 1000003;
static final int NTT_MOD1 = 998244353;
static final int NTT_MOD2 = 1053818881;
static final int NTT_MOD3 = 1004535809;
static long MAX = 1000000000000000000l;
public static void main(String[] args){
PrintWriter out = new PrintWriter(System.out);
InputReader sc=new InputReader(System.in);
int n = sc.nextInt();
int[] p = sc.nextIntArray(n);
long[] a = sc.nextLongArray(n);
int[] inv = new int[n];
for (int i = 0; i < inv.length; i++) {
inv[p[i] - 1] = i;
}
LazysegTreemin lg = new LazysegTreemin(n);
for (int i = 0; i < n; i++) {
lg.apply(i, n, a[i]);
}
long min = a[0];
long sum = 0;
for (int i = 0; i < n; i++) {
sum += a[inv[i]];
lg.apply(inv[i], n, -2 * a[inv[i]]);
min = Math.min(min, sum + lg.prod(0, n - 1));
}
System.out.println(min);
}
static class LazysegTreemin{
int size;
long[] dat;
long[] lazy;
long INF=Long.MAX_VALUE/2;
public LazysegTreemin(int n) {
int n_=1;
while (n_<n) {
n_*=2;
}
size=n_;
dat=new long[2*n_-1];
lazy=new long[2*n_-1];
}
void propagate(int k,int l,int r) {
if (lazy[k]!=0) {
dat[k] += lazy[k];
if(r - l > 1) {
lazy[2*k+1] += lazy[k];
lazy[2*k+2] += lazy[k];
}
lazy[k] = 0;
}
}
void add(int a,int b,long x,int k,int l,int r) {//a<=x<b加算 add(...,0,0,seg.size)で呼ぶ
this.propagate(k,l,r);
if (a<=l&&r<=b) {
lazy[k]+=x;
this.propagate(k,l,r);
}
else if (l<b&&a<r) {//交わっている場合
this.add(a, b, x, k*2+1,l,(l+r)/2);
this.add(a, b, x, k*2+2, (l+r)/2, r);
dat[k] = Math.min(dat[2*k+1],dat[2*k+2]);
}
}
void apply(int a,int b,long x) {
this.add(a, b, x, 0, 0, size);
}
long getmin(int a,int b,int k,int l,int r) {//kが節点番号,l rがその節点番号の範囲
if (r<=a||b<=l) {
return INF;
}
this.propagate(k, l, r);
if (a<=l&&r<=b) {
return dat[k];
}
else {
long vl=this.getmin(a, b, k*2+1,l,(l+r)/2);
long vr=this.getmin(a, b, k*2+2, (l+r)/2, r);
return (Math.min(vl, vr));
}
}
long prod(int a,int b) {
return getmin(a, b, 0, 0, size);
}
}
static class InputReader {
private InputStream in;
private byte[] buffer = new byte[1024];
private int curbuf;
private int lenbuf;
public InputReader(InputStream in) {
this.in = in;
this.curbuf = this.lenbuf = 0;
}
public boolean hasNextByte() {
if (curbuf >= lenbuf) {
curbuf = 0;
try {
lenbuf = in.read(buffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return false;
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[curbuf++];
else
return -1;
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private void skip() {
while (hasNextByte() && isSpaceChar(buffer[curbuf]))
curbuf++;
}
public boolean hasNext() {
skip();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (!isSpaceChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = nextDouble();
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 char[][] nextCharMap(int n, int m) {
char[][] map = new char[n][m];
for (int i = 0; i < n; i++)
map[i] = next().toCharArray();
return map;
}
}
}
|
java
|
13
|
A
|
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.
|
[
"implementation",
"math"
] |
import java.util.*;
import java.io.*;
public class practice {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new PrintWriter(System.out)));
StringBuilder sb = new StringBuilder();
int a = Integer.parseInt(br.readLine());
int sum = 0;
int cnt = 0;
for (int i = 2; i < a; i++) {
int temp = a;
while (temp > 0) {
sum += temp % i;
temp /= i;
}
cnt++;
}
int gcd = gcd(sum, cnt);
while (gcd != 1) {
sum /= gcd;
cnt /= gcd;
gcd = gcd(sum, cnt);
}
sb.append(sum + "/" + cnt);
pw.println(sb.toString().trim());
pw.close();
br.close();
}
public static int gcd(int x, int y) {
if (x == 0) return y;
return gcd(y % x, x);
}
}
|
java
|
1312
|
D
|
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
|
[
"combinatorics",
"math"
] |
import java.io.*;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class copy {
static int log=18;
static int[][] ancestor;
static int[] depth;
static void sieveOfEratosthenes(int n, ArrayList<Integer> arr) {
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a
// prime
if (prime[p]) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++) {
if (prime[i]) {
arr.add(i);
}
}
}
public static long fac(long N, long mod) {
if (N == 0)
return 1;
if(N==1)
return 1;
return ((N % mod) * (fac(N - 1, mod) % mod)) % mod;
}
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;
}
// Returns n^(-1) mod p
static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static long nCrModPFermat(long n, long r,
long p) {
if (n < r)
return 0;
// Base case
if (r == 0)
return 1;
return ((fac(n, p) % p * (modInverse(fac(r, p), p)
% p)) % p * (modInverse(fac(n - r, p), p)
% p)) % p;
}
public static int find(int[] parent, int x) {
if (parent[x] == x)
return x;
return find(parent, parent[x]);
}
public static void merge(int[] parent, int[] rank, int x, int y,int[] child) {
int x1 = find(parent, x);
int y1 = find(parent, y);
if (rank[x1] > rank[y1]) {
parent[y1] = x1;
child[x1]+=child[y1];
} else if (rank[y1] > rank[x1]) {
parent[x1] = y1;
child[y1]+=child[x1];
} else {
parent[y1] = x1;
child[x1]+=child[y1];
rank[x1]++;
}
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static int power(int x, int y, int p)
{
int res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static int nCrModPFermat(int n, int r,
int p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
public static long[][] ncr(int n,int r)
{
long[][] dp=new long[n+1][r+1];
for(int i=0;i<=n;i++)
dp[i][0]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=r;j++)
{
if(j>i)
continue;
dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
}
}
return dp;
}
public static boolean prime(long N)
{
int c=0;
for(int i=2;i*i<=N;i++)
{
if(N%i==0)
++c;
}
return c==0;
}
public static int sparse_ancestor_table(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[] child)
{
int c=0;
for(int i:arr.get(x))
{
if(i!=parent)
{
// System.out.println(i+" hello "+x);
depth[i]=depth[x]+1;
ancestor[i][0]=x;
// if(i==2)
// System.out.println(parent+" hello");
for(int j=1;j<log;j++)
ancestor[i][j]=ancestor[ancestor[i][j-1]][j-1];
c+=sparse_ancestor_table(arr,i,x,child);
}
}
child[x]=1+c;
return child[x];
}
public static int lca(int x,int y)
{
if(depth[x]<depth[y])
{
int temp=x;
x=y;
y=temp;
}
x=get_kth_ancestor(depth[x]-depth[y],x);
if(x==y)
return x;
// System.out.println(x+" "+y);
for(int i=log-1;i>=0;i--)
{
if(ancestor[x][i]!=ancestor[y][i])
{
x=ancestor[x][i];
y=ancestor[y][i];
}
}
return ancestor[x][0];
}
public static int get_kth_ancestor(int K,int x)
{
if(K==0)
return x;
int node=x;
for(int i=0;i<log;i++)
{
if(K%2!=0)
{
node=ancestor[node][i];
}
K/=2;
}
return node;
}
public static ArrayList<Integer> primeFactors(int n)
{
// Print the number of 2s that divide n
ArrayList<Integer> factors=new ArrayList<>();
if(n%2==0)
factors.add(2);
while (n%2==0)
{
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
if(n%i==0)
factors.add(i);
while (n%i == 0)
{
n /= i;
}
}
// This condition is to handle the case when
// n is a prime number greater than 2
if (n > 2)
{
factors.add(n);
}
return factors;
}
static long ans=1,mod=1000000007;
public static void recur(long X,long N,int index,ArrayList<Integer> temp)
{
// System.out.println(X);
if(index==temp.size())
{
System.out.println(X);
ans=((ans%mod)*(X%mod))%mod;
return;
}
for(int i=0;i<=60;i++)
{
if(X*Math.pow(temp.get(index),i)<=N)
recur(X*(long)Math.pow(temp.get(index),i),N,index+1,temp);
else
break;
}
}
public static int upper(ArrayList<Integer> temp,int X)
{
int l=0,r=temp.size()-1;
while(l<=r)
{
int mid=(l+r)/2;
if(temp.get(mid)==X)
return mid;
// System.out.println(mid+" "+temp.get(mid));
if(temp.get(mid)<X)
l=mid+1;
else
{
if(mid-1>=0 && temp.get(mid-1)>=X)
r=mid-1;
else
return mid;
}
}
return -1;
}
public static int lower(ArrayList<Integer> temp,int X)
{
int l=0,r=temp.size()-1;
while(l<=r)
{
int mid=(l+r)/2;
if(temp.get(mid)==X)
return mid;
// System.out.println(mid+" "+temp.get(mid));
if(temp.get(mid)>X)
r=mid-1;
else
{
if(mid+1<temp.size() && temp.get(mid+1)<=X)
l=mid+1;
else
return mid;
}
}
return -1;
}
public static int[] check(String shelf,int[][] queries)
{
int[] arr=new int[queries.length];
ArrayList<Integer> indices=new ArrayList<>();
for(int i=0;i<shelf.length();i++)
{
char ch=shelf.charAt(i);
if(ch=='|')
indices.add(i);
}
for(int i=0;i<queries.length;i++)
{
int x=queries[i][0]-1;
int y=queries[i][1]-1;
int left=upper(indices,x);
int right=lower(indices,y);
if(left<=right && left!=-1 && right!=-1)
{
arr[i]=indices.get(right)-indices.get(left)+1-(right-left+1);
}
else
arr[i]=0;
}
return arr;
}
public static void main(String[] args) throws IOException {
Reader.init(System.in);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
// int T=Reader.nextInt();
// for(int m=1;m<=T;m++)
// {
int N=Reader.nextInt();
int M=Reader.nextInt();
if(N==2)
output.write(0+"\n");
else
{
long mod = 998244353;
long ans = nCrModPFermat(M, N - 1, mod) % mod;
ans = ((ans % mod) * ((N - 2) % mod)) % mod;
ans = ((ans % mod) * ((power(2, N - 3, mod)) % mod)) % mod;
output.write(ans + "");
}
output.flush();
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
left=null;
right=null;
this.data=data;
}
}
class div {
long x;
long y;
div(long x,long y) {
this.x = x;
this.y=y;
}
}
|
java
|
1303
|
E
|
E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
|
[
"dp",
"strings"
] |
// I know stuff but probably my rating tells otherwise...
// It is strange,-but true; for truth is always strange;
// Stranger than fiction: if it could be told,
// How much would novels gain by the exchange!
// How differently the world would men behold!
// Kya hua, code samajhne ki koshish kar rhe ho?? Mat karo,
// mujhe bhi samajh nhi aata kya likha hai
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class _1303E {
static char a[], b[];
static int dp[][][] = new int[401][401][401];
static void Mangni_ke_bail_ke_dant_na_dekhal_jye() {
t = ni();
here:
while (t-- > 0) {
a = ns().toCharArray();
b = ns().toCharArray();
n = a.length;
m = b.length;
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < m + 1; j++)
for (int k = 0; k < m + 1; k++)
dp[i][j][k] = -1;
}
for (int k = 0; k < m; k++) {
if (laura_lassan(k) == m - k) {
pl("YES");
continue here;
}
}
pl("NO");
}
}
static int laura_lassan(int k) {
int dp[] = new int[k + 1];
Arrays.fill(dp, -mod9);
dp[0] = 0;
for (int i = 0; i < n; i++) {
for (int j = k; j >= 0; j--) {
if(dp[j] >= 0) {
if (j < k && a[i] == b[j]) {
dp[j + 1] = max(dp[j], dp[j + 1]);
}
if(dp[j] < m - k && a[i] == b[k + dp[j]]){
dp[j]++;
}
}
}
}
return dp[k];
}
//----------------------------------------The main code ends here------------------------------------------------------
/*-------------------------------------------------------------------------------------------------------------------*/
//-----------------------------------------Rest's all dust-------------------------------------------------------------
static int mod9 = 1_000_000_007;
static int n, m, l, k, t;
static AwesomeInput input;
static PrintWriter pw;
static long power(long a, long b) {
long x = max(a, b);
if (b == 0) return 1;
if ((b & 1) == 1) return a * power(a * a, b >> 1);
return power(a * a, b >> 1);
}
// The Awesome Input Code is a fast IO method //
static class AwesomeInput {
private InputStream letsDoIT;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private AwesomeInput(InputStream incoming) {
this.letsDoIT = incoming;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = letsDoIT.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private long ForLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
private String ForString() {
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 interface SpaceCharFilter {
boolean isSpaceChar(int ch);
}
}
// functions to take input//
static int ni() {
return (int) input.ForLong();
}
static String ns() {
return input.ForString();
}
static long nl() {
return input.ForLong();
}
//functions to give output
static void pl() {
pw.println();
}
static void p(Object o) {
pw.print(o + " ");
}
static void pws(Object o) {
pw.print(o + "");
}
static void pl(Object o) {
pw.println(o);
}
// Fast Sort is Radix Sort
public static int[] fastSort(int[] f) {
int n = f.length;
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;
}
public static void main(String[] args) { //threading has been used to increase the stack size.
try {
input = new AwesomeInput(System.in);
pw = new PrintWriter(System.out, true);
input = new AwesomeInput(new FileInputStream("/home/saurabh/Desktop/input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("/home/saurabh/Desktop/output.txt")), true);
} catch (Exception e) {
}
new Thread(null, null, "AApan_gand_hawai_dusar_ke_kare_dawai", 1 << 25) //the last parameter is stack size desired.
{
public void run() {
try {
double s = System.currentTimeMillis();
Mangni_ke_bail_ke_dant_na_dekhal_jye();
//System.out.println(("\nExecution Time : " + ((double) System.currentTimeMillis() - s) / 1000) + " s");
pw.flush();
pw.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
}
|
java
|
1299
|
A
|
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
|
[
"brute force",
"greedy",
"math"
] |
import java.util.*;
import java.io.*;
public class Practice {
static boolean multipleTC = false;
FastReader in;
PrintWriter out;
static int mod = (int) (1e9 + 7);
static int mod2 = 998244353;
int parent[];
int rank[];
ArrayList<Integer> primes;
boolean sieve[];
int pf[];
int MAX = 1000005;
int dirX[] = { 1, -1, 0, 0 };
int dirY[] = { 0, 0, -1, 1 };
public static void main(String[] args) throws Exception {
new Practice().run();
}
void run() throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++)
solve(t);
out.flush();
out.close();
}
void pre() throws Exception {
}
// declare all variables fucking long even array indices.
// if you are copying some code make sure you done all necessary modifications
// that's leads WA.
// Divide by Zero Exception Ruin Your Life.
// Number Format Exception : Make sure you read constraint carefully.
// Always use TreeMap instead of HashMap.
// Always write comparators using wrapper classes;
// Integer wrapper class are traitor;
void solve(int TC) throws Exception {
int n = ni();
int arr[] = readArr(n);
if(n==1) {
pn(arr[0]);
return;
}
int idx = -1;
for(int i=31;i>=0;i--) {
int count =0;
for(int k = 0;k<n;k++) {
if((arr[k]&(1<<i))!=0) {
idx =k;
count++;
}
}
if(count==1) {
break;
}
}
StringBuilder ans = new StringBuilder();
idx= idx==-1?0:idx;
ans.append(arr[idx]+" ");
for(int i=0;i<n;i++ ) {
if(i==idx)continue;
ans.append(arr[i]+" ");
}
pn(ans);
}
ArrayList<Integer> getDivisors(int n) {
ArrayList<Integer> res = new ArrayList<>();
for (int i = 2; i * i <= n; i++) {
res.add(i);
if (i != n / i) {
res.add(n / i);
}
}
Collections.sort(res);
return res;
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
public StringBuilder printArr(int arr[]) {
StringBuilder sb = new StringBuilder();
int n = arr.length;
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
return sb;
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
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() throws Exception {
return in.next();
}
String nln() throws Exception {
return in.nextLine();
}
int ni() throws Exception {
return Integer.parseInt(in.next());
}
long nl() throws Exception {
return Long.parseLong(in.next());
}
double nd() throws Exception {
return Double.parseDouble(in.next());
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
}
|
java
|
1324
|
A
|
A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.
|
[
"implementation",
"number theory"
] |
// package c1324;
//
// Codeforces Round #627 (Div. 3) 2020-03-12 05:05
// A. Yet Another Tetris Problem
// https://codeforces.com/contest/1324/problem/A
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You are given some Tetris field consisting of n columns. The initial height of the i-th column of
// the field is a_i blocks. On top of these columns you can place figures of size 2 x 1 (i.e. the
// height of this figure is 2 blocks and the width of this figure is 1 block). Note that you rotate
// these figures.
//
// Your task is to say if you can clear the whole field by placing such figures.
//
// More formally, the problem can be described like this:
//
// The following process occurs while :
// 1. You place one figure 2 x 1 (choose some i from 1 to n and replace a_i with a_i + 2);
// 2. then, while all a_i are greater than zero, replace each a_i with a_i - 1.
//
// And your task is to determine if it is possible to clear the whole field (i.e. finish the
// described process), choosing the places for new figures properly.
//
// You have to answer t independent test cases.
//
// Input
//
// The first line of the input contains one integer t (1 <= t <= 100) -- the number of test cases.
//
// The next 2t lines describe test cases. The first line of the test case contains one integer n (1
// <= n <= 100) -- the number of columns in the Tetris field. The second line of the test case
// contains n integers a_1, a_2, ..., a_n (1 <= a_i <= 100), where a_i is the initial height of the
// i-th column of the Tetris field.
//
// Output
//
// For each test case, print the answer -- "YES" (without quotes) if you can clear the whole Tetris
// field and "NO" otherwise.
//
// Example
/*
input:
4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
output:
YES
NO
YES
YES
*/
// Note
//
// The first test case of the example field is shown below:
//
// https://espresso.codeforces.com/c3b3d19786c16dfd52f9729d83217c7154a5852f.png
//
// Gray lines are bounds of the Tetris field. Note that the field has no upper bound.
//
// One of the correct answers is to first place the figure in the first column. Then after the
// second step of the process, the field becomes [2, 0, 2]. Then place the figure in the second
// column and after the second step of the process, the field becomes [0, 0, 0].
//
// And the second test case of the example field is shown below:
//
// https://espresso.codeforces.com/9e670fa3eabfebd5ecdfa6085157f1f4ccfe494e.png
//
// It can be shown that you cannot do anything to end the process.
//
// In the third test case of the example, you first place the figure in the second column after the
// second step of the process, the field becomes [0, 2]. Then place the figure in the first column
// and after the second step of the process, the field becomes [0, 0].
//
// In the fourth test case of the example, place the figure in the first column, then the field
// becomes [102] after the first step of the process, and then the field becomes [0] after the
// second step of the process.
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1324A {
static final int MOD = 998244353;
static final Random RAND = new Random();
static boolean solve(int[] a) {
int n = a.length;
for (int v : a) {
int w = Math.abs(v - a[0]);
if (w % 2 != 0) {
return false;
}
}
return true;
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
boolean ans = solve(a);
System.out.println(ans? "YES" : "NO");
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 4000) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
java
|
1141
|
D
|
D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
|
[
"greedy",
"implementation"
] |
// package codeforce;
import java.util.*;
import java.net.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.io.*;
public class A {
static class Node {
int id1;
int id2;
Node(int v1, int w1){
this.id1= v1;
this.id2=w1;
}
Node(){}
}
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;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
}
static boolean[] seiveofEratoSthenes(int n) {
boolean[] isPrime= new boolean[n+1];
Arrays.fill(isPrime, true);
isPrime[0]=false;
isPrime[1]= false;
for(int i=2;i*i<=n;i++) {
for(int j=2*i; j<=n;j=j+i) {
isPrime[j]= false;
}
}
return isPrime;
}
static int in = 2;
// Function check whether a number
// is prime or not
public static boolean isPrime(int n)
{
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static class SortingComparator implements Comparator<Node>{
@Override
public int compare(Node p1, Node p2) {
// int n = p1.id1-p2.id1;
// if(n!=0)return n;
return p1.id2-p2.id2;
}
}
static int pp =1;
static long[] dp = new long[500001];
public static void main(String[] args) throws UnknownHostException {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
long n = sc.nextLong();
char[] a= sc.next().toCharArray();
char[] b = sc.next().toCharArray();
HashMap<Character, PriorityQueue<Integer>> hs = new HashMap<>();
HashSet<Integer> anonq= new HashSet<Integer>();
for(int i=0; i<a.length; i++) {
if(hs.containsKey(a[i])) {
PriorityQueue<Integer> al = hs.get(a[i]);
al.add(i);
hs.put(a[i], al);
}
else {
PriorityQueue<Integer> al= new PriorityQueue<Integer>();
al.add(i);
hs.put(a[i], al);
}
if(a[i]!='?')anonq.add(i);
}
int ans =0;
HashMap<Integer, Integer> hm = new HashMap<>();
PriorityQueue<Integer> bques= new PriorityQueue<Integer>();
PriorityQueue<Integer> bnonq= new PriorityQueue<Integer>();
for(int i=0; i<b.length; i++) {
if(hs.containsKey(b[i]) && b[i]!='?') {
ans++;
PriorityQueue<Integer> al = hs.get(b[i]);
int p = al.poll();
hm.put(i, p);
anonq.remove(p);
if(al.size()==0) {
hs.remove(b[i]);
}
}
else if(b[i]=='?'){
bques.add(i);
}
else {
bnonq.add(i);
}
}
PriorityQueue<Integer> aques= new PriorityQueue<Integer>();
if(hs.containsKey('?')) {
for(int e:hs.get('?')) {
aques.add(e);
}
}
while(aques.size()>0 && bnonq.size()>0) {
ans++;
hm.put(bnonq.poll(), aques.poll());
}
PriorityQueue<Integer> ano= new PriorityQueue<Integer>();
for(int e: anonq) {
ano.add(e);
}
while(ano.size()>0 && bques.size()>0) {
ans++;
hm.put(bques.poll(), ano.poll());
}
while(aques.size()>0 && bques.size()>0) {
ans++;
hm.put(bques.poll(), aques.poll());
}
out.println(ans);
for(HashMap.Entry<Integer, Integer> e: hm.entrySet() ) {
out.println((e.getValue()+1)+" "+(e.getKey()+1));
}
out.close();
}
static long nextPowerOf2(long N)
{
// if N is a power of two simply return it
if ((N & (N - 1)) == 0)
return N;
return 0x4000000000000000L
>> (Long.numberOfLeadingZeros(N) - 2);
}
public static int[] solve(int[] arr, int[] it) {
HashMap<Integer, Integer> hm = new HashMap<>();
for(int i=0; i<arr.length; i++) {
hm.put(arr[i], hm.getOrDefault(arr[i], 0)+1);
}
for(int i=0; i<arr.length; i++) {
it[i]= hm.get(arr[i]);
}
return it;
}
public static void rec(int l, int e, int[] arr) {
if(l>e || e>=arr.length || l<=0)return;
int mid = (e-l+1)%2==0?(e+l-1)/2:(e+l)/2;
if(arr[mid]==0 ) {
arr[mid]=pp;
pp++;
// if(pp>1)return;
}
if(e-mid-1<=mid-l-1) {rec(l, mid-1, arr);
rec(mid+1, e, arr);
}
else {
rec(mid+1, e, arr);
rec(l, mid-1, arr);
}
}
static double fact(double n)
{
int i=1;
double fact=1;
while(i<=n)
{
fact=fact*i;
i++;
}
return fact;
}
static double combination(int n,int r)
{
double com=fact(n)/(fact(n-r)*fact(r));
return com;
}
static boolean digit(long n) {
long ans = n;
while(n>0) {
long rem = n%10;
if(rem!=0 && ans%rem!=0)return false;
n=n/10;
}
return true;
}
static int nCr(int n, int r)
{
return fact(n) / (fact(r) *
fact(n - r));
}
// Returns factorial of n
static int fact(int n)
{
int res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l, Collections.reverseOrder());
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static boolean isPalindrome(char[] arr, int i, int j) {
while(i<j) {
if(arr[i]!=arr[j])return false;
i++;
j--;
}
return true;
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static int max =0;
static void dfs(int i, boolean[] vis , ArrayList<ArrayList<Integer>> adj) {
max = Math.max(max, i);
vis[i]= true;
for(int e: adj.get(i)) {
if(vis[e]==false) {
dfs(e, vis, adj);
}
}
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static double pow(int a, int b) {
long res= 1;
while(b>0) {
if((b&1)!=0) {
res= (res*a);
}
a= (a*a);
b= b>>1;
}
return res;
}
static void permute(String s , String answer, HashSet<String> hs)
{
if (s.length() == 0)
{
hs.add(answer);
return;
}
for(int i = 0 ;i < s.length(); i++)
{
char ch = s.charAt(i);
String left_substr = s.substring(0, i);
String right_substr = s.substring(i + 1);
String rest = left_substr + right_substr;
permute(rest, answer + ch, hs);
}
}
}
|
java
|
1307
|
A
|
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Next 2t2t lines contain a description of test cases — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100) — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.
|
[
"greedy",
"implementation"
] |
import java.util.* ;
import java.math.*;
import java.io.*;
public class javaTemplate {
public static final int M = 1000000007 ;
static FastReader sc = new FastReader();
// static Scanner sc = new Scanner(System.in) ;
public static void main(String[] args) {
int t = sc.nextInt() ;
while(t -- != 0) {
int n = sc.nextInt() ;
int d = sc.nextInt() ;
int arr[] = new int[n] ;
for(int i = 0 ; i< n ; i++) {
arr[i] = sc.nextInt() ;
}
while(d -- != 0) {
for(int i = 1 ; i<n ; i++) {
if(arr[i] > 0) {
arr[i]-- ;
arr[i-1] ++ ;
break ;
}
}
}
System.out.println(arr[0]);
}
}
//_________________________//Template//_____________________________________________________________________
// FAST I/O
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;
}
}
// Check Perfect Squre
public static boolean checkPerfectSquare(double number) {
double sqrt=Math.sqrt(number);
return ((sqrt - Math.floor(sqrt)) == 0);
}
static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
// Modulo
static int mod(int a)
{
return (a%M + M) % M;
}
// Palindrom or Not
static boolean isPalindrome(StringBuilder str, int low, int high) {
while (low < high) {
if (str.charAt(low) != str.charAt(high)) return false;
low++;
high--;
}
return true;
}
// Euler Tortient fx
static int Phi(int n) {
int count = 0 ;
for(int i = 1 ; i< n ; i++) {
if(GCD(i,n) == 1) count ++ ;
}
return count ;
}
// Integer Sort
static void sort(int[] a)
{
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
// Long Sort
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
// boolean Value
static void value(boolean val)
{
System.out.println(val ? "YES" : "NO");
System.out.flush();
}
// GCD
public static int GCD(int a , int b) {
if(b == 0) return a ;
return GCD(b, a%b) ;
}
// sieve
public static boolean [] sieveofEratosthenes(int n) {
boolean isPrime[] = new boolean[n+1] ;
Arrays.fill(isPrime, true);
isPrime[0] = false ;
isPrime[1] = false ;
for(int i = 2 ; i * i <= n ; i++) {
for(int j = 2 * i ; j<= n ; j+= i) {
isPrime[j] = false ;
}
}
return isPrime ;
}
// fastPower
public static long fastPowerModulo(long a, long b, long n) {
long res = 1 ;
while(b > 0) {
if((b&1) != 0) {
res = (res * a % n) % n ;
}
a = (a % n * a % n) % n ;
b = b >> 1 ;
}
return res ;
}
// check if sorted or not
public static boolean isSorted(int[] a)
{
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
static int LCM(int a, int b)
{
return (a / GCD(a, b)) * b;
}
}
|
java
|
1287
|
A
|
A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.
|
[
"greedy",
"implementation"
] |
//۰۪۫A۪۫۰۰۪۫B۪۫۰۰۪۫D۪۫۰۰۪۫-۪۫۰۰۪۫A۪۫۰۰۪۫L۪۫۰۰۪۫L۪۫۰۰۪۫A۪۫۰۰۪۫H۪۫۰
import java.util.*;
public class Main {
static Scanner z = new Scanner(System.in);
public static void main(String[] args) {
int d=z.nextInt();
while(d-->0){
int s=z.nextInt();
String c=z.next();
StringBuffer k = new StringBuffer(c);
int count=0;
while(true){
boolean h=false;
String l=k.toString();
StringBuffer r=new StringBuffer("") ;
for (int i = 1; i < s; i++) {
if(k.charAt(i-1)=='A'&&k.charAt(i)=='P'){
k.setCharAt(i, 'A');
h=true;
i++;
}
}
r=k;
if(h){
count++;
}
if(l.equals(r.toString())){
break;
}
}
System.out.println(count);
}
}
}
|
java
|
1141
|
B
|
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
|
[
"implementation"
] |
import java.io.*;
import java.util.*;
public class ProblemA {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
StringBuilder sb = new StringBuilder();
int n = in.readInt();
int a[] = new int[n];
for(int i = 0;i<n;i++){
a[i] = in.readInt();
}
int ans = 0;
for(int i = 0;i<n;i++){
if(a[i] == 1){
int count = 0;
while(i<n && a[i] == 1){
i++;
count++;
}
ans = Math.max(count, ans);
}
}
if(a[0] == 1 && a[n-1] == 1){
int count = 0;
for(int i = n-1;i>=0;i--){
if(a[i] == 1)count++;
else break;
}
for(int i = 0;i<n;i++){
if(a[i] == 1)count++;
else break;
}
ans = Math.max(ans, count);
}
System.out.println(ans);
}
public static int parity(int a){
return a%2;
}
public static void swap(int a[],int i, int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static boolean subsequence(String cur,String t){
int pos = 0;
for(int i = 0;i<cur.length();i++){
if(pos<t.length() && cur.charAt(i) == t.charAt(pos)){
pos++;
}
}
return pos == t.length();
}
public static long gcd(long a, long b){
return b ==0 ?a:gcd(b,a%b);
}
static class Pair{
int x,y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
}
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String read()
{
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int readInt() { return Integer.parseInt(read()); }
public long readLong() { return Long.parseLong(read()); }
public double readDouble(){return Double.parseDouble(read());}
public String readLine() throws Exception { return br.readLine(); }
}
}
|
java
|
1286
|
B
|
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2
|
[
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] |
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.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
BNumbersOnTree solver = new BNumbersOnTree();
solver.solve(1, in, out);
out.close();
}
static class BNumbersOnTree {
int N = 2010;
int M = N * 2;
int[] h = new int[N];
int[] e = new int[M];
int[] ne = new int[M];
int idx;
int n;
int[] a;
boolean f = true;
public void solve(int testNumber, InputReader in, OutputWriter out) {
Arrays.fill(h, -1);
idx = 0;
n = in.nextInt();
a = new int[n + 1];
int root = 0;
for (int i = 1; i <= n; i++) {
int x = in.nextInt();
if (x == 0) {
root = i;
} else {
add(x, i);
add(i, x);
}
a[i] = in.nextInt();
}
LinkedList<Integer> list = dfs(root, root);
if (!f) {
out.println("NO");
return;
}
for (int i = 1; i <= n; i++) {
a[list.get(i - 1)] = i;
}
out.println("YES");
for (int i = 1; i <= n; i++) {
out.print(a[i], "");
}
}
private LinkedList<Integer> dfs(int u, int p) {
LinkedList<Integer> res = new LinkedList<>();
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (j == p) {
continue;
}
res.addAll(dfs(j, u));
}
if (res.size() < a[u]) {
f = false;
return new LinkedList<>();
}
res.add(a[u], u);
return res;
}
void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
java
|
1290
|
A
|
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1) — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.
|
[
"brute force",
"data structures",
"implementation"
] |
import java.io.*;
import java.util.*;
public class tank {
static final FastScanner fs = new FastScanner();
//static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int t = fs.nextInt();
while(t-->0) {
run_case();
}
//out.close();
}
static void run_case() {
int n = fs.nextInt(), m = fs.nextInt(), k = fs.nextInt();
int[] arr = fs.readArray(n);
if(m == 1) {
System.out.println(Math.max(arr[0], arr[n - 1]));
return;
}
ArrayList<Integer> al = new ArrayList<>();
if(k > m - 1) k = m - 1;
int l = k, r = 0, ans = Integer.MAX_VALUE, cur = 0;
for (int i = 0; i <= m - 1; i++) {
al.add(Math.max(arr[i], arr[i + n - m]));
}
while(l >= 0) {
for (int i = l; i <= m - r - 1; i++) {
ans = Math.min(ans, al.get(i));
}
l--;
r++;
cur = Math.max(cur, ans);
ans = Integer.MAX_VALUE;
}
System.out.println(cur);
}
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();
}
String nextLine(){
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
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());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
java
|
1324
|
D
|
D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0
|
[
"binary search",
"data structures",
"sortings",
"two pointers"
] |
import java.util.*;
public class P4{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] a=new int[n];
int[] b=new int[n];
Integer[] c=new Integer[n];
long ans=0;
for (int i=0;i<n;++i) {
a[i]=sc.nextInt();
}
for (int i=0;i<n;++i) {
b[i]=sc.nextInt();
c[i]=a[i]-b[i];
}
Arrays.sort(c);
int l=0,r=n-1;
while(l<r){
if ((c[r]+c[l])>0) {
ans+=r-l;
--r;
}
else{
++l;
}
}
System.out.println(ans);
}
}
|
java
|
1141
|
B
|
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
|
[
"implementation"
] |
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[] a = sc.nextIntArray(n);
int ans = 0;
int max = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
ans = Math.max(max, ans);
max = 0;
} else
max++;
}
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
ans = Math.max(max, ans);
max = 0;
} else
max++;
}
pw.println(ans);
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws IOException {
br = new BufferedReader(new FileReader(file));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
protected String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
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 long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
java
|
1296
|
B
|
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111
|
[
"math"
] |
import java.util.Scanner;
public class foodBuying {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t= sc.nextInt();
for(int i=0;i<t;i++){
int n = sc.nextInt();
int sum=n;
while(n>=10){
int temp = (n-n%10)/10;
sum+= temp;
n =n-temp*10+temp;
}
System.out.println(sum);
}
}
}
|
java
|
1293
|
B
|
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.
|
[
"combinatorics",
"greedy",
"math"
] |
// package com.company.Codeforces;
import java.util.*;
import java.lang.*;
import java.io.*;
public class aaaaaa
{
public static void solve() {
int n = sc.nextInt();
double ans = 0;
for(int i=1; i<=n; i++){
ans += (1.0/i);
}
out.println(ans);
}
static PrintWriter out;
static StringBuilder str;
static Scanner sc;
public static void main (String[] args) throws java.lang.Exception
{
sc = new Scanner();
str = new StringBuilder();
out = new PrintWriter(System.out);
// int t = sc.nextInt();
int t = 1;
while(t-->0){
solve();
// str.append('\n');
}
// out.println(str);
out.close();
}
static long modInverse(long num, long mod){
return power(num, mod-2, mod);
}
private static long power(long a, long b) {
long res = 1;
while (b > 0) {
if ((b & 1)==1)
res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
private static long power(long a, long b, long m) {
a %= m;
long res = 1;
while (b > 0) {
if ((b & 1)==1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
private static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
private static long gcd(long a, long b) {
return (b == 0) ? a : gcd(b, a % b);
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new
InputStreamReader(System.in));
/*
try {
br = new BufferedReader(new
InputStreamReader(new FileInputStream(new File("file_i_o\\input.txt"))));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
*/
}
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;
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
Integer[] nextIntegerArray(int n) {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++) {
array[i] = nextLong();
}
return array;
}
String[] nextStringArray() {
return nextLine().split(" ");
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++) {
array[i] = next();
}
return array;
}
}
}
|
java
|
1301
|
C
|
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
|
[
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] |
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T-- > 0) {
int N = sc.nextInt();
int M = sc.nextInt();
long result = (1L * N * (N + 1)) / 2L;
int Z = N - M;
int K = Z / (M + 1);
result -= (1L * (M + 1) * K * (K + 1)) / 2L;
result -= (1L * (Z % (M + 1)) * (K + 1));
System.out.print(result + " ");
}
}
}
|
java
|
1321
|
A
|
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
|
[
"greedy"
] |
import java.util.*;
public class Sol {
public static void main(String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
for (int i = 0; i < n; i++)
b[i] = in.nextInt();
int c = 0;
int z = 0;
for (int i = 0; i < n; i++) {
if (a[i] == b[i])
continue;
if (b[i] == 1)
z++;
else if (a[i] == 1)
c++;
}
if (c == 0)
System.out.println(-1);
else if (z == 0)
System.out.println(1);
else
System.out.println((z / c) + 1);
in.close();
}
}
|
java
|
1296
|
A
|
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
|
[
"math"
] |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while((t--)>0)
{
int n=sc.nextInt();
int oddCount=0;
int []arr=new int[n];
for (int i = 0; i < n; i++) {
arr[i]= sc.nextInt();
if(arr[i]%2!=0)
{
oddCount++;
}
}
if(oddCount==0 || (oddCount==n && oddCount%2==0))
{
System.out.println("No");
}
else System.out.println("Yes");
}
}
}
|
java
|
1296
|
C
|
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
|
[
"data structures",
"implementation"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
public class Codeforces {
// static int mod = 998244353;
static int mod = 1000000007;
public static void main(String[] args) {
FastReader fastReader = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = fastReader.nextInt();
while (t-- > 0) {
int n = fastReader.nextInt();
char c[] = fastReader.nextLine().toCharArray();
HashMap<String, Integer> map = new HashMap<>();
int ans = -1;
int left = 0, right = 0;
map.put((0 + "*" + 0), -1);
int x = 0, y = 0;
for (int i = 0; i < n; i++) {
if (c[i] == 'L') {
x--;
} else if (c[i] == 'R') {
x++;
} else if (c[i] == 'U') {
y++;
} else {
y--;
}
String cur = x + "*" + y;
if (map.containsKey(cur)) {
if (ans == -1) {
ans = i - (map.get(cur)) + 2;
left = map.get(cur) + 1;
right = i;
} else {
int dis = i - (map.get(cur)) + 2;
if (dis < ans) {
ans = dis;
left = map.get(cur) + 1;
right = i;
}
}
}
map.put(cur, i);
}
if (ans == -1) {
out.println(-1);
} else {
out.println((left + 1) + " " + (right + 1));
}
}
out.close();
}
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
static Random __r = new Random();
// math util
static int minof(int a, int b, int c) {
return min(a, min(b, c));
}
static int minof(int... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return min(x[0], x[1]);
if (x.length == 3)
return min(x[0], min(x[1], x[2]));
int min = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] < min)
min = x[i];
return min;
}
static long minof(long a, long b, long c) {
return min(a, min(b, c));
}
static long minof(long... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return min(x[0], x[1]);
if (x.length == 3)
return min(x[0], min(x[1], x[2]));
long min = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] < min)
min = x[i];
return min;
}
static int maxof(int a, int b, int c) {
return max(a, max(b, c));
}
static int maxof(int... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return max(x[0], x[1]);
if (x.length == 3)
return max(x[0], max(x[1], x[2]));
int max = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] > max)
max = x[i];
return max;
}
static long maxof(long a, long b, long c) {
return max(a, max(b, c));
}
static long maxof(long... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return max(x[0], x[1]);
if (x.length == 3)
return max(x[0], max(x[1], x[2]));
long max = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] > max)
max = x[i];
return max;
}
static int powi(int a, int b) {
if (a == 0)
return 0;
int ans = 1;
while (b > 0) {
if ((b & 1) > 0)
ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static long powl(long a, int b) {
if (a == 0)
return 0;
long ans = 1;
while (b > 0) {
if ((b & 1) > 0)
ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static int fli(double d) {
return (int) d;
}
static int cei(double d) {
return (int) ceil(d);
}
static long fll(double d) {
return (long) d;
}
static long cel(double d) {
return (long) ceil(d);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static int[] exgcd(int a, int b) {
if (b == 0)
return new int[] { 1, 0 };
int[] y = exgcd(b, a % b);
return new int[] { y[1], y[0] - y[1] * (a / b) };
}
static long[] exgcd(long a, long b) {
if (b == 0)
return new long[] { 1, 0 };
long[] y = exgcd(b, a % b);
return new long[] { y[1], y[0] - y[1] * (a / b) };
}
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static long mix(long x) {
x += 0x9e3779b97f4a7c15L;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
return x ^ (x >> 31);
}
public static boolean[] findPrimes(int limit) {
assert limit >= 2;
final boolean[] nonPrimes = new boolean[limit];
nonPrimes[0] = true;
nonPrimes[1] = true;
int sqrt = (int) Math.sqrt(limit);
for (int i = 2; i <= sqrt; i++) {
if (nonPrimes[i])
continue;
for (int j = i; j < limit; j += i) {
if (!nonPrimes[j] && i != j)
nonPrimes[j] = true;
}
}
return nonPrimes;
}
// array util
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
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());
}
int[] ria(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = Integer.parseInt(next());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] rla(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = Long.parseLong(next());
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
java
|
1311
|
A
|
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.
|
[
"greedy",
"implementation",
"math"
] |
import java.util.*;
public class Same{
public static void main(String args[]){
Scanner s=new Scanner(System.in);
//System.out.println("enter n:");
int n=s.nextInt();
for(int i=0;i<n;i++){
int count=0,d=0;
int a=s.nextInt();
int b=s.nextInt();
if(a==b){
System.out.println("0");
continue;
}
if(a>b){
d=a-b;
count+=1;
if(d%2!=0){
count+=1;
}
}
if(a<b){
d=b-a;
count+=1;
if(d%2!=1){
count+=1;
}
}
System.out.println(count);
}
}
}
|
java
|
1301
|
D
|
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
|
[
"constructive algorithms",
"graphs",
"implementation"
] |
import java.util.LinkedList;
import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
solve(s.nextInt(), s.nextInt(), s.nextInt());
}
public static void solve(int h, int w, int d) {
if (d > 4 * h * w - 2 * h - 2 * w) {System.out.println("NO"); return;}
System.out.println("YES");
LinkedList<String> moves = new LinkedList<>();
for (int i = 1; i < w; i++) {
if (d != 0) {
moves.add("1 R");
d--;
}
if (h != 1) {
if (d >= h - 1) {
d -= h - 1;
moves.add((h - 1) + " D");
} else {
if (d == 0) break;
moves.add(d + " D");
d = 0;
break;
}
if (d >= h - 1) {
d -= h - 1;
moves.add((h - 1) + " U");
} else {
if (d == 0) break;
moves.add(d + " U");
d = 0;
break;
}
}
}
if (w != 1) {
if (d >= w - 1) {
d -= w - 1;
moves.add((w - 1) + " L");
} else {
if (d != 0)
moves.add(d + " L");
d = 0;
}
}
for (int i = 1; i < h; i++) {
if (d != 0) {
moves.add("1 D");
d--;
}
if (w != 1) {
if (d >= w - 1) {
d -= w - 1;
moves.add((w - 1) + " R");
} else {
if (d == 0) break;
moves.add(d + " R");
d = 0;
break;
}
if (d >= w - 1) {
d -= w - 1;
moves.add((w - 1) + " L");
} else {
if (d == 0) break;
moves.add(d + " L");
d = 0;
break;
}
}
}
if (h != 1) {
if (d >= h - 1) {
d -= h - 1;
moves.add((h - 1) + " U");
} else {
if (d != 0)
moves.add(d + " U");
d = 0;
}
}
System.out.println(moves.size());
for (String i: moves) System.out.println(i);
}
}
|
java
|
1323
|
B
|
B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is:
|
[
"binary search",
"greedy",
"implementation"
] |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Manav
*/
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);
BCountSubrectangles solver = new BCountSubrectangles();
solver.solve(1, in, out);
out.close();
}
static class BCountSubrectangles {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt();
long k = in.nextLong();
int[] a = in.nextIntArray(n), b = in.nextIntArray(m);
long[] row = new long[n + 1], col = new long[m + 1];
for (int i = 0; i < n; i++) {
if (a[i] == 1) {
int j = i;
while (j < n && a[j] == 1) {
j++;
}
int count = j - i;
for (int l = 1; l <= count; l += 1) {
row[l] += (count - l + 1);
}
i = j - 1;
}
}
for (int i = 0; i < m; i++) {
if (b[i] == 1) {
int j = i;
while (j < m && b[j] == 1) {
j++;
}
int count = j - i;
for (int l = 1; l <= count; l += 1) {
col[l] += (count - l + 1);
}
i = j - 1;
}
}
long ans = 0;
for (long i = 1; i * i <= k; i += 1) {
if (k % i == 0) {
long p = i, q = k / i;
if (p <= n && q <= m) {
ans += row[(int) p] * col[(int) q];
// out.println(p,q,ans);
}
if (q <= n && p <= m && p != q) {
ans += row[(int) q] * col[(int) p];
// out.println(q,p,ans);
}
}
}
// out.println(row);
// out.println(col);
out.println(ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
|
java
|
1141
|
F1
|
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
|
[
"greedy"
] |
// package codeforce.Training1900;
import java.io.PrintWriter;
import java.util.*;
//https://codeforces.com/problemset/problem/1141/F2
public class SameSumBlocks {
// MUST SEE BEFORE SUBMISSION
// check whether int part would overflow or not, especially when it is a * b!!!!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
// int t = sc.nextInt();
int t = 1;
for (int i = 0; i < t; i++) {
solve(sc, pw);
}
pw.close();
}
static void solve(Scanner in, PrintWriter out){
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
Map<Long, List<int[]>> mp = new HashMap<>();
long[] pre = new long[n + 1];
for (int i = 1; i <= n; i++) {
pre[i] = pre[i - 1] + arr[i - 1];
}
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
long sz = pre[j + 1] - pre[i];
if (!mp.containsKey(sz)) mp.put(sz, new ArrayList<>());
mp.get(sz).add(new int[]{i, j});
}
}
int max = 0;
List<int[]> ans = new ArrayList<>();
for(List<int[]> ls : mp.values()){
Collections.sort(ls, (a, b) -> {
if (a[1] == b[1]) return b[0] - a[0];
return a[1] - b[1];
});
List<int[]> tt = new ArrayList<>();
int cnt = 0;
int pr = -1;
for (int i = 0; i < ls.size(); i++) {
int[] get = ls.get(i);
if (get[0] <= pr) continue;
cnt++;
tt.add(get);
pr = get[1];
}
if (max < cnt){
ans = tt;
max = cnt;
}
}
out.println(max);
for(int[] v : ans){
out.println((v[0] + 1) + " " + (v[1] + 1));
}
}
}
|
java
|
1293
|
B
|
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.
|
[
"combinatorics",
"greedy",
"math"
] |
import java.util.Scanner;
public class JoeIsOnTV {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double n = in.nextDouble();
double ans = 0;
while ( n > 0){
ans += 1/n;
n--;
}
System.out.println(ans);
}
}
|
java
|
1304
|
D
|
D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.
|
[
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] |
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
//https://codeforces.com/problemset/problem/1304/D
public class ShortestandLongestLIS {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
solve(sc, pw);
}
pw.close();
}
static void solve(Scanner in, PrintWriter out){
int n = in.nextInt();
String s = in.next();
char[] cs = s.toCharArray();
int[] l1 = findMinLength(n, cs);
int[] l2 = findMaxLength(n, cs);
for(int x : l1){
out.print(x+" ");
}
out.println();
for(int x : l2){
out.print(x+" ");
}
out.println();
}
static int[] findMinLength(int n, char[] cs){
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = n - i;
}
for (int i = 0; i < n - 1; i++) {
int j = i;
while (j < cs.length && cs[j] == '<') j++;
rev(i, j, arr);
if (j > i) i = j - 1;
}
return arr;
}
static int[] findMaxLength(int n, char[] cs){
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
}
for (int i = 0; i < n - 1; i++) {
int j = i;
while (j < cs.length && cs[j] == '>') j++;
rev(i, j, arr);
if (j > i) i = j - 1;
}
return arr;
}
static void rev(int l, int r, int[] arr){
while (l < r){
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;r--;
}
}
// Use this instead of Arrays.sort() on an array of ints. Arrays.sort() is n^2
// worst case since it uses a version of quicksort. Although this would never
// actually show up in the real world, in codeforces, people can hack, so
// this is needed.
static void ruffleSort(int[] a) {
//ruffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n), temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
}
|
java
|
1296
|
A
|
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
|
[
"math"
] |
import java.util.*;
public class acmp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n = sc.nextInt();
int[] arr = new int[n];
boolean even = false;
boolean odd = false;
int c = 0;
for(int j = 0; j < n; j++){
arr[j] = sc.nextInt();
if(arr[j] % 2 == 0) even = true;
else odd = true;
c += arr[j];
}
if(c % 2 == 1) System.out.println("YES");
else{
if(even && odd) System.out.println("YES");
else System.out.println("NO");
}
}
}
}
|
java
|
1307
|
C
|
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
|
[
"brute force",
"dp",
"math",
"strings"
] |
import java.io.*;
import java.util.*;
public class Cow_and_Message {
static FastScanner fs;
static FastWriter fw;
static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null;
private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}};
private static final int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
private static final int iMax = (int) (1e9 + 100), iMin = (int) (-1e9 - 100);
private static final long lMax = (long) (1e18 + 100), lMin = (long) (-1e18 - 100);
private static final int mod1 = (int) (1e9 + 7);
private static final int mod2 = 998244353;
public static void main(String[] args) throws IOException {
fs = new FastScanner();
fw = new FastWriter();
int t = 1;
//t = fs.nextInt();
while (t-- > 0) {
solve();
}
fw.out.close();
}
private static void solve() {
String s = fs.nextLine();
int n = s.length();
long[][] prefix_sum = new long[n + 1][26];
for (int i = n - 1; i >= 0; i--) {
int ascii = s.charAt(i) - 'a';
prefix_sum[i][ascii] = 1;
for (int j = 0; j < 26; j++) {
prefix_sum[i][j] += prefix_sum[i + 1][j];
}
}
List<List<Integer>> indexes = new ArrayList<>();
for (int i = 0; i < 26; i++) {
indexes.add(new ArrayList<>());
}
for (int i = 0; i < n; i++) {
int ascii = s.charAt(i) - 'a';
indexes.get(ascii).add(i);
}
long result = 0;
for (List<Integer> list : indexes) {
result = Math.max(result, list.size());
long[] ans = new long[26];
for (int i : list) {
for (int j = 0; j < 26; j++) {
ans[j] += prefix_sum[i + 1][j];
}
}
for (long x : ans) result = Math.max(result, x);
}
fw.out.println(result);
}
private static class UnionFind {
private final int[] parent;
private final int[] rank;
UnionFind(int n) {
parent = new int[n + 5];
rank = new int[n + 5];
for (int i = 0; i <= n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
private int find(int i) {
if (parent[i] == i)
return i;
return parent[i] = find(parent[i]);
}
private void union(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (rank[a] < rank[b]) {
int temp = a;
a = b;
b = temp;
}
parent[b] = a;
if (rank[a] == rank[b])
rank[a]++;
}
}
}
private static class Calc_nCr {
private final long[] fact;
private final long[] invfact;
private final int p;
Calc_nCr(int n, int prime) {
fact = new long[n + 5];
invfact = new long[n + 5];
p = prime;
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (i * fact[i - 1]) % p;
}
invfact[n] = pow(fact[n], p - 2, p);
for (int i = n - 1; i >= 0; i--) {
invfact[i] = (invfact[i + 1] * (i + 1)) % p;
}
}
private long nCr(int n, int r) {
if (r > n || n < 0 || r < 0) return 0;
return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;
}
}
private static long gcd(long a, long b) {
return (b == 0 ? a : gcd(b, a % b));
}
private static long lcm(long a, long b) {
return ((a * b) / gcd(a, b));
}
private static long pow(long a, long b, int mod) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long ceilDiv(long a, long b) {
return ((a + b - 1) / b);
}
private static long getMin(long... args) {
long min = lMax;
for (long arg : args)
min = Math.min(min, arg);
return min;
}
private static long getMax(long... args) {
long max = lMin;
for (long arg : args)
max = Math.max(max, arg);
return max;
}
private static boolean isPalindrome(String s, int l, int r) {
int i = l, j = r;
while (j - i >= 1) {
if (s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
private static List<Integer> primes(int n) {
boolean[] primeArr = new boolean[n + 5];
Arrays.fill(primeArr, true);
for (int i = 2; (i * i) <= n; i++) {
if (primeArr[i]) {
for (int j = i * i; j <= n; j += i) {
primeArr[j] = false;
}
}
}
List<Integer> primeList = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (primeArr[i])
primeList.add(i);
}
return primeList;
}
private static int noOfSetBits(long x) {
int cnt = 0;
while (x != 0) {
x = x & (x - 1);
cnt++;
}
return cnt;
}
private static boolean isPerfectSquare(long num) {
long sqrt = (long) Math.sqrt(num);
return ((sqrt * sqrt) == num);
}
private static class Pair<U, V> {
private final U first;
private final V second;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return first.equals(pair.first) && second.equals(pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
private Pair(U ff, V ss) {
this.first = ff;
this.second = ss;
}
}
private static void randomizeIntArr(int[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swapInIntArr(arr, i, j);
}
}
private static void randomizeLongArr(long[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swapInLongArr(arr, i, j);
}
}
private static void swapInIntArr(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
private static void swapInLongArr(long[] arr, int a, int b) {
long temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
private static int[] readIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextInt();
return arr;
}
private static long[] readLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextLong();
return arr;
}
private static List<Integer> readIntList(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(fs.nextInt());
return list;
}
private static List<Long> readLongList(int n) {
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(fs.nextLong());
return list;
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws IOException {
if (checkOnlineJudge)
this.br = new BufferedReader(new FileReader("src/input.txt"));
else
this.br = new BufferedReader(new InputStreamReader(System.in));
this.st = new StringTokenizer("");
}
public String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException err) {
err.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
if (st.hasMoreTokens()) {
return st.nextToken("").trim();
}
try {
return br.readLine().trim();
} catch (IOException err) {
err.printStackTrace();
}
return "";
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
private static class FastWriter {
PrintWriter out;
FastWriter() throws IOException {
if (checkOnlineJudge)
out = new PrintWriter(new FileWriter("src/output.txt"));
else
out = new PrintWriter(System.out);
}
}
}
|
java
|
1315
|
B
|
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
|
[
"binary search",
"dp",
"greedy",
"strings"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.StringTokenizer;
public class Solution {
static HashSet<String> set;
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
FastScanner fs = new FastScanner();
DecimalFormat formatter = new DecimalFormat("#0.000000");
int ti = fs.nextInt();
outer: while (ti-- > 0) {
int a = fs.nextInt();
int b = fs.nextInt();
int p = fs.nextInt();
char[] c = fs.next().toCharArray();
int n = c.length;
int res = n - 1;
for (int i = n - 2; i >= 0; i--) {
res = i + 1;
while (i > 0 && c[i] == c[i - 1])
i--;
if (c[i] == 'A')
p -= a;
else
p -= b;
if (p < 0)
break;
}
if (p >= 0)
res = 0;
out.println(res + 1);
}
out.close();
}
static final int mod = 1_000_000_007;
static void sort(long[] a) {
Random random = new Random();
int n = a.length;
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n);
long temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void sort(int[] a) {
Random random = new Random();
int n = a.length;
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
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());
}
float nextFloat() {
return Float.parseFloat(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());
}
}
static class Pair {
String a;
int b;
public Pair(String a, int b) {
this.a = a;
this.b = b;
}
}
}
|
java
|
1141
|
E
|
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1
|
[
"math"
] |
import java.io.*;
import java.util.*;
public class ProblemB {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
StringBuilder sb = new StringBuilder();
long h = in.readLong();
int n = in.readInt();
int a[] = new int[n];
long sum = 0;
for(int i = 0;i<n;i++){
a[i] = in.readInt();
sum+=a[i];
}
long ans = -1;
long prefix[] = new long[n];
long min = Long.MAX_VALUE;
TreeMap<Long,Integer>mp = new TreeMap<>();
int ind =0;
for(int i = 0;i<n;i++){
prefix[i] = a[i];
if(i-1>=0)prefix[i]+=prefix[i-1];
if(prefix[i]+h<=0){
System.out.println(i+1);
return;
}
if(prefix[i]<0 && !mp.containsKey(-prefix[i]))mp.put(-prefix[i], i);
}
if(mp.size()==0 || sum>=0){
System.out.println(-1);
return;
}else{
long t = mp.lastKey();
sum = -sum;
long full = (h-t)/sum;
h-=(full*sum);
ans = full*n;
for(int i=0;;i=(i+1)%n){
if(h<=0)break;
ans++;
h+=a[i];
}
System.out.println(ans);
}
}
public static void sort(int a[]){
ArrayList<Integer>l = new ArrayList<>();
for(int it:a)l.add(it);
Collections.sort(l);
for(int i = 0;i<l.size();i++)a[i] = l.get(i);
}
public static int lower(int target,int l,int r,int a[]){
int index = l;
while(l<=r){
int mid = (l+r)/2;
if(a[mid]<=target){
index = mid;
l = mid+1;
}else r= mid-1;
}
return index;
}
public static int[] get(long n){
int count1=0,count2=0;
while(n%2 == 0){
n/=2;
count1++;
}
while(n%3 == 0){
n/=3;
count2++;
}
return new int[]{count1,count2};
}
public static boolean isPalindrome(int val){
String s = String.valueOf(val);
for(int i = 0;i<s.length()/2;i++){
if(s.charAt(i) != s.charAt(s.length()-i-1))return false;
}
return true;
}
public static int sum(int n){
int sum = 0;
while(n>0){
sum+=(n%10);
n/=10;
}
return sum;
}
public static void swap(int a[],int i, int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static boolean subsequence(String cur,String t){
int pos = 0;
for(int i = 0;i<cur.length();i++){
if(pos<t.length() && cur.charAt(i) == t.charAt(pos)){
pos++;
}
}
return pos == t.length();
}
public static long gcd(long a, long b){
return b ==0 ?a:gcd(b,a%b);
}
static class Pair{
int x,y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
}
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String read()
{
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int readInt() { return Integer.parseInt(read()); }
public long readLong() { return Long.parseLong(read()); }
public double readDouble(){return Double.parseDouble(read());}
public String readLine() throws Exception { return br.readLine(); }
}
}
|
java
|
1291
|
A
|
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
|
[
"greedy",
"math",
"strings"
] |
import java.util.*;
import java.lang.Math;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
int n = sc.nextInt();
String str = sc.next();
int a,count=0, ansp1=0;
for(int i=0; i<str.length(); i++)
{
a = str.charAt(i) - '0';
if(a%2!=0)
{
ansp1 = 10*ansp1 + a;
count++;
}
if(count>=2)
break;
}
if(count<2)
System.out.println(-1);
else
System.out.println(ansp1);
}
}
}
|
java
|
1320
|
D
|
D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No
|
[
"data structures",
"hashing",
"strings"
] |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class C1320D {
static long modulo1 = (long) 1e9 + 9;
static long modulo2 = (long) 1e9 + 7;
static long r1 = 2;
static long r2 = 3;
static int[] bits1 = new int[]{0, 1};
static int[] bits2 = new int[]{1, 2};
public static void main(String[] args) {
var scanner = new BufferedScanner();
var writer = new PrintWriter(new BufferedOutputStream(System.out));
var n = scanner.nextInt();
var t = scanner.next();
var count0 = new int[n + 1];
{
count0[0] = 0;
for (int len = 1; len <= n; len++) {
count0[len] = count0[len - 1] + (t.charAt(len - 1) == '0' ? 1 : 0);
}
}
var power1 = new long[n + 1];
var power2 = new long[n + 1];
power1[0] = 1;
power2[0] = 1;
for (int i = 1; i <= n; i++) {
power1[i] = power1[i - 1] * r1 % modulo1;
power2[i] = power2[i - 1] * r2 % modulo2;
}
var hashEven1 = new long[n + 1][];
var hashOdd1 = new long[n + 1][];
calcHash(t, n, power1, hashEven1, hashOdd1, count0, modulo1, r1, bits1);
var hashEven2 = new long[n + 1][];
var hashOdd2 = new long[n + 1][];
calcHash(t, n, power2, hashEven2, hashOdd2, count0, modulo2, r2, bits2);
var q = scanner.nextInt();
for (int qi = 0; qi < q; qi++) {
var l1 = scanner.nextInt() - 1;
var l2 = scanner.nextInt() - 1;
var len = scanner.nextInt();
var ans = false;
// 首先,0的个数得一样多
if (count0[l1 + len] - count0[l1] == count0[l2 + len] - count0[l2]) {
// 其次,从各子串开头算起的0的下标得对应位同奇偶。
var fp11 = fingerprint(l1, l1 + len - 1, power1, hashEven1, hashOdd1, count0, modulo1);
var fp21 = fingerprint(l2, l2 + len - 1, power1, hashEven1, hashOdd1, count0, modulo1);
var fp12 = fingerprint(l1, l1 + len - 1, power2, hashEven2, hashOdd2, count0, modulo2);
var fp22 = fingerprint(l2, l2 + len - 1, power2, hashEven2, hashOdd2, count0, modulo2);
// System.out.println(String.format("[%d] %d,%d %d,%d", qi + 1, fp11, fp21, fp12, fp22));
if (fp11 == fp21 && fp12 == fp22) {
ans = true;
}
}
writer.println(ans ? "Yes" : "No");
}
scanner.close();
writer.flush();
writer.close();
}
private static void calcHash(String t, int n, long[] power, long[][] hashEven, long[][] hashOdd, int[] count0,
long modulo, long r, int[] bits) {
var limit = r * modulo;
// System.out.println(String.format("modulo=%d,r=%d,bits=%s", modulo, r, Arrays.toString(bits)));
for (int len = 1; len <= n; len <<= 1) {
hashEven[len] = new long[n];
hashOdd[len] = new long[n];
var he = 0L;
var ho = 0L;
for (int i = 0; i < n; i++) {
if (t.charAt(i) == '0') {
var bitEven = bits[i & 1]; // 对偶数开头子字符串来说,i是偶数在子字符串也是偶数位,用0表示;否则用1。
var bitOdd = bits[1 - (i & 1)]; // 对奇数位开头的子字符串来说,i是偶数在子字符串是奇数位,用1表示;否则用0。
he = (he * r + bitEven) % modulo;
ho = (ho * r + bitOdd) % modulo;
}
if (i >= len && t.charAt(i - len) == '0') {
var bitEven0 = bits[(i - len) & 1];
var bitOdd0 = bits[1 - ((i - len) & 1)];
var cnt0 = count0[i + 1] - count0[i + 1 - len];
he = (he + limit - power[cnt0] * bitEven0) % modulo; // power[cnt0]*bitEven0<modulo*r
ho = (ho + limit - power[cnt0] * bitOdd0) % modulo; // power[cnt0]*bitOdd0<modulo*r
}
if (i >= len - 1) {
hashEven[len][i - len + 1] = he;
hashOdd[len][i - len + 1] = ho;
}
if (he < 0 || ho < 0) {
throw new RuntimeException("wtf");
}
}
}
}
private static long fingerprint(int start, int end, long[] power, long[][] hashEven, long[][] hashOdd, int[] count0,
long modulo) {
if ((start & 1) == 0) {
return fingerprint(start, end, power, hashEven, count0, modulo);
} else {
return fingerprint(start, end, power, hashOdd, count0, modulo);
}
}
private static long fingerprint(int start, int end, long[] power, long[][] hash, int[] count0, long modulo) {
var len = 1 << (int) (Math.log(end - start + 1) / Math.log(2));
var fp = 0L;
while (start <= end) {
var cnt0 = count0[start + len] - count0[start];
fp = (fp * power[cnt0] + hash[len][start]) % modulo;
if (fp < 0) {
throw new RuntimeException("wtf");
}
start += len;
while (len > 0 && start + len - 1 > end) {
len >>= 1;
}
}
return fp;
}
public static class BufferedScanner {
BufferedReader br;
StringTokenizer st;
public BufferedScanner(Reader reader) {
br = new BufferedReader(reader);
}
public BufferedScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b > 0) {
long tmp = b;
b = a % b;
a = tmp;
}
return a;
}
static long inverse(long a, long m) {
long[] ans = extgcd(a, m);
return ans[0] == 1 ? (ans[1] + m) % m : -1;
}
private static long[] extgcd(long a, long m) {
if (m == 0) {
return new long[]{a, 1, 0};
} else {
long[] ans = extgcd(m, a % m);
long tmp = ans[1];
ans[1] = ans[2];
ans[2] = tmp;
ans[2] -= ans[1] * (a / m);
return ans;
}
}
private static List<Integer> primes(double upperBound) {
var limit = (int) Math.sqrt(upperBound);
var isComposite = new boolean[limit + 1];
var primes = new ArrayList<Integer>();
for (int i = 2; i <= limit; i++) {
if (isComposite[i]) {
continue;
}
primes.add(i);
int j = i + i;
while (j <= limit) {
isComposite[j] = true;
j += i;
}
}
return primes;
}
}
|
java
|
1307
|
B
|
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
|
[
"geometry",
"greedy",
"math"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class CowAndFriend {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr=new PrintWriter(System.out);
int t=Integer.parseInt(br.readLine());
while(t!=0){
solve(br,pr);
t--;
}
pr.flush();
pr.close();
}
public static void solve(BufferedReader br,PrintWriter pr) throws IOException{
String[] temp=br.readLine().split(" ");
int n=Integer.parseInt(temp[0]);
int x=Integer.parseInt(temp[1]);
temp=br.readLine().split(" ");
int[] nums=new int[n];
int max=0;
for(int i=0;i<n;i++){
nums[i]=Integer.parseInt(temp[i]);
if(nums[i]==x){
pr.println(1);
return;
}
max=Math.max(nums[i],max);
}
if(max>x){
pr.println(2);
return;
}
int res=(x%max==0?x/max:x/max+1);
pr.println(res);
}
}
|
java
|
1324
|
C
|
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.
|
[
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] |
import java.util.*;
public class frogJumps {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int tt=0;tt<t;tt++) {
String s = "R" + sc.next() + "R";
int maxDist = 1;
int currDist = 0;
for (int i = 0 ; i < s.length() ; i++) {
if (s.charAt(i) == 'R') {
maxDist = Math.max(maxDist, currDist);
currDist = 1;
} else {
currDist++;
}
}
System.out.println(maxDist);
}
}
}
|
java
|
1311
|
D
|
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
|
[
"brute force",
"math"
] |
// package c1311;
//
// Codeforces Round #624 (Div. 3) 2020-02-24 06:35
// D. Three Integers
// https://codeforces.com/contest/1311/problem/D
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You are given three integers a <= b <= c.
//
// In one move, you can add +1 or -1 to of these integers (i.e. increase or decrease any number by
// one). You can perform such operation any (possibly, zero) number of times, you can even perform
// this operation several times with one number. .
//
// You have to perform the minimum number of such operations in order to obtain three integers A <=
// B <= C such that B is divisible by A and C is divisible by B.
//
// You have to answer t independent test cases.
//
// Input
//
// The first line of the input contains one integer t (1 <= t <= 100) -- the number of test cases.
//
// The next t lines describe test cases. Each test case is given on a separate line as three
// space-separated integers a, b and c (1 <= a <= b <= c <= 10^4).
//
// Output
//
// For each test case, print the answer. In the first line print res -- the minimum number of
// operations you have to perform to obtain three integers A <= B <= C such that B is divisible by A
// and C is divisible by B. On the second line print suitable triple A, B and C.
//
// Example
/*
input:
8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
output:
1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
public class C1311D {
static final int MOD = 998244353;
static final Random RAND = new Random();
static List<Integer>[] DIVS = computeDivisors(20000);
static int[] solve(int a, int b, int c) {
int[] ans = new int[4];
// a,b,c in [1,10000]
ans[0] = 50000;
// Evaluate possible values of the middle number
for (int v = 1; v <= 20000; v++) {
if (Math.abs(b - v) >= ans[0]) {
continue;
}
int[] curr = new int[] {a, a, v, c};
for (int x : DIVS[v]) {
if (Math.abs(a - x) < curr[0]) {
curr[0] = Math.abs(a - x);
curr[1] = x;
}
}
curr[0] += Math.abs(b - v);
int r = c % v;
if (c < v) {
curr[0] += v - c;
curr[3] = v;
} else if (r != 0) {
if (r <= v - r) {
curr[0] += r;
curr[3] = c - r;
} else {
curr[0] += v - r;
curr[3] = c + (v - r);
}
}
if (curr[0] < ans[0]) {
ans = curr;
}
}
return ans;
}
static List<Integer>[] computeDivisors(int n) {
List<Integer>[] divs = new ArrayList[n + 1];
for (int i = 0; i <= n; i++) {
divs[i] = new ArrayList<>();
}
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j += i) {
divs[j].add(i);
}
}
return divs;
}
static void test(int[] exp, int a, int b, int c) {
int[] ans = solve(a, b, c);
boolean ok = exp[0] == ans[0] && exp[1] == ans[1] && exp[2] == ans[2] && exp[3] == ans[3];
System.out.format("%d %d %d => %d %d %d %d %s\n",
a, b, c, ans[0], ans[1], ans[2], ans[3],
ok ? "":"Expected " + exp[0] + " " + exp[1] + " " + exp[2] + " " + exp[3]);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(new int[] {2, 137, 10001, 10001}, 137, 10000, 10000);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int[] ans = solve(a, b, c);
System.out.format("%d\n%d %d %d\n", ans[0], ans[1], ans[2], ans[3]);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 4000) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
java
|
1324
|
D
|
D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0
|
[
"binary search",
"data structures",
"sortings",
"two pointers"
] |
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static final PrintWriter out =new PrintWriter(System.out);
static final FastReader sc = new FastReader();
//I invented a new word!Plagiarism!
//Did you hear about the mathematician who’s afraid of negative numbers?He’ll stop at nothing to avoid them
//What do Alexander the Great and Winnie the Pooh have in common? Same middle name.
//I finally decided to sell my vacuum cleaner. All it was doing was gathering dust!
//ArrayList<Integer> a=new ArrayList <Integer>();
//PriorityQueue<Integer> pq=new PriorityQueue<>();
//char[] a = s.toCharArray();
// char s[]=sc.next().toCharArray();
public static boolean sorted(int a[])
{
int n=a.length,i;
int b[]=new int[n];
for(i=0;i<n;i++)
b[i]=a[i];
Arrays.sort(b);
for(i=0;i<n;i++)
{
if(a[i]!=b[i])
return false;
}
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
int i; long pos=0;
long ans=0;
for(i=0;i<n;i++)
a[i]=sc.nextInt();
for(i=0;i<n;i++)
b[i]=sc.nextInt();
ArrayList<Long> arr=new ArrayList<>();
ArrayList<Long> neg=new ArrayList<>();
for(i=0;i<n;i++)
{
arr.add((long)b[i]-(long)a[i]);
if(a[i]-b[i]<=0)
neg.add((long)a[i]-(long)b[i]);
else
pos++;
}
ans=(pos*(pos-1))/2;
Collections.sort(arr);
for(long it:neg)
ans+=lower_bound(arr,0,arr.size()-1,it);
System.out.println(ans);
}
public static int first(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)
return mid;
else if (x > arr.get(mid))
return first(arr, (mid + 1), high, x, n);
else
return first(arr, low, (mid - 1), x, n);
}
return -1;
}
public static int last(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)
return mid;
else if (x < arr.get(mid))
return last(arr, low, (mid - 1), x, n);
else
return last(arr, (mid + 1), high, x, n);
}
return -1;
}
public static int lis(int[] arr) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>=x) {
al.add(arr[i]);
}else {
int v = upper_bound(al, 0, al.size(), arr[i]);
al.set(v, arr[i]);
}
}
return al.size();
}
public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k)
{
//Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get((int)mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long mod=1000000007;
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
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;
}
}
}
|
java
|
1141
|
B
|
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
|
[
"implementation"
] |
public class B {
public static void main(String args[]) {
for (java.util.Scanner scanner : new java.util.Scanner[]{new java.util.Scanner(System.in)}) {
for (int n : new int[]{scanner.nextInt()}) {
for (java.util.List<Integer> days : new java.util.ArrayList[]{new java.util.ArrayList<Integer>()}) {
for (int n_copy : new int[]{n}) {
while (n_copy-- > 0) {
for (boolean $ : new boolean[]{days.add(scanner.nextInt())}) {
if (n_copy == 0) {
for (int i : new int[]{0}) {
for (int run : new int[]{0}) {
for (int best : new int[]{0}) {
while (i++ < n) {
for (boolean $1 : new boolean[]{days.add(days.get(i - 1))}) {
if (i == n) {
for (int j : new int[]{0}) {
while (j++ < (n * 2)) {
for (int $2 : new int[]{best = Math.max(best, run)}) {
for (int $3 : new int[]{run += days.get(j - 1) == 1 ? 1 : -run}) {
if (j == n * 2) {
if (System.out.printf("%d\n", best) == null) {
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
|
java
|
1324
|
F
|
F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.
|
[
"dfs and similar",
"dp",
"graphs",
"trees"
] |
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static Scanner cin = new Scanner(System.in);
public int n;
public int a[], d[], c[], ans[];
public int use[];
public int res[];
public List<Integer> vec[];
public int dfs(int u) {
use[u] = 1;
int ttl = (a[u] == 1 ? 1 : -1);
for (int v : vec[u]) {
if (use[v] == 0) {
ttl += dfs(v);
}
}
if (ttl < 0) {
ttl = 0;
}
c[u] = ttl;
return c[u];
}
public void dfsA(int u, int k) {
use[u] = 2;
int ttl = (a[u] == 1 ? 1 : -1) + k;
for (int v : vec[u]) {
if (use[v] == 1) {
ttl += c[v];
}
}
for (int v : vec[u]) {
if (use[v] == 1) {
int x = ttl - c[v];
if (x < 0) x = 0;
dfsA(v, x);
}
}
ans[u] = ttl;
}
public void solve() {
n = cin.nextInt();
a = new int[n+1];
res = new int[n+1];
use = new int[n+1];
vec = new List[n+1];
c = new int[n+1];
ans = new int[n+1];
for (int i = 1; i <= n; i++) {
a[i] = cin.nextInt();
}
for (int i = 1; i <= n; i++) {
use[i] = 0;
vec[i] = new ArrayList<>();
}
for (int i = 1; i < n; i++) {
int x = cin.nextInt();
int y = cin.nextInt();
vec[x].add(y);
vec[y].add(x);
}
dfs(1);
dfsA(1, 0);
StringBuffer sb = new StringBuffer();
for (int i = 1; i <= n; i++) {
sb.append(ans[i]).append(" ");
}
System.out.println(sb.toString());
}
public static void main(String [] args) {
Main t = new Main();
t.solve();
}
}
|
java
|
1325
|
E
|
E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence.
|
[
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] |
import java.math.*;
import java.io.*;
import java.util.*;
import java.awt.*;
public class Main implements Runnable {
@Override
public void run() {
try {
new Solver().solve();
System.exit(0);
} catch (Exception | Error e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
//new Thread(null, new Main(), "Solver", 1l << 25).start();
new Main().run();
}
}
class Solver {
final Helper hp;
final int MAXN = 1000_006;
final long MOD = (long) 1e9 + 7;
final Timer timer;
final TimerTask task;
Solver() {
hp = new Helper(MOD, MAXN);
hp.initIO(System.in, System.out);
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
try {
hp.println(ans > MAXN ? -1 : ans);
hp.flush();
System.exit(0);
} catch (Exception e) {
}
}
};
timer.schedule(task, 2800);
}
int N;
ArrayList<Integer>[] graph;
void solve() throws Exception {
int i, j, k;
hp.setSieve();
int[] sieve = hp.sieve;
TreeSet<int[]> edges = new TreeSet<>((a, b) -> a[0] != b[0] ?
Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1]));
HashSet<Integer> singles = new HashSet<>();
int n = hp.nextInt();
for (i = 0; i < n; ++i) {
int ele = hp.nextInt();
HashSet<Integer> primes = new HashSet<>();
while (ele > 1) {
int f = sieve[ele];
boolean flag = false;
while (ele % f == 0) {
ele /= f;
flag = !flag;
}
if (flag) {
if (primes.contains(f)) primes.remove(f);
else primes.add(f);
}
}
if (primes.isEmpty()) {
ans = Math.min(ans, 1);
} else if (primes.size() == 1) {
Iterator<Integer> itr = primes.iterator();
int a = 1, b = itr.next();
int[] e = new int[] {Math.min(a, b), Math.max(a, b)};
if (edges.contains(e)) ans = Math.min(ans, 2);
edges.add(e);
} else if (primes.size() == 2) {
Iterator<Integer> itr = primes.iterator();
int a = itr.next(), b = itr.next();
int[] e = new int[] {Math.min(a, b), Math.max(a, b)};
if (edges.contains(e)) ans = Math.min(ans, 2);
edges.add(e);
} else {
System.exit(7 / 0);
}
}
//System.err.println(singles);
//edges.forEach(a -> System.err.print(Arrays.toString(a)));
N = MAXN;
graph = new ArrayList[N];
for (i = 0; i < N; ++i) graph[i] = new ArrayList<>();
for (int[] e : edges) {
graph[e[0]].add(e[1]);
graph[e[1]].add(e[0]);
}
Integer[] list = new Integer[N];
for (i = 0; i < N; ++i) list[i] = i;
//hp.shuffle(list);
Arrays.sort(list, (a, b) -> -Integer.compare(graph[a].size(), graph[b].size()));
for (int itr : list) if (graph[itr].size() > 1) {
//System.err.println("BFS from " + itr);
bfs(itr);
//System.err.println();
}
hp.println(ans > N ? -1 : ans);
timer.cancel();
hp.flush();
}
int ans = MAXN + 3;
void bfs(final int root) {
HashMap<Integer, Integer> vis = new HashMap<>();
ArrayDeque<Integer> deque = new ArrayDeque<>();
deque.addLast(root);
vis.put(root, 0);
for (int d = 1; 2 * d - 1 < ans && !deque.isEmpty(); ++d) {
ArrayDeque<Integer> nextLevel = new ArrayDeque<>();
while (!deque.isEmpty()) {
int node = deque.pollFirst();
//System.err.println(node + " = " + graph[node] + " " + vis);
for (int itr : graph[node]) {
if (vis.containsKey(itr)) {
int itrLvl = vis.get(itr), nodeLvl = d - 1;
if (itrLvl < nodeLvl) {
continue;
} else if (itrLvl > nodeLvl) {
ans = Math.min(ans, itrLvl * 2);
} else {
ans = Math.min(ans, nodeLvl * 2 + 1);
}
return;
}
nextLevel.addLast(itr);
vis.put(itr, d);
}
}
deque = nextLevel;
//System.err.println(deque);
}
}
}
class Helper {
final long MOD;
final int MAXN;
final Random rnd;
public Helper(long mod, int maxn) {
MOD = mod;
MAXN = maxn;
rnd = new Random();
}
public static int[] sieve;
public static ArrayList<Integer> primes;
public void setSieve() {
primes = new ArrayList<>();
sieve = new int[MAXN];
int i, j;
for (i = 2; i < MAXN; ++i)
if (sieve[i] == 0) {
primes.add(i);
for (j = i; j < MAXN; j += i) {
sieve[j] = i;
}
}
}
public static long[] factorial;
public void setFactorial() {
factorial = new long[MAXN];
factorial[0] = 1;
for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD;
}
public long getFactorial(int n) {
if (factorial == null) setFactorial();
return factorial[n];
}
public long ncr(int n, int r) {
if (r > n) return 0;
if (factorial == null) setFactorial();
long numerator = factorial[n];
long denominator = factorial[r] * factorial[n - r] % MOD;
return numerator * pow(denominator, MOD - 2, MOD) % MOD;
}
public long[] getLongArray(int size) throws Exception {
long[] ar = new long[size];
for (int i = 0; i < size; ++i) ar[i] = nextLong();
return ar;
}
public int[] getIntArray(int size) throws Exception {
int[] ar = new int[size];
for (int i = 0; i < size; ++i) ar[i] = nextInt();
return ar;
}
public String[] getStringArray(int size) throws Exception {
String[] ar = new String[size];
for (int i = 0; i < size; ++i) ar[i] = next();
return ar;
}
public String joinElements(long... ar) {
StringBuilder sb = new StringBuilder();
for (long itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(int... ar) {
StringBuilder sb = new StringBuilder();
for (int itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(String... ar) {
StringBuilder sb = new StringBuilder();
for (String itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public String joinElements(Object... ar) {
StringBuilder sb = new StringBuilder();
for (Object itr : ar) sb.append(itr).append(" ");
return sb.toString().trim();
}
public long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public long max(long... ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.max(ret, itr);
return ret;
}
public int max(int... ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.max(ret, itr);
return ret;
}
public long min(long... ar) {
long ret = ar[0];
for (long itr : ar) ret = Math.min(ret, itr);
return ret;
}
public int min(int... ar) {
int ret = ar[0];
for (int itr : ar) ret = Math.min(ret, itr);
return ret;
}
public long sum(long... ar) {
long sum = 0;
for (long itr : ar) sum += itr;
return sum;
}
public long sum(int... ar) {
long sum = 0;
for (int itr : ar) sum += itr;
return sum;
}
public void shuffle(int[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void shuffle(long[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = rnd.nextInt(ar.length);
if (r != i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void reverse(int[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = ar.length - 1 - i;
if (r > i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public void reverse(long[] ar) {
int r;
for (int i = 0; i < ar.length; ++i) {
r = ar.length - 1 - i;
if (r > i) {
ar[i] ^= ar[r];
ar[r] ^= ar[i];
ar[i] ^= ar[r];
}
}
}
public long pow(long base, long exp, long MOD) {
base %= MOD;
long ret = 1;
while (exp > 0) {
if ((exp & 1) == 1) ret = ret * base % MOD;
base = base * base % MOD;
exp >>= 1;
}
return ret;
}
static final int BUFSIZE = 1 << 20;
static byte[] buf;
static int index, total;
static InputStream in;
static BufferedWriter bw;
public void initIO(InputStream is, OutputStream os) {
try {
in = is;
bw = new BufferedWriter(new OutputStreamWriter(os));
buf = new byte[BUFSIZE];
} catch (Exception e) {
}
}
public void initIO(String inputFile, String outputFile) {
try {
in = new FileInputStream(inputFile);
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFile)));
buf = new byte[BUFSIZE];
} catch (Exception e) {
}
}
private int scan() throws Exception {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public String next() throws Exception {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan())
sb.append((char) c);
return sb.toString();
}
public int nextInt() throws Exception {
int c, val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public long nextLong() throws Exception {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public void print(Object a) throws Exception {
bw.write(a.toString());
}
public void printsp(Object a) throws Exception {
print(a);
print(" ");
}
public void println() throws Exception {
bw.write("\n");
}
public void println(Object a) throws Exception {
print(a);
println();
}
public void flush() throws Exception {
bw.flush();
}
}
|
java
|
1284
|
B
|
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
|
[
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] |
import java.util.*;
public class New_Year_And_Ascent_Sequence {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t = n;
long res = 0;
ArrayList<Integer> first = new ArrayList<>();
ArrayList<Integer> last = new ArrayList<>();
while(n-->0) {
int l = sc.nextInt();
int arr[] = new int[l];
arr[0] = sc.nextInt();
boolean flag = false;
for(int i=1;i<l;i++) {
arr[i] = sc.nextInt();
if(arr[i]>arr[i-1])
flag = true;
}
if(!flag) {
first.add(arr[0]);
last.add(arr[l-1]);
}else {
res += ((2*t)-1);
t--;
}
}
int m = first.size();
// res += (long)(m)*(long)(m-1);
Collections.sort(first);
Collections.sort(last);
int i=0,j=0,total =0;
while(i<m&&j<m) {
if(last.get(i)<first.get(j)) {
i++;total++;
}else {
res += total;
j++;
}
}
if(j<m)
res += (long)(m-j)*(long)(total);
System.out.println(res);
}
}
|
java
|
1322
|
A
|
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.
|
[
"greedy"
] |
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static long mod = (int)1e9+7;
public static void main (String[] args) throws java.lang.Exception
{
FastReader sc =new FastReader();
// int t=sc.nextInt();
int t=1;
while(t-->0)
{
int n=sc.nextInt();
char arr[] = sc.next().toCharArray();
int count = 0;
int left = 0 , right = 0;
for(char x:arr)
{
if(x=='(')
{
left++;
}
else
{
right++;
}
}
if(left!=right)
{
System.out.println(-1);
continue;
}
int prefix[] = new int[n+1];
for(int i=0;i<n;i++)
{
prefix[i+1] = prefix[i] + ((arr[i]=='(')?1:-1);
}
for(int i=0;i<n;i++)
{
if(prefix[i]<=0 && prefix[i+1]<=0)
{
count++;
}
}
System.out.println(count);
}
}
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());
}
float nextFloat()
{
return Float.parseFloat(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readArrayLong(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
public static int[] radixSort2(int[] a)
{
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for(int v : a) {
c0[(v&0xff)+1]++;
c1[(v>>>8&0xff)+1]++;
c2[(v>>>16&0xff)+1]++;
c3[(v>>>24^0x80)+1]++;
}
for(int i = 0;i < 0xff;i++) {
c0[i+1] += c0[i];
c1[i+1] += c1[i];
c2[i+1] += c2[i];
c3[i+1] += c3[i];
}
int[] t = new int[n];
for(int v : a)t[c0[v&0xff]++] = v;
for(int v : t)a[c1[v>>>8&0xff]++] = v;
for(int v : a)t[c2[v>>>16&0xff]++] = v;
for(int v : t)a[c3[v>>>24^0x80]++] = v;
return a;
}
static void reverse_sorted(int[] arr)
{
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<arr.length;i++)
{
list.add(arr[i]);
}
Collections.sort(list , Collections.reverseOrder());
for(int i=0;i<arr.length;i++)
{
arr[i] = list.get(i);
}
}
static int LowerBound(int a[], int x) { // x is the target value or key
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int UpperBound(ArrayList<Integer> list, int x) {// x is the key or target value
int l=-1,r=list.size();
while(l+1<r) {
int m=(l+r)>>>1;
if(list.get(m)<=x) l=m;
else r=m;
}
return l+1;
}
public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<Integer, Integer> > list =
new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() {
public int compare(Map.Entry<Integer, Integer> o1,
Map.Entry<Integer, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// put data from sorted list to hashmap
HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
static void leftRotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
leftRotatebyOne(arr, n);
}
static void leftRotatebyOne(int arr[], int n)
{
int i, temp;
temp = arr[0];
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[n-1] = temp;
}
static boolean isPalindrome(String str)
{
// Pointers pointing to the beginning
// and the end of the string
int i = 0, j = str.length() - 1;
// While there are characters to compare
while (i < j) {
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;
// Increment first pointer and
// decrement the other
i++;
j--;
}
// Given string is a palindrome
return true;
}
static boolean palindrome_array(char arr[], int n)
{
// Initialise flag to zero.
int flag = 0;
// Loop till array size n/2.
for (int i = 0; i <= n / 2 && n != 0; i++) {
// Check if first and last element are different
// Then set flag to 1.
if (arr[i] != arr[n - i - 1]) {
flag = 1;
break;
}
}
// If flag is set then print Not Palindrome
// else print Palindrome.
if (flag == 1)
return false;
else
return true;
}
static boolean allElementsEqual(int[] arr,int n)
{
int z=0;
for(int i=0;i<n-1;i++)
{
if(arr[i]==arr[i+1])
{
z++;
}
}
if(z==n-1)
{
return true;
}
else
{
return false;
}
}
static boolean allElementsDistinct(int[] arr,int n)
{
int z=0;
for(int i=0;i<n-1;i++)
{
if(arr[i]!=arr[i+1])
{
z++;
}
}
if(z==n-1)
{
return true;
}
else
{
return false;
}
}
public static void reverse(int[] array)
{
// Length of the array
int n = array.length;
// Swaping the first half elements with last half
// elements
for (int i = 0; i < n / 2; i++) {
// Storing the first half elements temporarily
int temp = array[i];
// Assigning the first half to the last half
array[i] = array[n - i - 1];
// Assigning the last half to the first half
array[n - i - 1] = temp;
}
}
public static void reverse_Long(long[] array)
{
// Length of the array
int n = array.length;
// Swaping the first half elements with last half
// elements
for (int i = 0; i < n / 2; i++) {
// Storing the first half elements temporarily
long temp = array[i];
// Assigning the first half to the last half
array[i] = array[n - i - 1];
// Assigning the last half to the first half
array[n - i - 1] = temp;
}
}
static boolean isSorted(int[] a)
{
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
static boolean isReverseSorted(int[] a)
{
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] < a[i + 1]) {
return false;
}
}
return true;
}
static int[] rearrangeEvenAndOdd(int arr[], int n)
{
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(arr[i]%2==0)
{
list.add(arr[i]);
}
}
for(int i=0;i<n;i++)
{
if(arr[i]%2!=0)
{
list.add(arr[i]);
}
}
int len = list.size();
int[] array = list.stream().mapToInt(i->i).toArray();
return array;
}
static long[] rearrangeEvenAndOddLong(long arr[], int n)
{
ArrayList<Long> list = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(arr[i]%2==0)
{
list.add(arr[i]);
}
}
for(int i=0;i<n;i++)
{
if(arr[i]%2!=0)
{
list.add(arr[i]);
}
}
int len = list.size();
long[] array = list.stream().mapToLong(i->i).toArray();
return array;
}
static boolean isPrime(long n)
{
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (long i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static long getSum(long n)
{
long sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = n/10;
}
return sum;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcdLong(long a, long b)
{
if (b == 0)
return a;
return gcdLong(b, a % b);
}
static void swap(int i, int j)
{
int temp = i;
i = j;
j = temp;
}
static int countDigit(int n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
}
|
java
|
1311
|
A
|
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.
|
[
"greedy",
"implementation",
"math"
] |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int test = input.nextInt();
for( int i = 0; i < test; i++ ){
int a = input.nextInt();
int b = input.nextInt();
if( a == b ) System.out.println("0");
else{
if( (a % 2 == 0 && b % 2 == 0) || ( a % 2 == 1 && b % 2 == 1 )){
if( a > b ) System.out.println("1");
else System.out.println("2");
}
else{
if( a > b ) System.out.println("2");
else System.out.println("1");
}
}
}
//input.close();
}
}
|
java
|
1316
|
A
|
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.
|
[
"implementation"
] |
import java.util.*;
public class Solution{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int t=in.nextInt();
for(int c=0;c<t;c++)
{
int n=in.nextInt();
int m=in.nextInt();
int[] arr = new int[n];
int sum=0;
for(int i=0;i<n;i++)
{
arr[i]=in.nextInt();
sum=sum+arr[i];
}
if(sum>m)
System.out.println(m);
else
System.out.println(sum);
}
}
}
|
java
|
1299
|
C
|
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.
|
[
"data structures",
"geometry",
"greedy"
] |
//package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static class Task {
public void solve(Scanner sc, PrintWriter pw) throws IOException {
int n = sc.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = sc.nextInt();
}
long[] sum = new long[n];
int[] count = new int[n];
int idx = 0;
for (int x: numbers) {
long curSum = x;
int curCount = 1;
while (idx > 0) {
long p = sum[idx - 1];
int c = count[idx - 1];
if (p * curCount >= (long) c * curSum) {
curSum += p;
curCount += c;
idx--;
} else {
break;
}
}
sum[idx] = curSum;
count[idx] = curCount;
idx++;
}
for (int i = 0; i < idx; i++) {
double avg = 1.0 * sum[i] / count[i];
for (int j = 0; j < count[i]; j++) {
pw.println(avg);
}
}
}
}
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("input"));
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
// PrintWriter pw = new PrintWriter(new FileOutputStream("input"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);
System.err.println("Time used: " + (TIME_END - TIME_START) + ".");
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
java
|
1301
|
C
|
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
|
[
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CAyoubsFunction solver = new CAyoubsFunction();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class CAyoubsFunction {
public void solve(int testNumber, InputReader in, OutputWriter out) {
long n = in.nextInt();
long m = in.nextInt();
long a = (n - m) / (m + 1);
long b = (n - m) % (m + 1);
long t1 = (m + 1) * (a + 1) * a / 2;
long t2 = (a + 1) * b;
long tot = (n + 1) * n / 2;
out.println(tot - t1 - t2);
}
}
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 UnknownError();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int 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 UnknownError();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
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 String next() {
return nextString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
|
java
|
1299
|
A
|
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
|
[
"brute force",
"greedy",
"math"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
public class Round12 {
public static void main(String[] args) {
FastReader fastReader = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;
while (t-- > 0) {
int n = fastReader.nextInt();
int a[] = fastReader.ria(n);
int freq[] = new int[32];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 32; j++) {
if ((a[i] & (1 << j)) != 0) {
freq[j]++;
}
}
}
int mask = 0;
for (int j = 0; j < 32; j++) {
if (freq[j] == 1) {
mask |= (1 << j);
}
}
int max = 0;
int maxInd = 0;
for (int i = 0; i < n; i++) {
int val = a[i] & mask;
if (val > max) {
max = val;
maxInd = i;
}
}
StringBuilder ans = new StringBuilder();
ans.append(a[maxInd]).append(" ");
for (int i = 0; i < n; i++) {
if (i == maxInd) continue;
ans.append(a[i]).append(" ");
}
out.println(ans);
}
out.close();
}
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 92233720368547L;
static Random __r = new Random();
// math util
static int minof(int a, int b, int c) {
return min(a, min(b, c));
}
static int minof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
int min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static long minof(long a, long b, long c) {
return min(a, min(b, c));
}
static long minof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
long min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static int maxof(int a, int b, int c) {
return max(a, max(b, c));
}
static int maxof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
int max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static long maxof(long a, long b, long c) {
return max(a, max(b, c));
}
static long maxof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
long max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static int powi(int a, int b) {
if (a == 0) return 0;
int ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static long powl(long a, int b) {
if (a == 0) return 0;
long ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static int fli(double d) {
return (int) d;
}
static int cei(double d) {
return (int) ceil(d);
}
static long fll(double d) {
return (long) d;
}
static long cel(double d) {
return (long) ceil(d);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static int[] exgcd(int a, int b) {
if (b == 0) return new int[]{1, 0};
int[] y = exgcd(b, a % b);
return new int[]{y[1], y[0] - y[1] * (a / b)};
}
static long[] exgcd(long a, long b) {
if (b == 0) return new long[]{1, 0};
long[] y = exgcd(b, a % b);
return new long[]{y[1], y[0] - y[1] * (a / b)};
}
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static long mix(long x) {
x += 0x9e3779b97f4a7c15L;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
return x ^ (x >> 31);
}
public static boolean[] findPrimes(int limit) {
assert limit >= 2;
final boolean[] nonPrimes = new boolean[limit];
nonPrimes[0] = true;
nonPrimes[1] = true;
int sqrt = (int) Math.sqrt(limit);
for (int i = 2; i <= sqrt; i++) {
if (nonPrimes[i]) continue;
for (int j = i; j < limit; j += i) {
if (!nonPrimes[j] && i != j) nonPrimes[j] = true;
}
}
return nonPrimes;
}
// array util
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
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());
}
int[] ria(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = Integer.parseInt(next());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] rla(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = Long.parseLong(next());
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
java
|
1301
|
D
|
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
|
[
"constructive algorithms",
"graphs",
"implementation"
] |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) {
var scanner = new BufferedScanner();
var writer = new PrintWriter(new BufferedOutputStream(System.out));
var n = scanner.nextInt();
var m = scanner.nextInt();
var k = scanner.nextInt();
var ans = solve(n, m, k);
if (ans != null) {
writer.println("YES");
writer.println(ans.size());
assert ans.size() <= 3000;
for (Step step : ans) {
writer.println(step.f + " " + step.s);
}
} else {
writer.println("NO");
}
scanner.close();
writer.flush();
writer.close();
}
static final int[][] MOVE = {
{0, 1}, // R
{1, 0}, // D
{-1, 0}, // U
{0, -1} // L
};
static final char[] DIR = {0, 'R', 'D', 'U', 'L'};
private static List<Step> solve(int n, int m, int k) {
var atMost = 4 * n * m - 2 * n - 2 * m;
if (k > atMost) {
return null;
}
// 每条路只能走一遍,每个格子可以走多遍
// atMost步是一定可以走通的。主要问题变成了怎么分组使得能够在3000步以内表达。
var ans = new ArrayList<Step>();
var current = 0;
var r = 1;
var c = 1;
while (current < k) {
// RDU...
if (r < n) {
var countRDU = Math.min(m - c, (k - current) / 3);
if (countRDU > 0) {
ans.add(new Step(countRDU, "RDU"));
c += countRDU;
current += 3 * countRDU;
if (current == k) {
break;
}
if (k - current < 3 && c < m) {
// finishRDU(k - current, ans);
if (k - current == 2) {
ans.add(new Step(1, "R"));
ans.add(new Step(1, "D"));
} else {
ans.add(new Step(1, "R"));
}
break;
}
}
} else { // R...
var countR = Math.min(k - current, m - c);
if (countR > 0) {
ans.add(new Step(countR, "R"));
c += countR;
current += countR;
if (current == k) {
break;
}
}
}
// L...
{
var countL = Math.min(k - current, c - 1);
if (countL > 0) {
ans.add(new Step(countL, "L"));
c -= countL;
current += countL;
if (current == k) {
break;
}
}
}
// D...
if (r < n) {
ans.add(new Step(1, "D"));
r++;
current++;
if (current == k) {
break;
}
} else {
var countU = k - current;
ans.add(new Step(countU, "U"));
r -= countU;
current += countU;
}
}
return ans;
}
static final boolean DEBUG = true;
private static void log(Object... a) {
if (DEBUG) {
for (Object x : a) {
System.out.println(x + " ");
}
}
}
static class Step {
int f;
String s;
Step(int f, String s) {
this.f = f;
this.s = s;
assert s.length() <= 4;
}
}
public static class BufferedScanner {
BufferedReader br;
StringTokenizer st;
public BufferedScanner(Reader reader) {
br = new BufferedReader(reader);
}
public BufferedScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b > 0) {
long tmp = b;
b = a % b;
a = tmp;
}
return a;
}
static long inverse(long a, long m) {
long[] ans = extgcd(a, m);
return ans[0] == 1 ? (ans[1] + m) % m : -1;
}
private static long[] extgcd(long a, long m) {
if (m == 0) {
return new long[]{a, 1, 0};
} else {
long[] ans = extgcd(m, a % m);
long tmp = ans[1];
ans[1] = ans[2];
ans[2] = tmp;
ans[2] -= ans[1] * (a / m);
return ans;
}
}
private static List<Integer> primes(double upperBound) {
var limit = (int) Math.sqrt(upperBound);
var isComposite = new boolean[limit + 1];
var primes = new ArrayList<Integer>();
for (int i = 2; i <= limit; i++) {
if (isComposite[i]) {
continue;
}
primes.add(i);
int j = i + i;
while (j <= limit) {
isComposite[j] = true;
j += i;
}
}
return primes;
}
}
|
java
|
1313
|
C2
|
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
|
[
"data structures",
"dp",
"greedy"
] |
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.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
C2SkyscrapersHardVersion solver = new C2SkyscrapersHardVersion();
solver.solve(1, in, out);
out.close();
}
static class C2SkyscrapersHardVersion {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] arr = in.nextIntArray(n);
int[] b = Arrays.copyOf(arr, n);
reverse(b, 0, n - 1);
long[] t1 = calc(arr);
long[] t2 = calc(b);
long ans = 0;
int ind = -1;
for (int i = 0; i < n; i++) {
long t = t1[i];
t += t2[n - i - 1];
t -= arr[i];
if (t > ans) {
ans = t;
ind = i;
}
}
// out.println(ind);
int[] fans = new int[n];
int m = arr[ind];
for (int i = ind; i >= 0; i--) {
fans[i] = Math.min(m, arr[i]);
m = Math.min(m, arr[i]);
}
m = arr[ind];
for (int i = ind; i < n; i++) {
fans[i] = Math.min(m, arr[i]);
m = Math.min(m, arr[i]);
}
out.println(fans);
}
void reverse(int[] arr, int i, int j) {
while (i < j) {
swap(arr, i++, j--);
}
}
void swap(int[] arr, int i, int j) {
if (i != j) {
arr[i] ^= arr[j];
arr[j] ^= arr[i];
arr[i] ^= arr[j];
}
}
long[] calc(int[] arr) {
int n = arr.length;
long[] narr = new long[n];
int[] temp = nsv(arr);
Arrays.fill(narr, -1);
for (int i = 0; i < n; i++) {
if (temp[i] == -1) {
narr[i] = (long) (i + 1) * arr[i];
} else {
narr[i] = (long) (i - temp[i]) * arr[i] + narr[temp[i]];
}
}
return narr;
}
int[] nsv(int[] a) {
int n = a.length;
int[] p = new int[n];
for (int i = 0; i < n; i++) {
int j = i - 1;
while (j != -1 && a[j] >= a[i]) {
j = p[j];
}
p[i] = j;
}
return p;
}
}
static class InputReader {
BufferedReader reader;
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[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void println(int[] array) {
print(array);
writer.println();
}
public void close() {
writer.close();
}
}
}
|
java
|
1307
|
C
|
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
|
[
"brute force",
"dp",
"math",
"strings"
] |
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static final PrintWriter out =new PrintWriter(System.out);
static final FastReader sc = new FastReader();
/*
_oo0oo_
o8888888o
88" . "88
(| -_- |)
0\ = /0
___/`---'\___
.' \\| |// '.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' |_/ |
\ .-\__ '-' ___/-. /
___'. .' /--.--\ `. .'___
."" '< `.___\_<|>_/___.' >' "".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `_. \_ __\ /__ _/ .-` / /
=====`-.____`.___ \_____/___.-`___.-'=====
`=---='
*/
static class Pair{
int f,l;
public Pair(int first,int last)
{
this.f=first;
this.l=last;
}
}
public static boolean sorted(int a[])
{
int n=a.length,i;
int b[]=new int[n];
for(i=0;i<n;i++)
b[i]=a[i];
Arrays.sort(b);
for(i=0;i<n;i++)
{
if(a[i]!=b[i])
return false;
}
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
int tes=1;
while(tes-->0)
{
String s=sc.next();
int n=s.length(),i,j;
long a[]=new long[26];
long b[][]=new long[26][26];
for(i=0;i<n;i++)
{
int val=s.charAt(i)-'a';
for(j=0;j<26;j++)
b[j][val]+=a[j];
a[val]++;
}
long max=0;
for(i=0;i<26;i++)
max=Math.max(max,a[i]);
for(i=0;i<26;i++)
{
for(j=0;j<26;j++)
max=Math.max(max,b[i][j]);
}
System.out.println(max);
}
}
public static int first(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)
return mid;
else if (x > arr.get(mid))
return first(arr, (mid + 1), high, x, n);
else
return first(arr, low, (mid - 1), x, n);
}
return -1;
}
public static int last(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)
return mid;
else if (x < arr.get(mid))
return last(arr, low, (mid - 1), x, n);
else
return last(arr, (mid + 1), high, x, n);
}
return -1;
}
public static int lis(int[] arr) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>=x) {
al.add(arr[i]);
}else {
int v = upper_bound(al, 0, al.size(), arr[i]);
al.set(v, arr[i]);
}
}
return al.size();
}
public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get((int)mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long mod=1000000007;
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
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;
}
}
}
|
java
|
1305
|
C
|
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
|
[
"brute force",
"combinatorics",
"math",
"number theory"
] |
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class C_Kuroni_and_Impossible_Calculation {
static long mod = Long.MAX_VALUE;
static OutputStream outputStream = System.out;
static PrintWriter out = new PrintWriter(outputStream);
static FastReader f = new FastReader();
public static void main(String[] args) {
int t = 1;
while(t-- > 0){
solve();
}
out.close();
}
public static void solve() {
int n = f.nextInt();
long m = f.nextLong();
long arr[] = new long[n];
for(int i = 0; i < n; i++) {
arr[i] = f.nextLong();
}
if(n > m) {
out.println(0);
return;
}
long ans = 1;
for(int i = 1; i < n; i++) {
for(int j = 0; j < i; j++) {
ans = (ans*abs(arr[i]-arr[j]))%m;
}
}
out.println(ans);
}
// Sort an array
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
// Find all divisors of n
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
// Check if n is prime or not
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
// Find gcd of a and b
public static long gcd(long a, long b) {
long dividend = a > b ? a : b;
long divisor = a < b ? a : b;
while(divisor > 0) {
long reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
// Find lcm of a and b
public static long lcm(long a, long b) {
long lcm = gcd(a, b);
long hcf = (a * b) / lcm;
return hcf;
}
// Find factorial in O(n) time
public static long fact(int n) {
long res = 1;
for(int i = 2; i <= n; i++) {
res = res * i;
}
return res;
}
// Find power in O(logb) time
public static long power(long a, long b) {
long res = 1;
while(b > 0) {
if((b&1) == 1) {
res = (res * a)%mod;
}
a = (a * a)%mod;
b >>= 1;
}
return res;
}
// Find nCr
public static long nCr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / (fact(r) * fact(n-r));
return ans;
}
// Find nPr
public static long nPr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / fact(r);
return ans;
}
// sort all characters of a string
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// User defined class for fast I/O
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();
}
boolean hasNext() {
if (st != null && st.hasMoreTokens()) {
return true;
}
String tmp;
try {
br.mark(1000);
tmp = br.readLine();
if (tmp == null) {
return false;
}
br.reset();
} catch (IOException e) {
return false;
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
// (a/b)%mod == (a * moduloInverse(b)) % mod;
// moduloInverse(b) = power(b, mod-2);
|
java
|
1141
|
F1
|
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
|
[
"greedy"
] |
//package com.company;
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
public static class Task {
public void solve(Scanner sc, PrintWriter pw) throws IOException {
int n = sc.nextInt();
int[] arr = new int[n];
int[] pref = new int[n + 1];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
pref[i + 1] = pref[i] + arr[i];
}
int best = 0;
List<int[]> ret = new ArrayList<>();
for (int L = 1; L <= n; L++) {
for (int i = 0; i + L <= n; i++) {
int sum = 0;
for (int j = i; j < i + L; j++) {
sum += arr[j];
}
int cur = 1;
int stop = i + L;
List<int[]> cu = new ArrayList<>();
cu.add(new int[]{i, i + L - 1});
for (int j = i + L; j < n; j++) {
for (int k = stop; k <= j; k++) {
if (pref[j + 1] - pref[k] == sum) {
cur++;
cu.add(new int[]{k, j});
stop = j + 1;
break;
}
}
}
if (cur > best) {
best = cur;
ret = cu;
}
}
}
pw.println(best);
for (int[] x: ret) {
pw.println(x[0] + 1 + " " + (x[1] + 1));
}
}
}
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
// PrintWriter pw = new PrintWriter(new FileOutputStream("ans.txt"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);
System.err.println("Time used: " + (TIME_END - TIME_START) + ".");
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
java
|
1288
|
D
|
D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
|
[
"binary search",
"bitmasks",
"dp"
] |
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) {
Problems problems = new Problems();
problems.solve();
}
}
class Problems {
Parser parser = new Parser();
void solve() {
int t = 1;
for (int i = 0; i < t; i++) {
Problem problem = new Problem();
problem.solve();
}
}
class Problem {
int lastSelectedA = -1;
int lastSelectedB = -1;
void solve() {
int n = parser.parseInt();
int m = parser.parseInt();
List<List<Integer>> arrs = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<Integer> arr = new ArrayList<>();
for (int j = 0; j < m; j++) {
arr.add(parser.parseInt());
}
arrs.add(arr);
}
int left = -1, right = 1_000_000_009;
while (left + 1 < right) {
int mid = (left + right) / 2;
if (ok(arrs, mid)) left = mid;
else right = mid;
}
System.out.println(lastSelectedA + " " + lastSelectedB);
}
boolean ok(List<List<Integer>> arrs, int v) {
int n = arrs.size();
int m = arrs.get(0).size();
Map<Integer, Integer> counts = new HashMap<>();
for (int i = 0; i < n; i++) {
int bit = 0;
List<Integer> arr = arrs.get(i);
for (int j = 0; j < m; j++) {
if (arr.get(j) < v) continue;
bit |= (1 << j);
}
counts.put(bit, i);
}
for (int i = 0; i < (1 << m); i++) {
for (int j = 0; j < (1 << m); j++) {
if ((i | j) != (1 << m) - 1) continue;
if (counts.containsKey(i) &&
counts.containsKey(j)) {
lastSelectedA = counts.get(i) + 1;
lastSelectedB = counts.get(j) + 1;
return true;
}
}
}
return false;
}
}
}
class Parser {
private final Iterator<String> stringIterator;
private final Deque<String> inputs;
Parser() {
this(System.in);
}
Parser(InputStream in) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
stringIterator = br.lines().iterator();
inputs = new ArrayDeque<>();
}
void fill() {
while (inputs.isEmpty()) {
if (!stringIterator.hasNext()) throw new NoSuchElementException();
inputs.addAll(Arrays.asList(stringIterator.next().split(" ")));
while (!inputs.isEmpty() && inputs.getFirst().isEmpty()) {
inputs.removeFirst();
}
}
}
Integer parseInt() {
fill();
if (!inputs.isEmpty()) {
return Integer.parseInt(inputs.pollFirst());
}
throw new NoSuchElementException();
}
Long parseLong() {
fill();
if (!inputs.isEmpty()) {
return Long.parseLong(inputs.pollFirst());
}
throw new NoSuchElementException();
}
Double parseDouble() {
fill();
if (!inputs.isEmpty()) {
return Double.parseDouble(inputs.pollFirst());
}
throw new NoSuchElementException();
}
String parseString() {
fill();
return inputs.removeFirst();
}
}
|
java
|
13
|
C
|
C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1
|
[
"dp",
"sortings"
] |
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
/*
getOrDefault
valueOf
toCharArray()
System.out.println();
*/
public class HelloWorld{
public static void main(String []args) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T=Integer.parseInt(st.nextToken());
int[] arr=new int[T];
st = new StringTokenizer(infile.readLine());
build(arr,st,0);
PriorityQueue<Integer> pq=new PriorityQueue<>((a,b)->b-a);
long res=0;
for(int i=0;i<T;i++){
if(!pq.isEmpty() && arr[i]<pq.peek()){
res+=pq.poll()-arr[i];
pq.add(arr[i]);
}
pq.add(arr[i]);
}
System.out.println(res);
}
public static void build(int[] arr, StringTokenizer st, int lo){
for(int i=lo;i<arr.length;i++){
arr[i]=Integer.parseInt(st.nextToken());
}
}
}
|
java
|
1316
|
E
|
E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.
|
[
"bitmasks",
"dp",
"greedy",
"sortings"
] |
import java.io.*;
import java.util.*;
public class TeamBuilding {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(System.out);
static boolean debug = false;
//param
static int poolSize;
static int teamSize;
static int audSize;
static Person[] pool;
public static void main(String[] args) throws IOException {
//parse
StringTokenizer st = new StringTokenizer(br.readLine());
poolSize = Integer.parseInt(st.nextToken());
teamSize = Integer.parseInt(st.nextToken());
audSize = Integer.parseInt(st.nextToken());
pool = new Person[poolSize];
st = new StringTokenizer(br.readLine());
for (int i=0;i<poolSize;i++){
pool[i] = new Person();
pool[i].audStrength = Integer.parseInt(st.nextToken());
}
for (int i=0;i<poolSize;i++){
st = new StringTokenizer(br.readLine());
for (int j=0;j<teamSize;j++){
pool[i].positionStrength[j]=Integer.parseInt(st.nextToken());
}
}
//greedy
Arrays.sort(pool, Comparator.comparingLong(a->-a.audStrength));
if (debug) for (Person p : pool) System.out.println(p);
//greedy bitset dp
//dp[on xth sweep][team composition]
//setup
int subsets = 1<<teamSize;
long[][] dp = new long[poolSize+1][subsets];
for (int r=0;r<=poolSize;r++) for (int c=0;c<subsets;c++) dp[r][c]=-1;
dp[0][0]=0;
//transition
for (int x=1;x<=poolSize;x++){
for (int s=0;s<subsets;s++){
//try adding x as aud
int aud = x - 1 - Integer.bitCount(s);
if (aud < audSize) {
if (dp[x-1][s]!=-1){
dp[x][s]=dp[x-1][s]+pool[x-1].audStrength;
}
}
else {
if (dp[x-1][s]!=-1){
dp[x][s]=dp[x-1][s];
}
}
//try adding x to position
for (int position=0;position<teamSize;position++){
int bit = 1 << position;
if ((s&bit)!=0 && dp[x-1][s^bit]!=-1){
dp[x][s]=Math.max(dp[x][s],dp[x-1][s^bit]+pool[x-1].positionStrength[position]);
}
}
}
}
if (debug){
for (int i=0;i<=poolSize;i++){
System.out.println(Arrays.toString(dp[i]));
}
}
out.println(dp[poolSize][subsets-1]);
out.close();
}
private static class Person {
long[] positionStrength;
long audStrength;
public Person(){
positionStrength = new long[teamSize];
}
public String toString(){
return "["+audStrength+", "+Arrays.toString(positionStrength)+"]";
}
}
}
|
java
|
1310
|
A
|
A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.
|
[
"data structures",
"greedy",
"sortings"
] |
import java.io.*;
import java.util.*;
public class tank {
static final FastScanner fs = new FastScanner();
//static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int t = 1;
while(t-- > 0) run_case();
//out.close();
}
static void run_case() {
int n = fs.nextInt();
Integer[][] a = new Integer[n][2];
for (int i = 0; i < n; i++) {
a[i][0] = fs.nextInt();
}
for (int i = 0; i < n; i++) {
a[i][1] = fs.nextInt();
}
Arrays.sort(a, new comp());
PriorityQueue<Integer> pq = new PriorityQueue<>(new comp2());
int i = 0;
long ans = 0, sum = 0, cur = 0;
while(!pq.isEmpty() || i < n) {
if(pq.isEmpty()) {
pq.offer(a[i][1]);
sum = a[i][1];
cur = a[i][0];
i++;
for (; i < n && a[i][0].equals(a[i - 1][0]); i++) {
pq.offer(a[i][1]);
sum += a[i][1];
}
}
sum -= pq.poll();
ans += sum;
cur++;
while(i < n && a[i][0] == cur) {
sum += a[i][1];
pq.offer(a[i][1]);
i++;
}
}
System.out.println(ans);
}
static class comp implements Comparator<Integer[]> {
@Override
public int compare(Integer[] o1, Integer[] o2) {
if(o1[0] > o2[0]) return 1;
else if(o1[0].equals(o2[0])) {
if(o1[1] < o2[1]) return 1;
else if(o1[1].equals(o2[1])) return 0;
}
return -1;
}
}
static class comp2 implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
if(o1 < o2) return 1;
else if(o1.equals(o2)) return 0;
return -1;
}
}
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();
}
String nextLine(){
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
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());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
java
|
1296
|
C
|
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
|
[
"data structures",
"implementation"
] |
import java.awt.image.AreaAveragingScaleFilter;
import java.awt.image.MemoryImageSource;
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.StringTokenizer;
public class cf799 {
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str=br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static int fast(){
FastReader sc = new FastReader();
return sc.nextInt();
}
static int [] parent=new int[100001];
static int [] rank=new int[100001];
public static void makeSet(){
for(int i=0;i<parent.length;i++){
parent[i]=i;
rank[i]=0;
}
}
public static int findParent(int num){
if(parent[num]==num)return num;
return parent[num]=findParent(parent[num]);
}
public static void union(int a,int b){
int ff=findParent(a);
int ss=findParent(b);
if(rank[ff]<rank[ss]){
parent[ff]=ss;
}
else if(rank[ss]<rank[ff]){
parent[ss]=ff;
}
else{
parent[ff]=ss;
rank[ss]++;
}
}
public static void main(String[] args) {
try {
FastReader sc = new FastReader();
FastWriter out = new FastWriter();
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
String s=sc.next();
int st=0;
int en=0;
int min=Integer.MAX_VALUE;
HashMap<ArrayKey, Integer> map=new HashMap<>();
map.put(new ArrayKey(new int[]{0,0}),0);
int ff=0;
int ss=0;
for(int i=0;i<n;i++){
char ch=s.charAt(i);
if(ch=='L')ff++;
if(ch=='R')ff--;
if(ch=='U')ss++;
if(ch=='D')ss--;
if(map.containsKey(new ArrayKey(new int[]{ff,ss}))){
if(i-map.get(new ArrayKey(new int[]{ff,ss}))+1<min){
min=i-map.get(new ArrayKey(new int[]{ff,ss}))+1;
st=map.get(new ArrayKey(new int[]{ff,ss}));
en=i;
}
}
map.put(new ArrayKey(new int[]{ff,ss}), i+1);
}
if(min==Integer.MAX_VALUE){
System.out.println(-1);
}else{
System.out.println((st+1)+" "+(en+1));
}
}
}catch (Exception e) {
return;
}
}
public static int codeventure(int n , int [] dp){
if(n==0){
return 1;
}
if(n<0)return 0;
if(dp[n]!=-1)return dp[n];
return dp[n]=codeventure(n-1,dp)+codeventure(n-2,dp);
}
public static void swap(int [] arr,int i,int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void dfs(ArrayList<Integer> temp , HashMap<Integer,Integer> map,ArrayList<ArrayList<Integer>> adjancy_list ,int num){
temp.add(num);
map.put(num,1);
for(int child:adjancy_list.get(num)){
if(!map.containsKey(child))
dfs(temp,map,adjancy_list,child);
}
}
public static long yup(long number,int [] arr){
long ans=0;
int n=arr.length;
int running_sum=0;
int ff=0;
int ss=0;
for(int i=0;i<n;i++){
running_sum+=arr[i];
if(running_sum==number){
ans+=ss-ff;
ff=i+1;
running_sum=0;
}
else if(running_sum>number){
return -1;
}
ss++;
}
if(running_sum==0)return ans;
else return -1;
}
private static StringBuilder integerToBinary(int n) {
StringBuilder sb=new StringBuilder();
while(n>0){
if((n&1)==1)sb.append('1');
else sb.append('0');
n=n>>1;
}
return sb.reverse();
}
static boolean isPrime(int num)
{
if(num<=1)
{
return true;
}
for(int i=2;i*i<=num;i++)
{
if((num%i)==0)
return false;
}
return true;
}
public static long kadane(int [] arr,int i,int j){
long ans=0;
long max=0;
for(int f=i;f<j;f++){
max+=arr[f];
if(max<0){
max=0;
}
ans=Math.max(ans,max);
}
return ans;
}
public static int lcm(int a,int b){
return (a/gcd(a,b))*b;
}
private static int gcd(int a, int b) {
if(b==0)return a;
return gcd(b,a%b);
}
static class Pair {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
static class ArrayKey {
private int[] array;
public ArrayKey(int[] array) {
this.array = array;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ArrayKey arrayKey = (ArrayKey) o;
return Arrays.equals(array, arrayKey.array);
}
@Override
public int hashCode() {
return Arrays.hashCode(array);
}
}
}
|
java
|
1295
|
D
|
D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.
|
[
"math",
"number theory"
] |
import java.util.HashSet;
import java.util.Scanner;
public class E1295D {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int test = scn.nextInt();
while (test-- > 0) {
long a = scn.nextLong();
long b = scn.nextLong();
long gcd = gcd(a, b);
b /= gcd;
HashSet<Long> primeDivs = new HashSet<>();
long ans = b;
for (long i = 2; i * i <= b && b > 0; i++) {
while (b % i == 0) {
primeDivs.add(i);
b /= i;
}
}
if (b > 1)
primeDivs.add(b);
for (long div : primeDivs) {
ans /= div;
ans *= div - 1;
}
System.out.println(ans);
}
}
static long gcd(long a, long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
}
|
java
|
1313
|
C1
|
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
|
[
"brute force",
"data structures",
"dp",
"greedy"
] |
import java.util.*;
import java.io.*;
public class Main {
static long mod = 1000000007;
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
int t = 1;
while( t-- > 0) {
int n = sc.nextInt();
long arr[] = new long[n];
for( int i = 0 ;i < n ;i++) {
arr[i] = sc.nextLong();
}
long ans = Long.MIN_VALUE;
int idx = -1;
for( int i = 0 ; i < n ;i++) {
long sum = 0;
int j = i;
sum+=arr[j];
long min = arr[j];
j--;
for( ; j >= 0 ; j--) {
if( arr[j] <= min) {
sum+=arr[j];
min = arr[j];
}
else {
sum+=min;
}
}
j = i;
min = arr[i];
j++;
for( ; j < n ;j++) {
if( arr[j] <= min) {
sum+=arr[j];
min = arr[j];
}
else {
sum+=min;
}
}
if( sum > ans) {
ans = sum;
idx = i;
}
}
// out.println(ans + " " + idx);
long a[] = new long[n];
a[idx] = arr[idx];
long min = a[idx];
for( int i = idx+1 ;i < n; i++) {
if(arr[i] <= min) {
a[i] = arr[i];
min = arr[i];
}
else {
a[i] = min;
}
}
min = a[idx];
for( int i = idx-1 ;i >= 0; i--) {
if(arr[i] <= min) {
a[i] = arr[i];
min = arr[i];
}
else {
a[i] = min;
}
}
for( long x : a) {
out.print(x+" ");
}
out.println();
}
out.flush();
}
/*
* WARNING -> DONT EVER USE ARRAYS.SORT() IN ANY WAY.
* A B C are easy just dont give up , you can do it!
* FIRST AND VERY IMP -> READ AND UNDERSTAND THE QUESTION VERY CAREFULLY.
* WARNING -> DONT CODE BULLSHIT , ALWAYS CHECK THE LOGIC ON MULTIPLE TESTCASES AND EDGECASES BEFORE.
* SECOND -> TRY TO FIND RELEVENT PATTERN SMARTLY.
* WARNING -> IF YOU THINK YOUR SOLUION IS JUST DUMB DONT SUBMIT IT BEFORE RECHECKING ON YOUR END.
*/
public static boolean ifpowof2(long n ) {
return ((n&(n-1)) == 0);
}
static boolean isprime(long x ) {
if( x== 2) {
return true;
}
if( x%2 == 0) {
return false;
}
for( long i = 3 ;i*i <= x ;i+=2) {
if( x%i == 0) {
return false;
}
}
return true;
}
static boolean[] sieveOfEratosthenes(long n) {
boolean prime[] = new boolean[(int)n + 1];
for (int i = 0; i <= n; i++) {
prime[i] = true;
}
for (long p = 2; p * p <= n; p++) {
if (prime[(int)p] == true) {
for (long i = p * p; i <= n; i += p)
prime[(int)i] = false;
}
}
return prime;
}
public static int[] nextLargerElement(int[] arr, int n) {
Stack<Integer> stack = new Stack<>();
int rtrn[] = new int[n];
rtrn[n-1] = -1;
stack.push( n-1);
for( int i = n-2 ;i >= 0 ; i--){
int temp = arr[i];
int lol = -1;
while( !stack.isEmpty() && arr[stack.peek()] <= temp){
if(arr[stack.peek()] == temp ) {
lol = stack.peek();
}
stack.pop();
}
if( stack.isEmpty()){
if( lol != -1) {
rtrn[i] = lol;
}
else {
rtrn[i] = -1;
}
}
else{
rtrn[i] = stack.peek();
}
stack.push( i);
}
return rtrn;
}
static void mysort(int[] arr) {
for(int i=0;i<arr.length;i++) {
int rand = (int) (Math.random() * arr.length);
int loc = arr[rand];
arr[rand] = arr[i];
arr[i] = loc;
}
Arrays.sort(arr);
}
static void mySort(long[] arr) {
for(int i=0;i<arr.length;i++) {
int rand = (int) (Math.random() * arr.length);
long loc = arr[rand];
arr[rand] = arr[i];
arr[i] = loc;
}
Arrays.sort(arr);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b)
{
return (a / gcd(a, b)) * b;
}
static long rightmostsetbit(long n) {
return n&-n;
}
static long leftmostsetbit(long n)
{
long k = (long)(Math.log(n) / Math.log(2));
return k;
}
static HashMap<Long,Long> primefactor( long n){
HashMap<Long ,Long> hm = new HashMap<>();
long temp = 0;
while( n%2 == 0) {
temp++;
n/=2;
}
if( temp!= 0) {
hm.put( 2L, temp);
}
long c = (long)Math.sqrt(n);
for( long i = 3 ; i <= c ; i+=2) {
temp = 0;
while( n% i == 0) {
temp++;
n/=i;
}
if( temp!= 0) {
hm.put( i, temp);
}
}
if( n!= 1) {
hm.put( n , 1L);
}
return hm;
}
static ArrayList<Integer> allfactors(int abs) {
HashMap<Integer,Integer> hm = new HashMap<>();
ArrayList<Integer> rtrn = new ArrayList<>();
for( int i = 2 ;i*i <= abs; i++) {
if( abs% i == 0) {
hm.put( i , 0);
hm.put(abs/i, 0);
}
}
for( int x : hm.keySet()) {
rtrn.add(x);
}
if( abs != 0) {
rtrn.add(abs);
}
return rtrn;
}
public static int[][] prefixsum( int n , int m , int arr[][] ){
int prefixsum[][] = new int[n+1][m+1];
for( int i = 1 ;i <= n ;i++) {
for( int j = 1 ; j<= m ; j++) {
int toadd = 0;
if( arr[i-1][j-1] == 1) {
toadd = 1;
}
prefixsum[i][j] = toadd + prefixsum[i][j-1] + prefixsum[i-1][j] - prefixsum[i-1][j-1];
}
}
return prefixsum;
}
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;
}
}
}
|
java
|
1285
|
C
|
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1
|
[
"brute force",
"math",
"number theory"
] |
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static final PrintWriter out =new PrintWriter(System.out);
static final FastReader sc = new FastReader();
public static boolean sorted(int a[])
{
int n=a.length,i;
int b[]=new int[n];
for(i=0;i<n;i++)
b[i]=a[i];
Arrays.sort(b);
for(i=0;i<n;i++)
{
if(a[i]!=b[i])
return false;
}
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
long x=sc.nextLong();
long i,min=Integer.MAX_VALUE,max=0;
for(i=1;i*i<=x;i++)
{
if(x%i==0 && gcd(x/i,i)==1)
min=i;
}
System.out.println((x/min)+" "+min);
}
public static int first(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)
return mid;
else if (x > arr.get(mid))
return first(arr, (mid + 1), high, x, n);
else
return first(arr, low, (mid - 1), x, n);
}
return -1;
}
public static int last(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)
return mid;
else if (x < arr.get(mid))
return last(arr, low, (mid - 1), x, n);
else
return last(arr, (mid + 1), high, x, n);
}
return -1;
}
public static int lis(int[] arr) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>=x) {
al.add(arr[i]);
}else {
int v = upper_bound(al, 0, al.size(), arr[i]);
al.set(v, arr[i]);
}
}
return al.size();
}
public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get((int)mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long mod=1000000007;
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
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;
}
}
}
|
java
|
1325
|
D
|
D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.
|
[
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] |
import java.text.DecimalFormat;
import java.io.*;
import java.util.*;
public class Main
{
static class Pair
{
long a;
int b;
public Pair(long a,int b)
{
this.a=a;
this.b=b;
}
}
static final int INF = 1 << 30;
static final long INFL = 1L << 60;
static final long NINF = INFL * -1;
static final long mod = (long) 1e9 + 7;
static final long mod2 = 998244353;
static DecimalFormat df = new DecimalFormat("0.00000000000000");
public static final double PI = 3.141592653589793d, eps = 1e-9;
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC
{
static long[] find(long x,long y)
{
if(x<y)
{
return new long[]{-1};
}
else if(x==y)
{
return new long[]{y};
}
else if(((x-y)&1)!=0)
{
return new long[]{-1};
}
else
{
long a=(x-y)/2L;
if((a&y)==0)
{
long b=a+y;
return new long[]{a,b};
}
else
{
return new long[]{y,a,a};
}
}
}
public static void solve(int testNumber, InputReader in, OutputWriter out)
{
//int t = in.ni();
int t=1;
while (t-->0)
{
long u=in.nextLong();
long v=in.nextLong();
if(u==0 && v==0)
{
out.printLine(0);
continue;
}
long[] arr=find(v,u);
if(arr[0]==-1)
{
out.printLine(-1);
}
else
{
out.printLine(arr.length);
out.printLine(arr);
}
}
}
}
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 ni() {
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 char nc() { return (char)skip(); }
public int[] na(int arraySize) {
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = ni();
}
return array;
}
private int skip() {
int b;
while ((b = read()) != -1 && isSpaceChar(b)) ;
return b;
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
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 = read();
}
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;
}
int[][] nim(int h, int w) {
int[][] a = new int[h][w];
for (int i = 0; i < h; i++) {
a[i] = na(w);
}
return a;
}
long[][] nlm(int h, int w) {
long[][] a = new long[h][w];
for (int i = 0; i < h; i++) {
a[i] = nla(w);
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isNewLine(int c) {
return c == '\n';
}
public String nextLine() {
int c = read();
StringBuilder result = new StringBuilder();
do {
result.appendCodePoint(c);
c = read();
} while (!isNewLine(c));
return result.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
long result = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
result *= 10;
result += c & 15;
c = read();
} while (!isSpaceChar(c));
return result * sign;
}
public long[] nla(int arraySize) {
long array[] = new long[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextLong();
}
return array;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = (byte) read();
while (c <= ' ') {
c = (byte) read();
}
boolean neg = (c == '-');
if (neg) {
c = (byte) read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = (byte) read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = (byte) read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
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);
}
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
public static class CP
{
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n == 2 || n == 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; (long) i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
public static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static long pow(long a, long n, long mod) {
// a %= mod;
long ret = 1;
int x = 63 - Long.numberOfLeadingZeros(n);
for (; x >= 0; x--) {
ret = ret * ret % mod;
if (n << 63 - x < 0)
ret = ret * a % mod;
}
return ret;
}
public static void nextPermutation(int[] nums) {
//find first decreasing digit
int mark = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
mark = i - 1;
break;
}
}
if (mark == -1) {
reverse(nums, 0, nums.length - 1);
return;
}
int idx = nums.length-1;
for (int i = nums.length-1; i >= mark+1; i--) {
if (nums[i] > nums[mark]) {
idx = i;
break;
}
}
CP.swap(nums, mark, idx);
CP.reverse(nums, mark + 1, nums.length - 1);
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void reverse(int[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
public static boolean isComposite(long n) {
if (n < 2)
return true;
if (n == 2 || n == 3)
return false;
if (n % 2 == 0 || n % 3 == 0)
return true;
for (long i = 6L; i * i <= n; i += 6)
if (n % (i - 1) == 0 || n % (i + 1) == 0)
return true;
return false;
}
static int ifnotPrime(int[] prime, int x) {
return (prime[x / 64] & (1 << ((x >> 1) & 31)));
}
static long log2(long n)
{
return (long)(Math.log10(n)/Math.log10(2L));
}
static void makeComposite(int[] prime, int x) {
prime[x / 64] |= (1 << ((x >> 1) & 31));
}
public static String swap(String a, int i, int j) {
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
static void reverse(long arr[]){
int l = 0, r = arr.length-1;
while(l<r){
long temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
static void reverse(int arr[]){
int l = 0, r = arr.length-1;
while(l<r){
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
public static int[] sieveEratosthenes(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[] isnp = 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 j = 0; j < sup; j += tp) {
for (int i = 0; i < tp && i + j < sup; i++) {
isnp[j + i] |= 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 = ~isnp[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;
if ((long) p * p > n)
continue;
for (int q = (p * p - 3) / 2; q <= h; q += p)
isnp[q >> 5] |= 1 << q;
}
}
return Arrays.copyOf(ret, pos);
}
static long digitSum(long s) {
long brute = 0;
while (s > 0) {
brute+=s%10;
s /= 10;
}
return brute;
}
public static int[] primefacts(int n, int[] primes) {
int[] ret = new int[15];
int rp = 0;
for (int p : primes) {
if (p * p > n) break;
int i;
for (i = 0; n % p == 0; n /= p, i++) ;
if (i > 0) ret[rp++] = p;
}
if (n != 1) ret[rp++] = n;
return Arrays.copyOf(ret, rp);
}
public static long[] sort(long arr[]) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list);
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static long[] revsort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static int[] revsort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static ArrayList<Integer> reverse(
ArrayList<Integer> data,
int left, int right)
{
while (left < right)
{
int temp = data.get(left);
data.set(left++,
data.get(right));
data.set(right--, temp);
}
return data;
}
static ArrayList<Integer> sieve(long size)
{
ArrayList<Integer> pr = new ArrayList<Integer>();
boolean prime[] = new boolean[(int) size];
for (int i = 2; i < prime.length; i++) prime[i] = true;
for (int i = 2; i * i < prime.length; i++) {
if (prime[i]) {
for (int j = i * i; j < prime.length; j += i) {
prime[j] = false;
}
}
}
for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i);
return pr;
}
static ArrayList<Integer> segmented_sieve(int l, int r, ArrayList<Integer> primes) {
ArrayList<Integer> al = new ArrayList<>();
if (l == 1) ++l;
int max = r - l + 1;
int arr[] = new int[max];
for (int p : primes) {
if (p * p <= r) {
int i = (l / p) * p;
if (i < l) i += p;
for (; i <= r; i += p) {
if (i != p) {
arr[i - l] = 1;
}
}
}
}
for (int i = 0; i < max; ++i) {
if (arr[i] == 0) {
al.add(l + i);
}
}
return al;
}
static boolean isfPrime(long n, int iteration) {
if (n == 0 || n == 1)
return false;
if (n == 2)
return true;
if (n % 2 == 0)
return false;
Random rand = new Random();
for (int i = 0; i < iteration; i++) {
long r = Math.abs(rand.nextLong());
long a = r % (n - 1) + 1;
if (modPow(a, n - 1, n) != 1)
return false;
}
return true;
}
static long modPow(long a, long b, long c) {
long res = 1;
for (int i = 0; i < b; i++) {
res *= a;
res %= c;
}
return res % c;
}
private static long binPower(long a, long l, long mod) {
long res = 0;
while (l > 0) {
if ((l & 1) == 1) {
res = mulmod(res, a, mod);
l >>= 1;
}
a = mulmod(a, a, mod);
}
return res;
}
private static long mulmod(long a, long b, long c) {
long x = 0, y = a % c;
while (b > 0) {
if (b % 2 == 1) {
x = (x + y) % c;
}
y = (y * 2L) % c;
b /= 2;
}
return x % c;
}
static long binary_Expo(long a, long b) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res *= a;
--b;
}
a *= a;
b /= 2;
}
return res;
}
static void swap(int a, int b) {
int tp = b;
b = a;
a = tp;
}
static long Modular_Expo(long a, long b, long mod) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res = (res * a) % mod;
--b;
}
a = (a * a) % mod;
b /= 2;
}
return res % mod;
}
static int i_gcd(int a, int b) {
while (true) {
if (b == 0)
return a;
int c = a;
a = b;
b = c % b;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static int gcd(int a,int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long ceil_div(long a, long b) {
return (a + b - 1) / b;
}
static int getIthBitFromInt(int bits, int i) {
return (bits >> (i - 1)) & 1;
}
static long getIthBitFromLong(long bits, int i) {
return (bits >> (i - 1)) & 1;
}
static boolean isPerfectSquare(long a)
{
long sq=(long)(Math.floor(Math.sqrt(a))*Math.floor(Math.sqrt(a)));
return sq==a;
}
private static TreeMap<Long, Long> primeFactorize(long n) {
TreeMap<Long, Long> pf = new TreeMap<>(Collections.reverseOrder());
long cnt = 0;
long total = 1;
for (long i = 2; (long) i * i <= n; ++i) {
if (n % i == 0) {
cnt = 0;
while (n % i == 0) {
++cnt;
n /= i;
}
pf.put(cnt, i);
//total*=(cnt+1);
}
}
if (n > 1) {
pf.put(1L, n);
//total*=2;
}
return pf;
}
//less than or equal
private static int lower_bound(ArrayList<Long> list, long val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(int[] arr, int val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(long[] arr, long val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid]>=val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
// greater than or equal
private static int upper_bound(List<Integer> list, int val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(int[] arr, int val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(long[] arr, long val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int[] LIS(long arr[], int n) {
List<Long> list = new ArrayList<>();
int[] cnt=new int[n];
for (int i = 0; i < n; i++) {
int idx = find1(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
cnt[i]=list.size();
}
return cnt;
}
private static int find1(List<Long> list, long val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid)>=val) {
ret = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ret;
}
private static int LNDS(int[] arr, int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find2(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find2(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) <= val) {
i = mid + 1;
} else {
ret = mid;
j = mid - 1;
}
}
return ret;
}
private static long nCr(long n, long r,long mod) {
if (n - r > r)
r = n - r;
long ans = 1L;
for (long i = r + 1; i <= n; i++)
ans = (ans%mod*i%mod)%mod;
for (long i = 2; i <= n - r; i++)
ans /= i;
return ans%mod;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
static void initStringHash(String s,long[] dp,long[] inv,long p)
{
long pow=1;
inv[0]=1;
int n=s.length();
dp[0]=((s.charAt(0)-'a')+1);
for(int i=1;i<n;++i)
{
pow=(pow*p)%mod;
dp[i]=(dp[i-1]+((s.charAt(i)-'a')+1)*pow)%mod;
inv[i]=CP.modinv(pow,mod)%mod;
}
}
static long getStringHash(long[] dp,long[] inv,int l,int r)
{
long ans=dp[r];
if(l-1>=0)
{
ans-=dp[l-1];
}
ans=(ans*inv[l])%mod;
return ans;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
private static String sortString(String str) {
int[] arr = new int[256];
for (char ch : str.toCharArray())
arr[ch]++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; i++)
while (arr[i]-- > 0)
sb.append((char) i);
return sb.toString();
}
static boolean isSquarefactor(int x, int factor, int target) {
int s = (int) Math.round(Math.sqrt(x));
return factor * s * s == target;
}
static boolean isSquare(long x) {
long s = (long) Math.round(Math.sqrt(x));
return x * x == s;
}
static int bs(ArrayList<Integer> al, int val) {
int l = 0, h = al.size() - 1, mid = 0, ans = -1;
while (l <= h) {
mid = (l + h) >> 1;
if (al.get(mid) == val) {
return mid;
} else if (al.get(mid) > val) {
h = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
static void sort(int a[]) // heap sort
{
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 0; i < a.length; i++)
q.add(a[i]);
for (int i = 0; i < a.length; i++)
a[i] = q.poll();
}
static void shuffle(int[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * in.length);
fast_swap(in, idx, i);
}
}
public static int[] radixSort2(int[] a) {
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for (int v : a) {
c0[(v & 0xff) + 1]++;
c1[(v >>> 8 & 0xff) + 1]++;
c2[(v >>> 16 & 0xff) + 1]++;
c3[(v >>> 24 ^ 0x80) + 1]++;
}
for (int i = 0; i < 0xff; i++) {
c0[i + 1] += c0[i];
c1[i + 1] += c1[i];
c2[i + 1] += c2[i];
c3[i + 1] += c3[i];
}
int[] t = new int[n];
for (int v : a) t[c0[v & 0xff]++] = v;
for (int v : t) a[c1[v >>> 8 & 0xff]++] = v;
for (int v : a) t[c2[v >>> 16 & 0xff]++] = v;
for (int v : t) a[c3[v >>> 24 ^ 0x80]++] = v;
return a;
}
static int[] computeLps(String pat) {
int len = 0, i = 1, m = pat.length();
int lps[] = new int[m];
lps[0] = 0;
while (i < m) {
if (pat.charAt(i) == pat.charAt(len)) {
++len;
lps[i] = len;
++i;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = len;
++i;
}
}
}
return lps;
}
static ArrayList<Integer> kmp(String s, String pat) {
ArrayList<Integer> al = new ArrayList<>();
int n = s.length(), m = pat.length();
int lps[] = computeLps(pat);
int i = 0, j = 0;
while (i < n) {
if (s.charAt(i) == pat.charAt(j)) {
i++;
j++;
if (j == m) {
al.add(i - j);
j = lps[j - 1];
}
} else {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return al;
}
static ArrayList<Long> primeFact(long n) {
ArrayList<Long> al = new ArrayList<>();
al.add(1L);
while (n % 2 == 0) {
if (!al.contains(2L)) {
al.add(2L);
}
n /= 2L;
}
for (long i = 3; (long) i * i <= n; i += 2) {
while ((n % i == 0)) {
if (!al.contains((long) i)) {
al.add((long) i);
}
n /= i;
}
}
if (n > 2) {
if (!al.contains(n)) {
al.add(n);
}
}
return al;
}
public static long totFact(long n)
{
long cnt = 0, tot = 1;
while (n % 2 == 0) {
n /= 2;
++cnt;
}
tot *= (cnt + 1);
for (int i = 3; i <= Math.sqrt(n); i += 2) {
cnt = 0;
while (n % i == 0) {
n /= i;
++cnt;
}
tot *= (cnt + 1);
}
if (n > 2) {
tot *= 2;
}
return tot;
}
static int[] z_function(String s)
{
int n = s.length(), z[] = new int[n];
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = Math.min(z[i - l], r - i + 1);
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))
++z[i];
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
static void fast_swap(int[] a, int idx1, int idx2) {
if (a[idx1] == a[idx2])
return;
a[idx1] ^= a[idx2];
a[idx2] ^= a[idx1];
a[idx1] ^= a[idx2];
}
public static void fast_sort(long[] array) {
ArrayList<Long> copy = new ArrayList<>();
for (long i : array)
copy.add(i);
Collections.sort(copy);
for (int i = 0; i < array.length; i++)
array[i] = copy.get(i);
}
static int factorsCount(int n) {
boolean hash[] = new boolean[n + 1];
Arrays.fill(hash, true);
for (int p = 2; p * p < n; p++)
if (hash[p] == true)
for (int i = p * 2; i < n; i += p)
hash[i] = false;
int total = 1;
for (int p = 2; p <= n; p++) {
if (hash[p]) {
int count = 0;
if (n % p == 0) {
while (n % p == 0) {
n = n / p;
count++;
}
total = total * (count + 1);
}
}
}
return total;
}
static long binomialCoeff(long n, long k) {
long res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res = (res * (n - i));
res /= (i + 1);
}
return res;
}
static long nck(long fact[], long inv[], long n, long k) {
if (k > n) return 0;
long res = fact[(int) n]%mod;
res = (int) ((res%mod* inv[(int) k]%mod))%mod;
res = (int) ((res%mod*inv[(int) (n - k)]%mod))%mod;
return res % mod;
}
public static long fact(long x) {
long fact = 1;
for (int i = 2; i <= x; ++i) {
fact = fact * i;
}
return fact;
}
public static ArrayList<Long> getFact(long x) {
ArrayList<Long> facts = new ArrayList<>();
facts.add(1L);
for (long i = 2; i * i <= x; ++i) {
if (x % i == 0) {
facts.add(i);
if (i != x / i) {
facts.add(x / i);
}
}
}
return facts;
}
static void matrix_ex(long n, long[][] A, long[][] I) {
while (n > 0) {
if (n % 2 == 0) {
Multiply(A, A);
n /= 2;
} else {
Multiply(I, A);
n--;
}
}
}
static void Multiply(long[][] A, long[][] B) {
int n = A.length, m = A[0].length, p = B[0].length;
long[][] C = new long[n][p];
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < m; k++) {
C[i][j] += ((A[i][k] % mod) * (B[k][j] % mod)) % mod;
C[i][j] = C[i][j] % mod;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
A[i][j] = C[i][j];
}
}
}
public static HashMap<Integer,Long> sortIntMapDesc(HashMap<Integer,Long> map) {
List<Map.Entry<Integer, Long>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) ->(int) (o2.getValue() - o1.getValue()));
HashMap<Integer, Long> temp = new LinkedHashMap<>();
for (Map.Entry<Integer,Long> i : list) {
temp.put(i.getKey(),i.getValue());
}
return temp;
}
public static HashMap<Long, Integer> sortMapDesc(HashMap<Long,Integer> map) {
List<Map.Entry<Long, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
HashMap<Long, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Long, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Character, Integer> sortMapDescch(HashMap<Character, Integer> map) {
List<Map.Entry<Character, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
HashMap<Character, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Character, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Long,Long> sortMapAsclng(HashMap<Long,Long> map) {
List<Map.Entry<Long,Long>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> (int)(o1.getValue() - o2.getValue()));
HashMap<Long,Long> temp = new LinkedHashMap<>();
for (Map.Entry<Long,Long> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Integer, Integer> sortMapAsc(HashMap<Integer, Integer> map) {
List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue());
HashMap<Integer, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Integer, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static long lcm(long l, long l2) {
long val = gcd(l, l2);
return (l * l2) / val;
}
public static boolean isSubsequence(String s, String t) {
int n = s.length();
int m = t.length();
if (m > n) {
return false;
}
int i = 0, j = 0, skip = 0;
while (i < n && j < m) {
if (s.charAt(i) == t.charAt(j)) {
--skip;
++j;
}
++skip;
++i;
}
return j==m;
}
public static long[][] combination(int l, int r) {
long[][] pascal = new long[l + 1][r + 1];
pascal[0][0] = 1;
for (int i = 1; i <= l; ++i) {
pascal[i][0] = 1;
for (int j = 1; j <= r; ++j) {
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
}
return pascal;
}
public static long gcd(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = gcd(ret, array[i]);
return ret;
}
public static long min(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]);
return ret;
}
public static long max(long a, long b) {
return a > b ? a : b;
}
public static long max(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]);
return ret;
}
public static long sum(long... array) {
long ret = 0;
for (long i : array) ret += i;
return ret;
}
public static long[] facts(int n,long m)
{
long[] fact=new long[n];
fact[0]=1;
fact[1]=1;
for(int i=2;i<n;i++)
{
fact[i]=(long)(i*fact[i-1])%m;
}
return fact;
}
public static long[] inv(long[] fact,int n,long mod)
{
long[] inv=new long[n];
inv[n-1]= CP.Modular_Expo(fact[n-1],mod-2,mod)%mod;
for(int i=n-2;i>=0;--i)
{
inv[i]=(inv[i+1]*(i+1))%mod;
}
return inv;
}
public static int modinv(long x, long mod) {
return (int) (CP.Modular_Expo(x, mod - 2, mod) % mod);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void printLine(long[] array) {
print(array);
writer.println();
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
public void printLine(int i) {
writer.println(i);
}
public void printLine(char c) {
writer.println(c);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void py()
{
print("YES");
writer.println();
}
public void pn()
{
print("NO");
writer.println();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
void flush() {
writer.flush();
}
}
}
|
java
|
1304
|
F2
|
F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
|
[
"data structures",
"dp",
"greedy"
] |
import java.util.*;
import java.io.*;
public class Animals{
static int lim=80000;
static int n,m,k,temp,max;
static int[][] M = new int[55][lim];
static int[][] DP = new int[55][40050];
static Deque<tuple> mono = new LinkedList<>();
public static void insert(tuple e){
while(!mono.isEmpty()&& e.v>mono.peekLast().v){mono.removeLast();}
mono.addLast(e);
}
public static void drop(int i){
if(mono.peekFirst().i==i){mono.removeFirst();}
}
public static int sum(int l,int p,int q){
return M[l][q]-M[l][p-1];
}
public static int lpun(int l, int x){
return DP[l-1][x]-M[l][x+k-1];
}
public static int rpun(int l, int x){
return DP[l-1][x]+M[l][x-1];
}
public static void main(String[] args) throws IOException{
Reader in = new Reader();
n = in.nextInt();m = in.nextInt();k = in.nextInt();
for (int i = 1; i <=n; i++) {
for (int j = 1; j <=m; j++) {
M[i][j]=in.nextInt()+M[i][j-1];
}
}
for (int i = 1; i <= m-k+1; i++) {
DP[1][i]=sum(1,i,i+k-1)+sum(2,i,i+k-1);
}
tuple tem;
for (int i = 2; i <= n; i++) {
//left
max=0;mono.clear();
for (int j = 1; j <= m-k+1; j++) {
if(j>k){drop(j-k);max = Math.max(max,DP[i-1][j-k]);}
insert(new tuple(j, lpun(i,j)));
tem = mono.peekFirst();
DP[i][j] = Math.max(DP[i-1][tem.i]+sum(i,tem.i+k,j+k-1), max+sum(i,j,j+k-1));
}
//right
max=0;mono.clear();
for (int j = m-k+1; j >= 1; j--) {
if(j+k<= m-k+1){drop(j+k);max = Math.max(max,DP[i-1][j+k]);}
insert(new tuple(j, rpun(i,j)));
tem = mono.peekFirst();
DP[i][j] = Math.max(DP[i][j],Math.max(DP[i-1][tem.i]+sum(i,j,tem.i-1), max+sum(i,j,j+k-1)));
}
for(int j=1;j<=m+k-1;j++){DP[i][j]+=sum(i+1,j,j+k-1);}
}
int ans=0;
for (int i = 1; i <= m-k+1; i++) {
ans = Math.max(DP[n][i],ans);
}
System.out.println(ans);
in.close();
}
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();
}
}
}
class tuple{
int i,v;
public tuple(int a,int b){
this.i=a;this.v=b;
}
}
|
java
|
1293
|
A
|
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
|
[
"binary search",
"brute force",
"implementation"
] |
import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int tc = 0; tc < t; ++tc) {
int n = sc.nextInt();
int s = sc.nextInt();
int k = sc.nextInt();
int[] a = new int[k];
for (int i = 0; i < a.length; ++i) {
a[i] = sc.nextInt();
}
System.out.println(solve(n, s, a));
}
sc.close();
}
static int solve(int n, int s, int[] a) {
Set<Integer> closed = Arrays.stream(a).boxed().collect(Collectors.toSet());
return Math.min(computeDistance(closed, s, 0, -1), computeDistance(closed, s, n + 1, 1));
}
static int computeDistance(Set<Integer> closed, int s, int end, int offset) {
for (int i = s; i != end; i += offset) {
if (!closed.contains(i)) {
return Math.abs(i - s);
}
}
return Integer.MAX_VALUE;
}
}
|
java
|
1323
|
B
|
B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is:
|
[
"binary search",
"greedy",
"implementation"
] |
// practice with kaiboy
import java.io.*;
import java.util.*;
public class CF1323B extends PrintWriter {
CF1323B() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1323B o = new CF1323B(); o.main(); o.flush();
}
int[] qu = new int[600];
void count(int[] aa, int n, int[] kk) {
for (int i = 0, l = 0; i <= n; i++)
if (i == n || aa[i] == 0) {
if (l > 0)
kk[l]++;
l = 0;
} else
l++;
int cnt = 0;
for (int l = 1; l <= n; l++)
if (kk[l] > 0) {
qu[cnt++] = l;
qu[cnt++] = kk[l];
}
for (int l_ = 1; l_ <= n; l_++) {
int k_ = 0;
for (int h = 0; h < cnt; h += 2) {
int l = qu[h], k = qu[h + 1];
if (l_ <= l)
k_ += (l - l_ + 1) * k;
}
kk[l_] = k_;
}
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int[] aa = new int[n];
for (int i = 0; i < n; i++)
aa[i] = sc.nextInt();
int[] bb = new int[m];
for (int j = 0; j < m; j++)
bb[j] = sc.nextInt();
int[] ka = new int[n + 1];
count(aa, n, ka);
int[] kb = new int[m + 1];
count(bb, m, kb);
long ans = 0;
for (int la = 1; la <= k && la <= n; la++)
if (k % la == 0) {
int lb = k / la;
if (lb <= m)
ans += (long) ka[la] * kb[lb];
}
println(ans);
}
}
|
java
|
1303
|
D
|
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
|
[
"bitmasks",
"greedy"
] |
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.InputMismatchException;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
Output out = new Output(outputStream);
DFillTheBag solver = new DFillTheBag();
int testCount = Integer.parseInt(in.next());
for(int i = 1; i<=testCount; i++)
solver.solve(i, in, out);
out.close();
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29);
thread.start();
thread.join();
}
static class DFillTheBag {
public DFillTheBag() {
}
public void solve(int kase, InputReader in, Output pw) {
long n = in.nextLong();
int m = in.nextInt(), ans = 0;
int[] cnt = new int[64];
for(int i = 0; i<m; i++) {
cnt[63-Long.numberOfLeadingZeros(in.nextInt())]++;
}
for(int i = 0; i<63; i++) {
boolean on = (n&1L<<i)>0;
if(on) {
if(cnt[i]==0) {
int j;
for(j = i; j<=63&&cnt[j]==0; j++) ;
if(j==64) {
pw.println("-1");
return;
}
ans += j-i;
cnt[j]--;
cnt[i] += 1<<j-i;
}
cnt[i]--;
}
cnt[i+1] += cnt[i] >> 1;
}
pw.println(ans);
}
}
static class Output implements Closeable, Flushable {
public StringBuilder sb;
public OutputStream os;
public int BUFFER_SIZE;
public boolean autoFlush;
public String LineSeparator;
public Output(OutputStream os) {
this(os, 1<<16);
}
public Output(OutputStream os, int bs) {
BUFFER_SIZE = bs;
sb = new StringBuilder(BUFFER_SIZE);
this.os = new BufferedOutputStream(os, 1<<17);
autoFlush = false;
LineSeparator = System.lineSeparator();
}
public void println(int i) {
println(String.valueOf(i));
}
public void println(String s) {
sb.append(s);
println();
if(autoFlush) {
flush();
}else if(sb.length()>BUFFER_SIZE >> 1) {
flushToBuffer();
}
}
public void println() {
sb.append(LineSeparator);
}
private void flushToBuffer() {
try {
os.write(sb.toString().getBytes());
}catch(IOException e) {
e.printStackTrace();
}
sb = new StringBuilder(BUFFER_SIZE);
}
public void flush() {
try {
flushToBuffer();
os.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
public void close() {
flush();
try {
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
static interface InputReader {
int nextInt();
long nextLong();
}
static class FastReader implements InputReader {
final private int BUFFER_SIZE = 1<<16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer;
private int bytesRead;
public FastReader(InputStream is) {
din = new DataInputStream(is);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
StringBuilder ret = new StringBuilder(64);
byte c = skip();
while(c!=-1&&!isSpaceChar(c)) {
ret.appendCodePoint(c);
c = read();
}
return ret.toString();
}
public int nextInt() {
int ret = 0;
byte c = skipToDigit();
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() {
long ret = 0;
byte c = skipToDigit();
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;
}
private boolean isSpaceChar(byte b) {
return b==' '||b=='\r'||b=='\n'||b=='\t'||b=='\f';
}
private byte skip() {
byte ret;
while(isSpaceChar((ret = read()))) ;
return ret;
}
private boolean isDigit(byte b) {
return b>='0'&&b<='9';
}
private byte skipToDigit() {
byte ret;
while(!isDigit(ret = read())&&ret!='-') ;
return ret;
}
private void fillBuffer() {
try {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
}catch(IOException e) {
e.printStackTrace();
throw new InputMismatchException();
}
if(bytesRead==-1) {
buffer[0] = -1;
}
}
private byte read() {
if(bytesRead==-1) {
throw new InputMismatchException();
}else if(bufferPointer==bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
}
}
|
java
|
1304
|
A
|
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
|
[
"math"
] |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int tc = 0; tc < t; ++tc) {
int x = sc.nextInt();
int y = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(solve(x, y, a, b));
}
sc.close();
}
static int solve(int x, int y, int a, int b) {
return ((y - x) % (a + b) == 0) ? ((y - x) / (a + b)) : -1;
}
}
|
java
|
1304
|
D
|
D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.
|
[
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] |
// practice with kaiboy
import java.io.*;
import java.util.*;
public class CF1304D extends PrintWriter {
CF1304D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1304D o = new CF1304D(); o.main(); o.flush();
}
void reverse(int[] aa, int i, int j) {
while (i < j) {
int tmp = aa[i]; aa[i] = aa[j]; aa[j] = tmp;
i++; j--;
}
}
void main() {
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
byte[] cc = sc.next().getBytes();
int[] aa = new int[n];
int[] bb = new int[n];
for (int i = 0; i < n; i++) {
aa[i] = n - i;
bb[i] = i + 1;
}
for (int i = 0, j; i < n - 1; i = j) {
byte c = cc[i];
j = i + 1;
while (j < n - 1 && cc[j] == c)
j++;
reverse(c == '<' ? aa : bb, i, j);
}
for (int i = 0; i < n; i++)
print(aa[i] + " ");
println();
for (int i = 0; i < n; i++)
print(bb[i] + " ");
println();
}
}
}
|
java
|
1296
|
F
|
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1
|
[
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] |
import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class BerlandBeauty {
ArrayList<int[]>[] adj;
int[] in;
int[] out;
int[][] parentOf;
int time;
int[] minBeauty;
public static void main(String[] args) throws IOException {
new BerlandBeauty().solve();
}
public void solve() throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(f.readLine());
this.adj = new ArrayList[n];
this.in = new int[n];
this.out = new int[n];
this.parentOf = new int[n][2];
for (int i = 0; i < n; i++) {
parentOf[i] = new int[2];
}
for (int i = 0; i < n; i++) {
this.adj[i] = new ArrayList<int[]>();
}
for (int i = 0; i < n - 1; i++) {
StringTokenizer tokenizer = new StringTokenizer(f.readLine());
int a = Integer.parseInt(tokenizer.nextToken()) - 1;
int b = Integer.parseInt(tokenizer.nextToken()) - 1;
int[] ar1 = {a, i + 1};
int[] ar2 = {b, i + 1};
adj[a].add(ar2);
adj[b].add(ar1);
}
this.time = 0;
dfs1(0);
adj = null;
int m = Integer.parseInt(f.readLine());
int[][] queries = new int[m][3];
minBeauty = new int[n];
Arrays.fill(minBeauty, 1);
for (int i = 0; i < m; i++) {
StringTokenizer tokenizer = new StringTokenizer(f.readLine());
int a = Integer.parseInt(tokenizer.nextToken()) - 1;
int b = Integer.parseInt(tokenizer.nextToken()) - 1;
int min = Integer.parseInt(tokenizer.nextToken());
queries[i][0] = a;
queries[i][1] = b;
queries[i][2] = min;
this.dfs2(a, b, min);
this.dfs2(b, a, min);
}
boolean isPossible = true;
for (int i = 0; i < m; i++) {
boolean currentIsGood = checkIfGood(queries[i][0], queries[i][1], queries[i][2]) || checkIfGood(queries[i][1], queries[i][0], queries[i][2]);
isPossible = isPossible && currentIsGood;
}
PrintWriter out = new PrintWriter(System.out);
if (isPossible) {
out.print(minBeauty[1]);
for (int i = 2; i <= n - 1; i ++) {
out.print(" ");
out.print(minBeauty[i]);
}
out.println();
} else {
out.println(-1);
}
out.close();
}
private void dfs1(int node) {
this.in[node] = time++;
for (int[] adjacent : adj[node]) {
if (adjacent[0] != parentOf[node][0]) {
parentOf[adjacent[0]][0] = node;
parentOf[adjacent[0]][1] = adjacent[1];
dfs1(adjacent[0]);
}
}
this.out[node] = time++;
}
private boolean checkIfGood(int startNode, int otherNode, int minimum) {
while (!(this.in[startNode] <= this.in[otherNode] && out[startNode] >= out[otherNode])) {
int newNode = parentOf[startNode][0];
//System.out.println(this.minBeauty[parentOf[startNode][1]] + " " + minimum);
if (this.minBeauty[parentOf[startNode][1]] == minimum) {
return true;
}
// System.out.println(parentOf[startNode][1] + " " + this.minBeauty[parentOf[startNode][1]]);
startNode = newNode;
}
return false;
}
private void dfs2(int startNode, int otherNode, int minimum) {
// System.out.println("wop " + startNode);
while (!(this.in[startNode] <= this.in[otherNode] && out[startNode] >= out[otherNode])) {
int newNode = parentOf[startNode][0];
this.minBeauty[parentOf[startNode][1]] = Math.max(minBeauty[parentOf[startNode][1]], minimum);
// System.out.println(parentOf[startNode][1] + " " + this.minBeauty[parentOf[startNode][1]]);
startNode = newNode;
}
}
}
|
java
|
1325
|
B
|
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].
|
[
"greedy",
"implementation"
] |
import java.util.*;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
for (int caze = 0; caze < cases; caze++) {
int n = scanner.nextInt();
Set<Integer> unique = new HashSet<>();
for (int i = 0; i < n; i++) {
unique.add(scanner.nextInt());
}
System.out.println(unique.size());
}
}
}
|
java
|
1296
|
D
|
D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6
|
[
"greedy",
"sortings"
] |
import java.io.*;
import java.util.*;
public class A{
public static void main(String[] args) {
FastScanner fs=new FastScanner();
PrintWriter out = new PrintWriter(System.out);
// int T = fs.nextInt();
// for (int tt=0; tt<T; tt++) {
// }
int n = fs.nextInt();
int a = fs.nextInt();
int b = fs.nextInt();
int k = fs.nextInt();
int[][] arr = new int[n][2];
int sum = a+b;
for(int i=0; i<n; i++) {
arr[i][0] = fs.nextInt();
int mod = arr[i][0]%sum;
if(mod==0) mod=sum;
int skip = 0;
if(mod>a) {
mod-=a;
skip = mod/a;
if(mod%a!=0) skip++;
}
arr[i][1] = skip;
}
Arrays.sort(arr, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[1]-b[1];
}
});
int res = 0;
int curSkips = 0;
for(int i=0; i<n; i++) {
if(curSkips+arr[i][1]>k) break;
res++;
curSkips+=arr[i][1];
}
out.println(res);
out.close();
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static 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());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
}
}
|
java
|
1313
|
C2
|
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
|
[
"data structures",
"dp",
"greedy"
] |
import java.io.*;
import java.util.Comparator;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Solution {
private static final String checkerSolutionOutput = "/home/quanvda/Main/Projects/MyProject/java-competitive-programming/src/_checker.solution.out";
private static final String checkerInput = "/home/quanvda/Main/Projects/MyProject/java-competitive-programming/src/_checker.in";
private static final String checkerBruteforcesOutput = "/home/quanvda/Main/Projects/MyProject/java-competitive-programming/src/_checker.bruteforces.out";
private static final String fileInput = "/home/quanvda/Main/Projects/MyProject/java-competitive-programming/src/_in";
private static final String fileOutput = "/home/quanvda/Main/Projects/MyProject/java-competitive-programming/src/_out";
private static class Config {
private static final boolean useInputFile = false;
private static final boolean useOutputFile = false;
private static final String inputFile = fileInput;
private static final String outputFile = checkerSolutionOutput;
}
public static void main(String[] args) throws Exception {
run();
}
public static void run() throws Exception {
FastScanner sc = new FastScanner();
int t = 1;
BufferedWriter writer = getWriter();
for (int i = 0; i < t; i++)
solve(sc, writer);
writer.flush();
}
static int n, a[];
static int[] rise() {
int b[] = new int[n];
for (int i = 0; i < n; i++) b[i] = a[i];
for (int i = n - 2; i >= 0; i--)
if (b[i] > b[i + 1])
b[i] = b[i + 1];
return b;
}
static int[] fall() {
int b[] = new int[n];
for (int i = 0; i < n; i++) b[i] = a[i];
for (int i = 1; i < n; i++)
if (b[i] > b[i - 1])
b[i] = b[i - 1];
return b;
}
static class Node {
int val;
int occ;
public Node(int val, int occ) {
this.val = val;
this.occ = occ;
}
}
static long[] calcPrefix() {
long[] res = new long[n];
TreeSet<Node> tr = new TreeSet<>(Comparator.comparingInt(x -> x.val));
Stack<Node> st = new Stack<>();
long sum = 0;
for (int i = 0; i < n; i++) {
if (i == 0) {
Node v = new Node(a[i], 1);
// push
tr.add(v);
st.add(v);
// upd sum
sum += a[i];
res[i] = sum;
} else {
Node cur = new Node(a[i], 1);
Node ceil = tr.ceiling(cur);
while (true && ceil != null) {
// pop
Node top = st.pop();
tr.remove(top);
// upd sum
sum -= 1L * top.val * top.occ;
cur.occ += top.occ;
if (top.equals(ceil))
break;
}
// push
tr.add(cur);
st.add(cur);
// upd sum
sum += 1L * cur.val * cur.occ;
res[i] = sum;
}
}
return res;
}
static void rev() {
int i = 0, j = n - 1;
while (i <= j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++;
j--;
}
}
static int[] riseFall() {
long[] pref = calcPrefix();
rev();
long[] postf = calcPrefix();
rev();
int i = 0, j = n - 1;
while (i <= j) {
long tmp = postf[i];
postf[i] = postf[j];
postf[j] = tmp;
i++;
j--;
}
int maxk = 0;
long mx = 0;
for (int k = 1; k < n - 1; k++) {
long vl = pref[k] + postf[k] - a[k];
if (vl > mx) {
maxk = k;
mx = vl;
}
}
int b[] = new int[n];
for (int k = 0; k < n; k++) b[k] = a[k];
for (int k = maxk - 1; k >= 0; k--)
if (b[k] > b[k + 1])
b[k] = b[k + 1];
for (int k = maxk + 1; k < n; k++)
if (b[k] > b[k - 1])
b[k] = b[k - 1];
return b;
}
static long calc(int[] b) {
long ans = 0;
for (int x : b) ans += x;
return ans;
}
private static void solve(FastScanner sc, BufferedWriter writer) throws Exception {
n = sc.nextInt();
a = sc.readArray(n);
int[] res = new int[n];
int[] ri = rise();
if (calc(ri) > calc(res))
res = ri;
int[] fa = fall();
if (calc(fa) > calc(res))
res = fa;
int[] rf = riseFall();
if (calc(rf) > calc(res))
res = rf;
for (int x : res)
writer.write(x + " ");
writer.write("\n");
}
private static class Pair<A, B> {
A first;
B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public Pair() {
}
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
private FastScanner() throws FileNotFoundException {
if (Config.useInputFile)
this.br = new BufferedReader(new InputStreamReader(new FileInputStream(Config.inputFile)));
else
this.br = new BufferedReader(new InputStreamReader(System.in));
this.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());
}
}
private static BufferedWriter getWriter() throws Exception {
if (Config.useOutputFile)
return getFileWriter();
return getConsoleWriter();
}
private static BufferedWriter getFileWriter() throws Exception {
PrintWriter writer = new PrintWriter(Config.outputFile);
writer.print("");
writer.close();
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(Config.outputFile)));
}
private static BufferedWriter getConsoleWriter() {
return new BufferedWriter(new OutputStreamWriter(System.out));
}
}
|
java
|
1307
|
B
|
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
|
[
"geometry",
"greedy",
"math"
] |
import java.util.*;
import java.io.*;
public class Practice {
static boolean multipleTC = true;
FastReader in;
PrintWriter out;
final static int mod = 1000000007;
final static int mod2 = 998244353;
final double E = 2.7182818284590452354;
final double PI = 3.14159265358979323846;
int MAX = 100005;
public static void main(String[] args) throws Exception {
new Practice().run();
}
void run() throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++)
solve(t);
out.flush();
out.close();
}
void pre() throws Exception {
}
void solve(int TC) throws Exception {
int n = ni(), x = ni(), arr[] = readArr(n);
HashSet<Integer> set = new HashSet<>();
for (int i : arr)
set.add(i);
if(set.contains(x)) {
pn("1");
return;
}
int max = max(arr);
int ans = x / max;
ans += ans == 0 ? 1 : 0;
if (x % max != 0)
ans++;
pn(ans);
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(long arr[]) {
ArrayList<Long> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
public StringBuilder printArr(int arr[]) {
StringBuilder sb = new StringBuilder();
int n = arr.length;
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
return sb;
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
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() throws Exception {
return in.next();
}
String nln() throws Exception {
return in.nextLine();
}
int ni() throws Exception {
return Integer.parseInt(in.next());
}
long nl() throws Exception {
return Long.parseLong(in.next());
}
double nd() throws Exception {
return Double.parseDouble(in.next());
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
}
|
java
|
1304
|
E
|
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
|
[
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1304e {
static Node[] euler;
static int p = 0, lg;
public static void main(String[] args) throws IOException {
int n = ri(), buf = n;
while(buf > 0) {
++lg;
buf >>= 1;
}
Node[] g = new Node[n];
euler = new Node[n + n];
for(int i = 0; i < n; ++i) {
g[i] = new Node();
}
for(int i = 0; i < n - 1; ++i) {
int u = rni() - 1, v = ni() - 1;
g[u].nei.add(g[v]);
g[v].nei.add(g[u]);
}
g[0].dfs(null);
int q = ri();
while (q --> 0) {
int x = rni() - 1, y = ni() - 1, a = ni() - 1, b = ni() - 1, k = ni();
long d = dist(g[a], g[b]);
if (k >= d && (k - d) % 2 == 0) {
prY();
continue;
}
d = (long) dist(g[a], g[x]) + 1 + dist(g[y], g[b]);
if (k >= d && (k - d) % 2 == 0) {
prY();
continue;
}
d = (long) dist(g[a], g[y]) + 1 + dist(g[x], g[b]);
if (k >= d && (k - d) % 2 == 0) {
prY();
continue;
}
d = (long) dist(g[a], g[x]) + 1 + dist(g[y], g[x]) + dist(g[x], g[b]);
if (k >= d && (k - d) % 2 == 0) {
prY();
continue;
}
d = (long) dist(g[a], g[x]) + 1 + dist(g[y], g[x]) + dist(g[x], g[b]);
if (k >= d && (k - d) % 2 == 0) {
prY();
continue;
}
prN();
}
close();
}
static int dist(Node a, Node b) {
Node lca = lca(a, b);
return (a.dep - lca.dep) + (b.dep - lca.dep);
}
static Node lca(Node a, Node b) {
if(a.dep < b.dep) {
Node __swap = a;
a = b;
b = __swap;
}
Node bufa = a, bufb = b, lca;
for(int i = lg; i >= 0; --i) {
if(bufa.dep - (1 << i) >= bufb.dep) {
bufa = bufa.anc[i];
}
}
if(bufa == bufb) {
lca = bufa;
} else {
for(int i = lg; i >= 0; --i) {
if(bufa.anc[i] != bufb.anc[i]) {
bufa = bufa.anc[i];
bufb = bufb.anc[i];
}
}
lca = bufa.par;
}
return lca;
}
static class Node {
List<Node> nei = new ArrayList<>();
int dep, sz = 1;
Node par, anc[] = new Node[lg + 1];
void dfs(Node par) {
euler[p++] = this;
if(par != null) {
dep = par.dep + 1;
this.par = par;
}
anc[0] = par;
for(int i = 1; i <= lg && anc[i - 1] != null; ++i) {
anc[i] = anc[i - 1].anc[i - 1];
}
for(Node n : nei) {
if(n != par) {
n.dfs(this);
sz += n.sz;
}
}
euler[p++] = this;
}
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int)d;}
static int cei(double d) {return (int)ceil(d);}
static long fll(double d) {return (long)d;}
static long cel(double d) {return (long)ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// graph util
static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for(int i = 0; i < n; ++i) a[i] = nl(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(double... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();}
static void h() {__out.println("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
}
|
java
|
1141
|
C
|
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1
|
[
"math"
] |
import java.util.*;
import java.io.*;
/*
https://codeforces.com/problemset/problem/1263/C
*/
public class problem {
public static void main(String[] str) {
boolean muiltTestCases = false;
var cin = new FastScanner();
PrintWriter cout = new PrintWriter(new BufferedOutputStream(System.out));
int n = 1;
if (muiltTestCases)
n = cin.nextInt();
var s = new testCaseSolution(cin, cout);
while (n-- > 0) {
s.solve();
cout.println();
}
cout.flush();
}
}
class testCaseSolution {
private int[][] mem;
private FastScanner cin;
PrintWriter cout;
public testCaseSolution(FastScanner cin, PrintWriter cout) {
this.cin = cin;
this.cout = cout;
}
class elem implements Comparable<elem> {
public int value;
public int index;
public elem(int value, int index) {
this.value = value;
this.index = index;
}
public int compareTo(elem e) {
return Integer.compare(this.value, e.value);
}
}
long mod = (long) 1e9 + 7;
boolean[] visited;
ArrayList<ArrayList<Integer>> g;
void solve() {
int n = cin.nextInt();
var d = new int[n - 1];
for (int i = 0; i < n - 1; i++)
d[i] = cin.nextInt();
int l = 1, r = n;
for (int i = 0; i < d.length; i++) {
l += d[i];
r += d[i];
if ((l < 1 || l > n) && (r < 1 || r > n)) {
cout.print(-1);
return;
}
l = Math.max(1, l);
l = Math.min(n, l);
r = Math.max(1, r);
r = Math.min(n, r);
}
var ans = new int[n];
var set = new TreeSet<Integer>();
ans[n - 1] = l;
set.add(l);
for (int i = n - 2; i >= 0; i--) {
ans[i] = ans[i + 1] - d[i];
set.add(ans[i]);
}
if (set.size() != n) {
cout.print(-1);
return;
}
for (int i : ans)
cout.print(i + " ");
}
int dfs(int root) {
if (visited[root])
return 0;
visited[root] = true;
int n = 1;
for (int adj : g.get(root)) {
n += dfs(adj);
}
return n;
}
}
final class Algo {
private Algo() {
}
// O(log(n))
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// O(log(sqrt(n))
public static TreeSet<Integer> getDivisors(int n) {
var st = new TreeSet<Integer>();
for (int i = 1; i * i <= n; i++) {
if (n % i == 0)
st.add(i);
if (n % (n / i) == 0)
st.add(n / i);
}
return st;
}
// O(n(log(log(N)))
public static ArrayList<Integer> primesTill_N(int n) {
var ans = new ArrayList<Integer>();
var prime = new ArrayList<Integer>(n + 1);
for (int i = 0; i < n + 1; i++)
prime.add(1);
for (int p = 2; p * p <= n; p++) {
if (prime.get(p) == 1) {
for (int i = p * p; i <= n; i += p)
prime.set(i, 0);
}
}
for (int p = 2; p <= n; p++)
if (prime.get(p) == 1)
ans.add(p);
return ans;
}
// O(sqrt(N))
public static TreeMap<Integer, Integer> getPrimeFactors(int n) {
var ans = new TreeMap<Integer, Integer>();
var primes = primesTill_N((int) (Math.sqrt(n) + 1));
for (int p : primes) {
while (n % p == 0) {
ans.putIfAbsent(p, 0);
ans.put(p, ans.get(p) + 1);
n /= p;
}
}
if (n > 2) {
ans.putIfAbsent(n, 0);
ans.put(n, ans.get(n) + 1);
}
return ans;
}
private static long mod = (long) 1e9 + 7;
// O(exponent)
public static long pow_long(long base, long exponent) {
long ans = 1;
base %= mod;
for (long i = 0; i < exponent; i++) {
ans *= base;
ans %= mod;
}
return ans;
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
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;
}
}
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.