contest_id
stringclasses 33
values | problem_id
stringclasses 14
values | statement
stringclasses 181
values | tags
sequencelengths 1
8
| code
stringlengths 21
64.5k
| language
stringclasses 3
values |
---|---|---|---|---|---|
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.util.*;
import java.io.*;
public class dp {
static BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(br.readLine());
int n=Integer.parseInt(st.nextToken());
st=new StringTokenizer(br.readLine());
long[] a=new long[n+1];
long[] ansl=new long[n+2];
long[] ansr=new long[n+2];
int[] l=new int[n+2];
int[] r=new int[n+2];
long ans=0; int p=0;
for(int i=1;i<=n;i++)a[i]=Long.parseLong(st.nextToken());
for(int i=1;i<=n;i++){
int j=i-1;
while((j>0)&&(a[j]>a[i])){
j=l[j];
}
l[i]=j;
ansl[i]=ansl[j]+(i-j)*a[i];
}
for(int i=n;i>=1;i--){
int j=i+1;
while((j<=n)&&(a[j]>a[i])){
j=r[j];
}
r[i]=j;
ansr[i]=ansr[j]+(j-i)*a[i];
if(ansl[i]+ansr[i]-a[i]>ans){
ans=ansl[i]+ansr[i]-a[i];
p=i;
}
}
for(int i=p-1;i>=1;i--){
a[i]=Math.min(a[i],a[i+1]);
}
for(int i=p+1;i<=n;i++){
a[i]=Math.min(a[i],a[i-1]);
}
for(int i=1;i<=n;i++){
bw.write(String.valueOf(a[i]+" "));
}
bw.flush();
bw.close();
}
}
| 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.io.*;
import java.util.*;
public class Solution {
private static final int MAX_VALUE = 1000000;
private static final int MAX_ROOT = 1000;
public void solve() {
List<Integer> prime = sieve(MAX_VALUE);
HashMap<Integer, Integer> idx = new HashMap<>();
int cnt = 0;
int n = reader.nextInt();
int[][] edges = new int[n][2];
HashSet<Integer> root = new HashSet<>();
for (int i = 0; i < n; i++) {
int[] a = simplify(prime, reader.nextInt());
int x = a[0], y = a[1];
int s = x * y;
if (s == 1) {
writer.println(1);
return;
}
if (!idx.containsKey(x)) idx.put(x, cnt++);
if (!idx.containsKey(y)) idx.put(y, cnt++);
int u = idx.get(x);
int v = idx.get(y);
edges[i][0] = u;
edges[i][1] = v;
if (x <= MAX_ROOT) root.add(u);
if (y <= MAX_ROOT) root.add(v);
}
List<Integer>[] adj = new List[cnt];
for (int i = 0; i < cnt; i++) adj[i] = new ArrayList<>();
for (int i = 0; i < n; i++) {
int u = edges[i][0];
int v = edges[i][1];
adj[u].add(v);
adj[v].add(u);
}
writer.println(shortestCycle(adj, root));
}
private int shortestCycle(List<Integer>[] adj, HashSet<Integer> root) {
int res = MAX_VALUE;
int n = adj.length;
int[] parent = new int[n];
int[] level = new int[n];
Deque<Integer> queue = new LinkedList<>();
for (int start : root) {
Arrays.fill(level, -1);
parent[start] = start;
level[start] = 0;
queue.add(start);
while (!queue.isEmpty()) {
int u = queue.poll();
if (level[u] + 1 >= res) continue;
for (int v : adj[u]) {
if (level[v] == -1) {
parent[v] = u;
level[v] = level[u] + 1;
queue.add(v);
continue;
}
if (v == parent[u]) continue;
res = Math.min(res, level[u] + level[v] + 1);
}
}
}
return res < MAX_VALUE ? res : -1;
}
private int[] simplify(List<Integer> prime, int a) {
for (int p : prime) {
int q = p * p;
if (q > a) break;
while (a % q == 0) a /= q;
}
for (int p : prime) {
if (p * p > a) break;
if (a % p == 0) return new int[]{p, a / p};
}
return new int[]{1, a};
}
private List<Integer> sieve(int n) {
boolean[] removed = new boolean[n + 1];
for (int i = 2; i * i <= n; i++) {
for (int j = i * i; j <= n; j += i) {
removed[j] = true;
}
}
List<Integer> prime = new LinkedList<>();
prime.add(2);
for (int i = 3; i <= n; i += 2) {
if (!removed[i]) prime.add(i);
}
return prime;
}
private InputReader reader;
private PrintWriter writer;
public Solution(InputReader reader, PrintWriter writer) {
this.reader = reader;
this.writer = writer;
}
public static void main(String[] args) {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out);
Solution solution = new Solution(reader, writer);
solution.solve();
writer.flush();
}
static class InputReader {
private static final int BUFFER_SIZE = 1 << 20;
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE);
tokenizer = null;
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
}
}
| java |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22. | [
"math"
] | import java.util.Scanner;
public class Main {
Scanner sc = new Scanner(System.in);
public Main() {
int n = sc.nextInt();
sc.nextLine();
String s = sc.nextLine();
System.out.println(n+1);
}
public static void main(String[] args) {
new Main();
}
}
| java |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. | [
"data structures",
"greedy",
"implementation",
"math"
] | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
new Main().solve(new InputReader(System.in), new PrintWriter(System.out));
}
private void solve(InputReader in, PrintWriter pw) {
// int tt = 1;
int tt = in.nextInt();
int x = in.nextInt();
int mex = 0;
int[] cnt = new int[x];
while (tt-- > 0) {
int y = in.nextInt();
y = (y + x) % x;
cnt[y]++;
while (cnt[mex % x] > mex / x) {
mex++;
}
pw.println(mex);
}
pw.close();
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
private int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
}
class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String str;
try {
str = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return str;
}
public boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String nextLine = null;
try {
nextLine = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (nextLine == null)
return false;
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] nextArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
}
return a;
}
} | 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.Arrays;
import java.util.Scanner;
import static java.sql.Types.NULL;
public class CopyCopyCopyCopyCopy_v2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
int[][] array = new int[t][];
for (int i=0; i<t; i++) {
int l = scanner.nextInt();
array[i] = new int[l];
for (int j=0; j<l; j++) {
array[i][j] = scanner.nextInt();
}
}
for (int i=0; i<t; i++) {
Arrays.sort(array[i]);
deleteDuplicated(array[i]);
System.out.println(count(array[i]));
//System.out.println(Arrays.toString(array[i]));
}
}
private static void deleteDuplicated(int[] array) {
for (int i=0; i<array.length-1; i++) {
if (array[i] == array[i+1]) {
array[i] = NULL;
}
}
}
private static int count(int[] array) {
int count=array.length;
for (int i=0; i<array.length; i++) {
if (array[i] == 0) {
count--;
}
}
return count;
}
}
| java |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Task_5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
processWithoutDp(scanner);
// processWithDp(scanner);
}
private static void processWithDp(Scanner scanner) {
int t = getT(scanner);
for (int i = 0; i < t; i++) {
int elementsCount = Integer.parseInt(scanner.nextLine());
int[] values = getValues(scanner);
int sumElementsCount = 0;
int[] dp = new int[elementsCount];
if (values.length == 1) {
sumElementsCount = values[0] % 2 == 0 ? 1 : -1;
} else {
dp[0] = (values[0] + values[1]) % 2 == 0 || values[0] % 2 == 0 ? values[0] : 0;
sumElementsCount = dp[0] == 0 ? 0 : 1;
for (int j = 1; j < dp.length; j++) {
int value = dp[j - 1] + values[j];
if (value % 2 == 0) {
dp[j] = value;
sumElementsCount++;
} else {
dp[j] = 0;
}
}
}
System.out.println(sumElementsCount);
if (sumElementsCount != -1) {
int max = Arrays.stream(dp).max().orElse(0);
int index = Arrays.stream(dp).mapToObj(n -> new Integer(n)).collect(Collectors.toList()).indexOf(max);
Stream.iterate(index + 2 - sumElementsCount, n -> ++n)
.limit(sumElementsCount)
.forEach(n -> System.out.print(n.intValue() + " "));
System.out.println();
}
}
}
private static void processWithoutDp(Scanner scanner) {
int t = getT(scanner);
for (int i = 0; i < t; i++) {
scanner.nextLine();
int[] values = getValues(scanner);
int value = Arrays.stream(values).filter(n -> n % 2 == 0).findFirst().orElse(0);
if (value != 0) {
int index =
Arrays.stream(values).mapToObj(n -> new Integer(n)).collect(Collectors.toList()).indexOf(value);
System.out.println(1);
System.out.println(index + 1);
} else {
int index = 0;
int sum = 0;
for (int j = 0; j < values.length; j++) {
sum += values[j];
if (sum % 2 == 0) {
index = j;
break;
}
}
if (index == 0) {
System.out.println(-1);
} else {
System.out.println(index + 1);
for (int d = 0; d < index + 1; d++) {
System.out.print(d + 1 + " ");
}
}
}
}
}
private static int[] getValues(Scanner scanner) {
return Arrays.stream(scanner.nextLine().split(" "))
.mapToInt(Integer::parseInt)
.toArray();
}
private static int getT(Scanner scanner) {
return Integer.parseInt(scanner.nextLine());
}
}
| java |
1301 | E | E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105) — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
OutputCopy16
4
4
4
0
InputCopy6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
OutputCopy36
4
16
16
16
InputCopy8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
OutputCopy64
0
16
4
16
4
36
0
NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray. | [
"binary search",
"data structures",
"dp",
"implementation"
] | //package round619;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.function.IntPredicate;
public class E {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni(), Q = ni();
char[][] map = nm(n,m);
int[][][] colors = new int[4][][];
colors[0] = cum(map, (x) -> x == 'R');
colors[1] = cum(map, (x) -> x == 'G');
colors[2] = cum(map, (x) -> x == 'Y');
colors[3] = cum(map, (x) -> x == 'B');
int[][] rd = down(map, (x) -> x == 'R');
int[][] rr = trans(down(trans(map), (x) -> x == 'R'));
int[][] hs = new int[n][m];
for(int i = 0;i < n;i++) {
for(int j = 0;j < m;j++) {
if(rd[i][j] > 0 && rd[i][j] == rr[i][j]) {
int u = rd[i][j];
if(
i+2*u <= n && j+2*u <= m &&
sum(colors[0], i, j, i+u, j+u) == u*u &&
sum(colors[1], i, j+u, i+u, j+2*u) == u*u &&
sum(colors[2], i+u, j, i+2*u, j+u) == u*u &&
sum(colors[3], i+u, j+u, i+2*u, j+2*u) == u*u
) {
hs[i][j] = u;
}
}
}
}
int[][][] cums = new int[251][][];
for(int i = 1;i <= 250;i++) {
int ii = i;
cums[i] = cum(hs, (x) -> x == ii);
}
for(int z = 0;z < Q;z++) {
int r1 = ni()-1, c1 = ni()-1;
int r2 = ni()-1, c2 = ni()-1;
int low = 0, high = 251;
while(high - low > 1) {
int h = high+low>>1;
if(sum(cums[h], r1, c1, r2+1-2*h+1, c2+1-2*h+1) > 0) {
low = h;
}else {
high = h;
}
}
out.println(low*low*4);
}
}
public static long sum(int[][] cum, int r1, int c1, int r2, int c2)
{
if(r1 >= r2 || c1 >= c2)return 0;
return cum[r2][c2] + cum[r1][c1] - cum[r1][c2] - cum[r2][c1];
}
public static int[][] down(char[][] map, IntPredicate pr)
{
int n = map.length, m = map[0].length;
int[][] ret = new int[n][m];
for(int i = n-1;i >= 0;i--){
for(int j = 0;j < m;j++){
ret[i][j] = i == n-1 ? 1 : ret[i+1][j] + 1;
if(!pr.test(map[i][j]))ret[i][j] = 0;
}
}
return ret;
}
public static char[][] trans(char[][] a)
{
if(a.length == 0)return new char[0][0];
int n = a.length, m = a[0].length;
char[][] ret = new char[m][n];
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
ret[i][j] = a[j][i];
}
}
return ret;
}
public static int[][] trans(int[][] a)
{
if(a.length == 0)return new int[0][0];
int n = a.length, m = a[0].length;
int[][] ret = new int[m][n];
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
ret[i][j] = a[j][i];
}
}
return ret;
}
public static int[][] cum(char[][] a, IntPredicate pr)
{
int n = a.length, m = a[0].length;
int[][] cum = new int[n+1][m+1];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
cum[i+1][j+1] = cum[i+1][j] + cum[i][j+1] - cum[i][j] + (pr.test(a[i][j]) ? 1 : 0);
}
}
return cum;
}
public static int[][] cum(int[][] a, IntPredicate pr)
{
int n = a.length, m = a[0].length;
int[][] cum = new int[n+1][m+1];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
cum[i+1][j+1] = cum[i+1][j] + cum[i][j+1] - cum[i][j] + (pr.test(a[i][j]) ? 1 : 0);
}
}
return cum;
}
void run() throws Exception
{
// int n = 500, m = 500, Q = 300000;
// Random gen = new Random();
// StringBuilder sb = new StringBuilder();
// sb.append(n + " ");
// sb.append(m + " ");
// sb.append(Q + " ");
// for (int i = 0; i < n; i++) {
// for (int j = 0;j < m;j++) {
// sb.append("RBGY".charAt(gen.nextInt(4)));
// }
// sb.append("\n");
// }
// for(int i = 0;i < Q;i++) {
// int v1 = gen.nextInt(n);
// int v2 = gen.nextInt(n);
// int w1 = gen.nextInt(m);
// int w2 = gen.nextInt(m);
// sb.append(Math.min(v1, v2) + 1 + " ");
// sb.append(Math.min(w1, w2) + 1 + " ");
// sb.append(Math.max(v1, v2) + 1 + " ");
// sb.append(Math.max(w1, w2) + 1 + " ");
// }
// INPUT = sb.toString();
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new E().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| java |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | [
"implementation",
"strings"
] | import java.util.Scanner;
public class New_Year_Naming{
public static void main(String[] args)
{
Scanner Sc = new Scanner(System.in);
int N_Strings = Sc.nextInt();
int M_Strings = Sc.nextInt();
String[] List1 = new String[N_Strings];
String[] List2 = new String[M_Strings];
for(int i=0; i<N_Strings; i++)
List1[i] = Sc.next();
for(int i=0; i<M_Strings; i++)
List2[i] = Sc.next();
int Queries = Sc.nextInt();
while(Queries-- != 0)
{
int year = Sc.nextInt();
String a = List1[(year-1)%List1.length];
String b = List2[(year-1)%List2.length];
System.out.println(a+b);
}
Sc.close();
}
} | 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.*;
import java.math.*;
import java.util.*;
// @author : Dinosparton
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Sort implements Comparator<Pair>
{
@Override
public int compare(Pair a, Pair b)
{
if(a.x!=b.x)
{
return (int)(a.x - b.x);
}
else
{
return (int)(a.y-b.y);
}
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static int recursion(String s,int k,int n) {
if(s.length() == n) {
int ans = 0;
for(int i=0;i<s.length();i++) {
if(s.charAt(i)=='1') {
ans += s.length()-i;
}
else {
for(int j=i+1;j<s.length();j++) {
if(s.charAt(j)=='1') {
ans += s.length()-j;
break;
}
}
}
}
System.out.println(s+" "+ans);
return ans;
}
int pos1 = Integer.MIN_VALUE;
if(k>0) {
pos1 = recursion(s+'1',k-1,n);
}
int pos2 = recursion(s+'0',k,n);
return Math.max(pos1, pos2);
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuilder res = new StringBuilder();
int tc = sc.nextInt();
while(tc-->0) {
long n = sc.nextLong();
long m = sc.nextLong();
long total = (n*(n+1))/2;
long gap = (n-m)/(m+1);
total -= ((gap*(gap+1))/2)*(m+1);
total -= (gap+1)*((n-m)%(m+1));
res.append(total+"\n");
}
System.out.println(res);
}
}
| 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"
] | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static final int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static final long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static final long mod = (long) 1e9 + 7;
static void solve() {
int caseNo = 1;
// for (int T = sc.nextInt(); T > 1; T--, caseNo++) { solveIt(caseNo); }
solveIt(caseNo);
}
// Solution
static void solveIt(int testCaseNo) {
int n = sc.nextInt();
int a[] = sc.readIntArray(n);
HashMap<Long, List<int[]>> map = new HashMap<>();
for (int i = 0; i < n; i++) {
long sum = 0;
for (int j = i; j < n; j++) {
sum += (long) a[j];
map.putIfAbsent(sum, new ArrayList<>());
map.get(sum).add(new int[] { i + 1, j + 1 });
}
}
List<int[]> ans = new ArrayList<>();
for (long key : map.keySet()) {
List<int[]> al = new ArrayList<>();
for (int i = map.get(key).size() - 1; i >= 0; i--) {
if (al.isEmpty() || al.get(al.size() - 1)[0] > map.get(key).get(i)[1]) {
al.add(map.get(key).get(i));
}
}
if (al.size() > ans.size()) { ans = al; }
}
System.out.println(ans.size());
for (int x[] : ans) System.out.println(x[0] + " " + x[1]);
}
public static void main(String[] args) throws Exception {
long S = System.currentTimeMillis();
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
solve();
out.flush();
long G = System.currentTimeMillis();
sc.tr(G - S + "ms");
}
static class sc {
private static boolean endOfFile() {
if (bufferLength == -1) return true;
int lptr = ptrbuf;
while (lptr < bufferLength) {
if (!isThisTheSpaceCharacter(inputBufffferBigBoi[lptr++])) return false;
}
try {
is.mark(1000);
while (true) {
int b = is.read();
if (b == -1) {
is.reset();
return true;
} else if (!isThisTheSpaceCharacter(b)) {
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inputBufffferBigBoi = new byte[1024];
static int bufferLength = 0, ptrbuf = 0;
private static int justReadTheByte() {
if (bufferLength == -1) throw new InputMismatchException();
if (ptrbuf >= bufferLength) {
ptrbuf = 0;
try {
bufferLength = is.read(inputBufffferBigBoi);
} catch (IOException e) {
throw new InputMismatchException();
}
if (bufferLength <= 0) return -1;
}
return inputBufffferBigBoi[ptrbuf++];
}
private static boolean isThisTheSpaceCharacter(int c) { return !(c >= 33 && c <= 126); }
private static int skipItBishhhhhhh() {
int b;
while ((b = justReadTheByte()) != -1 && isThisTheSpaceCharacter(b));
return b;
}
private static double nextDouble() { return Double.parseDouble(next()); }
private static char nextChar() { return (char) skipItBishhhhhhh(); }
private static String next() {
int b = skipItBishhhhhhh();
StringBuilder sb = new StringBuilder();
while (!(isThisTheSpaceCharacter(b))) {
sb.appendCodePoint(b);
b = justReadTheByte();
}
return sb.toString();
}
private static char[] readCharArray(int n) {
char[] buf = new char[n];
int b = skipItBishhhhhhh(), p = 0;
while (p < n && !(isThisTheSpaceCharacter(b))) {
buf[p++] = (char) b;
b = justReadTheByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] readCharMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = readCharArray(m);
return map;
}
private static int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
private static long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
private static int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if (b == '-') {
minus = true;
b = justReadTheByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = justReadTheByte();
}
}
private static long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if (b == '-') {
minus = true;
b = justReadTheByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = justReadTheByte();
}
}
private static void tr(Object... o) {
if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o));
}
}
}
// And I wish you could sing along, But this song is a joke, and the melody I
// wrote, wrong | java |
1286 | C1 | C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4
a
aa
a
cb
b
c
cOutputCopy? 1 2
? 3 4
? 4 4
! aabc | [
"brute force",
"constructive algorithms",
"interactive",
"math"
] | import java.io.*;
import java.util.*;
public class Main {
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
if (n <= 3) {
char[] s = new char[n];
for (int i = 1; i <= n; ++i) {
out.println("? " + i + " " + i);
out.flush();
s[i - 1] = in.next().toCharArray()[0];
}
out.println("! " + new String(s));
return;
}
out.println("? 1 " + n);
out.flush();
List<String> s1 = new ArrayList<>();
for (int i = 0; i < (n + 1) * n / 2; ++i) {
char[] s = in.next().toCharArray();
Arrays.sort(s);
s1.add(new String(s));
}
Collections.sort(s1);
out.println("? 2 " + n);
out.flush();
List<String> s2 = new ArrayList<>();
for (int i = 0; i < (n - 1) * n / 2; ++i) {
char[] s = in.next().toCharArray();
Arrays.sort(s);
s2.add(new String(s));
}
Collections.sort(s2);
List<String> t1;
t1 = new ArrayList<>(s1);
for (String s : s2) {
t1.remove(s);
}
Collections.sort(t1, Comparator.comparingInt(String::length));
char[] s = new char[n];
for (int i = 0; i < n; ++i) {
if (i == 0) {
s[0] = t1.get(i).charAt(0);
continue;
}
int[] count = new int[26];
for (char c: t1.get(i - 1).toCharArray()) {
count[c - 'a']--;
}
for (char c: t1.get(i).toCharArray()) {
count[c - 'a']++;
}
for (int j = 0; j < 26; ++j) {
if (count[j] > 0) {
s[i] = (char) (j + 'a');
}
}
}
out.println("! " + new String(s));
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
new Main().solve(in, out);
out.flush();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
/**
5
x
a
s
d
xa
as
sd
xas
asd
xasd
s
d
u
a
sd
du
ua
sdu
dua
sdua
4
x
a
y
t
xa
ay
yt
xay
ayt
xayt
a
y
t
ay
yt
ayt
**/ | java |
1325 | A | A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100) — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14. | [
"constructive algorithms",
"greedy",
"number theory"
] | import java.util.Arrays;
import java.util.Iterator;
import java.util.Scanner;
public class Problems {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t > 0) {
int n = in.nextInt();
System.out.println(1 + " " + (n - 1));
t--;
}
}
} | java |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class test {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
StringBuilder result = new StringBuilder();
if (n % 2 == 0) {
result.append("1");
n -= 2;
} else {
result.append("7");
n -= 3;
}
while (n > 0) {
result.append("1");
n -= 2;
}
pw.println(result.toString());
}
pw.flush();
pw.close();
br.close();
}
} | java |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good. | [
"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;
/*
*
* 820 = 729,81,9,1;
* 0 , 0 ,
*
*
* */
public class Codeforces {
public static void main(String[] args) {
FastReader fastReader = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int tt = fastReader.nextInt();
while(tt--> 0){
int n = fastReader.nextInt();
int g = fastReader.nextInt();
int b = fastReader.nextInt();
long m = (n+1)/2;
long ans = (m-1)/g * (g+b) + (m%g > 0 ? m%g : g);
out.println(max(ans,n));
}
out.close();
}
static class Pair{
int x;
int y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
}
// 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 |
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.util.*;
import java.io.*;
public class Div712 {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// /////////
//////// /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// /////////
//////// /////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
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.nextIntArr(n);
int[] cost = sc.nextIntArr(n);
int size = 1;
while (size < n) size <<= 1;
SegmentTree tree = new SegmentTree(size);
long sum = 0;
for (int i = 0; i < n; i++) {
sum += cost[i];
tree.update_range(a[i], n, cost[i]);
}
long ans = sum;
long cur = 0;
for (int i = 0; i < n - 1; i++) {
cur += cost[i];
sum -= cost[i];
ans = Math.min(ans, Math.min(sum, cur));
tree.update_range(a[i], n, -cost[i]);
tree.update_range(1, a[i] - 1, cost[i]);
tree.update_range(a[i], a[i], (long) -2e16);
ans = Math.min(ans, tree.query(1, n));
}
pw.println(ans);
pw.flush();
}
static class SegmentTree { // 1-based DS, OOP
int N; //the number of elements in the array as a power of 2 (i.e. after padding)
long[] sTree, lazy;
SegmentTree(int size) {
N = size;
sTree = new long[N << 1]; //no. of nodes = 2*N - 1, we add one to cross out index zero
lazy = new long[N << 1];
Arrays.fill(sTree, (long) 2e16);
}
void update_range(int i, int j, long val) // O(log n)
{
update_range(1, 1, N, i, j, val);
}
void update_range(int node, int b, int e, int i, int j, long val) {
if (i > e || j < b)
return;
if (b >= i && e <= j) {
sTree[node] += val;
lazy[node] += val;
} else {
int mid = b + e >> 1;
propagate(node, b, mid, e);
update_range(node << 1, b, mid, i, j, val);
update_range(node << 1 | 1, mid + 1, e, i, j, val);
sTree[node] = Math.min(sTree[node << 1], sTree[node << 1 | 1]);
}
}
void propagate(int node, int b, int mid, int e) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
sTree[node << 1] += lazy[node];
sTree[node << 1 | 1] += lazy[node];
lazy[node] = 0;
}
long query(int i, int j) {
return query(1, 1, N, i, j);
}
long query(int node, int b, int e, int i, int j) // O(log n)
{
if (i > e || j < b)
return (long) 1e18;
if (b >= i && e <= j)
return sTree[node];
int mid = b + e >> 1;
propagate(node, b, mid, e);
long q1 = query(node << 1, b, mid, i, j);
long q2 = query(node << 1 | 1, mid + 1, e, i, j);
return Math.min(q1, q2);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] nextIntArr(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| java |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] |
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 build(int node, int start, int end,int[]tree,int[]arr) {
if (start == end) {
tree[node] = arr[start];
} else {
int mid = (start + end) / 2;
int left = node * 2;
int right = node * 2 + 1;
build(left, start, mid,tree,arr);
build(right, mid + 1, end,tree,arr);
tree[node] = Math.max(tree[left], tree[right]);
}
}
static int query(int node, int start, int end, int l, int r,int[]tree,int[]arr) {
if (end < l || r < start)return Integer.MIN_VALUE;
if (start == end) {
return tree[node];
} else if (l <= start && end <= r) {
return tree[node];
} else {
int mid = (start + end) / 2;
int left = query(node * 2, start, mid, l, r,tree,arr);
int right = query(node * 2 + 1, mid + 1, end, l, r,tree,arr);
return Math.max(left, right);
}
}
static int get(int v,int k,int max){
int lo=1;
int hi=k;
int ans=-1;
while(lo<=hi){
int mid=(lo+hi)/2;
if(v/mid>max){
lo=mid+1;
}
else{
ans=mid;
hi=mid-1;
}
}
return ans;
}
static long solve( ArrayList<Pair> ls,long time,long sx,long sy){
long ans=0;
for(int i=0;i<ls.size();i++){
Pair p=ls.get(i);
long stx=p.x;
long sty=p.y;
long temp=(Math.abs(sx-stx)+Math.abs(sy-sty));
long cans=0;
if(temp<=time)cans++;
else continue;
for(int j=i+1;j<ls.size();j++){
Pair p1=ls.get(j);
long temp1=(Math.abs(p1.x-stx)+Math.abs(p1.y-sty));
temp+=temp1;
// System.out.println(cans+" "+temp+" "+p1.x);
if(temp<=time)cans++;
else break;
stx=p1.x;
sty=p1.y;
}
// System.out.println(time+" "+temp+" "+(time-temp));
ans=Math.max(ans,cans);
}
return ans;
}
static void solve(int cnt) {
long x0=l();
long y0=l();
long ax=l();
long ay=l();
long bx=l();
long by=l();
long xs=l();
long ys=l();
long time=l();
long st=(long)(1e16)*2;
ArrayList<Pair> ls=new ArrayList<>();
long currX=x0;
long currY=y0;
while(currX<=st&&currY<=st){
Pair p=new Pair(currX,currY);
ls.add(p);
currX=(currX*ax)+bx;
currY=(currY*ay)+by;
}
// System.out.println(ls);
long ans1= solve(ls,time,xs,ys);
Collections.reverse(ls);
long ans2= solve(ls,time,xs,ys);
ans1=Math.max(ans1,ans2);
sb.append(ans1+"\n");
}
public static void main(String[] args) {
sb = new StringBuilder();
int test = 1;
fact=new long[(int)1e6+10];
fact[0]=fact[1]=1;
for(int i=2;i<fact.length;i++)
{ fact[i]=((long)(i%mod)*(long)(fact[i-1]%mod))%mod; }
int cnt=1;
while (test-- > 0) {
solve(cnt);
cnt++;
}
System.out.println(sb);
}
//**************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) ;
y--;
}
x = (x * x);
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] = i;
}
int find(int a) {
if (parent[a] ==a)
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> {
long x;
long y;
Pair(long 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 |
1286 | C1 | C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4
a
aa
a
cb
b
c
cOutputCopy? 1 2
? 3 4
? 4 4
! aabc | [
"brute force",
"constructive algorithms",
"interactive",
"math"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedOutputStream;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
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
*
* @author mikit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
LightScanner in = new LightScanner(inputStream);
LightWriter out = new LightWriter(outputStream);
C1MadhouseEasyVersion solver = new C1MadhouseEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class C1MadhouseEasyVersion {
public void solve(int testNumber, LightScanner in, LightWriter out) {
// out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP);
out.enableAutoFlush();
int m = in.ints(), n = (m + 1) / 2;
char[] p1 = guess(in, out, 1, n);
char[] ans = new char[m];
if (n == 1) {
ans[0] = p1[0];
} else {
char[] p2 = guess(in, out, 1, n - 1);
int[] cnt = new int[26];
for (int i = 0; i < n; i++) cnt[p1[i] - 'a']++;
for (int i = 0; i < n - 1; i++) cnt[p2[i] - 'a']--;
for (int i = 0; i < 26; i++) if (cnt[i] > 0) ans[n - 1] = (char) (i + 'a');
for (int i = 0; i < n / 2; i++) {
if (ans[n - i - 1] != p1[n - i - 1]) ArrayUtil.swap(p1, i, n - i - 1);
ans[i] = p1[i];
if (ans[i] != p2[i]) ArrayUtil.swap(p2, i, n - i - 2);
ans[n - i - 2] = p2[n - i - 2];
}
}
char[] p3 = guess(in, out, 1, m);
for (int i = 0; i < n; i++) {
if (p3[i] != ans[i]) ArrayUtil.swap(p3, i, m - i - 1);
}
out.ans('!').ans(String.valueOf(p3)).ln();
}
private static char[] guess(LightScanner in, LightWriter out, int from, int to) {
int n = to - from + 1;
if (n == 0) return new char[0];
out.ans('?').ans(from).ans(to).ln();
int n2 = (n + 1) / 2;
int[][] cnt = new int[26][n + 1];
for (int i = 0; i < n * (n + 1) / 2; i++) {
char[] s = in.string().toCharArray();
if (s.length < n2) continue;
for (char c : s) cnt[c - 'a'][s.length]++;
}
for (int i = n2; i < n; i++) {
for (int j = 0; j < 26; j++) {
cnt[j][i] -= cnt[j][i + 1];
}
}
for (int i = n; i >= n2 + 1; i--) {
for (int j = 0; j < 26; j++) {
cnt[j][i] -= cnt[j][i - 1];
}
}
char[] ans = new char[n];
for (int i = 0; i < n; i++) {
int ref = Math.max(n - i, i + 1);
for (int j = 0; j < 26; j++) {
if (cnt[j][ref] > 0) {
cnt[j][ref]--;
ans[i] = (char) ('a' + j);
break;
}
}
}
return ans;
}
}
static class LightScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public LightScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public String string() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return tokenizer.nextToken();
}
public int ints() {
return Integer.parseInt(string());
}
}
static class LightWriter implements AutoCloseable {
private final Writer out;
private boolean autoflush = false;
private boolean breaked = true;
public LightWriter(Writer out) {
this.out = out;
}
public LightWriter(OutputStream out) {
this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));
}
public void enableAutoFlush() {
autoflush = true;
}
public LightWriter print(char c) {
try {
out.write(c);
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter print(String s) {
try {
out.write(s, 0, s.length());
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter ans(char c) {
if (!breaked) {
print(' ');
}
return print(c);
}
public LightWriter ans(String s) {
if (!breaked) {
print(' ');
}
return print(s);
}
public LightWriter ans(int i) {
return ans(Integer.toString(i));
}
public LightWriter ln() {
print(System.lineSeparator());
breaked = true;
if (autoflush) {
try {
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
return this;
}
public void close() {
try {
out.close();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
static final class ArrayUtil {
private ArrayUtil() {
}
public static void swap(char[] a, int x, int y) {
char t = a[x];
a[x] = a[y];
a[y] = t;
}
}
}
| java |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.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 as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO". | [
"geometry",
"greedy",
"math",
"number theory"
] | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a % b == 0 ? "Yes" : "No");
}
}
}
| java |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t-- != 0) {
int n = in.nextInt();
int[] arr = new int[n];
int index = 0;;
boolean isEven = false;
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
if (arr[i] % 2 == 0) {
isEven = true;
index = i+1;
}
}
if (isEven) {
System.out.println(1 + "\n" +index);
continue;
}
System.out.println(arr.length == 1 ? -1 : 2 + "\n" + 1 + " " + 2 );
}
// int n;
// cin >> n;
// int stw[n];
// int c = 0;
// for (int i = 0; i < n; i++){
// cin >> stw[i];
// }
// int ns = sizeof(stw) / sizeof(stw[0]);
// sort(stw,stw+ns);
// int max = stw[n-1];
// int min = stw[0];
// for (int i = 0; i < n; i++)
// {
// if (stw[i] < max && stw[i] > min)
// {
// c++;
// }
// }
}
}
| java |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | 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.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.InputMismatchException;
import java.util.Objects;
/**
* 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);
DKuroniAndTheCelebration solver = new DKuroniAndTheCelebration();
solver.solve(1, in, out);
out.close();
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28);
thread.start();
thread.join();
}
static class DKuroniAndTheCelebration {
private final int iinf = 1_000_000_000;
Output pw;
InputReader in;
ArrayList<Integer>[] graph;
int n;
BitSet valid;
BitSet path;
BitSet next;
int[] from;
public DKuroniAndTheCelebration() {
}
public int[] bfs(int u) {
int[] dist = new int[n];
Arrays.fill(dist, iinf);
ArrayDeque<Pair<Integer, Integer>> q = new ArrayDeque<>(n);
q.addLast(new Pair<>(u, dist[u] = 0));
while(!q.isEmpty()) {
Pair<Integer, Integer> cur = q.removeFirst();
for(int v: graph[cur.a]) {
if(dist[v]==iinf&&valid.get(v)) {
q.addLast(new Pair<>(v, dist[v] = cur.b+1));
from[v] = cur.a;
}
}
}
return dist;
}
public Pair<Integer, Integer> diameter() {
int start = valid.nextSetBit(0);
int[] dist = bfs(start);
int max = 0, v = start;
for(int i = 0; i<n; i++) {
if(dist[i]>max&&valid.get(i)) {
max = dist[i];
v = i;
}
}
from = new int[n];
path = new BitSet(n);
dist = bfs(v);
int u = v;
max = v = 0;
for(int i = 0; i<n; i++) {
if(dist[i]>max&&valid.get(i)) {
max = dist[i];
v = i;
}
}
for(int i = v; i!=u; i = from[i]) {
path.set(i);
}
path.set(u);
return new Pair<>(v, u);
}
public void solve() {
if(valid.cardinality()==1) {
pw.println("!", valid.nextSetBit(0)+1);
return;
}
var q = diameter();
pw.println("?", q.a+1, q.b+1);
pw.flush();
next = new BitSet(n);
dfs(in.nextInt()-1);
valid = next;
solve();
}
public void dfs(int u) {
next.set(u);
for(int v: graph[u]) {
if(!path.get(v)&&!next.get(v)&&valid.get(v)) {
dfs(v);
}
}
}
public void solve(int kase, InputReader in, Output pw) {
n = in.nextInt();
graph = in.nextUndirectedGraph(n, n-1);
from = new int[n];
valid = new BitSet(n);
valid.set(0, n);
this.in = in;
this.pw = pw;
solve();
pw.flush();
}
}
static class Output implements Closeable, Flushable {
public StringBuilder sb;
public OutputStream os;
public int BUFFER_SIZE;
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);
lineSeparator = System.lineSeparator();
}
public void print(String s) {
sb.append(s);
if(sb.length()>BUFFER_SIZE >> 1) {
flushToBuffer();
}
}
public void println(Object... o) {
for(int i = 0; i<o.length; i++) {
if(i!=0) {
print(" ");
}
print(String.valueOf(o[i]));
}
println();
}
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 class Pair<T1, T2> implements Comparable<Pair<T1, T2>> {
public T1 a;
public T2 b;
public Pair(Pair<T1, T2> p) {
this(p.a, p.b);
}
public Pair(T1 a, T2 b) {
this.a = a;
this.b = b;
}
public String toString() {
return a+" "+b;
}
public int hashCode() {
return Objects.hash(a, b);
}
public boolean equals(Object o) {
if(o instanceof Pair) {
Pair p = (Pair) o;
return a.equals(p.a)&&b.equals(p.b);
}
return false;
}
public int compareTo(Pair<T1, T2> p) {
int cmp = ((Comparable<T1>) a).compareTo(p.a);
if(cmp==0) {
return ((Comparable<T2>) b).compareTo(p.b);
}
return cmp;
}
}
static interface InputReader {
int nextInt();
default ArrayList<Integer>[] nextUndirectedGraph(int n, int m) {
ArrayList<Integer>[] ret = new ArrayList[n];
for(int i = 0; i<n; i++) {
ret[i] = new ArrayList<>();
}
for(int i = 0; i<m; i++) {
int u = nextInt()-1, v = nextInt()-1;
ret[u].add(v);
ret[v].add(u);
}
return ret;
}
}
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 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;
}
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 |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
| [
"brute force",
"data structures",
"sortings"
] | import java.util.*;
import java.io.*;
public class F {
public static void main(String[] args) throws IOException {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n, m, p; n = fs.nextInt(); m = fs.nextInt(); p = fs.nextInt();
List<Pair> atk, def; atk = new ArrayList<>(); def = new ArrayList<>();
for(int i = 0; i < n; i++){
int a, b; a = fs.nextInt(); b = fs.nextInt();
atk.add(new Pair(a, b));
}
for(int i = 0; i < m; i++){
int a, b; a = fs.nextInt(); b = fs.nextInt();
def.add(new Pair(a, b));
}
Collections.sort(def);
int[] minForDefense = new int[def.size()];
int mn = (int)1e9;
for(int i = def.size() - 1; i >= 0; i--){
mn = Math.min(mn, def.get(i).s);
minForDefense[i] = mn;
}
long[] profit = new long[(int)(1e6 + 1)];
int l = 0; int r = 1;
while(r < profit.length){
while(l < def.size() && def.get(l).f < r){
l++;
}
if(l >= def.size()){
profit[r] = (long)(-1e10);
} else {
profit[r] = (long)(-minForDefense[l]);
}
r++;
}
//out.println("---");
List<Dragon> dragons = new ArrayList<>();
for(int i = 0; i < p; i++){
int a, b, c; a = fs.nextInt(); b = fs.nextInt(); c = fs.nextInt();
dragons.add(new Dragon(a, b, c));
}
Collections.sort(dragons);
SegmentTree st = new SegmentTree(0, profit.length - 1, profit);
//do precomp
long[] precomp = new long[dragons.size()];
for(int i = 0; i < dragons.size(); i++){
int pos = dragons.get(i).b;
long amt = dragons.get(i).c;
st.rangeUpdate(pos + 1, profit.length - 1, amt); //every purchase at this defense level and above gets amt benefit
precomp[i] = st.maxRangeQuery(1, profit.length - 1);
//out.println(i + " " + pos + " " + amt + " " + precomp[i]);
}
//out.println("---");
int mnAtkCost = (int)1e9;
for(int i = 0; i < atk.size(); i++){
mnAtkCost = Math.min(mnAtkCost, atk.get(i).s);
}
long ans = -(mn + mnAtkCost);
for(int i = 0; i < atk.size(); i++){
//try this atk
long cost = atk.get(i).s;
int amt = atk.get(i).f;
l = 0;
r = dragons.size() - 1;
int at = -1;
while(l <= r){
int mid = (l + r)/2;
if(dragons.get(mid).a < amt){
at = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
//out.println(i + " " + cost + " " + amt);
if(at != -1){
ans = Math.max(ans, precomp[at] - cost);
}
}
out.println(ans);
out.close();
}
}
class Pair implements Comparable<Pair> {
int f, s;
Pair(int a, int b){
this.f = a; this.s = b;
}
@Override
public int compareTo(Pair o){
if(o.f < this.f){
return 1;
} else if (o.f > this.f){
return -1;
} else {
if(o.s < this.s){
return 1;
} else if (o.s > this.s){
return -1;
} else {
return 0;
}
}
}
}
class Dragon implements Comparable<Dragon> {
int a, b, c;
Dragon(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(Dragon o){
if(o.a < this.a){
return 1;
} else if (o.a > this.a){
return -1;
} else {
return 0;
}
}
}
class SegmentTree {
private SegmentTree lTree, rTree;
private int lIdx, rIdx;
private long max, sum;
private long lazy;
public SegmentTree(int l, int r, long arr[]){
lIdx = l;
rIdx = r;
lazy = 0;
if(l == r){
max = arr[l];
sum = arr[l];
} else {
lTree = new SegmentTree(l, (r + l)/2, arr);
rTree = new SegmentTree((r + l)/2 + 1, r, arr);
max = Math.max(lTree.getMax(), rTree.getMax());
sum = lTree.getSum() + rTree.getSum();
}
}
public long getMax(){
return max;
}
public long getSum(){
return sum;
}
public long maxRangeQuery(int l, int r){
if(lazy > 0){
max += lazy;
//System.out.println("UPDATED MY MAX TO " + max + " " + lazy + " " + lIdx + " " + rIdx);
if(lTree != null){
lTree.lazyPush(lazy);
}
if(rTree != null){
rTree.lazyPush(lazy);
}
lazy = 0;
}
if(l > rIdx || r < lIdx){
return Long.MIN_VALUE;
}
if(l <= lIdx && r >= rIdx){
//System.out.println("CAPTURED RANGE " + lIdx + " " + rIdx + " " + min);
return max;
}
return Math.max(lTree.maxRangeQuery(l, r), rTree.maxRangeQuery(l, r));
}
public long sumRangeQuery(int l, int r){
if(lazy > 0){
sum = (lazy * (rIdx - lIdx + 1));
if(lTree != null){
lTree.lazyPush(lazy);
}
if(rTree != null){
rTree.lazyPush(lazy);
}
lazy = 0;
}
if(l > rIdx || r < lIdx){
return 0;
}
if(l <= lIdx && r >= rIdx){
return sum;
}
return lTree.sumRangeQuery(l, r) + rTree.sumRangeQuery(l, r);
}
public void lazyPush(long val){
lazy += val;
}
public void rangeUpdate(int l, int r, long inc){
if(lazy > 0){
max += lazy;
if(lTree != null){
lTree.lazyPush(lazy);
}
if(rTree != null){
rTree.lazyPush(lazy);
}
lazy = 0;
}
if(l > rIdx || r < lIdx){
return;
}
if(l <= lIdx && r >= rIdx){
//System.out.println("updated on " + lIdx + " " + rIdx);
sum += inc * (rIdx - lIdx + 1);
max += inc;
if(lTree != null){
lTree.lazyPush(inc);
}
if(rTree != null){
rTree.lazyPush(inc);
}
} else {
lTree.rangeUpdate(l, r, inc);
rTree.rangeUpdate(l, r, inc);
max = Math.max(lTree.getMax(), rTree.getMax());
sum = lTree.getSum() + rTree.getSum();
}
}
public void pointUpdate(int pos, long elem){
if(lIdx != rIdx){
if(pos <= (rIdx + lIdx)/2){
lTree.pointUpdate(pos, elem);
} else {
rTree.pointUpdate(pos, elem);
}
max = Math.max(lTree.getMax(), rTree.getMax());
sum = lTree.getSum() + rTree.getSum();
} else {
max = elem;
sum = elem;
}
}
}
//FastScanner fetched from: https://gist.github.com/codekansas/998da051fba0005111d43b0d11246478
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() throws FileNotFoundException {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
| java |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | import java.util.Scanner;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.LinkedList;
import java.util.TreeSet;
import java.util.PriorityQueue;
import java.util.Deque;
public class Solution{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int test_cases = sc.nextInt();
outer : for(int h=0;h<test_cases;h++){
//scan the input
int n = sc.nextInt();
if(n%2==1){
System.out.print(7);
n-=3;
}
for(int i=0;i<n/2;i++){
System.out.print(1);
}
System.out.println();
}
sc.close();
}
public static boolean check_sorted(long a[]){
for(int i=0;i<a.length-1;i++){
if(a[i]<=a[i+1]){
return true;
}
}
return false;
}
public static void scan_string_array(String s[] , int n, Scanner sc){
for(int i=0;i<n;i++){
s[i] = sc.next();
}
}
public static void swap_elements(int a[], int s_index, int e_index){
int temp = a[s_index];
a[s_index] = a[e_index];
a[e_index] = temp;
}
public static void scan_array_long(long a[], int n, Scanner sc){
for(int i=0;i<n;i++){
a[i] = sc.nextLong();
}
}
public static void scan_array(int a[], int n, Scanner sc){
for(int i=0;i<n;i++){
a[i] = sc.nextInt();
}
}
public static void print_array(int a[]){
for(int i=0;i<a.length;i++){
if(i==a.length-1){
System.out.println(a[i]);
return;
}
System.out.print(a[i]);
}
}
public static long sum_array(long a[]){
long sum = 0;
for(int i=0;i<a.length;i++){
sum+=a[i];
}
return sum;
}
public static boolean perfect_square(double num){
boolean isSq = false;
double b = Math.sqrt(num);
double c = Math.sqrt(num) - Math.floor(b);
if(c==0){
isSq=true;
}
return isSq;
}
public static boolean ispalindrome(String s){
int i=0, j =s.length()-1;
while(i<=j){
if(s.charAt(i)!=s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
public static boolean ispowerOftwo(int n){
if(n>0 && (int)(n & (n-1))==0){
return true;
}
else{
return false;
}
}
public static int calculate_gcd(int x,int y){
int gcd = 1;
if(x%y==0){
return y;
}
else if(y%x==0){
return x;
}
else{
for(int i=2;i<=x && i<=y;i++){
if(x%i==0 && y%i==0){
gcd = i;
}
}
return gcd;
}
}
public static long calculate_factorial(long x){
long ans = 1;
for(int i=1;i<=x;i++){
ans*=i;
}
return ans;
}
public static void swap(int a[], int b[], int index_a, int index_b){
int temp = a[index_a];
a[index_a] = b[index_b];
b[index_b] = temp;
}
public static int find_maximum(int a[]){
int max = Integer.MIN_VALUE;
for(int i=0;i<a.length;i++){
max = Math.max(a[i], max);
}
return max;
}
public static int find_minimum(int a[]){
int min = Integer.MAX_VALUE;
for(int i=0;i<a.length;i++){
min = Math.min(a[i], min);
}
return min;
}
public static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
Random random = new Random();
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
int temp=a[oi];
a[oi]=a[i];
a[i]=temp;
}
Arrays.sort(a);
}
public static int sum_of_digits(int n){
int s =0;
while(n!=0){
s+=n%10;
n/=10;
}
return s;
}
public static int[] mergeSort(int[] array) {
if (array.length <= 1) {
return array;
}
int midpoint = array.length / 2;
int[] left = new int[midpoint];
int[] right;
if (array.length % 2 == 0) {
right = new int[midpoint];
} else {
right = new int[midpoint + 1];
}
for (int i = 0; i < left.length; i++) {
left[i] = array[i];
}
for (int i = 0; i < right.length; i++) {
right[i] = array[i + midpoint];
}
int[] result = new int[array.length];
left = mergeSort(left);
right = mergeSort(right);
result = merge(left, right);
return result;
}
public static int[] merge(int[] left, int[] right) {
int[] result = new int[left.length + right.length];
int leftPointer = 0, rightPointer = 0, resultPointer = 0;
while (leftPointer < left.length || rightPointer < right.length) {
if (leftPointer < left.length && rightPointer < right.length) {
if (left[leftPointer] < right[rightPointer]) {
result[resultPointer++] = left[leftPointer++];
} else {
result[resultPointer++] = right[rightPointer++];
}
} else if (leftPointer < left.length) {
result[resultPointer++] = left[leftPointer++];
} else {
result[resultPointer++] = right[rightPointer++];
}
}
return result;
}
} | 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.*;
import java.lang.reflect.Array;
import java.util.*;
public class edu130 {
//private static Object m;
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 boolean func(long x,long k){
return (k-((x*x)+(x)+1))%(2*x)==0;
}
public static void gg(int [] arr, int l, int r, int count , int[] ans){
if(r<l){
return;
}
if(r==l){
ans[l]=count;
return;
}
int m=l;
for(int i=l+1;i<=r;i++){
if(arr[i]>arr[m]){
m=i;
}
}
ans[m]=count;
gg(arr,l,m-1,count+1,ans);
gg(arr,m+1,r,count+1,ans);
}
public static void main(String[] args) {
//RSRRSRSSSR
try {
FastReader sc = new FastReader();
FastWriter out = new FastWriter();
int t=sc.nextInt();
long ans=0;
ArrayList<Integer> small=new ArrayList<>();
ArrayList<Integer> greatest=new ArrayList<>();
int count=t;
while(t-->0){
int n=sc.nextInt();
int [] arr=new int[n];
//count=n;
boolean issame=false;
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
if(i>0 && arr[i]!=arr[i-1])issame=true;
}
if(n==1 || !issame){
small.add(arr[0]);
greatest.add(arr[0]);
}else{
int min=arr[0];
int max=arr[0];
int ff=0;
boolean check=false;
int ss=0;
for(int i=1;i<n;i++){
if(arr[i]<=min ){
min=arr[i];
ff=i;
}
if(arr[i]>=max || arr[i]>min){
max=arr[i];
ss=i;
}
if(max>min && ss>ff){
check=true;
break;
}
}
if(check){
ans+=(count-1)*2L+1;
count--;
}else{
small.add(min);
greatest.add(max);
}
}
}
//System.out.println(ans);
Collections.sort(greatest);
int length=greatest.size();
for(int i=0;i<small.size();i++){
int num=small.get(i);
int ff=0;
int ss=length-1;
while(ff<=ss){
int mid=ff-(ff-ss)/2;
if(greatest.get(mid)>num){
ss=mid-1;
}else{
ff=mid+1;
}
}
ans+=length-ff;
}
System.out.println(ans);
}catch(Exception e){
return;
}
}
public static int gfg(int [] arr,int n,int index,int i,int [] dp){
if(i>=n)return 0;
// if(i==n-1){
// if(index==-1)return arr[i];
// if(arr[i]<=arr[index])return 0;
// if(index-arr[index]!=i-arr[i])return 0;
// return arr[i];
// }
if(index!=-1)
if(dp[i]!=-1 && index-arr[index]==i-arr[i] )return dp[i];
int nottake= gfg(arr, n, index, i + 1, dp);
int take=0;
if(index==-1 || (arr[i]>arr[index]) && (index-arr[index]==i-arr[i])){
take=arr[i]+gfg(arr,n,i,i+1,dp);
}
return dp[i]=Math.max(dp[i],Math.max(take,nottake));
}
private static void swap(int[] arr, int i, int ii) {
int temp=arr[i];
arr[i]=arr[ii];
arr[ii]=temp;
}
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;
}
}
} | java |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] | import java.math.BigInteger;
import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int testcase=sc.nextInt();
for(int tc=1;tc<=testcase;tc++){
//System.out.print("Case #"+tc+": ");
long n = sc.nextInt();
long m = sc.nextInt();
long count = 0;
long i = 9;
while(i <= m){
count++;
i = i*10 + 9;
}
System.out.println((long)count*n);
}
sc.close();
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to return LCM of two numbers
// static int lcm(int a, int b)
// {
// return (a / gcd(a, b)) * b;
// }
static int f(int order[], int disAmount){
int count = 0;
for(int x : order){
if(x > 0 && disAmount % x == 0)
count++;
}
return count;
}
static int upper_bound(int arr[], int key)
{
int mid, N = arr.length;
// Initialise starting index and
// ending index
int low = 0;
int high = N;
// Till low is less than high
while (low < high && low != N) {
// Find the index of the middle element
mid = low + (high - low) / 2;
// If key is greater than or equal
// to arr[mid], then find in
// right subarray
if (key >= arr[mid]) {
low = mid + 1;
}
// If key is less than arr[mid]
// then find in left subarray
else {
high = mid;
}
}
// If key is greater than last element which is
// array[n-1] then upper bound
// does not exists in the array
if (low > N ) {
low--;
}
// Print the upper_bound index
return low;
}
static int lower_bound(int array[], int key)
{
// Initialize starting index and
// ending index
int low = 0, high = array.length;
int mid;
// Till high does not crosses low
while (low < high) {
// Find the index of the middle element
mid = low + (high - low) / 2;
// If key is less than or equal
// to array[mid], then find in
// left subarray
if (key <= array[mid]) {
high = mid;
}
// If key is greater than array[mid],
// then find in right subarray
else {
low = mid + 1;
}
}
// If key is greater than last element which is
// array[n-1] then lower bound
// does not exists in the array
if(low==-1)
low++;
// Returning the lower_bound index
return low;
}
static boolean palin(int arr[], int i, int j){
while(i < j){
if(arr[i] != arr[j])
return false;
i++;
j--;
}
return true;
}
static boolean palin(String s){
int i=0,j=s.length()-1;
while(i<j){
if(s.charAt(i)!=s.charAt(j))
return false;
i++;
j--;
}
return true;
}
static long minSum(int arr[], int n, int k)
{
// k must be smaller than n
if (n < k)
{
// System.out.println("Invalid");
return -1;
}
// Compute sum of first window of size k
long res = 0;
for (int i=0; i<k; i++)
res += arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
long curr_sum = res;
for (int i=k; i<n; i++)
{
curr_sum += arr[i] - arr[i-k];
res = Math.min(res, curr_sum);
}
return res;
}
static int nextIndex(int a[], int x){
int n=a.length;
for(int i=x;i<n-1;i++){
if(a[i]>a[i+1]){
return i;
}
}
return n;
}
static void rev(int a[], int i, int j){
while(i<j){
int t=a[i];
a[i]=a[j];
a[j]=t;
i++;
j--;
}
}
static int sorted(int arr[], int n)
{
// Array has one or no element or the
// rest are already checked and approved.
if (n == 1 || n == 0)
return 1;
// Unsorted pair found (Equal values allowed)
if (arr[n - 1] < arr[n - 2])
return 0;
// Last pair was sorted
// Keep on checking
return sorted(arr, n - 1);
}
static void sieveOfEratosthenes(int n, Set<Integer> set)
{
// Create a boolean array "prime[0..n]" and
// initialize all entries it as true. A value in
// prime[i] will finally be false if i is Not a
// prime, else true.
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] == true) {
// Update all multiples of p greater than or
// equal to the square of it numbers which
// are multiple of p and are less than p^2
// are already been marked.
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] == true)
set.add(i);
}
}
static boolean isPowerOfTwo(int n)
{
return (int)(Math.ceil((Math.log(n) / Math.log(2))))
== (int)(Math.floor(((Math.log(n) / Math.log(2)))));
}
static int countBits(int number)
{
// log function in base 2
// take only integer part
return (int)(Math.log(number) /
Math.log(2) + 1);
}
public static void swap(int ans[], int i, int j) {
int temp=ans[i];
ans[i]=ans[j];
ans[j]=temp;
}
static int power(int x, int y, int p)
{
int res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
} | 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.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class f
{
public static void print(String str,int val){
System.out.println(str+" "+val);
}
public long gcd(long a, long b) {
if (b==0L) return a;
return gcd(b,a%b);
}
public static void debug(long[][] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.println(Arrays.toString(arr[i]));
}
}
public static void debug(int[][] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.println(Arrays.toString(arr[i]));
}
}
public static void debug(String[] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.println(arr[i]);
}
}
public static void print(int[] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.print(arr[i]+" ");
}
System.out.print('\n');
}
public static void print(String[] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.print(arr[i]+" ");
}
System.out.print('\n');
}
public static void print(long[] arr){
int len = arr.length;
for(int i=0;i<len;i++){
System.out.print(arr[i]+" ");
}
System.out.print('\n');
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
public FastReader(String path) throws FileNotFoundException {
br = new BufferedReader(new FileReader(path));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader s=new FastReader();
// int t = s.nextInt();
// for(int tt=0;tt<t;tt++){
int n = s.nextInt();
int m = s.nextInt();
int k = s.nextInt();
solve(n,m,k) ;
}
static void print(ArrayList<String> list){
System.out.println(list.size());
for(String s:list){
System.out.println(s);
}
}
static void solve(long n,long m,long k){
if(k>(4*n*m - 2*n-2*m)){
System.out.println("NO");
return ;
}
ArrayList<String> list = new ArrayList<>();
System.out.println("YES");
for(int i=0;i<n-1;i++){
if(k==0){
print(list);
return;
}
//frontwards
if(k>=(m-1)){
if((m-1)!=0)
list.add((m-1)+" R");
k-=(m-1);
}
else {
list.add(k+" R");
print(list);
return;
}
if(k==0){
print(list);
return;
}
//backwards
if(k>=3*(m-1)){
if((m-1)!=0)
list.add((m-1)+" DUL");
k-=(3*(m-1));
}
else {
long n_times = k/3;
if(n_times!=0){
list.add(n_times+" DUL");
}
int rem = (int)(k%3);
if(rem==1){
list.add(1+" D");
}
if(rem==2){
list.add(1+" DU");
}
print(list);
return;
}
if(k==0){
print(list);
return;
}
if(k>=1){
list.add(1+" D");
k--;
}
}
//now one down and (m-1) right
if(k==0){
print(list);
return;
}
if(k>=(m-1)){
if((m-1)!=0)
list.add((m-1)+" R");
k-=(m-1);
}
else {
list.add((k)+" R");
print(list);
return;
}
if(k==0){
print(list);
return;
}
if(k>=(m-1)){
if((m-1)!=0)
list.add((m-1)+" L");
k-=(m-1);
}
else {
list.add((k)+" L");
print(list);
return;
}
if(k==0){
print(list);
return;
}
list.add(k+" U");
print(list);
}
// OutputStream out = new BufferedOutputStream( System.out );
// for(int i=1;i<n;i++){
// out.write((arr[i]+" ").getBytes());
// }
// out.flush();
// long start_time = System.currentTimeMillis();
// long end_time = System.currentTimeMillis();
// System.out.println((end_time - start_time) + "ms");
}
| 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.util.*;
import java.lang.*;
public class X
{
public static void main(String[] args)
{
X ob=new X();
Scanner sc=new Scanner(System.in);
long N=sc.nextInt();
long[] M=new long[(int)N];
for(long i=0;i<N;i++)
M[(int)i]=sc.nextLong();
ob.solve(M);
}
void solve(long[] M)
{
long[] lsmall;
lsmall=left(M);
long[] rsmall;
rsmall=right(M);
long[] L=new long[lsmall.length];
L[0]=M[0];
for(long i=1;i<L.length;i++)
{
if(lsmall[(int)i]==-1)
L[(int)i]=(i+1)*M[(int)i];
else
L[(int)i]=L[(int)lsmall[(int)i]]+(i-lsmall[(int)i])*M[(int)i];
}
long[] R=new long[lsmall.length];
R[R.length-1]=M[M.length-1];
for(long i=R.length-2;0<=i;i--)
{
if(rsmall[(int)i]==R.length)
R[(int)i]=(R.length-i)*M[(int)i];
else
R[(int)i]=R[(int)rsmall[(int)i]]+(rsmall[(int)i]-i)*M[(int)i];
}
long MX=0l;
long peak=0l;
for(long i=0;i<M.length;i++)
{
if(MX<(L[(int)i]+R[(int)i]-M[(int)i]))
{
MX=L[(int)i]+R[(int)i]-M[(int)i];
peak=i;
}
}
long[] A=new long[M.length];
long mn=M[(int)peak];
for(long i=peak+1;i<A.length;i++)
{
mn=Math.min(mn,M[(int)i]);
A[(int)i]=mn;
}
mn=M[(int)peak];
for(long i=peak-1;0<=i;i--)
{
mn=Math.min(mn,M[(int)i]);
A[(int)i]=mn;
}
A[(int)peak]=M[(int)peak];
for(int i=0;i<A.length;i++)
System.out.print(A[(int)i]+" ");
}
long[] left(long[] A)
{
Stack<Integer> s=new Stack<Integer>();
long[] L=new long[A.length];
for(int i=0;i<L.length;i++)
{
while(0<s.size() && A[i]<=A[s.peek()])
s.pop();
if(s.size()==0)
L[(int)i]=-1;
else
L[(int)i]=s.peek();
s.push(i);
}
return L;
}
long[] right(long[] A)
{
Stack<Integer> s=new Stack<Integer>();
long[] R=new long[A.length];
for(int i=R.length-1;0<=i;i--)
{
while(0<s.size() && A[i]<=A[s.peek()])
s.pop();
if(s.size()==0)
R[(int)i]=R.length;
else
R[(int)i]=s.peek();
s.push(i);
}
return R;
}
} | java |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.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 as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO". | [
"geometry",
"greedy",
"math",
"number theory"
] | import java.util.Scanner;
public class CFR83D2 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t>0){
t--;
int a=sc.nextInt();
int b=sc.nextInt();
if(a>b&&a%b==0){
System.out.println( "YES");
}else{
System.out.println("NO");
}
}
}
}
| 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.*;
public class Main{
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
String ans = "";
if(k>(4*n*m - 2*n - 2*m))
System.out.println("NO");
else if (m==1&n==1)
System.out.println("NO");
else {
if (n == 1 && m > 1) {
if(k<=m-1)
System.out.println("YES\n1\n" + k + " R");
else
System.out.println("YES\n2\n" + (m-1) + " R\n" + (k-m+1) + " L");
}
else if (m == 1 && n > 1) {
if(k<=n-1)
System.out.println("YES\n1\n" + k + " D");
else
System.out.println("YES\n2\n" + (n-1) + " D\n" + (k-n+1) + " U");
}
else {
int step = k/(1+4*(m-1))*3;
if(k <= (n-1)*(1+4*(m-1))) {
int j = k%(1+4*(m-1));
if (j<=m-1 && j>0) {
ans = j +" R";
step++;
}
else if (j>0) {
if((j-m+1)/3==0) {
if((j-m+1)%3 == 1) {
ans = (m-1) + " R\n1 D";
step+=2;
}
else {
ans = (m-1) + " R\n1 D\n1 U";
step+=3;
}
}
else {
int i = (j-m+1)%3;
if (i == 1) {
ans = (m-1) + " R\n" + (j-m+1)/3 + " DUL\n1 D";
step+=3;
}
else if(i==2){
ans = (m-1) + " R\n" + (j-m+1)/3 + " DUL\n1 D\n1 U";
step+=4;
}
else if (i==0) {
ans = (m-1) + " R\n" + (j-m+1)/3 + " DUL";
step += 2;
}
}
}
System.out.println("YES" + "\n" + step);
for(int i = 0 ; i<k/(1+4*(m-1)) ; i++) {
System.out.println((m-1) + " R\n" + (m-1) + " DUL\n1 D");
}
System.out.println(ans);
}
else {
step = k/(1+4*(m-1))*3;
k = k - (n-1)*(1+4*(m-1));
if(k<=(m-1)) {
System.out.println("YES" + "\n" + (step+1));
for(int i = 0 ; i<(n-1) ; i++) {
System.out.println((m-1) + " R\n" + (m-1) + " DUL\n1 D");
}
System.out.println(k +" R");
}
else if (k<=2*(m-1)) {
System.out.println("YES" + "\n" + (step+2));
for(int i = 0 ; i<(n-1) ; i++) {
System.out.println((m-1) + " R\n" + (m-1) + " DUL\n1 D");
}
System.out.println((m-1) +" R\n" +(k-m+1)+" L");
}
else {
System.out.println("YES" + "\n" + (step+3));
for(int i = 0 ; i<(n-1) ; i++) {
System.out.println((m-1) + " R\n" + (m-1) + " DUL\n1 D");
}
System.out.println((m-1) +" R\n" +(m-1)+" L\n" + (k-2*(m-1)) + " U");
}
}
}
}
}
}
| 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"
] | import java.io.*;
import java.util.*;
public class D1275 {
static int N = (int)1e5 + 7;
static int[][] nod = new int[30 * N][2];
static int res = (1 << 30);
static void dfs(int u, int cur, int lvl) {
if(nod[u][0] == 0 && nod[u][1] == 0) res = Math.min(res, cur);
else if(nod[u][0] > 0 && nod[u][1] > 0) {
cur += (1 << lvl);
dfs(nod[u][0], cur, lvl - 1);
dfs(nod[u][1], cur, lvl - 1);
}
else {
if(nod[u][0] > 0) dfs(nod[u][0], cur, lvl - 1);
else dfs(nod[u][1], cur, lvl - 1);
}
}
public static void main(String[] args) {
//Scanner sc = new Scanner(System.in);
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int T, cs=0;
int n = fs.nextInt(), tot = 0;
for (int i = 0; i < n; i++) {
int x;
x = fs.nextInt();
int cur = 0;
for (int j = 30; j >= 0; j--) {
int bit = 1 & (x >> j);
if(nod[cur][bit] == 0) nod[cur][bit] = ++tot;
cur = nod[cur][bit];
}
}
dfs(0, 0, 30);
out.println(res);
out.close();
}
public static void dbg(Object... o){
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber() + ": ");
System.err.println(Arrays.deepToString(o));
}
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());
}
}
} | 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 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 |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.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 new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
| [
"math"
] | import java.util.*;
public class Collectingcoins {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i=0;i<n;i++)
{
int a[]=new int[3];
for(int j=0;j<3;j++)
{
a[j]=in.nextInt();
}
int no = in.nextInt();
Arrays.sort(a);
int g = a[2]-a[0];
int h =a[2]-a[1];
no=no-(g+h);
if(no%3==0&&no>=0)
System.out.println("YES");
else
System.out.println("NO");
}
}
}
| java |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22. | [
"greedy",
"implementation",
"math"
] | import java.util.Arrays;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 00:26:39 03/05/2021
Custom Competitive programming helper.
*/
public class Main {
static int n,m;
public static void solve() {
n = in.nextInt(); m = in.nextInt();
int[][] a = new int[m][n];
for(int i = 0; i<n; i++)for(int j = 0; j<m; j++) a[j][i] = in.nextInt();
int ans = 0;
for(int i = 0; i<m; i++) ans += fix(a[i],i, n, m);
out.println(ans);
}
public static int fix(int[] a, int iii, int n, int m) {
HashMap<Integer,Integer> goal = new HashMap<>();
for(int i = 0; i<n; i++) goal.put(m*(i)+iii+1, i);
int[] shift = new int[n];
Arrays.fill(shift, -1);
HashMap<Integer,Integer> shiftF = new HashMap<>();
for(int i = 0; i<n; i++) {
if(!goal.containsKey(a[i])) continue;
int to = goal.get(a[i]);
if(to<=i) shift[i] = i-to;
else shift[i] = n-to+i;
shiftF.put(shift[i], shiftF.getOrDefault(shift[i], 0)+1);
}
int ans = Integer.MAX_VALUE;
for(int i = 0; i<=n; i++) {
int left = n - shiftF.getOrDefault(i, 0);
ans = Math.min(ans, left+i);
}
return ans;
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = 1;
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util{
private static Random random = new Random();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i*i <= n; i++) if (isPrime[i])
for (int j = i; i*j <= n; j++) isPrime[i*j] = false;
return isPrime;
}
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(char[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
char tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
| 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"
] | /*
*created by Kraken on 17-03-2020 at 23:54
*/
//package com.kraken;
import java.util.*;
import java.io.*;
public class E {
static int n;
static int[] di = { -1, 1, 0, 0 };
static int[] dj = { 0, 0, -1, 1 };
static boolean valid(int i, int j) {
return i >= 0 && i < n && j >= 0 && j < n;
}
static char empty = '#';
static boolean eq(int[] a, int[] b) {
return a[0] == b[0] && a[1] == b[1];
}
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
int[][][] a = new int[n][n][2];
char[][] ans = new char[n][n];
Queue<int[]> q = new LinkedList();
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
ans[i][j] = empty;
for (int k = 0; k < 2; k++)
a[i][j][k] = sc.nextInt() - 1;
if (a[i][j][0] == i && a[i][j][1] == j) {
q.add(new int[] { i, j });
ans[i][j] = 'X';
}
}
char[] dir = "UDLR".toCharArray();
while (!q.isEmpty()) {
int[] curr = q.poll();
int i = curr[0], j = curr[1];
for (int k = 0; k < 4; k++) {
int i2 = i + di[k], j2 = j + dj[k];
if (!valid(i2, j2) || ans[i2][j2] != empty)
continue;
if (eq(a[i2][j2], a[i][j])) {
ans[i2][j2] = dir[k ^ 1];
q.add(new int[] { i2, j2 });
}
}
}
boolean ok = true;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
if (ans[i][j] != empty)
continue;
if (a[i][j][0] != -2) {
ok = false;
break;
}
int deg = 0;
for (int k = 0; k < 4; k++) {
int i2 = i + di[k], j2 = j + dj[k];
if (!valid(i2, j2) || !eq(a[i2][j2], a[i][j]))
continue;
deg++;
ans[i][j] = dir[k];
if (ans[i2][j2] == empty) {
ans[i2][j2] = dir[k ^ 1];
}
break;
}
ok&=deg>0;
}
if (!ok) {
System.out.println("INVALID");
return;
}
out.println("VALID");
for (char[] x : ans)
out.println(x);
out.close();
}
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 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — 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≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement. | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int testCases = input.nextInt();
for(int index = 0; index < testCases; index++) {
int numDaughters = input.nextInt();
int[] necklaces = new int[numDaughters];
int[] braceletes = new int[numDaughters];
for(int counter = 0; counter < numDaughters; counter++) {
necklaces[counter] = input.nextInt();
}
for(int counter = 0; counter < numDaughters; counter++) {
braceletes[counter] = input.nextInt();
}
Arrays.sort(necklaces);
Arrays.sort(braceletes);
for(int counter = 0; counter < numDaughters; counter++) {
System.out.print(necklaces[counter] + " ");
}
System.out.println();
for(int counter = 0; counter < numDaughters; counter++) {
System.out.print(braceletes[counter] + " ");
}
System.out.println();
}
}
} | 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"
] | 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.TreeSet;
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);
E2StringColoringHardVersion solver = new E2StringColoringHardVersion();
solver.solve(1, in, out);
out.close();
}
static class E2StringColoringHardVersion {
static int n;
static char[] arr;
static int[] ans;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
arr = in.next().toCharArray();
ans = new int[n];
int color = 1;
int[] last = new int[26];
for (int i = 0; i < n; i++) {
last[arr[i] - 'a'] = i;
}
Arrays.fill(ans, 1);
TreeSet<Integer>[] list = new TreeSet[100];
for (int i = 0; i < 100; i++) {
list[i] = new TreeSet<>();
}
for (int i = 0; i < n; i++) {
for (int j = 1; j <= 50; j++) {
if (list[j].higher(arr[i] - 'a') == null) {
ans[i] = j;
list[j].add(arr[i] - 'a');
break;
}
}
}
int sz = 0;
TreeSet<Integer> set = new TreeSet<>();
for (int a : ans) set.add(a);
out.println(set.size());
out.println(ans);
}
}
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 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();
}
public void println(int i) {
writer.println(i);
}
}
}
| java |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES" | [
"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 = 1;
while(t-- > 0) {
run_case();
}
//out.close();
}
static void run_case() {
int n = fs.nextInt(), k =fs.nextInt();
char[][] s = new char[n][];
for (int i = 0; i < n; i++) {
s[i] = fs.next().toCharArray();
}
HashSet<String> hs = new HashSet<>();
for (int i = 0; i < n; i++) {
hs.add(new String(s[i]));
}
long ans = 0;
char[] tr = {'S', 'E', 'T'};
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
char[] nw = new char[k];
for (int l = 0; l < k; l++) {
if(s[i][l] == s[j][l]) {
nw[l] = s[i][l];
}else {
for (int m = 0; m < 3; m++) {
if(s[i][l] != tr[m] &&
s[j][l] != tr[m]) {
nw[l] = tr[m];
}
}
}
}
if(hs.contains(new String(nw))) ans++;
}
}
System.out.println(ans / 3);
}
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 |
1322 | C | C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11. | [
"graphs",
"hashing",
"math",
"number theory"
] | import java.io.*;
import java.sql.Array;
import java.util.*;
public class Contest1 {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// /////////
//////// /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// /////////
//////// /////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static ArrayList<Integer>[]adj;
static long mod= (int)1e9+9;
static long base= (int)1e9+7;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
long[]pow = new long[500001];
pow[0]=1;
for (int i =1;i<=500000;i++){
pow[i]=base*pow[i-1];
pow[i]%=mod;
}
while (t-->0) {
int n = sc.nextInt();
int m = sc.nextInt();
adj = new ArrayList[n];
for (int i = 0; i < n; i++){
adj[i] = new ArrayList<>();
}
long[] gcds = new long[n];
long[] vals = new long[n];
long g = 0;
for (int i = 0; i < n; i++) {
vals[i] = sc.nextLong();
}
while (m-- > 0) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adj[v].add(u);
}
TreeMap<ArrayList<Integer>,Long>ts = new TreeMap<>(new Comparator<ArrayList<Integer>>() {
public int compare(ArrayList<Integer> t1, ArrayList<Integer> t2) {
if (t1.size()!=t2.size())
return t1.size()-t2.size();
return t1.get(t1.size()-1)-t2.get(t2.size()-1);
}
});
for (int i =0;i<n;i++){
Collections.sort(adj[i]);
if (adj[i].isEmpty())continue;
long hsv= 0;
int id=0;
for (int x:adj[i]){
hsv+=x*pow[id++];
hsv%=mod;
}
adj[i].add((int)hsv);
ts.put(adj[i],ts.getOrDefault(adj[i],0l)+vals[i]);
}
while (!ts.isEmpty()) {
g= gcd(g,ts.pollFirstEntry().getValue());
}
pw.println(g);
}
pw.flush();
}
static long gcd(long a,long b){
if (a==0)return b;
return gcd(b%a,a);
}
static class SparseTable {
int A[], SpT[][];
SparseTable(int[] A)
{
int n = A.length; this.A = A;
int k = (int)Math.floor(Math.log(n) / Math.log(2)) + 1;
SpT = new int[n][k];
for (int i = 0; i < n; i++)
SpT[i][0] = i; // RMQ of sub array starting at index i and of length 2^0=1
//overall time complexity = O(n log n)
for (int j = 1; (1<<j) <= n; j++)
for (int i = 0; i + (1<<j) - 1 < n; i++)
if (A[SpT[i][j-1]] > A[SpT[i+(1<<(j-1))][j-1]])
SpT[i][j] = SpT[i][j-1]; // start at index i of length 2^(j-1)
else // start at index i+2^(j-1) of length 2^(j-1)
SpT[i][j] = SpT[i+(1<<(j-1))][j-1];
}
int query(int i, int j)
{
int k = (int)Math.floor(Math.log(j-i+1) / Math.log(2)); // 2^k <= (j-i+1)
if (A[SpT[i][k]] >= A[SpT[j-(1<<k)+1][k]])
return SpT[i][k];
else
return SpT[j-(1<<k)+1][k];
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | java |
1290 | D | D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 3n22k3n22k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 3n22k≤15 0003n22k≤15 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 3n22k3n22k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 3n22k≤15 0003n22k≤15 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5. | [
"constructive algorithms",
"graphs",
"interactive"
] | import java.io.*;
import java.util.*;
public class A {
FastScanner in;
PrintWriter out;
void solve(int n, int k) {
int block = Math.max(1, k / 2);
int maxMoves = 3 * n * n / 2 / k;
if (maxMoves > 16000) {
throw new AssertionError();
}
int blocks = 1 + (n - 1) / block;
boolean[][] seen = new boolean[blocks][blocks];
List<Integer>[] insideBlock = new List[blocks];
for (int i = 0; i < insideBlock.length; i++) {
insideBlock[i] = new ArrayList<>();
}
for (int i = 0; i < n; i++) {
insideBlock[i / block].add(i + 1);
}
int resets = 30000;
boolean[] alive = new boolean[n];
Arrays.fill(alive, true);
while (true) {
out.println("R");
out.flush();
if (resets-- < 0) {
throw new AssertionError();
}
int first = -1;
if (blocks == 1) {
first = 0;
}
for (int i = 0; i < blocks; i++) {
for (int j = i + 1; j < blocks; j++) {
if (!seen[i][j]) {
first = i;
break;
}
}
if (first != -1) {
break;
}
}
if (first == -1) {
break;
}
while (true) {
for (int v : insideBlock[first]) {
out.println("? " + v);
out.flush();
String s = in.next();
if (s.equals("Y")) {
alive[v - 1] = false;
}
if (!s.equals("N") && !s.equals("Y")) {
throw new AssertionError();
}
}
maxMoves -= block;
boolean found = false;
for (int next = first + 1; next < blocks; next++) {
if (!seen[first][next]) {
seen[first][next] = true;
first = next;
found = true;
break;
}
}
if (!found) {
break;
}
}
if (blocks == 1) {
break;
}
}
int cntAlive = 0;
for (int i = 0; i < n; i++) {
if (alive[i]) {
cntAlive++;
}
}
out.println("! " + cntAlive);
out.flush();
}
void solve() {
solve(in.nextInt(), in.nextInt());
}
void run() {
try {
in = new FastScanner(new File("A.in"));
out = new PrintWriter(new File("A.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
try {
new A().runIO();
} catch (AssertionError e) {
while (true) {}
}
}
} | java |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | import java.util.*;
import java.io.*;
public class Main extends PrintWriter {
Main() { super(System.out); }
static boolean cases = false;
// Solution
void solve(int t) {
int n = sc.nextInt();
int a[] = sc.readIntArray(n);
HashMap<Integer, Long> map = new HashMap<>();
long max = 0;
for (int i = 0; i < n; i++) {
int e = a[i] - (i + 1);
map.put(e, map.getOrDefault(e, 0l) + (long) a[i]);
max = Math.max(max, map.get(e));
}
System.out.println(max);
}
public static void main(String[] args) {
Main obj = new Main();
int c = 1;
for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve(c);
obj.solve(c);
obj.flush();
}
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[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
char[] readCharArray(int n) {
char a[] = new char[n];
String s = sc.next();
for (int i = 0; i < n; i++) { a[i] = s.charAt(i); }
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() { return Long.parseLong(next()); }
}
final int ima = Integer.MAX_VALUE;
final int imi = Integer.MIN_VALUE;
final long lma = Long.MAX_VALUE;
final long lmi = Long.MIN_VALUE;
static final long mod = (long) 1e9 + 7;
private static final FastScanner sc = new FastScanner();
private PrintWriter out = new PrintWriter(System.out);
} | 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 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.*;
/*
-> Give your 100%, that's it!
-> Feynman's Rule To Solve Any Problem:
1. Read the problem.
2. Think About It.
3. Solve it!
*/
public class Template {
static int mod = 1000000007;
public static void main(String[] args){
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int yo = 1;
while (yo-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int[] a = sc.readInts(n);
int[] b = sc.readInts(m);
int[] prefA = new int[n];
for(int i = 0; i < n; i++){
if(i == 0){
prefA[i] = a[i];
}
else {
if(a[i] == 1){
prefA[i] = prefA[i-1] + 1;
}
else {
prefA[i] = 0;
}
}
}
int[] prefB = new int[m];
for(int i = 0; i < m; i++){
if(i == 0){
prefB[i] = b[i];
}
else {
if(b[i] == 1){
prefB[i] = prefB[i-1] + 1;
}
else {
prefB[i] = 0;
}
}
}
List<Pair> list = new ArrayList<>();
for(int i = 1; i*i <= k; i++){
if(k%i == 0){
int x = i;
int y = k/i;
list.add(new Pair(x,y));
if(x != y) list.add(new Pair(y,x));
}
}
long ans = 0;
for(Pair p : list){
int r = p.x; // itne rows of 1s
int c = p.y; // itne cols of 1s
long c1 = 0;
for(int i = 0; i < n; i++){
if(prefA[i] >= r)
c1++;
}
long c2 = 0;
for(int i = 0; i < m; i++){
if(prefB[i] >= c){
c2++;
}
}
ans += c1*c2;
}
out.println(ans);
}
out.close();
}
/*
Source: hu_tao
Random stuff to try when stuck:
-if it's 2C then it's dp
-for combo/probability problems, expand the given form we're interested in
-make everything the same then build an answer (constructive, make everything 0 then do something)
-something appears in parts of 2 --> model as graph
-assume a greedy then try to show why it works
-find way to simplify into one variable if multiple exist
-treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them)
-find lower and upper bounds on answer
-figure out what ur trying to find and isolate it
-see what observations you have and come up with more continuations
-work backwards (in constructive, go from the goal to the start)
-turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements)
-instead of solving for answer, try solving for complement (ex, find n-(min) instead of max)
-draw something
-simulate a process
-dont implement something unless if ur fairly confident its correct
-after 3 bad submissions move on to next problem if applicable
-do something instead of nothing and stay organized
-write stuff down
Random stuff to check when wa:
-if code is way too long/cancer then reassess
-switched N/M
-int overflow
-switched variables
-wrong MOD
-hardcoded edge case incorrectly
Random stuff to check when tle:
-continue instead of break
-condition in for/while loop bad
Random stuff to check when rte:
-switched N/M
-long to int/int overflow
-division by 0
-edge case for empty list/data structure/N=1
*/
public static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void sort(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
for (int i = 0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] sieve(int N) {
boolean[] sieve = new boolean[N + 1];
for (int i = 2; i <= N; i++)
sieve[i] = true;
for (int i = 2; i <= N; i++) {
if (sieve[i]) {
for (int j = 2 * i; j <= N; j += i) {
sieve[j] = false;
}
}
}
return sieve;
}
public static long power(long x, long y, long p) {
long res = 1L;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y >>= 1;
x = (x * x) % p;
}
return res;
}
public static void print(int[] arr) {
//for debugging only
for (int x : arr)
out.print(x + " ");
out.println();
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
// For Input.txt and Output.txt
// FileInputStream in = new FileInputStream("input.txt");
// FileOutputStream out = new FileOutputStream("output.txt");
// PrintWriter pw = new PrintWriter(out);
// Scanner sc = new Scanner(in);
} | java |
1325 | A | A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100) — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14. | [
"constructive algorithms",
"greedy",
"number theory"
] | import java.util.*;
public class CP{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int testcases = sc.nextInt();
while(testcases-->0){
long x = sc.nextLong();
System.out.println("1 " + (x-1));
}
}
} | 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.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
PrintWriter out = new PrintWriter(System.out);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer("");
String next() throws IOException {
if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }
return tok.nextToken();
}
int ni() throws IOException { return Integer.parseInt(next()); }
long nl() throws IOException { return Long.parseLong(next()); }
long mod=1000000007;
void solve() throws IOException {
int n=ni(),m=ni();
int[][]A=new int[n+1][m];
for (int i=1;i<=n;i++) for (int j=0;j<m;j++) A[i][j]=ni();
int lt=0;
int rt=1000000001;
int a1=1;
int a2=1;
int tar=(1<<m)-1;
while (lt+1<rt) {
int av=(lt+rt)/2;
int[]B=new int[256];
for (int i=1;i<=n;i++) {
int p=1;
int h=0;
for (int j=0;j<m;j++) {
if (A[i][j]>=av) h|=p;
p<<=1;
}
if (B[h]==0) B[h]=i;
}
boolean f=false;
outer: for (int x=0;x<256;x++) {
if (B[x]==0) continue;
for (int y=x;y<256;y++) {
if (B[y]==0) continue;
if ((x|y)==tar) { f=true; a1=B[x]; a2=B[y]; break outer; }
}
}
if (f) lt=av;
else rt=av;
}
out.println(a1+" "+a2);
out.flush();
}
int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); }
long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); }
long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; }
public static void main(String[] args) throws IOException {
new Main().solve();
}
} | 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.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int k=sc.nextInt();
while(k-->0){
int n=sc.nextInt();
String str=sc.next();
int odd=0;
for(int i=0;i<str.length();i++){
if((str.charAt(i)-'0')%2!=0) odd++;
}
if(odd<=1) System.out.println("-1");
else{
StringBuilder sb=new StringBuilder();
for(int i=0;i<str.length();i++){
if((str.charAt(i)-'0')%2!=0) sb.append(str.charAt(i));
if(sb.length()==2) break;
}
System.out.println(sb.toString());
}
}
}
} | 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.io.*;
import java.util.*;
public class Main {
public static long m;
static int mod = 998244353;
static int inf = (int) 1e9 + 7;
static int st[][];
static int sum_of_d[] = new int[1000001];
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
//int t = sc.nextInt();
int t = 1;
Gr1zler:
for (int WTF = 0; WTF < t; WTF++) {
long n = sc.nextLong();
long qw=Long.MAX_VALUE;
for(long i=1;i*i<=n;i++){
if(n%i==0){
if(lcm(i,n/i)==n){
qw=Math.min(qw,Math.max(i,n/i));
}
}
}
System.out.println(qw+" "+n/qw);
}
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static void sort(int[] a) {
int n = a.length;
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++)
b[i] = a[i];
Arrays.sort(b);
for (int i = 0; i < n; i++)
a[i] = b[i];
}
static void sort(long[] a) {
int n = a.length;
Long[] b = new Long[n];
for (int i = 0; i < n; i++)
b[i] = a[i];
Arrays.sort(b);
for (int i = 0; i < n; i++)
a[i] = b[i];
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextArrInt(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextArrLong(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
}
| java |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | import java.util.*;
public class AssigningToTheClass {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int t=sc.nextInt();
while(t--!=0) {
int n=sc.nextInt();
int a[]= new int[2*n];
for(int i=0;i<a.length;i++) a[i]=sc.nextInt();
Arrays.sort(a);
System.out.println(a[n]-a[n-1]);
}
}
} | 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.io.*;
import java.util.*;
public class Codeforces
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
String num=sc.next();
String c=num; int sum=0;
int a[]=new int[n];
int i=n;
for(int j=0;j<n;j++)
{
char ch =num.charAt(j);
a[j]=ch - '0';
sum+=a[j];
}
int last=n-1;
if(sum%2==0)
{
if(a[n-1]%2==1)
System.out.println(num);
else
{
for(i=n-1;i>=0;i--)
{
if(a[i]%2==1)
{
last=i;
break;
}
else
{
sum-=a[i];
a[i]=-1;
}
}
num="";boolean first0=true;
for(i=0;i<n;i++)
{
if(a[i]!=0 && a[i]!=-1 && first0==true)
first0=false;
if(a[i]!=-1 && first0==false)
num+=a[i];
}
if(a[last]%2==1 && sum%2==0)
System.out.println(num);
else
System.out.println(-1);
}
}
else
{
if(a[n-1]%2==1)
{
for(i=0;i<n;i++)
{
if(a[i]%2==1)
{
sum-=a[i];
a[i]=-1;
break;
}
}
num=""; boolean first0=true;
for(i=0;i<n;i++)
{
if(a[i]!=0 && a[i]!=-1 && first0==true)
first0=false;
if(a[i]!=-1 && first0==false)
num+=a[i];
}
if(a[n-1]!=-1 && a[n-1]%2==1 && sum%2==0)
System.out.println(num);
else
System.out.println(-1);
}
else
{
for(i=n-1;i>=0;i--)
{
if(a[i]%2==1)
{
last=i;
break;
}
else
{
sum-=a[i];
a[i]=-1;
}
}
for(i=0;i<n;i++)
{
if(a[i]%2==1)
{
sum-=a[i];
a[i]=-1;
break;
}
}
num="";boolean first0=true;
for(i=0;i<n;i++)
{
if(a[i]!=0 && a[i]!=-1 && first0==true)
first0=false;
if(a[i]!=-1 && first0==false)
num+=a[i];
}
if(a[last]%2==1 && sum%2==0)
System.out.println(num);
else
System.out.println(-1);
}
}
}
}
} | java |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
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 {
if (st.hasMoreTokens()) {
str = st.nextToken("\n");
} else {
str = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void heapify(int arr[], int n, int i) {
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify(arr, n, largest);
}
}
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static int lcm(int a, int b) {
return (a *b/ gcd(a, b)) ;
}
public static String sortString(String inputString) {
// Converting input string to character array
char[] tempArray = inputString.toCharArray();
// Sorting temp array using
Arrays.sort(tempArray);
// Returning new sorted string
return new String(tempArray);
}
public static void main(String[] args) throws java.lang.Exception {
FastReader sc = new FastReader();
int t = sc.nextInt();
while (t-- != 0) {
long n = sc.nextLong();
if(n%2==1 ){
System.out.print(7);
n=n-3;
}
while(n>0) {
System.out.print(1);
n=n-2;
}
System.out.println();
}
}
}
| 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 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.*;
public class Template {
static int mod = 1000000007;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int yo = sc.nextInt();
while (yo-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int[] arr = sc.readInts(n);
int[][] dp = new int[n+1][n+1];
int min = helper(n,m,k,arr,0,n-1,1,dp);
out.println(min);
}
}
private static int helper(int n, int m, int k, int[] arr, int start, int end, int frnd, int[][] dp) {
if(frnd == m) {
return dp[start][end] = Math.max(arr[start], arr[end]);
}
if(dp[start][end] != 0) {
return dp[start][end];
}
if(k == 0) {
int min1 = helper(n,m,k,arr,start+1,end,frnd+1,dp);
int min2 = helper(n,m,k,arr,start,end-1,frnd+1,dp);
return dp[start][end] = Math.min(min1, min2);
}
else {
int min1 = helper(n,m,k-1,arr,start+1,end,frnd+1,dp);
int min2 = helper(n,m,k-1,arr,start,end-1,frnd+1,dp);
return dp[start][end] = Math.max(min1, min2);
}
}
public static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void sort(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
for (int i = 0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] sieve(int N) {
boolean[] sieve = new boolean[N + 1];
for (int i = 2; i <= N; i++)
sieve[i] = true;
for (int i = 2; i <= N; i++) {
if (sieve[i]) {
for (int j = 2 * i; j <= N; j += i) {
sieve[j] = false;
}
}
}
return sieve;
}
public static long power(long x, long y, long p) {
long res = 1L;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y >>= 1;
x = (x * x) % p;
}
return res;
}
public static void print(int[] arr) {
//for debugging only
for (int x : arr)
out.print(x + " ");
out.println();
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
// For Input.txt and Output.txt
// FileInputStream in = new FileInputStream("input.txt");
// FileOutputStream out = new FileOutputStream("output.txt");
// PrintWriter pw = new PrintWriter(out);
// Scanner sc = new Scanner(in);
} | java |
1305 | E | E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5) | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.BufferedOutputStream;
import java.io.UncheckedIOException;
import java.util.List;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author mikit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
LightScanner in = new LightScanner(inputStream);
LightWriter out = new LightWriter(outputStream);
EKuroniAndTheScoreDistribution solver = new EKuroniAndTheScoreDistribution();
solver.solve(1, in, out);
out.close();
}
static class EKuroniAndTheScoreDistribution {
public void solve(int testNumber, LightScanner in, LightWriter out) {
long start = System.currentTimeMillis();
int n = in.ints();
long m = in.longs();
List<Long> added = new ArrayList<>();
Map<Long, Integer> map = new HashMap<>();
for (long cur = 1; 0 < m && added.size() < n && System.currentTimeMillis() - start < 900; cur++) {
int p = map.getOrDefault(cur, 0);
if (p > m) continue;
m -= p;
for (long x : added) map.merge(x + cur, 1, Integer::sum);
added.add(cur);
}
if (m == 0) {
long min = 1;
while (added.contains(min)) min++;
long max = 1_000_000_000;
while (added.size() < n) {
added.add(max);
max -= min;
}
} else if (added.size() != n || m > 0) {
out.ans(-1).ln();
return;
}
added.sort(Comparator.naturalOrder());
for (long x : added) out.ans(x);
out.ln();
}
}
static class LightScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public LightScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public String string() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return tokenizer.nextToken();
}
public int ints() {
return Integer.parseInt(string());
}
public long longs() {
return Long.parseLong(string());
}
}
static class LightWriter implements AutoCloseable {
private final Writer out;
private boolean autoflush = false;
private boolean breaked = true;
public LightWriter(Writer out) {
this.out = out;
}
public LightWriter(OutputStream out) {
this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));
}
public LightWriter print(char c) {
try {
out.write(c);
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter print(String s) {
try {
out.write(s, 0, s.length());
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter ans(String s) {
if (!breaked) {
print(' ');
}
return print(s);
}
public LightWriter ans(long l) {
return ans(Long.toString(l));
}
public LightWriter ans(int i) {
return ans(Integer.toString(i));
}
public LightWriter ln() {
print(System.lineSeparator());
breaked = true;
if (autoflush) {
try {
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
return this;
}
public void close() {
try {
out.close();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
}
| java |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | 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 ArrayList<HashSet<Integer>> graph;
static HashSet<Integer> leaves;
//akhasdk
static void solve() {
int n = i();
graph = new ArrayList();
leaves = new HashSet();
for(int i =0;i<n;i++) graph.add(new HashSet());
for(int i =0;i<n-1;i++){
int u = i()-1;
int v = i()-1;
graph.get(u).add(v);
graph.get(v).add(u);
}
for(int i = 0;i<n;i++){
int sz = graph.get(i).size();
if(sz==1) leaves.add(i);
}
while(leaves.size()>1){
int u = leaves.iterator().next();
leaves.remove(u);
int v = leaves.iterator().next();
leaves.remove(v);
int w = query(u,v);
if(w==u||w==v){
System.out.println("! "+(w+1));
System.out.flush();
return;
}
delete(u,w,-1);
delete(v,w,-1);
if(graph.get(w).size()<=1){
leaves.add(w);
}
}
int ans = leaves.iterator().next();
System.out.println("! "+(ans+1));
System.out.flush();
}
static void delete(int u,int lca,int p){
leaves.remove(u);
for(int v : graph.get(u)){
if(v==p) continue;
else if(v==lca) graph.get(lca).remove(u);
else delete(v,lca,u);
}
}
static int query(int u,int v){
u++;
v++;
System.out.println("? "+u+" "+v);
System.out.flush();
int lca = i()-1;
return lca;
}
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 |
1292 | C | C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment: With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment: With this assignment, all non-zero mex value are listed below: mex(1,3)=1mex(1,3)=1 mex(1,5)=2mex(1,5)=2 mex(2,3)=1mex(2,3)=1 mex(2,5)=2mex(2,5)=2 mex(3,4)=1mex(3,4)=1 mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10. | [
"combinatorics",
"dfs and similar",
"dp",
"greedy",
"trees"
] | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1292c_2 {
public static void main(String[] args) throws IOException {
int n = ri();
Graph g = Graph.tree(n);
int sz[][] = new int[n][n], par[][] = new int[n][n];
long dp[][] = new long[n][n], ans = 0;
for (int i = 0; i < n; ++i) {
dfs(g, i, i, sz[i], par[i]);
fill(dp[i], -1);
dp[i][i] = 0;
}
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
ans = max(ans, dp(i, j, sz, par, dp));
}
}
prln(ans);
close();
}
static long dp(int u, int v, int[][] sz, int[][] par, long[][] dp) {
if (dp[u][v] != -1) {
return dp[u][v];
}
return dp[u][v] = (long) sz[u][v] * sz[v][u] + max(dp(u, par[u][v], sz, par, dp), dp(par[v][u], v, sz, par, dp));
}
static void dfs(Graph g, int i, int p, int[] sz, int[] par) {
par[i] = p;
sz[i] = 1;
for (int j : g.get(i)) {
if (j != p) {
dfs(g, j, i, sz, par);
sz[i] += sz[j];
}
}
}
static class Graph extends ArrayList<List<Integer>> {
static void c(Graph g, int u, int v) {
g.get(u).add(v);
g.get(v).add(u);
}
static void cto(Graph g, int u, int v) {
g.get(u).add(v);
}
static Graph tree(int n) throws IOException {
return graph(n, n - 1);
}
static Graph graph(int n, int m) throws IOException {
Graph g = new Graph();
for (int i = 0; i < n; ++i) {
g.add(new ArrayList<>());
}
for (int i = 0; i < m; ++i) {
c(g, rni() - 1, ni() - 1);
}
return g;
}
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// graph util
static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static void pryesno(boolean b) {prln(b ? "yes" : "no");};
static void pryn(boolean b) {prln(b ? "Yes" : "No");}
static void prYN(boolean b) {prln(b ? "YES" : "NO");}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | 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 class Lca {
int lim, t = 0, n;
int[] tin, tout, d;
int[][] up;
public Lca(List<Integer>[] g, int u) {
this.n = g.length;
this.tin = new int[n];
this.tout = new int[n];
this.d = new int[n];
this.lim = 31 - Integer.numberOfLeadingZeros(this.n);
if(Integer.bitCount(this.n) != 1)
++this.lim;
this.up = new int[this.n][this.lim + 1];
dfs(g, u, u, 0);
}
void dfs(List<Integer>[] g, int u, int p, int dep) {
tin[u] = ++t;
up[u][0] = p;
d[u] = dep;
for(int i = 1; i <= lim; ++i)
up[u][i] = up[up[u][i - 1]][i - 1];
for(int v: g[u])
if(v != p)
dfs(g, v, u, dep + 1);
tout[u] = ++t;
}
boolean is_anc(int u, int v) {
return tin[u] <= tin[v] && tout[u] >= tout[v];
}
int lca(int u, int v) {
if(is_anc(u, v))
return u;
if(is_anc(v, u))
return v;
for(int i = lim; i >= 0; --i)
if(!is_anc(up[u][i], v))
u = up[u][i];
return up[u][0];
}
int dis(int u, int v) {
return d[u] + d[v] - 2 * d[lca(u, v)];
}
}
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
List<Integer>[] g = new List[n];
for(int i = 0; i < n; ++i)
g[i] = new ArrayList<Integer>();
for(int i = 1; i < n; ++i) {
int u = in.nextInt() - 1, v = in.nextInt() - 1;
g[u].add(v);
g[v].add(u);
}
Lca lca = new Lca(g, 0);
int q = in.nextInt();
while(q-- > 0) {
int x = in.nextInt() - 1, y = in.nextInt() - 1;
int a = in.nextInt() - 1, b = in.nextInt() - 1;
int k = in.nextInt(), p = lca.dis(a, b);
if(p <= k && p % 2 == k % 2) {
System.out.println("YES");
continue;
}
p = lca.dis(a, x) + lca.dis(b, y) + 1;
if(p <= k && p % 2 == k % 2) {
System.out.println("YES");
continue;
}
p = lca.dis(a, y) + lca.dis(b, x) + 1;
System.out.println(p <= k && p % 2 == k % 2 ? "YES" : "NO");
}
}
} | java |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations. | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] | /*
Rating: 1367
Date: 24-11-2021
Time: 01-24-23
Author: Kartik Papney
Linkedin: https://www.linkedin.com/in/kartik-papney-4951161a6/
Leetcode: https://leetcode.com/kartikpapney/
Codechef: https://www.codechef.com/users/kartikpapney
*/
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class B_Kuroni_and_Simple_Strings {
public static void s() {
ArrayList<Integer> arr = new ArrayList<>();
String s = sc.nextLine();
int start = 0;
int end = s.length()-1;
int cnt = 0;
while(start < end) {
while(start < end && s.charAt(start) == ')') start++;
while(end > start && s.charAt(end) == '(') end--;
if(s.charAt(start) == '(' && s.charAt(end) == ')') {
arr.add(start+1);
arr.add(end+1);
cnt++;
start++;
end--;
}
}
Collections.sort(arr);
if(cnt != 0) {
p.writeln(1);
p.writeln(2*cnt);
for(int val : arr) p.writes(val);
p.writeln();
} else {
p.writeln(0);
}
}
public static void main(String[] args) {
int t = 1;
// t = sc.nextInt();
while (t-- != 0) {
s();
}
p.print();
}
static final Integer MOD = (int) 1e9 + 7;
static final FastReader sc = new FastReader();
static final Print p = new Print();
static class Functions {
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static 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 max(int[] a) {
int max = Integer.MIN_VALUE;
for (int val : a) max = Math.max(val, max);
return max;
}
static int min(int[] a) {
int min = Integer.MAX_VALUE;
for (int val : a) min = Math.min(val, min);
return min;
}
static long min(long[] a) {
long min = Long.MAX_VALUE;
for (long val : a) min = Math.min(val, min);
return min;
}
static long max(long[] a) {
long max = Long.MIN_VALUE;
for (long val : a) max = Math.max(val, max);
return max;
}
static long sum(long[] a) {
long sum = 0;
for (long val : a) sum += val;
return sum;
}
static int sum(int[] a) {
int sum = 0;
for (int val : a) sum += val;
return sum;
}
public static long mod_add(long a, long b) {
return (a % MOD + b % MOD + MOD) % MOD;
}
public static long pow(long a, long b) {
long res = 1;
while (b > 0) {
if ((b & 1) != 0)
res = mod_mul(res, a);
a = mod_mul(a, a);
b >>= 1;
}
return res;
}
public static long mod_mul(long a, long b) {
long res = 0;
a %= MOD;
while (b > 0) {
if ((b & 1) > 0) {
res = mod_add(res, a);
}
a = (2 * a) % MOD;
b >>= 1;
}
return res;
}
public static long gcd(long a, long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
public static long factorial(long n) {
long res = 1;
for (int i = 1; i <= n; i++) {
res = (i % MOD * res % MOD) % MOD;
}
return res;
}
public static int count(int[] arr, int x) {
int count = 0;
for (int val : arr) if (val == x) count++;
return count;
}
public static ArrayList<Integer> generatePrimes(int n) {
boolean[] primes = new boolean[n];
for (int i = 2; i < primes.length; i++) primes[i] = true;
for (int i = 2; i < primes.length; i++) {
if (primes[i]) {
for (int j = i * i; j < primes.length; j += i) {
primes[j] = false;
}
}
}
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < primes.length; i++) {
if (primes[i]) arr.add(i);
}
return arr;
}
}
static class Print {
StringBuffer strb = new StringBuffer();
public void write(Object str) {
strb.append(str);
}
public void writes(Object str) {
char c = ' ';
strb.append(str).append(c);
}
public void writeln(Object str) {
char c = '\n';
strb.append(str).append(c);
}
public void writeln() {
char c = '\n';
strb.append(c);
}
public void writes(int[] arr) {
for (int val : arr) {
write(val);
write(' ');
}
}
public void writes(long[] arr) {
for (long val : arr) {
write(val);
write(' ');
}
}
public void writeln(int[] arr) {
for (int val : arr) {
writeln(val);
}
}
public void print() {
System.out.print(strb);
}
public void println() {
System.out.println(strb);
}
}
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());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
double[] readArrayDouble(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
String nextLine() {
String str = new String();
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | java |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | /*
This code is written by KESHAV DAGA
@keshavkeshu
*/
import java.util.*;
import java.io.*;
public class Main
{
static FastReader in=new FastReader();
static final Random random=new Random();
static int mod=1000000007;
static int inf=Integer.MAX_VALUE;
static int ninf=Integer.MIN_VALUE;
static HashMap<String,Integer>map=new HashMap<>();
static String yes="YES",no="NO";
public static void main(String args[]) throws IOException {
/*
This is main section or the coding part
@keshavkeshu
*/
int t=in.nextInt();
StringBuilder res=new StringBuilder();
while(t-->0)
{
// logic
int n=in.nextInt();
int arr[]=in.ria(2*n);
Arrays.sort(arr);
int ans=arr[n]-arr[n-1];
res.append(ans+"\n");
}
print(res);
}
static int max(int a, int b)
{
if(a<b)
return b;
return a;
}
static int min(int a, int b)
{
if(a>b)
return b;
return a;
}
static long max(long a, long b)
{
if(a<b)
return b;
return a;
}
static long min(long a, long b)
{
if(a>b)
return b;
return a;
}
static int max(int a, int b, int c)
{
if(a>b && a>c)
return a;
else if(b>a && b>c)
return b;
else
return c;
}
static int min(int a, int b, int c)
{
if(a<b && a<c)
return a;
else if(b<a && b<c)
return b;
else
return c;
}
static void ruffleSort(int[] a) {
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 < E > void print(E res)
{
System.out.println(res);
}
static int gcd(int a,int b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static int abs(int a)
{
if(a<0)
return -1*a;
return 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;
}
int [] ria(int n) {
int res [] = new int [n];
for(int i = 0; i<n; i++)res[i] = nextInt();
return res;
}
long [] rla(int n) {
long res [] = new long [n];
for(int i = 0; i<n; i++)res[i] = nextLong();
return res;
}
}
} | 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"
] | import java.util.*;
import java.io.*;
public class _1299_C {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(in.readLine());
StringTokenizer line = new StringTokenizer(in.readLine());
int[] a = new int[n + 1];
long[] psum = new long[n + 1];
Point[] slopes = new Point[n];
for(int i = 1; i <= n; i++) {
a[i] = Integer.parseInt(line.nextToken());
psum[i] = psum[i - 1] + a[i];
slopes[i - 1] = new Point(i, psum[i]);
}
Arrays.sort(slopes);
Stack<Point> points = new Stack<Point>();
points.push(new Point(0, 0));
for(int i = 0; i < n; i++) {
while(points.size() >= 2) {
Point p1 = points.get(points.size() - 2);
Point p2 = points.get(points.size() - 1);
if(orientation(p1, p2, slopes[i]) < 1) {
points.pop();
}else {
break;
}
}
points.push(slopes[i]);
if(slopes[i].x == n) {
break;
}
}
int prev = -1;
for(Point p : points) {
if(prev != -1) {
double avg = (double)(psum[p.x] - psum[prev]) / (p.x - prev);
for(int i = 0; i < p.x - prev; i++) {
out.println(avg);
}
}
prev = p.x;
}
in.close();
out.close();
}
static int orientation(Point a, Point b, Point c) {
double v = a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y);
if(v < 0) {
return -1; //clockwise
}else if(v > 0) {
return 1; //counter-clockwise
}
return 0;
}
static class Point implements Comparable<Point> {
int x;
long y;
double slope;
Point(int xx, long yy) {
x = xx;
y = yy;
if(x != 0) {
slope = (double)y / x;
}
}
@Override
public int compareTo(Point o) {
if(slope > o.slope) {
return 1;
}else if(slope < o.slope) {
return -1;
}
return x - o.x;
}
}
}
| 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.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
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);
BMindControl solver = new BMindControl();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class BMindControl {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
int[] arr = in.nextIntArray(n);
k = Math.min(k, m - 1);
int left = m - 1 - k;
int ans = 0;
for (int i = 0; i <= k; i++) {
int rem = k - i;
int val = Integer.MAX_VALUE;
for (int j = 0; j <= left; j++) {
int x = left - j;
int p1 = i + j;
int p2 = n - 1 - (rem + x);
val = Math.min(val, Math.max(arr[p1], arr[p2]));
}
ans = Math.max(ans, val);
}
out.println(ans);
}
}
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(int i) {
writer.println(i);
}
}
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());
}
}
}
| 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"
] | /*
Author : Akshat Jindal
from NIT Jalandhar , Punjab , India
JAI MATA DI
*/
import java.util.*;
import javax.swing.text.Segment;
import java.io.*;
import java.math.*;
import java.sql.Array;
public class Main {
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static void rvrs(int[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static void rvrs(long[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long mod_mul(long a , long b ,long mod) {
return ((a%mod)*(b%mod))%mod;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2, m);
}
static long power(long x, long y, long m){
if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z;
private long[] z1;
private long[] z2;
public Combinations(long N , long mod) {
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return invrsFac((int)n);
}
long ncr(long N, long R, long mod)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.min(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
/**
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = Math.min(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(1e17);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return Math.min(left, right);
}
public void update(int index , int val) {
arr[index] = val;
for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
*/
/* ***************************************************************************************************************************************************/
static Scanner sc = new Scanner();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
tc = sc.nextInt();
for(int i = 1 ; i<=tc ; i++) {
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.println(sb);
}
static void TEST_CASE() {
long a = sc.nextLong() , m = sc.nextLong();
long s = a , e = a + m-1;
ArrayList<Long> al = new ArrayList<>();
for(long i = 1 ; i*i <= m ; i++) {
if(m%i == 0) {
if(m/i != i) {
al.add(i);
al.add(m/i);
}else {
al.add(i);
}
}
}
Collections.sort(al);
int n = al.size();
// System.out.println(al);
// System.out.println(s+" "+e);
long[] dp = new long[n];
for(int i = n-1 ; i>=0 ; i--) {
long num = al.get(i);
long sub = 0;
for(int j =i+1 ; j<n ; j++) {
long v = al.get(j);
if(v%num == 0) sub += dp[j];
}
long add = e/num - (s-1)/num;
dp[i] = add - sub;
// System.out.println("------");
// System.out.println(i+" "+num+" "+dp[i]);
}
long gcd = gcd(a, m);
for(int i =0 ; i < n ;i++) {
if(al.get(i) == gcd) {
sb.append(dp[i]+"\n");
return;
}
}
}
}
/*******************************************************************************************************************************************************/
/**
Given a and m
gcd(a , m) == gcd(a+x , m)
0 <= x < m 1 <= a < m <= 1e10
12 , 30 - > 6
a - > [12 , 42)
*/
| java |
1304 | C | C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied. | [
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] |
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 = fastReader.nextInt();
while (t-- > 0) {
int n = fastReader.nextInt();
long m = fastReader.nextLong();
ArrayList<Pairs> list = new ArrayList<>();
boolean ans = true;
for (int i = 0; i < n; i++) {
int time = fastReader.nextInt();
int l = fastReader.nextInt();
int r = fastReader.nextInt();
list.add(new Pairs(time, l, r));
}
long l = m;
long r = m;
long prev = 0;
for (int i = 0; i < n; i++) {
long time = list.get(i).t;
r += time - prev;
l -= time - prev;
if (list.get(i).l > r || list.get(i).r < l) {
ans = false;
}
l = max(l,list.get(i).l);
r = min(r,list.get(i).r);
prev = time;
}
out.println(ans ? "YES" : "NO");
}
out.close();
}
static class Pairs {
int t;
int l;
int r;
Pairs(int t, int l, int r) {
this.l = l;
this.t = t;
this.r = r;
}
}
// 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 |
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.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
{
public static void solve(int testNumber, InputReader in, OutputWriter out)
{
//int t = in.ni();
int t=1;
while (t-->0)
{
int n=in.ni();
char[] ch=in.ns().toCharArray();
int ans=0,cnt=0,s=-1;
for(int i=0;i<n;i++)
{
if(ch[i]=='(')
{
++cnt;
}
else
{
--cnt;
}
if(cnt<0)
{
if(s==-1)
{
s=i;
}
}
else if(cnt==0)
{
if(s!=-1)
{
ans+=(i-s)+1;
s=-1;
}
}
}
if(cnt!=0 || s!=-1)
{
out.printLine(-1);
}
else
{
out.printLine(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 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,Integer> sortIntMapDesc(HashMap<Integer,Integer> map) {
List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) ->(int) (o2.getValue() - o1.getValue()));
HashMap<Integer,Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Integer,Integer> 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 |
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 c1296;
//
// Codeforces Round #617 (Div. 3) 2020-02-04 06:35
// C. Yet Another Walking Robot
// https://codeforces.com/contest/1296/problem/C
// time limit per test 1 second; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There is a robot on a coordinate plane. Initially, the robot is located at the point (0, 0). Its
// path is described as a string s of length n 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) to the point (x - 1, y);
// * 'R' (right): means that the robot moves from the point (x, y) to the point (x + 1, y);
// * 'U' (up): means that the robot moves from the point (x, y) to the point (x, y + 1);
// * 'D' (down): means that the robot moves from the point (x, y) to the point (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 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 (x_e, y_e), then after optimization (i.e. removing some single substring from s) the
// robot also ends its path at the point (x_e, y_e).
//
// This optimization is a low-budget project so you need to remove possible 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 s).
//
// Recall that the substring of s is such string that can be obtained from s 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 t independent test cases.
//
// Input
//
// The first line of the input contains one integer t (1 <= t <= 1000) -- the number of test cases.
//
// The next 2t lines describe test cases. Each test case is given on two lines. The first line of
// the test case contains one integer n (1 <= n <= 2 * 10^5) -- the length of the robot's path. The
// second line of the test case contains one string s consisting of n characters 'L', 'R', 'U', 'D'
// -- the robot's path.
//
// It is guaranteed that the sum of n over all test cases does not exceed 2 * 10^5 (\sum n <= 2 *
// 10^5).
//
// Output
//
// For each test case, print the answer on it. If you cannot remove such substring that the endpoint
// of the robot's path doesn't change, print -1. Otherwise, print two integers l and r such that 1
// <= l <= r <= n -- endpoints of the substring you remove. The value r-l+1 should be minimum
// possible. If there are several answers, print any of them.
//
// Example
/*
input:
4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
output:
1 2
1 4
3 4
-1
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
public class C1296C {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int[] solve(String s) {
int n = s.length();
int[] ans = new int[2];
Map<Long, Integer> sim = new HashMap<>();
sim.put(0L, 0);
int x = 0;
int y = 0;
int mind = -1;
for (int i = 1; i <= n; i++) {
char ch = s.charAt(i-1);
if (ch == 'L') {
x--;
} else if (ch == 'R') {
x++;
} else if (ch == 'U') {
y++;
} else if (ch == 'D') {
y--;
}
long key = ((long)x << 18) + y;
if (sim.containsKey(key)) {
int d = i - sim.get(key);
if (mind < 0 || d < mind) {
mind = d;
ans[0] = sim.get(key) + 1;
ans[1] = i;
}
}
sim.put(key, i);
}
return mind < 0 ? null : ans;
}
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();
String s = in.next();
int[] ans = solve(s);
if (ans == null) {
System.out.println("-1");
} else {
System.out.format("%d %d\n", ans[0], ans[1]);
}
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
System.out.format("%d %d\n", a[0], a[1]);
}
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 |
1310 | D | D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8
0 1 2 2 0
0 0 1 1 2
0 1 0 0 0
2 1 1 0 0
2 0 1 2 0
OutputCopy2
InputCopy3 2
0 1 1
2 0 1
2 2 0
OutputCopy3
| [
"dp",
"graphs",
"probabilities"
] | 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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class C1310D {
public static void main(String[] args) {
var scanner = new BufferedScanner();
var writer = new PrintWriter(new BufferedOutputStream(System.out));
var n = scanner.nextInt();
var k = scanner.nextInt();
var f = new int[n][n][k + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
f[i][j][1] = scanner.nextInt();
}
f[i][i][1] = Integer.MAX_VALUE;
}
var mid = new int[n][n][k + 1][2];
for (int k0 = 2; k0 <= k; k0++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
f[i][j][k0] = Integer.MAX_VALUE;
if (i == j && k0 % 2 == 1) {
continue;
}
for (int m = 0; m < n; m++) {
for (int k1 = 1; k1 < k0; k1++) {
int part1 = f[i][m][k1];
if (part1 == Integer.MAX_VALUE) {
continue;
}
var k2 = k0 - k1;
int part2 = f[m][j][k2];
if (part2 == Integer.MAX_VALUE) {
continue;
}
if (part1 + part2 < f[i][j][k0] && noOddCycle2(i, j, m, k1, k2, mid)) {
f[i][j][k0] = part1 + part2;
mid[i][j][k0] = new int[]{m, k1};
}
// f[i][j][k0] = Math.min(f[i][j][k0], part1 + part2);
}
}
}
}
}
writer.println(f[0][0][k]);
// printPath(0, 0, k, mid);
// System.out.println(1);
scanner.close();
writer.flush();
writer.close();
}
private static boolean noOddCycle(int i, int j, int m, int k1, int k2, int[][][][] mid) {
var path = new ArrayList<Integer>();
collectPath(i, m, k1, mid, path);
collectPath(m, j, k2, mid, path);
path.add(j);
var latest = new HashMap<Integer, Integer>();
for (int index = 0; index < path.size(); index++) {
var each = path.get(index);
var prev = latest.get(each);
if (prev == null) {
latest.put(each, index);
} else {
if (((index - prev) & 1) != 0) {
return false;
}
}
}
return true;
}
private static boolean noOddCycle2(int i, int j, int m, int k1, int k2, int[][][][] mid) {
var path1 = new ArrayList<Integer>();
collectPath(i, m, k1, mid, path1);
var latest = new HashMap<Integer, Integer>();
for (int index = 0; index < path1.size(); index++) {
var each = path1.get(index);
latest.put(each, index);
}
var path2 = new ArrayList<Integer>();
collectPath(m, j, k2, mid, path2);
path2.add(j);
for (int index = 0; index < path2.size(); index++) {
var each = path2.get(index);
var prev = latest.get(each);
if (prev != null && ((index + k1 - prev) & 1) != 0) {
return false;
}
}
return true;
}
/**
* 如果k1是偶数,那么path1和path2中相同点所处的index的奇偶性要相同相同;否则要不同。
* <p>
* 可以用80位二进制数来表示路径上的出现点的下标奇偶性。
*/
private static boolean noOddCycle3(int i, int j, int m, int k1, int k2, int[][][][] mid) {
var path1 = new ArrayList<Integer>();
collectPath(i, m, k1, mid, path1);
var latest = new HashMap<Integer, Integer>();
for (int index = 0; index < path1.size(); index++) {
var each = path1.get(index);
latest.put(each, index);
}
var path2 = new ArrayList<Integer>();
collectPath(m, j, k2, mid, path2);
path2.add(j);
for (int index = 0; index < path2.size(); index++) {
var each = path2.get(index);
var prev = latest.get(each);
if (prev != null && ((index + k1 - prev) & 1) != 0) {
return false;
}
}
return true;
}
static Map<Integer, List<Integer>> paths = new HashMap<>();
private static void collectPath(int i, int j, int k, int[][][][] mid, List<Integer> path) {
if (k == 1) {
path.add(i);
return;
}
var hash = (i * 81 + j) * 81 + k;
var cache = paths.get(hash);
if (cache != null) {
path.addAll(cache);
return;
}
var m = mid[i][j][k][0];
var k1 = mid[i][j][k][1];
var k2 = k - k1;
var part = new ArrayList<Integer>();
collectPath(i, m, k1, mid, part);
collectPath(m, j, k2, mid, part);
paths.put(hash, part);
path.addAll(part);
}
private static void printPath(int i, int j, int k, int[][][][] mid) {
// System.out.println(i + " " + j + " " + k);
if (k == 1) {
System.out.print((i + 1) + "->");
return;
}
var m = mid[i][j][k][0];
var k1 = mid[i][j][k][1];
var k2 = k - k1;
printPath(i, m, k1, mid);
printPath(m, j, k2, mid);
}
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 |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | //package com.rajan.codeforces.level_1400;
import java.io.*;
import java.util.Arrays;
public class JourneyPlanning {
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 n = Integer.parseInt(reader.readLine());
int[] a = new int[n];
String[] temp = reader.readLine().split("\\s+");
int[][] d = new int[n][];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(temp[i]);
d[i] = new int[]{a[i] - i, a[i]};
}
Arrays.sort(d, (x, y) -> Integer.compare(x[0], y[0]));
long ans = 0L;
for (int i = 0; i < n; ) {
int t = d[i][0];
int j = i;
long sum = 0L;
while (j < n && d[j][0] == d[i][0]) {
sum += d[j][1];
j++;
}
i = j;
ans = Math.max(ans, sum);
}
writer.write(ans + "\n");
writer.flush();
}
}
| 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 t = input.nextInt();
for(int i = 0; i < t; i++)
{
int a = input.nextInt();
int b = input.nextInt();
if(a < b)
{
if((b - a) % 2 == 0){
System.out.println(2);
}
else{
System.out.println(1);
}
}
else if(a > b)
{
if((a - b) % 2 == 0){
System.out.println(1);
}
else{
System.out.println(2);
}
}
else
{
System.out.println(0);
}
}
}
}
| 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 TwoArrays {
static int n,m;
static long[][] memo;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
m=sc.nextInt();
int arr[]=new int[2*m];
memo=new long[n+1][(2*m)+1];
for(int i=0;i<=n;i++) {
for(int j=0;j<=2*m;j++) {
memo[i][j]=-1;
}
}
// System.out.println(Arrays.deepToString(memo));
System.out.println(count(0,0,arr));
// System.out.println(Arrays.deepToString(memo));
}
public static long count(int num,int pos,int[] arr) {
// System.out.println(num+" "+" "+pos);
if(memo[num][pos]==-1) {
long ans=0;
if(pos==2*m) {
return 1;
}
for(int i=1;i<=n;i++) {
if(i>=num) {
ans=(ans+count(i,pos+1,arr))%1000000007;
}
}
return memo[num][pos]=ans;
}
return memo[num][pos];
}
}
| java |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations. | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] |
import java.io.*;
import java.util.*;
public class Main {
public static void solve(IO io) {
String s = io.getWord();
ArrayList<Integer> left = new ArrayList<>();
ArrayList<Integer> right = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
left.add(i);
}
}
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ')') {
right.add(i);
}
}
int i = 0;
ArrayList<Integer> ans = new ArrayList<>();
while (i < left.size() && i < right.size() && left.get(i) <= right.get(i)) {
ans.add(left.get(i));
ans.add(right.get(i));
i++;
}
if (i == 0) {
System.out.println(0);
return;
}
Collections.sort(ans);
System.out.println(1);
System.out.println(ans.size());
for (int j:ans) {
System.out.print((j + 1) + " ");
}
System.out.println();
}
public static void main(String[] args) {
IO io = new IO();
solve(io);
io.close();
}
static class IO extends PrintWriter {
public IO() {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(System.in));
}
public IO(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public IO(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int getInt() {
return Integer.parseInt(nextToken());
}
public double getDouble() {
return Double.parseDouble(nextToken());
}
public long getLong() {
return Long.parseLong(nextToken());
}
public String getWord() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
}
| 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.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.List;
import java.util.ArrayList;
public class Solution {
static int n, m;
static int[][] arrays;
static int[][][] memo;
static int[] depends;
static int mp;
public static void main(String[] args) throws IOException {
Reader input = new Reader();
n = input.nextInt();
m = input.nextInt();
arrays = new int[n][m];
int max = 0;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
arrays[i][j] = input.nextInt();
if(arrays[i][j] > max) max = arrays[i][j];
}
}
mp = (int)Math.pow(2, m);
int left = 0, right = max+1, middle, i = 0, j = 0;
while(left < right) {
middle = left+right>>1;
int[] a = solve(middle);
if(a != null) {
i = a[0];
j = a[1];
left = middle+1;
} else {
right = middle;
}
}
System.out.print(i+1 + " " + (j+1));
}
static int[] solve(int x) {
boolean[] set = new boolean[mp];
List<Integer>[] d = new List[mp];
for(int i = 0; i < mp; ++i) d[i] = new ArrayList<Integer>();
for(int i = 0; i < n; ++i) {
int t = 0;
for(int j = 0; j < m; ++j) {
int mask = (1 << j);
if(arrays[i][j] >= x) {
t |= mask;
}
}
set[t] = true;
d[t].add(i);
}
for(int i = 0; i < mp; ++i) {
if(!set[i]) continue;
for(int j = 0; j < mp; ++j) {
if(!set[j]) continue;
if((i|j) == mp-1) {
return new int[]{d[i].get(0), d[j].get(0)};
}
}
}
return null;
}
static class Reader {
BufferedReader bufferedReader;
StringTokenizer string;
public Reader() {
InputStreamReader inr = new InputStreamReader(System.in);
bufferedReader = new BufferedReader(inr);
}
public String next() throws IOException {
while(string == null || ! string.hasMoreElements()) {
string = new StringTokenizer(bufferedReader.readLine());
}
return string.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public String nextLine() throws IOException {
return bufferedReader.readLine();
}
}
} | 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.*;
public class Main {
public static void mergeSort(int[] array) {
if (array == null) {
return;
}
if (array.length > 1) {
int mid = array.length / 2;
// Split left part
int[] left = new int[mid];
for (int i = 0; i < mid; i++) {
left[i] = array[i];
}
// Split right part
int[] right = new int[array.length - mid];
for (int i = mid; i < array.length; i++) {
right[i - mid] = array[i];
}
mergeSort(left);
mergeSort(right);
int i = 0;
int j = 0;
int k = 0;
// Merge left and right arrays
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
array[k] = left[i];
i++;
} else {
array[k] = right[j];
j++;
}
k++;
}
// Collect remaining elements
while (i < left.length) {
array[k] = left[i];
i++;
k++;
}
while (j < right.length) {
array[k] = right[j];
j++;
k++;
}
}
}
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-1);
int last= 200000;
int [] arr= new int[n];
arr[n-1]=last;
int min=last;
for (int i=n-2;i>=0;i--) {
arr[i]=arr[i+1]-a[i];
min=Math.min(min, arr[i]);
}
for (int i=0;i<n;i++) {
arr[i]-=(min-1);
//pw.println(arr[i]);
}
int[] newArr=arr.clone();
mergeSort(newArr);
boolean flag= true;
for (int i=0;i<n;i++) {
if(newArr[i]-1!=i) {
pw.println(-1);
flag= false;
break;
}
}
if(flag) {
for (int i=0;i<n;i++)
pw.print(arr[i]+" ");
}
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 |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | 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)
{
int n=sc.nextInt();
int a[]=new int[n];
HashMap<Integer,Long> map=new HashMap<>();
int i,j; long ans=0;
for(i=0;i<n;i++)
a[i]=sc.nextInt();
for(i=0;i<n;i++)
map.put(a[i]-i,map.getOrDefault(a[i]-i,0L)+(long)a[i]);
for(Integer it:map.keySet())
ans=Math.max(map.get(it),ans);
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 |
1324 | B | B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.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.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes. | [
"brute force",
"strings"
] | 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>> C2 = Comparator.comparing(x -> x.second);
static Comparator<Pair<Integer, Integer>> C1 = Comparator.comparing(x -> x.first);
static Comparator<Pair<Integer, Integer>> D1 = Comparator.comparing(x -> x.first);
static Comparator<Pair<Integer, Integer>> D2 = Comparator.comparing(x -> x.second);
static long MOD = 1_000_000_000 + 7;
static String alpha = "abcdefghijklmnopqrstuvwxyz";
static Set<Long> seen = new HashSet<>();
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
int t = in.nextInt();
while (t-- > 0) {
solve();
}
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms");
exit(0);
}
static void solve() {
int n = in.nextInt();
int[] data = in.readAllInts(n);
for (int i = 0; i < n; i++) {
for (int j = i + 2; j < n; j++) {
if (data[i] == data[j]) {
y();
return;
}
}
}
n();
}
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(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;
} else if (data[mid] >= num) {
high = mid - 1;
ans = mid;
}
}
if (ans == -1) {
return 100000000;
}
return data[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;
}
}
return ans + 1;
}
}
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 |
13 | E | E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3 | [
"data structures",
"dsu"
] | import java.util.*;
import java.io.*;
public class EHoles2 {
// static InputReader in = new InputReader();
static OutputWriter out = new OutputWriter(System.out);
static int[] getArr(String s) {
String[] st = s.split(" ");
int ar[] = new int[st.length];
for (int i = 0; i < ar.length; i++)
ar[i] = Integer.parseInt(st[i]);
return ar;
}
public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int[] ar = getArr(read.readLine());
int N = ar[0];
int Q = ar[1];
int pow[] = getArr(read.readLine());
int sqrt = (int) Math.sqrt(pow.length);
int next[] = new int[pow.length];
int ans[] = new int[pow.length];
int last[] = new int[pow.length];
for (int i = pow.length - 1; i >= 0; i--) {
int nextt = i + pow[i];
int nextfac = (i / sqrt + 1) * sqrt;
if (nextt >= N) {
next[i] = nextt;
ans[i] = 1;
last[i] = i;
} else {
next[i] = nextt >= nextfac ? nextt : next[nextt];
ans[i] = 1 + (nextt < nextfac ? ans[nextt] : 0);
last[i] = last[nextt];
}
}
while (Q-- > 0) {
int arg[] = getArr(read.readLine());
if (arg[0] == 0) {
int hole = arg[1] - 1;
int newpower = arg[2];
pow[hole] = newpower;
int myfac = (hole / sqrt) * sqrt;
while (hole >= myfac) {
int i = hole;
int nextt = i + pow[i];
int nextfac = (hole / sqrt + 1) * sqrt;
if (nextt >= N) {
next[i] = nextt;
ans[i] = 1;
last[i] = i;
} else {
next[i] = nextt >= nextfac ? nextt : next[nextt];
ans[i] = 1 + (nextt < nextfac ? ans[nextt] : 0);
last[i] = last[nextt];
}
hole--;
}
} else {
// 1 hole
int hole = arg[1] - 1;
int curr = hole;
int jumps = ans[curr];
while (next[curr] < N) {
curr = next[curr];
jumps += ans[curr];
}
if (curr + pow[curr] < N) {
// jumps -= ans[curr];
while (curr + pow[curr] < N) {
curr += pow[curr];
// jumps++;
}
}
out.printLine((curr + 1) + " " + jumps);
}
}
// in.close();
out.flush();
out.close();
}
private static class InputReader implements AutoCloseable {
private static final int DEFAULT_BUFFER_SIZE = 1 << 16;
private static final InputStream DEFAULT_STREAM = System.in;
private static final int MAX_DECIMAL_PRECISION = 21;
private int c;
private final byte[] buf;
private final int bufferSize;
private int bufIndex;
private int numBytesRead;
private final InputStream stream;
// End Of File (EOF) character
private static final byte EOF = -1;
// New line character: '\n'
private static final byte NEW_LINE = 10;
// Space character: ' '
private static final byte SPACE = 32;
// Dash character: '-'
private static final byte DASH = 45;
// Dot character: '.'
private static final byte DOT = 46;
// A reusable character buffer when reading string data.
private char[] charBuffer;
// Primitive data type lookup tables used for optimizations
private static final byte[] bytes = new byte[58];
private static final int[] ints = new int[58];
private static final char[] chars = new char[128];
static {
char ch = ' ';
int value = 0;
byte _byte = 0;
for (int i = 48; i < 58; i++)
bytes[i] = _byte++;
for (int i = 48; i < 58; i++)
ints[i] = value++;
for (int i = 32; i < 128; i++)
chars[i] = ch++;
}
private static final double[][] doubles = {
{ 0.0d, 0.00d, 0.000d, 0.0000d, 0.00000d, 0.000000d, 0.0000000d, 0.00000000d, 0.000000000d,
0.0000000000d, 0.00000000000d, 0.000000000000d, 0.0000000000000d, 0.00000000000000d,
0.000000000000000d, 0.0000000000000000d, 0.00000000000000000d, 0.000000000000000000d,
0.0000000000000000000d, 0.00000000000000000000d, 0.000000000000000000000d },
{ 0.1d, 0.01d, 0.001d, 0.0001d, 0.00001d, 0.000001d, 0.0000001d, 0.00000001d, 0.000000001d,
0.0000000001d, 0.00000000001d, 0.000000000001d, 0.0000000000001d, 0.00000000000001d,
0.000000000000001d, 0.0000000000000001d, 0.00000000000000001d, 0.000000000000000001d,
0.0000000000000000001d, 0.00000000000000000001d, 0.000000000000000000001d },
{ 0.2d, 0.02d, 0.002d, 0.0002d, 0.00002d, 0.000002d, 0.0000002d, 0.00000002d, 0.000000002d,
0.0000000002d, 0.00000000002d, 0.000000000002d, 0.0000000000002d, 0.00000000000002d,
0.000000000000002d, 0.0000000000000002d, 0.00000000000000002d, 0.000000000000000002d,
0.0000000000000000002d, 0.00000000000000000002d, 0.000000000000000000002d },
{ 0.3d, 0.03d, 0.003d, 0.0003d, 0.00003d, 0.000003d, 0.0000003d, 0.00000003d, 0.000000003d,
0.0000000003d, 0.00000000003d, 0.000000000003d, 0.0000000000003d, 0.00000000000003d,
0.000000000000003d, 0.0000000000000003d, 0.00000000000000003d, 0.000000000000000003d,
0.0000000000000000003d, 0.00000000000000000003d, 0.000000000000000000003d },
{ 0.4d, 0.04d, 0.004d, 0.0004d, 0.00004d, 0.000004d, 0.0000004d, 0.00000004d, 0.000000004d,
0.0000000004d, 0.00000000004d, 0.000000000004d, 0.0000000000004d, 0.00000000000004d,
0.000000000000004d, 0.0000000000000004d, 0.00000000000000004d, 0.000000000000000004d,
0.0000000000000000004d, 0.00000000000000000004d, 0.000000000000000000004d },
{ 0.5d, 0.05d, 0.005d, 0.0005d, 0.00005d, 0.000005d, 0.0000005d, 0.00000005d, 0.000000005d,
0.0000000005d, 0.00000000005d, 0.000000000005d, 0.0000000000005d, 0.00000000000005d,
0.000000000000005d, 0.0000000000000005d, 0.00000000000000005d, 0.000000000000000005d,
0.0000000000000000005d, 0.00000000000000000005d, 0.000000000000000000005d },
{ 0.6d, 0.06d, 0.006d, 0.0006d, 0.00006d, 0.000006d, 0.0000006d, 0.00000006d, 0.000000006d,
0.0000000006d, 0.00000000006d, 0.000000000006d, 0.0000000000006d, 0.00000000000006d,
0.000000000000006d, 0.0000000000000006d, 0.00000000000000006d, 0.000000000000000006d,
0.0000000000000000006d, 0.00000000000000000006d, 0.000000000000000000006d },
{ 0.7d, 0.07d, 0.007d, 0.0007d, 0.00007d, 0.000007d, 0.0000007d, 0.00000007d, 0.000000007d,
0.0000000007d, 0.00000000007d, 0.000000000007d, 0.0000000000007d, 0.00000000000007d,
0.000000000000007d, 0.0000000000000007d, 0.00000000000000007d, 0.000000000000000007d,
0.0000000000000000007d, 0.00000000000000000007d, 0.000000000000000000007d },
{ 0.8d, 0.08d, 0.008d, 0.0008d, 0.00008d, 0.000008d, 0.0000008d, 0.00000008d, 0.000000008d,
0.0000000008d, 0.00000000008d, 0.000000000008d, 0.0000000000008d, 0.00000000000008d,
0.000000000000008d, 0.0000000000000008d, 0.00000000000000008d, 0.000000000000000008d,
0.0000000000000000008d, 0.00000000000000000008d, 0.000000000000000000008d },
{ 0.9d, 0.09d, 0.009d, 0.0009d, 0.00009d, 0.000009d, 0.0000009d, 0.00000009d, 0.000000009d,
0.0000000009d, 0.00000000009d, 0.000000000009d, 0.0000000000009d, 0.00000000000009d,
0.000000000000009d, 0.0000000000000009d, 0.00000000000000009d, 0.000000000000000009d,
0.0000000000000000009d, 0.00000000000000000009d, 0.000000000000000000009d } };
public InputReader() {
this(DEFAULT_STREAM, DEFAULT_BUFFER_SIZE);
}
public InputReader(int bufferSize) {
this(DEFAULT_STREAM, bufferSize);
}
public InputReader(InputStream stream) {
this(stream, DEFAULT_BUFFER_SIZE);
}
public InputReader(InputStream stream, int bufferSize) {
if (stream == null || bufferSize <= 0)
throw new IllegalArgumentException();
buf = new byte[bufferSize];
charBuffer = new char[128];
this.bufferSize = bufferSize;
this.stream = stream;
}
private byte read() throws IOException {
if (numBytesRead == EOF)
throw new IOException();
if (bufIndex >= numBytesRead) {
bufIndex = 0;
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return EOF;
}
return buf[bufIndex++];
}
private int readJunk(int token) throws IOException {
if (numBytesRead == EOF)
return EOF;
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > token)
return 0;
bufIndex++;
}
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return EOF;
bufIndex = 0;
} while (true);
}
public byte nextByte() throws IOException {
return (byte) nextInt();
}
public int nextInt() throws IOException {
if (readJunk(DASH - 1) == EOF)
throw new IOException();
int sgn = 1, res = 0;
c = buf[bufIndex];
if (c == DASH) {
sgn = -1;
bufIndex++;
}
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > SPACE) {
res = (res << 3) + (res << 1);
res += ints[buf[bufIndex++]];
} else {
bufIndex++;
return res * sgn;
}
}
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return res * sgn;
bufIndex = 0;
} while (true);
}
public long nextLong() throws IOException {
if (readJunk(DASH - 1) == EOF)
throw new IOException();
int sgn = 1;
long res = 0L;
c = buf[bufIndex];
if (c == DASH) {
sgn = -1;
bufIndex++;
}
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > SPACE) {
res = (res << 3) + (res << 1);
res += ints[buf[bufIndex++]];
} else {
bufIndex++;
return res * sgn;
}
}
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return res * sgn;
bufIndex = 0;
} while (true);
}
private void doubleCharBufferSize() {
char[] newBuffer = new char[charBuffer.length << 1];
for (int i = 0; i < charBuffer.length; i++)
newBuffer[i] = charBuffer[i];
charBuffer = newBuffer;
}
public String nextLine() throws IOException {
try {
c = read();
} catch (IOException e) {
return null;
}
if (c == NEW_LINE)
return ""; // Empty line
if (c == EOF)
return null; // EOF
int i = 0;
charBuffer[i++] = (char) c;
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] != NEW_LINE) {
if (i == charBuffer.length)
doubleCharBufferSize();
charBuffer[i++] = (char) buf[bufIndex++];
} else {
bufIndex++;
return new String(charBuffer, 0, i);
}
}
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return new String(charBuffer, 0, i);
bufIndex = 0;
} while (true);
}
public String nextString() throws IOException {
if (numBytesRead == EOF)
return null;
if (readJunk(SPACE) == EOF)
return null;
for (int i = 0;;) {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > SPACE) {
if (i == charBuffer.length)
doubleCharBufferSize();
charBuffer[i++] = (char) buf[bufIndex++];
} else {
bufIndex++;
return new String(charBuffer, 0, i);
}
}
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return new String(charBuffer, 0, i);
bufIndex = 0;
}
}
public double nextDouble() throws IOException {
String doubleVal = nextString();
if (doubleVal == null)
throw new IOException();
return Double.valueOf(doubleVal);
}
public double nextDoubleFast() throws IOException {
c = read();
int sgn = 1;
while (c <= SPACE)
c = read(); // while c is either: ' ', '\n', EOF
if (c == DASH) {
sgn = -1;
c = read();
}
double res = 0.0;
while (c > DOT) {
res *= 10.0;
res += ints[c];
c = read();
}
if (c == DOT) {
int i = 0;
c = read();
while (c > SPACE && i < MAX_DECIMAL_PRECISION) {
res += doubles[ints[c]][i++];
c = read();
}
}
return res * sgn;
}
public byte[] nextByteArray(int n) throws IOException {
byte[] ar = new byte[n];
for (int i = 0; i < n; i++)
ar[i] = nextByte();
return ar;
}
public int[] nextIntArray(int n) throws IOException {
int[] ar = new int[n];
for (int i = 0; i < n; i++)
ar[i] = nextInt();
return ar;
}
public long[] nextLongArray(int n) throws IOException {
long[] ar = new long[n];
for (int i = 0; i < n; i++)
ar[i] = nextLong();
return ar;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] ar = new double[n];
for (int i = 0; i < n; i++)
ar[i] = nextDouble();
return ar;
}
public double[] nextDoubleArrayFast(int n) throws IOException {
double[] ar = new double[n];
for (int i = 0; i < n; i++)
ar[i] = nextDoubleFast();
return ar;
}
public String[] nextStringArray(int n) throws IOException {
String[] ar = new String[n];
for (int i = 0; i < n; i++) {
String str = nextString();
if (str == null)
throw new IOException();
ar[i] = str;
}
return ar;
}
public byte[] nextByteArray1(int n) throws IOException {
byte[] ar = new byte[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextByte();
return ar;
}
public int[] nextIntArray1(int n) throws IOException {
int[] ar = new int[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextInt();
return ar;
}
public long[] nextLongArray1(int n) throws IOException {
long[] ar = new long[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextLong();
return ar;
}
public double[] nextDoubleArray1(int n) throws IOException {
double[] ar = new double[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextDouble();
return ar;
}
public double[] nextDoubleArrayFast1(int n) throws IOException {
double[] ar = new double[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextDoubleFast();
return ar;
}
public String[] nextStringArray1(int n) throws IOException {
String[] ar = new String[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextString();
return ar;
}
public byte[][] nextByteMatrix(int rows, int cols) throws IOException {
byte[][] matrix = new byte[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextByte();
return matrix;
}
public int[][] nextIntMatrix(int rows, int cols) throws IOException {
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextInt();
return matrix;
}
public long[][] nextLongMatrix(int rows, int cols) throws IOException {
long[][] matrix = new long[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextLong();
return matrix;
}
public double[][] nextDoubleMatrix(int rows, int cols) throws IOException {
double[][] matrix = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextDouble();
return matrix;
}
public double[][] nextDoubleMatrixFast(int rows, int cols) throws IOException {
double[][] matrix = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextDoubleFast();
return matrix;
}
public String[][] nextStringMatrix(int rows, int cols) throws IOException {
String[][] matrix = new String[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextString();
return matrix;
}
public byte[][] nextByteMatrix1(int rows, int cols) throws IOException {
byte[][] matrix = new byte[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextByte();
return matrix;
}
public int[][] nextIntMatrix1(int rows, int cols) throws IOException {
int[][] matrix = new int[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextInt();
return matrix;
}
public long[][] nextLongMatrix1(int rows, int cols) throws IOException {
long[][] matrix = new long[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextLong();
return matrix;
}
public double[][] nextDoubleMatrix1(int rows, int cols) throws IOException {
double[][] matrix = new double[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextDouble();
return matrix;
}
public double[][] nextDoubleMatrixFast1(int rows, int cols) throws IOException {
double[][] matrix = new double[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextDoubleFast();
return matrix;
}
public String[][] nextStringMatrix1(int rows, int cols) throws IOException {
String[][] matrix = new String[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextString();
return matrix;
}
public void close() throws IOException {
stream.close();
}
}
private static class OutputWriter implements AutoCloseable {
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();
}
}
} | java |
13 | E | E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3 | [
"data structures",
"dsu"
] | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Holes {
public static void main(String[] args) throws IOException {
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
Solution sol = new Solution();
sol.solve(log);
log.close();
}
}
class Solution {
int blk_sz;
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 {
if (st.hasMoreTokens()) {
str = st.nextToken("\n");
} else {
str = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
private boolean check(int i, int j) {
return (i / blk_sz) == (j / blk_sz);
}
public void solve(BufferedWriter log) throws IOException {
FastReader fr = new FastReader();
int n = fr.nextInt();
int m = fr.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = fr.nextInt();
int[] jumps = new int[n];
int[] next = new int[n];
int[] last = new int[n];
blk_sz = (int) Math.round(Math.sqrt(n));
for (int i = n - 1; i >= 0; i--) {
if ((i + arr[i]) >= n) {
jumps[i] = 1;
next[i] = -1;
last[i] = i;
} else if (check(i, i + arr[i])) {
jumps[i] = jumps[i + arr[i]] + 1;
next[i] = next[i + arr[i]];
last[i] = last[i + arr[i]];
} else {
jumps[i] = 1;
next[i] = i + arr[i];
last[i] = i;
}
}
// block_start[i] = Starting index of block to which i belongs to
int[] block_start = new int[n];
block_start[0] = 0;
for (int i = 1; i < n; i++) {
if (check(i, i - 1)) {
block_start[i] = block_start[i - 1];
} else {
block_start[i] = i;
}
}
for (int i = 0; i < m; i++) {
int type = fr.nextInt();
if (type == 0) {
// update
int idx = fr.nextInt();
idx--;
int val = fr.nextInt();
arr[idx] = val;
int beg = block_start[idx];
while (idx >= beg) {
if ((idx + arr[idx]) >= n) {
jumps[idx] = 1;
next[idx] = -1;
last[idx] = idx;
} else if (check(idx, idx + arr[idx])) {
jumps[idx] = jumps[idx + arr[idx]] + 1;
next[idx] = next[idx + arr[idx]];
last[idx] = last[idx + arr[idx]];
} else {
jumps[idx] = 1;
next[idx] = idx + arr[idx];
last[idx] = idx;
}
idx--;
}
} else {
// query
int idx = fr.nextInt();
idx--;
int numJumps = 0, lastIndex = -1;
while (idx != -1) {
numJumps += jumps[idx];
lastIndex = last[idx];
idx = next[idx];
}
lastIndex++;
log.write(lastIndex + " " + numJumps + "\n");
}
}
}
} | java |
1284 | E | E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213 | [
"combinatorics",
"geometry",
"math",
"sortings"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedOutputStream;
import java.io.UncheckedIOException;
import java.util.Objects;
import java.nio.charset.Charset;
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
*
* @author mikit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
LightScanner in = new LightScanner(inputStream);
LightWriter out = new LightWriter(outputStream);
ENewYearAndCastleConstruction solver = new ENewYearAndCastleConstruction();
solver.solve(1, in, out);
out.close();
}
static class ENewYearAndCastleConstruction {
public void solve(int testNumber, LightScanner in, LightWriter out) {
int n = in.ints();
Vec2l[] points = new Vec2l[n];
for (int i = 0; i < n; i++) points[i] = new Vec2l(in.longs(), in.longs());
long ans = n * (n - 1L) * (n - 2L) * (n - 3L) * (n - 4L) / 24;
for (int t = 0; t < n; t++) {
int m = 0;
Vec2l[] angles = new Vec2l[n - 1];
{
Vec2l now = points[t];
for (int i = 0; i < n; i++) {
if (i != t) {
angles[m] = new Vec2l(points[i].x - now.x, points[i].y - now.y);
m++;
}
}
Arrays.sort(angles, Vec2l::compareToByAngle);
}
//System.out.println(Arrays.stream(angles).map(angle -> Double.toString(Math.atan2(angle.y, angle.x))).collect(Collectors.joining(", ")));
int hi = 0;
for (int j = 0; j < m; j++) {
while (hi < j + m && (hi <= j || angles[j].det(angles[hi % m]) > 0)) {
hi++;
}
int cnt = hi - j;
ans -= (cnt - 1L) * (cnt - 2L) * (cnt - 3L) / 6;
}
}
out.ans(ans).ln();
}
}
static class Vec2l implements Comparable<Vec2l> {
public long x;
public long y;
public Vec2l(long x, long y) {
this.x = x;
this.y = y;
}
public long det(Vec2l other) {
return x * other.y - other.x * y;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vec2l vec2i = (Vec2l) o;
return x == vec2i.x &&
y == vec2i.y;
}
public int hashCode() {
return Objects.hash(x, y);
}
public String toString() {
return "(" + x + ", " + y + ")";
}
public int compareTo(Vec2l o) {
if (x == o.x) {
return Long.compare(y, o.y);
}
return Long.compare(x, o.x);
}
public int compareToByAngle(Vec2l o) {
if ((y >= 0) != (o.y >= 0)) {
return y >= 0 ? 1 : -1;
} else {
return Long.compare(0, x * o.y - o.x * y);
}
}
}
static class LightWriter implements AutoCloseable {
private final Writer out;
private boolean autoflush = false;
private boolean breaked = true;
public LightWriter(Writer out) {
this.out = out;
}
public LightWriter(OutputStream out) {
this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));
}
public LightWriter print(char c) {
try {
out.write(c);
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter print(String s) {
try {
out.write(s, 0, s.length());
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter ans(String s) {
if (!breaked) {
print(' ');
}
return print(s);
}
public LightWriter ans(long l) {
return ans(Long.toString(l));
}
public LightWriter ln() {
print(System.lineSeparator());
breaked = true;
if (autoflush) {
try {
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
return this;
}
public void close() {
try {
out.close();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
static class LightScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public LightScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public String string() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return tokenizer.nextToken();
}
public int ints() {
return Integer.parseInt(string());
}
public long longs() {
return Long.parseLong(string());
}
}
}
| java |
1311 | F | F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
| [
"data structures",
"divide and conquer",
"implementation",
"sortings"
] | //package psa.minrazdalja;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class minrazdalja {
/**
* Uvozena abstraktna funkcija za klic Paid<L, R>
*/
public static class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
assert left != null;
assert right != null;
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
/**?
* glavna funkcija racunanja:
* sprejme list tipa ArrayList<Pair<Integer, Integer>>, potem st vseh elementov in seveda listo vseh elementov.
*
* nato izracunamo maksimalno distance, ki je sestevek vseh distanc med posameznimi elementi, kar lahko storimo, ker je sortirana tabela.
* V drugem delu odstejemo od maksimalnega sestevka distanc, posamezne ki se sekajo v prihodnosti
* ostane nam samo tocni sestevek minimalnih distanc
*/
public static BigInteger elele(ArrayList<Pair<BigInteger,BigInteger>> elementi, int s, BigInteger[] x_el) {
BigInteger skupek = new BigInteger("0");
HashMap<BigInteger, Integer> pos = new HashMap<BigInteger, Integer>();
for(int i=0; i<s; ++i) {
skupek = skupek.add( (x_el[i].multiply( new BigInteger(Integer.toString(i) ))).add( (x_el[i].negate()).multiply(new BigInteger(Integer.toString(s - 1 - i)))));
pos.put(x_el[i], i);
}
for(int i=0; i<s; ++i){
skupek = skupek.subtract( (elementi.get(i).getRight()).multiply( new BigInteger( Integer.toString( (pos.get(elementi.get(i).getRight()) - i) ) ) ) );
}
// //2 1 4 3 5
// //2 2 2 3 4
return skupek;
}
public static void main(String[] args) throws IOException {
int st_el;
// uporabimo bufferedreader zaradi 1000x vecje hitrosti kot pa skener
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
//System.out.println("Vnesi stevilo elementov: ");
st_el = Integer.parseInt(br.readLine());
//System.out.println(st_el);
BigInteger[] x_el = new BigInteger[st_el];
BigInteger[] v_el = new BigInteger[st_el];
//System.out.println("Vnesi elemente: ");
String x = br.readLine();
String[] strs = x.trim().split("\\s+");
for(int i=0; i<st_el; ++i) {
x_el[i] = new BigInteger(strs[i]);
}
//System.out.println("Vnesi tezo elementov: ");
String y = br.readLine();
String[] strs2 = y.trim().split("\\s+");
for(int i=0; i<st_el; ++i) {
v_el[i] = new BigInteger(strs2[i]);
}
br.close();
//pospravimo skupej v par oblike <integer, integer> oz <hitrost, element>
ArrayList<Pair<BigInteger,BigInteger>> listt = new ArrayList<Pair<BigInteger, BigInteger>>(st_el);
for(int i=0; i<st_el; i++) {
Pair<BigInteger, BigInteger> pair = new Pair<BigInteger, BigInteger>(v_el[i],x_el[i]);
listt.add(pair);
}
/*sortiramo listt od najmanjsega do najvecjega
* - sortiramo prvo po hitrostih (to je glavno najbolj vazno)
* - ce je hitrost ista potem pa sortiramo se glede na element
* - O(n log n)
*/
Collections.sort(listt, new Comparator<Pair<BigInteger, BigInteger>>() {
@Override
public int compare(final Pair<BigInteger, BigInteger> o1, final Pair<BigInteger, BigInteger> o2) {
int oo = o1.getLeft().compareTo(o2.getLeft());
if(oo == -1) {
return -1;
} else if(oo == 0) {
int ooo = o1.getRight().compareTo(o2.getRight());
if(ooo == -1){
return -1;
}else{
return 1;
}
} else {
return 1;
}
}
});
//sortiramo se elemente
// O(n log n)
Arrays.sort(x_el);
//izpisemo elemente
System.out.println(elele(listt,st_el,x_el));
}
}
| java |
1301 | A | A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb. | [
"implementation",
"strings"
] | import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
String a=sc.next();
String b=sc.next();
String c=sc.next();
boolean flag=true;
for(int i=0;i<c.length();i++){
if(c.charAt(i)!=a.charAt(i) && c.charAt(i)!=b.charAt(i)){
System.out.println("NO");
flag=false;
break;
}
}
if(flag)
System.out.println("YES");
}
}
} | java |
1324 | B | B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.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.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes. | [
"brute force",
"strings"
] | import java.math.BigInteger;
import java.util.*;
import javax.lang.model.util.ElementScanner6;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int testcase=sc.nextInt();
for(int tc=1;tc<=testcase;tc++){
//System.out.print("Case #"+tc+": ");
int n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
boolean ans = false;
for(int i=0;i<n-2;i++){
for(int j=i+2;j<n;j++){
if(arr[j] == arr[i]){
ans = true;
break;
}
}
}
if(ans){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
sc.close();
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to return LCM of two numbers
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static int f(int order[], int disAmount){
int count = 0;
for(int x : order){
if(x > 0 && disAmount % x == 0)
count++;
}
return count;
}
static int upper_bound(int arr[], int key)
{
int mid, N = arr.length;
// Initialise starting index and
// ending index
int low = 0;
int high = N;
// Till low is less than high
while (low < high && low != N) {
// Find the index of the middle element
mid = low + (high - low) / 2;
// If key is greater than or equal
// to arr[mid], then find in
// right subarray
if (key >= arr[mid]) {
low = mid + 1;
}
// If key is less than arr[mid]
// then find in left subarray
else {
high = mid;
}
}
// If key is greater than last element which is
// array[n-1] then upper bound
// does not exists in the array
if (low > N ) {
low--;
}
// Print the upper_bound index
return low;
}
static int lower_bound(int array[], int key)
{
// Initialize starting index and
// ending index
int low = 0, high = array.length;
int mid;
// Till high does not crosses low
while (low < high) {
// Find the index of the middle element
mid = low + (high - low) / 2;
// If key is less than or equal
// to array[mid], then find in
// left subarray
if (key <= array[mid]) {
high = mid;
}
// If key is greater than array[mid],
// then find in right subarray
else {
low = mid + 1;
}
}
// If key is greater than last element which is
// array[n-1] then lower bound
// does not exists in the array
if(low==-1)
low++;
// Returning the lower_bound index
return low;
}
static boolean palin(int arr[], int i, int j){
while(i < j){
if(arr[i] != arr[j])
return false;
i++;
j--;
}
return true;
}
static boolean palin(String s){
int i=0,j=s.length()-1;
while(i<j){
if(s.charAt(i)!=s.charAt(j))
return false;
i++;
j--;
}
return true;
}
static long minSum(int arr[], int n, int k)
{
// k must be smaller than n
if (n < k)
{
// System.out.println("Invalid");
return -1;
}
// Compute sum of first window of size k
long res = 0;
for (int i=0; i<k; i++)
res += arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
long curr_sum = res;
for (int i=k; i<n; i++)
{
curr_sum += arr[i] - arr[i-k];
res = Math.min(res, curr_sum);
}
return res;
}
static int nextIndex(int a[], int x){
int n=a.length;
for(int i=x;i<n-1;i++){
if(a[i]>a[i+1]){
return i;
}
}
return n;
}
static void rev(int a[], int i, int j){
while(i<j){
int t=a[i];
a[i]=a[j];
a[j]=t;
i++;
j--;
}
}
static int sorted(char arr[], int n)
{
// Array has one or no element or the
// rest are already checked and approved.
if (n == 1 || n == 0)
return 1;
// Unsorted pair found (Equal values allowed)
if (arr[n - 1] < arr[n - 2])
return 0;
// Last pair was sorted
// Keep on checking
return sorted(arr, n - 1);
}
static void sieveOfEratosthenes(int n, Set<Integer> set)
{
// Create a boolean array "prime[0..n]" and
// initialize all entries it as true. A value in
// prime[i] will finally be false if i is Not a
// prime, else true.
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] == true) {
// Update all multiples of p greater than or
// equal to the square of it numbers which
// are multiple of p and are less than p^2
// are already been marked.
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] == true)
set.add(i);
}
}
static boolean isPowerOfTwo(int n)
{
return (int)(Math.ceil((Math.log(n) / Math.log(2))))
== (int)(Math.floor(((Math.log(n) / Math.log(2)))));
}
static int countBits(int number)
{
// log function in base 2
// take only integer part
return (int)(Math.log(number) /
Math.log(2) + 1);
}
public static void swap(int ans[], int i, int j) {
int temp=ans[i];
ans[i]=ans[j];
ans[j]=temp;
}
static int power(int x, int y, int p)
{
int res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
} | 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.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
public class CowAndFriend {
public static void main(String[] args) {
MyScanner scanner = new MyScanner();
int testCases = scanner.nextInt();
for (int i = 0; i < testCases; i++) {
int n = scanner.nextInt();
double x = scanner.nextDouble();
List<Double> lines = getDoubleList(n, scanner);
lines.sort(Collections.reverseOrder());
if (lines.contains(x)) {
System.out.println("1");
} else {
int minCount = lines.get(0) >= (x / 2) ? 2 : (int) Math.ceil(x / lines.get(0));
System.out.println(minCount);
}
}
}
/****** UTILITY *******/
static class Vector2D {
final double x;
final double y;
public Vector2D(double x, double y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
Vector2D vector = (Vector2D) o;
return x == vector.x && y == vector.y;
}
@Override
public int hashCode() {
return (int) (31 * (31 * x + y));
}
}
static List<Vector2D> getVectors(int n, MyScanner scanner) {
final List<Vector2D> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(new Vector2D(scanner.nextDouble(), scanner.nextDouble()));
}
return list;
}
static double distance(Vector2D a, Vector2D b) {
return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
}
static double manhattanDistance(Vector2D a, Vector2D b) {
return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
}
static Vector2D plus(Vector2D a, Vector2D b) {
return new Vector2D(a.x + b.x, a.y + b.y);
}
static Vector2D minus(Vector2D a, Vector2D b) {
return new Vector2D(a.x - b.x, a.y - b.y);
}
static Vector2D scalar(Vector2D v, double alpha) {
return new Vector2D(alpha * v.x, alpha * v.y);
}
static List<String> getStringList(int n, MyScanner scanner) {
final List<String> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(scanner.next());
}
return list;
}
static List<String[]> getStringArrays(int n, int m, MyScanner scanner) {
final List<String[]> arrays = new ArrayList<>();
for (int i = 0; i < n; i++) {
String[] array = new String[m];
for (int j = 0; j < m; j++) {
array[j] = scanner.next();
}
arrays.add(array);
}
return arrays;
}
static List<Long> getLongList(int n, MyScanner scanner) {
final List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(scanner.nextLong());
}
return list;
}
static List<long[]> getLongArrays(int n, int m, MyScanner scanner) {
final List<long[]> arrays = new ArrayList<>();
for (int i = 0; i < n; i++) {
long[] array = new long[m];
for (int j = 0; j < m; j++) {
array[j] = scanner.nextLong();
}
arrays.add(array);
}
return arrays;
}
static List<Integer> getIntList(int n, MyScanner scanner) {
final List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(scanner.nextInt());
}
return list;
}
static List<int[]> getIntArrays(int n, int m, MyScanner scanner) {
final List<int[]> arrays = new ArrayList<>();
for (int i = 0; i < n; i++) {
int[] array = new int[m];
for (int j = 0; j < m; j++) {
array[j] = scanner.nextInt();
}
arrays.add(array);
}
return arrays;
}
static List<Double> getDoubleList(int n, MyScanner scanner) {
final List<Double> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(scanner.nextDouble());
}
return list;
}
static List<double[]> getDoubleArrays(int n, int m, MyScanner scanner) {
final List<double[]> arrays = new ArrayList<>();
for (int i = 0; i < n; i++) {
double[] array = new double[m];
for (int j = 0; j < m; j++) {
array[j] = scanner.nextDouble();
}
arrays.add(array);
}
return arrays;
}
private static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| java |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements. | [
"geometry"
] | 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.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author lewin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
BAerodynamic solver = new BAerodynamic();
solver.solve(1, in, out);
out.close();
}
static class BAerodynamic {
public long[] x;
public long[] y;
public long[] rx;
public long[] ry;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
if (n % 2 == 1) {
out.println("NO");
return;
}
x = new long[n];
y = new long[n];
long cx = 0, cy = 0;
for (int i = 0; i < n; i++) {
x[i] = in.nextLong() * n;
y[i] = in.nextLong() * n;
cx += x[i];
cy += y[i];
}
cx /= n;
cy /= n;
rx = new long[n];
ry = new long[n];
for (int i = 0; i < n; i++) {
rx[i] = 2 * cx - x[(i + n / 2) % n];
ry[i] = 2 * cy - y[(i + n / 2) % n];
}
out.println(Arrays.equals(x, rx) && Arrays.equals(y, ry) ? "YES" : "NO");
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (this.numChars == -1) {
throw new InputMismatchException();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException var2) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return -1;
}
}
return this.buf[this.curChar++];
}
}
public int nextInt() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
;
}
byte sgn = 1;
if (c == 45) {
sgn = -1;
c = this.read();
}
int res = 0;
while (c >= 48 && c <= 57) {
res *= 10;
res += c - 48;
c = this.read();
if (isSpaceChar(c)) {
return res * sgn;
}
}
throw new InputMismatchException();
}
public long nextLong() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
;
}
byte sgn = 1;
if (c == 45) {
sgn = -1;
c = this.read();
}
long res = 0L;
while (c >= 48 && c <= 57) {
res *= 10L;
res += (long) (c - 48);
c = this.read();
if (isSpaceChar(c)) {
return res * (long) sgn;
}
}
throw new InputMismatchException();
}
public static boolean isSpaceChar(int c) {
return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| 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.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);
C1SkyscrapersEasyVersion solver = new C1SkyscrapersEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class C1SkyscrapersEasyVersion {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
long sum = 0, maxSum = 0;
int[] max = new int[n], current = new int[n];
for (int i = 0; i < n; i++) {
sum = a[i];
current[i] = a[i];
for (int j = i - 1; j >= 0; j += -1) {
current[j] = Math.min(current[j + 1], a[j]);
sum += current[j];
}
for (int j = i + 1; j < n; j++) {
current[j] = Math.min(current[j - 1], a[j]);
sum += current[j];
}
if (sum > maxSum) {
maxSum = sum;
max = current.clone();
}
}
out.println(max);
}
}
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 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 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 |
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.Scanner;
public class Gcd {
public static long res=0;
public static long great(long a, long b) {
if(a<b) {
long temp=a;
a=b;
b=temp;
}
while(b!=0) {
long temp=a;
a=b;
b=temp%b;
}
return a;
}
public static void add(int n, int i) {
while(n>0) {
res+=n%i;
n=n/i;
}
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=2;i<=n-1;i++) {
add(n,i);
}
long r=great(res,(n-2));
System.out.printf("%d/%d\n", res/r,(n-2)/r);
}
}
| java |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 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≤15001≤n≤1500) — 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
| [
"data structures",
"greedy"
] | import java.io.*;
import java.util.HashMap;
import java.util.StringTokenizer;
/**
* * @author zhengnaishan
* * @date 2023/2/9 9:15
*/
public class CF1141 {
public static void main(String[] args) {
HashMap<Long, Integer> cntMap = new HashMap<>();
//前缀和最后出现的位置
HashMap<Long, Integer> lastIndex = new HashMap<>();
Kattio io = new Kattio();
int n = io.nextInt();
int[] a = new int[n];
int maxCnt = 0;
long maxSum = 0;
for (int i = 0; i < n; i++) {
a[i] = io.nextInt();
long sum = 0;
for (int j = i; j >= 0; j--) {
sum += a[j];
if (lastIndex.getOrDefault(sum, -1) < j) {
lastIndex.put(sum, i);
int cnt = cntMap.getOrDefault(sum, 0) + 1;
cntMap.put(sum, cnt);
if (cnt > maxCnt) {
maxCnt = cnt;
maxSum = sum;
}
}
}
}
io.println(cntMap.get(maxSum));
long sum = 0;
HashMap<Long, Integer> sumMap = new HashMap<>();
sumMap.put(0L, -1);
for (int i = 0; i < n; i++) {
sum += a[i];
Integer v;
if ((v = sumMap.get(sum - maxSum)) != null) {
io.println(v + 2 + " " + (i + 1));
sumMap.clear();
sumMap.put(0L, i);
sum = 0;
} else {
sumMap.put(sum, i);
}
}
io.flush();
}
public static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// 标准 IO
public Kattio() {
this(System.in, System.out);
}
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// 文件 IO
public Kattio(String intput, String output) throws IOException {
super(output);
r = new BufferedReader(new FileReader(intput));
}
// 在没有其他输入时返回 null
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.readLine());
return st.nextToken();
} catch (Exception e) {
}
return null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| 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"
] | //package com.kraken.cf.cf627;
import java.util.*;
public class Codeforces {
static long[] dp, ans;
private static ArrayList<ArrayList<Integer>> tree;
private static int[] a;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
a = new int[n + 1];
dp = new long[n + 1];
ans = new long[n + 1];
tree = new ArrayList<>();
for (int i = 0; i <= n; i++) tree.add(new ArrayList<>());
for (int i = 1; i <= n; i++) {
a[i] = sc.nextInt();
if (a[i] == 0) a[i] = -1;
}
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
tree.get(u).add(v);
tree.get(v).add(u);
}
dfs(1, -1);
find(1, -1);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) sb.append(ans[i]).append(" ");
System.out.println(sb.toString());
}
private static void dfs(int v, int lv) {
dp[v] = a[v];
for (int x : tree.get(v)) {
if (x == lv) continue;
dfs(x, v);
dp[v] += Math.max(0, dp[x]);
}
}
private static void find(int v, int lv) {
ans[v] = dp[v];
for (int x : tree.get(v)) {
if (x == lv) continue;
dp[v] -= Math.max(0, dp[x]);
dp[x] += Math.max(0, dp[v]);
find(x, v);
dp[x] -= Math.max(0, dp[v]);
dp[v] += Math.max(0, dp[x]);
}
}
}
| java |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] |
import java.util.*;
public class Training1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int arr[]=new int[3];
arr[0] = sc.nextInt();
arr[1] = sc.nextInt();
arr[2] = sc.nextInt();
Arrays.sort(arr);
int res = 0;
if (arr[0] > 0) {
arr[0]--;
res++;
}
if (arr[1] > 0) {
arr[1]--;
res++;
}
if (arr[2] > 0) {
arr[2]--;
res++;
}
if (arr[2] > 0 && arr[0] > 0) {
arr[2]--;
arr[0]--;
res++;
}
if (arr[2] > 0 && arr[1] > 0) {
arr[2]--;
arr[1]--;
res++;
}
if (arr[0] > 0 && arr[1] > 0) {
arr[0]--;
arr[1]--;
res++;
}
if (arr[0] > 0 && arr[1] > 0&& arr[2]>0) {
res++;
}
System.out.println(res);
}
}
}
| 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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class F {
private static final FastReader in = new FastReader();
private static final FastWriter out = new FastWriter();
public static void main(String[] args) {
new F().run();
}
private void run() {
var t = 1;
while (t-- > 0) {
solve();
}
out.flush();
}
private Tree<?> tree;
private LCA lca;
private int[] w;
private void solve() {
var n = in.nextInt();
var g = Graph.unweighted(n);
var edges = new ArrayList<IntPair>(n - 1);
for (var i = 1; i < n; i++) {
var u = in.nextInt() - 1;
var v = in.nextInt() - 1;
g.addBidirectedEdges(u, v);
edges.add(IntPair.of(u, v));
}
tree = g.asTree(0);
lca = new LCA(tree);
var m = in.nextInt();
var queries = new ArrayList<IntTriple>();
for (var i = 0; i < m; i++) {
var q = IntTriple.of(in.nextInt() - 1, in.nextInt() - 1, in.nextInt());
queries.add(q);
}
queries.sort(Comparator.comparing(IntTriple::getC).reversed());
w = new int[n];
for (var q : queries) {
if (!mark(q)) {
out.println(-1);
return ;
}
}
var f = edges.stream()
.mapToInt(e -> {
var u = e.a;
var v = e.b;
if (tree.parents[u] == v) {
var t = u;
u = v;
v = t;
}
return w[v] > 0 ? w[v] : 1;
})
.toArray();
out.println(f);
}
boolean mark(IntTriple q) {
boolean valid = false;
int ancestor = lca.query(q.a, q.b);
int u = q.a;
while (u != ancestor) {
if (w[u] == 0) {
w[u] = q.c;
}
valid |= w[u] == q.c;
u = tree.parents[u];
}
int v = q.b;
while (v != ancestor) {
if (w[v] == 0) {
w[v] = q.c;
}
valid |= w[v] == q.c;
v = tree.parents[v];
}
return valid;
}
}
class FastReader {
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer in;
public String next() {
while (in == null || !in.hasMoreTokens()) {
try {
in = new StringTokenizer(br.readLine());
} catch (IOException e) {
return null;
}
}
return in.nextToken();
}
public BigDecimal nextBigDecimal() {
return new BigDecimal(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public boolean nextBoolean() {
return Boolean.valueOf(next());
}
public byte nextByte() {
return Byte.valueOf(next());
}
public double nextDouble() {
return Double.valueOf(next());
}
public double[] nextDoubleArray(int length) {
var a = new double[length];
for (var i = 0; i < length; i++) {
a[i] = nextDouble();
}
return a;
}
public int nextInt() {
return Integer.valueOf(next());
}
public int[] nextIntArray(int length) {
var a = new int[length];
for (var i = 0; i < length; i++) {
a[i] = nextInt();
}
return a;
}
public long nextLong() {
return Long.valueOf(next());
}
public long[] nextLongArray(int length) {
var a = new long[length];
for (var i = 0; i < length; i++) {
a[i] = nextLong();
}
return a;
}
}
class FastWriter extends PrintWriter {
public FastWriter() {
super(System.out);
}
public void println(boolean[] a) {
for (var i = 0; i < a.length; i++) {
print(a[i]);
print(i + 1 < a.length ? ' ' : '\n');
}
}
public void println(double[] a) {
for (var i = 0; i < a.length; i++) {
print(a[i]);
print(i + 1 < a.length ? ' ' : '\n');
}
}
public void println(int[] a) {
for (var i = 0; i < a.length; i++) {
print(a[i]);
print(i + 1 < a.length ? ' ' : '\n');
}
}
public void println(long[] a) {
for (var i = 0; i < a.length; i++) {
print(a[i]);
print(i + 1 < a.length ? ' ' : '\n');
}
}
public void println(Object... a) {
for (var i = 0; i < a.length; i++) {
print(a[i]);
print(i + 1 < a.length ? ' ' : '\n');
}
}
public <T> void println(List<T> l) {
println(l.toArray());
}
public void debug(String name, Object o) {
String value = Arrays.deepToString(new Object[] { o });
value = value.substring(1, value.length() - 1);
System.err.println(name + " => " + value);
}
}
abstract class Graph<T> {
public final int n;
final List<List<T>> adjacencyList;
Graph(int n) {
this.n = n;
this.adjacencyList = new ArrayList<>(n);
for (var i = 0; i < n; i++) {
this.adjacencyList.add(new ArrayList<>());
}
}
public static UnweightedGraph unweighted(int n) {
return new UnweightedGraph(n);
}
public static <T> WeightedGraph<T> weighted(int n) {
return new WeightedGraph<>(n);
}
public List<T> neighbors(int u) {
return adjacencyList.get(u);
}
public abstract int neighborId(T neighbor);
public int degree(int u) {
return neighbors(u).size();
}
public Tree<T> asTree(int root) {
return new Tree<>(this, root);
}
@Override
public String toString() {
String adj = IntStream.range(0, n)
.mapToObj(i -> " " + i + ": " + neighbors(i))
.collect(Collectors.joining(",\n"));
return "Graph {\n"
+ " nodeCount: " + n + ",\n"
+ " adjacencyList: {\n"
+ adj + "\n"
+ " }\n"
+ "}";
}
public static class UnweightedGraph extends Graph<Integer> {
UnweightedGraph(int n) {
super(n);
}
public void addEdge(int u, int v) {
adjacencyList.get(u).add(v);
}
public void addBidirectedEdges(int u, int v) {
addEdge(u, v);
addEdge(v, u);
}
@Override
public int neighborId(Integer neighbor) {
return neighbor;
}
}
public static class WeightedGraph<T> extends Graph<Edge<T>> {
WeightedGraph(int n) {
super(n);
}
public void addEdge(int u, int v, T w) {
adjacencyList.get(u).add(Edge.of(v, w));
}
public void addBidirectedEdges(int u, int v, T w) {
addEdge(u, v, w);
addEdge(v, u, w);
}
@Override
public int neighborId(Edge<T> neighbor) {
return neighbor.v;
}
}
public static class Edge<T> {
public final int v;
public final T w;
public Edge(int v, T w) {
this.v = v;
this.w = w;
}
public static <T> Edge<T> of(int v, T w) {
return new Edge<>(v, w);
}
public int getV() {
return v;
}
public T getW() {
return w;
}
@Override
public String toString() {
return String.format("(%s, %s)", v, w);
}
}
}
class IntPair extends Pair<Integer, Integer> {
IntPair(Integer a, Integer b) {
super(a, b);
}
public static IntPair of(int a, int b) {
return new IntPair(a, b);
}
}
class IntTriple extends Triple<Integer, Integer, Integer> {
IntTriple(Integer a, Integer b, Integer c) {
super(a, b, c);
}
public static IntTriple of(int a, int b, int c) {
return new IntTriple(a, b, c);
}
}
class LCA {
private final Tree<?> tree;
private final RMQ<Integer> rmq;
public LCA(Tree<?> tree) {
this.tree = tree.savePreOrderIds().saveEulerTour().build();
this.rmq = new RMQ<>(tree.eulerTour, Comparator.comparing(u -> tree.preOrderIds[u]));
}
public int query(int x, int y) {
var l = tree.firstSeenInEulerTour[x];
var r = tree.firstSeenInEulerTour[y];
if (l > r) {
var t = l;
l = r;
r = t;
}
return rmq.query(l, r + 1);
}
}
class Tree<T> {
public final Graph<T> graph;
public final int n;
public final int root;
public int[] parents;
public int[] depths;
public int[] subTreeSizes;
public int[] preOrderIds;
private int currentPreOrderId;
public int[] firstSeenInEulerTour;
public List<Integer> eulerTour;
public Tree(Graph<T> graph, int root) {
this.graph = graph;
this.n = graph.n;
this.root = root;
this.parents = new int[n];
}
public Tree<T> saveDepth() {
this.depths = new int[n];
return this;
}
public Tree<T> saveSubTreeSize() {
this.subTreeSizes = new int[n];
return this;
}
public Tree<T> savePreOrderIds() {
this.preOrderIds = new int[n];
return this;
}
public Tree<T> saveEulerTour() {
this.firstSeenInEulerTour = new int[n];
this.eulerTour = new ArrayList<>(n * 2 - 1);
return this;
}
public Tree<T> build() {
dfs(root, -1, 0);
return this;
}
private void dfs(int u, int parent, int depth) {
parents[u] = parent;
if (preOrderIds != null) {
preOrderIds[u] = currentPreOrderId++;
}
if (eulerTour != null) {
firstSeenInEulerTour[u] = eulerTour.size();
eulerTour.add(u);
}
forEachChild(u, v -> {
dfs(v, u, depth + 1);
if (eulerTour != null) {
eulerTour.add(u);
}
});
if (depths != null) {
depths[u] = depth;
}
if (subTreeSizes != null) {
subTreeSizes[u] = 1;
forEachChild(u, v -> subTreeSizes[u] += subTreeSizes[v]);
}
}
public void forEachChild(int u, IntConsumer consumer) {
for (var neighbor : graph.neighbors(u)) {
var v = graph.neighborId(neighbor);
if (v != parents[u]) {
consumer.accept(v);
}
}
}
public boolean isLeaf(int u) {
return u == root ? false : graph.neighbors(u).size() == 1;
}
}
class RMQ<T extends Comparable<T>> {
private final int n;
private final List<T> values;
private final Comparator<T> comparator;
private final int[][] ranges;
public RMQ(List<T> values) {
this(values, Comparator.naturalOrder());
}
public RMQ(List<T> values, Comparator<T> comparator) {
this.values = values;
this.comparator = comparator;
this.n = values.size();
this.ranges = new int[leftMostOneBit(n) + 1][];
build();
}
private int leftMostOneBit(int x) {
return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);
}
private void build() {
ranges[0] = new int[n];
for (var i = 0; i < n; i++) {
ranges[0][i] = i;
}
for (var i = 1; 1 << i <= n; i++) {
ranges[i] = new int[n - (1 << i) + 1];
for (var j = 0; j + (1 << i) <= n; j++) {
ranges[i][j] = betterIndex(ranges[i - 1][j], ranges[i - 1][j + (1 << (i - 1))]);
}
}
}
private int betterIndex(int l, int r) {
return comparator.compare(values.get(l), values.get(r)) < 0 ? l : r;
}
public int queryIndex(int l, int r) {
var exponent = leftMostOneBit(r - l);
return betterIndex(ranges[exponent][l], ranges[exponent][r - (1 << exponent)]);
}
public T query(int l, int r) {
return values.get(queryIndex(l, r));
}
}
class Triple<T, U, V> {
public T a;
public U b;
public V c;
Triple(T a, U b, V c) {
this.a = a;
this.b = b;
this.c = c;
}
public static <T, U, V> Triple<T, U, V> of(T a, U b, V c) {
return new Triple<>(a, b, c);
}
public T getA() {
return a;
}
public U getB() {
return b;
}
public V getC() {
return c;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Triple)) return false;
var other = (Triple<?, ?, ?>) obj;
return Objects.equals(a, other.a) && Objects.equals(b, other.b) && Objects.equals(c, other.c);
}
@Override
public String toString() {
return String.format("(%s, %s, %s)", a, b, c);
}
}
class Pair<T, U> {
public T a;
public U b;
Pair(T a, U b) {
this.a = a;
this.b = b;
}
public static <T, U> Pair<T, U> of(T a, U b) {
return new Pair<>(a, b);
}
public T getA() {
return a;
}
public U getB() {
return b;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Pair)) return false;
var other = (Pair<?, ?>) obj;
return Objects.equals(a, other.a) && Objects.equals(b, other.b);
}
@Override
public String toString() {
return String.format("(%s, %s)", a, b);
}
}
| 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 scn=new Scanner(System.in);
int t= scn.nextInt();
int spend=0;
int remaining=0;
int cashback=0;
for (int k = 0; k <t ; k++) {
int n= scn.nextInt();
spend=0;
remaining=n;
cashback=0;
while (n!=0){
if (n<10){
spend+=n;
n=0;
}
else {
cashback=n/10;
spend+=(n/10)*10;
n=n-((n/10)*10)+cashback;
}
}
System.out.println(spend);
}
}
}
| java |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3
| [
"dfs and similar",
"graphs",
"shortest paths"
] | import java.io.*;
import java.util.*;
/*
20 50
20 3
5 16
1 3
10 11
10 15
15 9
20 9
14 6
16 5
13 4
11 5
3 20
13 17
11 8
11 6
12 14
16 18
17 13
18 7
3 1
8 10
17 15
7 2
9 13
5 11
6 1
2 16
8 18
10 8
4 13
9 15
14 12
1 6
9 20
7 18
6 14
7 6
18 16
2 7
3 11
15 17
3 12
14 10
4 14
19 4
11 10
4 19
8 12
17 8
12 8
16
7 2 16 5 11 8 10 15 9 13 4 14 6 1 3 20
5 8
*/
public class CodeForces {
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void solve(int tCase) throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<Integer>[] adj = new ArrayList[n+1];
for(int i=0;i<=n;i++)adj[i] = new ArrayList<>();
for(int i=0;i<m;i++){
int x = sc.nextInt();
int y = sc.nextInt();
adj[y].add(x);
}
int k = sc.nextInt();
int[] path = new int[k];
for(int i=0;i<k;i++)path[i] = sc.nextInt();
int[] distance = new int[n+1];
Arrays.fill(distance,n+20);
int[] count = new int[n+1];
Queue<int[]> q= new ArrayDeque<>();
boolean[] isVis = new boolean[n+1];
isVis[path[k-1]] =true;
q.add(new int[]{path[k-1],0});
distance[path[k-1]] = 0;
while(!q.isEmpty()){
int[] x = q.poll();
for(int neig : adj[x[0]]){
if(distance[neig] > x[1] + 1){
distance[neig] = x[1] + 1;
count[neig] = 0;
}
if(distance[neig] == x[1] + 1)count[neig]++;
if(!isVis[neig]){
q.add(new int[]{neig,x[1]+1});
isVis[neig] = true;
}
}
}
int minDist = distance[path[0]];
int minCount = 0;
int maxCount = 0;
// out.println(Arrays.toString(count)+" "+Arrays.toString(distance));
for(int i=0;i<k-1;i++){
if(distance[path[i]] == minDist){
minDist--;
}
else {
minCount++;
minDist = distance[path[i]]-1;
}
}
// out.println(Arrays.toString(count));
minDist = distance[path[0]];
for(int i=0;i<k-1;i++){
// out.println(distance[path[i+1]]+" "+minDist);
if(distance[path[i+1]] == minDist-1){
if(count[path[i]]>1) maxCount++;
minDist--;
}else minDist = distance[path[i+1]];
}
out.println(minCount+" "+(minCount+maxCount));
}
public static void main(String[] args) throws IOException {
long s = System.currentTimeMillis();
openIO();
int testCase = 1;
// testCase = sc. nextInt();
for (int i = 1; i <= testCase; i++) solve(i);
// out.println((System.currentTimeMillis() - s)/1000d);
closeIO();
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
/*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/
public static int mod = (int) 1e9 + 7;
// public static int mod = 998244353;
public static int inf_int = (int) 2e9;
public static long inf_long = (long) 2e18;
public static void _sort(int[] arr, boolean isAscending) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
public static void _sort(long[] arr, boolean isAscending) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (long ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
// time : O(1), space : O(1)
public static int _digitCount(long num,int base){
// this will give the # of digits needed for a number num in format : base
return (int)(1 + Math.log(num)/Math.log(base));
}
// time : O(n), space: O(n)
public static long _fact(int n){
// simple factorial calculator
long ans = 1;
for(int i=2;i<=n;i++)
ans = ans * i % mod;
return ans;
}
// time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))
public static long[] factorial , inverseFact;
public static void _ncr_precompute(int n){
factorial = new long[n+1];
inverseFact = new long[n+1];
factorial[0] = inverseFact[0] = 1;
for (int i = 1; i <=n; i++) {
factorial[i] = (factorial[i - 1] * i) % mod;
inverseFact[i] = _modExpo(factorial[i], mod - 2);
}
}
// time of factorial calculation after pre-computation is O(1)
public static int _ncr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);
}
public static int _npr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[n - r] % mod);
}
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
while (a>0){
long x = a;
a = b % a;
b = x;
}
return b;
// if (a == 0)
// return b;
// return _gcd(b % a, a);
}
// lcm(a,b) * gcd(a,b) = a * b
public static long _lcm(long a, long b) {
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _modExpo(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
// function to find a/b under modulo mod. time : O(logn)
public static long _modInv(long a,long b){
return (a * _modExpo(b,mod-2)) % mod;
}
//sieve or first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
firstDivisor[j] = i;
return firstDivisor;
}
// check if x is a prime # of not. time : O( n ^ 1/2 )
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
static class Pair<K, V>{
K ff;
V ss;
public Pair(K ff, V ss) {
this.ff = ff;
this.ss = ss;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || this.getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return ff.equals(pair.ff) && ss.equals(pair.ss);
}
@Override
public int hashCode() {
return Objects.hash(ff, ss);
}
@Override
public String toString(){
return ff.toString()+" "+ss.toString();
}
}
/*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException {
sc = new FastestReader();
out = new PrintWriter(System.out);
}
public static void closeIO() throws IOException {
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {
}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final 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();
}
final 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();
}
final 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 {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
} | 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.io.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.math.*;
/**
* _ _
* ( _) ( _)
* / / \\ / /\_\_
* / / \\ / / | \ \
* / / \\ / / |\ \ \
* / / , \ , / / /| \ \
* / / |\_ /| / / / \ \_\
* / / |\/ _ '_| \ / / / \ \\
* | / |/ 0 \0\ / | | \ \\
* | |\| \_\_ / / | \ \\
* | | |/ \.\ o\o) / \ | \\
* \ | /\\`v-v / | | \\
* | \/ /_| \\_| / | | \ \\
* | | /__/_ - / ___ | | \ \\
* \| [__] \_/ |_________ \ | \ ()
* / [___] ( \ \ |\ | | //
* | [___] |\| \| / |/
* /| [____] \ |/\ / / ||
* ( \ [____ / ) _\ \ \ \| | ||
* \ \ [_____| / / __/ \ / / //
* | \ [_____/ / / \ | \/ //
* | / '----| /=\____ _/ | / //
* __ / / | / ___/ _/\ \ | ||
* (/-(/-\) / \ (/\/\)/ | / | /
* (/\/\) / / //
* _________/ / /
* \____________/ (
*
*
* @author NTUDragons-Reborn
*/
public class Solution {
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task {
double eps = 0.00000001;
static final int MAXN = 100005;
static final int MOD = 1000000007;
// stores smallest prime factor for every number
static int spf[] = new int[MAXN];
static boolean[] prime;
Map<Integer, Set<Integer>> dp = new HashMap<>();
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
public void sieve() {
spf[1] = 1;
for (int i = 2; i < MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i = 4; i < MAXN; i += 2)
spf[i] = 2;
for (int i = 3; i * i < MAXN; i++) {
// checking if i is prime
if (spf[i] == i) {
// marking SPF for all numbers divisible by i
for (int j = i * i; j < MAXN; j += i)
// marking spf[j] if it is not
// previously marked
if (spf[j] == j)
spf[j] = i;
}
}
}
void sieveOfEratosthenes(int n) {
// Create a boolean array
// "prime[0..n]" and
// initialize all entries
// it as true. A value in
// prime[i] will finally be
// false if i is Not a
// prime, else true.
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] == true) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
public Set<Integer> getFactorization(int x) {
if (dp.containsKey(x))
return dp.get(x);
Set<Integer> ret = new HashSet<>();
while (x != 1) {
if (spf[x] != 2)
ret.add(spf[x]);
x = x / spf[x];
}
dp.put(x, ret);
return ret;
}
public Map<Integer, Integer> getFactorizationPower(int x) {
Map<Integer, Integer> map = new HashMap<>();
while (x != 1) {
map.put(spf[x], map.getOrDefault(spf[x], 0) + 1);
x /= spf[x];
}
return map;
}
// function to find first index >= x
public int lowerIndex(List<Integer> arr, int n, int x) {
int l = 0, h = n - 1;
while (l <= h) {
int mid = (l + h) / 2;
if (arr.get(mid) >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
public int lowerIndex(int[] arr, int n, int x) {
int l = 0, h = n - 1;
while (l <= h) {
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
public int upperIndex(List<Integer> arr, int n, int y) {
int l = 0, h = n - 1;
while (l <= h) {
int mid = (l + h) / 2;
if (arr.get(mid) <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
public int upperIndex(int[] arr, int n, int y) {
int l = 0, h = n - 1;
while (l <= h) {
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
// function to count elements within given range
public int countInRange(List<Integer> arr, int n, int x, int y) {
// initialize result
int count = 0;
count = upperIndex(arr, n, y) -
lowerIndex(arr, n, x) + 1;
return count;
}
public int add(int a, int b) {
a += b;
while (a >= MOD)
a -= MOD;
while (a < 0)
a += MOD;
return a;
}
public int mul(int a, int b) {
long res = (long) a * (long) b;
return (int) (res % MOD);
}
public int power(int a, int b) {
int ans = 1;
while (b > 0) {
if ((b & 1) != 0)
ans = mul(ans, a);
b >>= 1;
a = mul(a, a);
}
return ans;
}
int[] fact = new int[MAXN];
int[] inv = new int[MAXN];
public int Ckn(int n, int k) {
if (k < 0 || n < 0)
return 0;
if (n < k)
return 0;
return mul(mul(fact[n], inv[k]), inv[n - k]);
}
public int inverse(int a) {
return power(a, MOD - 2);
}
public void preprocess() {
fact[0] = 1;
for (int i = 1; i < MAXN; i++)
fact[i] = mul(fact[i - 1], i);
inv[MAXN - 1] = inverse(fact[MAXN - 1]);
for (int i = MAXN - 2; i >= 0; i--) {
inv[i] = mul(inv[i + 1], i + 1);
}
}
/**
* return VALUE of lower bound for unsorted array
*/
public int lowerBoundNormalArray(int[] arr, int x) {
TreeSet<Integer> set = new TreeSet<>();
for (int num : arr)
set.add(num);
return set.lower(x);
}
/**
* return VALUE of upper bound for unsorted array
*/
public int upperBoundNormalArray(int[] arr, int x) {
TreeSet<Integer> set = new TreeSet<>();
for (int num : arr)
set.add(num);
return set.higher(x);
}
public void debugArr(int[] arr) {
for (int i : arr)
out.print(i + " ");
out.println();
}
public int rand() {
int min = 0, max = MAXN;
int random_int = (int) Math.floor(Math.random() * (max - min + 1) + min);
return random_int;
}
public void shuffleSort(int[] arr) {
shuffleArray(arr);
Arrays.sort(arr);
}
public void shuffleArray(int[] ar) {
// If running on Java 6 or older, use new Random() on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
InputReader in;
PrintWriter out;
Scanner sc = new Scanner(System.in);
CustomFileReader cin;
int[] xor = new int[3 * 100000 + 5];
int[] pow2 = new int[1000000 + 1];
public void solve(InputReader in, PrintWriter out) throws Exception {
this.in = in;
this.out = out;
// sieveOfEratosthenes((int) Math.ceil(Math.sqrt(1000000000)));
// sieve();
// pow2[0]=1;
// for(int i=1;i<pow2.length;i++){
// pow2[i]= mul(pow2[i-1],2);
// }
int t = 1;
// preprocess();
// int t=in.nextInt();
// int t= cin.nextIntArrLine()[0];
for (int i = 1; i <= t; i++)
solveD(i);
}
final double pi = Math.acos(-1);
List[] adjs;
int[] a;
int[] cost;
int[] res;
public void solveD(int test) {
int n = in.nextInt();
adjs = new List[n + 1];
a = new int[n + 1];
cost = new int[n + 1];
res = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
res[i] = Integer.MIN_VALUE;
if (a[i] == 0)
a[i] = -1; // to eliminate with '1'
adjs[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int u = in.nextInt(), v = in.nextInt();
adjs[u].add(v);
adjs[v].add(u);
}
precompute(1, 0);
reroot(1, 0);
for (int i = 1; i <= n; i++)
out.print(res[i] + " ");
out.println();
}
void precompute(int u, int p) {
cost[u] += a[u];
for (int v : (List<Integer>) adjs[u]) {
if (v == p)
continue;
precompute(v, u);
cost[u] += Math.max(0, cost[v]);
}
}
void reroot(int u, int p) {
res[u] = Math.max(res[u], cost[u]);
for (int v : (List<Integer>) adjs[u]) {
if (v == p)
continue;
cost[u] -= Math.max(cost[v], 0);
cost[v] += Math.max(cost[u], 0);
reroot(v, u);
cost[v] -= Math.max(cost[u], 0);
cost[u] += Math.max(cost[v], 0);
}
}
static class ListNode {
int idx = -1;
ListNode next = null;
public ListNode(int idx) {
this.idx = idx;
}
}
public long _gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return _gcd(b, a % b);
}
}
public long _lcm(long a, long b) {
return (a * b) / _gcd(a, b);
}
}
// static class SEG {
// Pair[] segtree;
// public SEG(int n){
// segtree= new Pair[4*n];
// Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE));
// }
// // void buildTree(int l, int r, int index) {
// // if (l == r) {
// // segtree[index].y = a[l];
// // return;
// // }
// // int mid = (l + r) / 2;
// // buildTree(l, mid, 2 * index + 1);
// // buildTree(mid + 1, r, 2 * index + 2);
// // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index +
// 2].y);
// // }
// void update(int l, int r, int index, int pos, Pair val) {
// if (l == r) {
// segtree[index] = val;
// return;
// }
// int mid = (l + r) / 2;
// if (pos <= mid) update(l, mid, 2 * index + 1, pos, val);
// else update(mid + 1, r, 2 * index + 2, pos, val);
// if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){
// segtree[index]= segtree[2 * index + 1];
// }
// else {
// segtree[index]= segtree[2 * index + 2];
// }
// }
// // Pair query(int l, int r, int from, int to, int index) {
// // if (from <= l && r <= to)
// // return segtree[index];
// // if (r < from | to < l)
// // return 0;
// // int mid = (l + r) / 2;
// // Pair left= query(l, mid, from, to, 2 * index + 1);
// // Pair right= query(mid + 1, r, from, to, 2 * index + 2);
// // if(left.y < right.y) return left;
// // else return right;
// // }
// }
static class Venice {
public Map<Long, Long> m = new HashMap<>();
public long base = 0;
public long totalValue = 0;
private int M = 1000000007;
private long addMod(long a, long b) {
a += b;
if (a >= M)
a -= M;
return a;
}
public void reset() {
m = new HashMap<>();
base = 0;
totalValue = 0;
}
public void update(long add) {
base = base + add;
}
public void add(long key, long val) {
long newKey = key - base;
m.put(newKey, addMod(m.getOrDefault(newKey, (long) 0), val));
}
}
static class Tuple implements Comparable<Tuple> {
int x, y, z;
public Tuple(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int compareTo(Tuple o) {
return this.z - o.z;
}
}
static class Point implements Comparable<Point> {
public double x;
public long y;
public Point(double x, long y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point o) {
if (this.y != o.y)
return (int) (this.y - o.y);
return (int) (this.x - o.x);
}
}
// static class Vector {
// public long x;
// public long y;
// // p1 -> p2
// public Vector(Point p1, Point p2){
// this.x= p2.x-p1.x;
// this.y= p2.y-p1.y;
// }
// }
static class Pair implements Comparable<Pair> {
public int x;
public int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if (this.x != o.x)
return (int) (this.x - o.x);
return (int) (this.y - o.y);
}
}
// public static class compareL implements Comparator<Tuple>{
// @Override
// public int compare(Tuple t1, Tuple t2) {
// return t2.l - t1.l;
// }
// }
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public int[] nextIntArr(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public long[] nextLongArr(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public List<Integer> nextIntList(int n) {
List<Integer> arr = new ArrayList<>();
for (int i = 0; i < n; i++)
arr.add(nextInt());
return arr;
}
public int[][] nextIntMatArr(int n, int m) {
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
mat[i][j] = nextInt();
return mat;
}
public List<List<Integer>> nextIntMatList(int n, int m) {
List<List<Integer>> mat = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<Integer> temp = new ArrayList<>();
for (int j = 0; j < m; j++)
temp.add(nextInt());
mat.add(temp);
}
return mat;
}
public char[] nextStringCharArr() {
return nextToken().toCharArray();
}
}
static class CustomFileReader {
String path = "";
Scanner sc;
public CustomFileReader(String path) {
this.path = path;
try {
sc = new Scanner(new File(path));
} catch (Exception e) {
}
}
public String nextLine() {
return sc.nextLine();
}
public int[] nextIntArrLine() {
String line = sc.nextLine();
String[] part = line.split("[\\s+]");
int[] res = new int[part.length];
for (int i = 0; i < res.length; i++)
res[i] = Integer.parseInt(part[i]);
return res;
}
}
} | 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 javax.swing.text.html.parser.Entity;
import java.io.*;
import java.util.*;
import java.math.BigInteger;
/**
_ _
( _) ( _)
/ / \\ / /\_\_
/ / \\ / / | \ \
/ / \\ / / |\ \ \
/ / , \ , / / /| \ \
/ / |\_ /| / / / \ \_\
/ / |\/ _ '_| \ / / / \ \\
| / |/ 0 \0\ / | | \ \\
| |\| \_\_ / / | \ \\
| | |/ \.\ o\o) / \ | \\
\ | /\\`v-v / | | \\
| \/ /_| \\_| / | | \ \\
| | /__/_ - / ___ | | \ \\
\| [__] \_/ |_________ \ | \ ()
/ [___] ( \ \ |\ | | //
| [___] |\| \| / |/
/| [____] \ |/\ / / ||
( \ [____ / ) _\ \ \ \| | ||
\ \ [_____| / / __/ \ / / //
| \ [_____/ / / \ | \/ //
| / '----| /=\____ _/ | / //
__ / / | / ___/ _/\ \ | ||
(/-(/-\) / \ (/\/\)/ | / | /
(/\/\) / / //
_________/ / /
\____________/ (
@author NTUDragons-Reborn
*/
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);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task{
double eps= 0.00000001;
static final int MAXN = 1010;
static final int MOD= 1000000007;
// stores smallest prime factor for every number
static int spf[] = new int[MAXN];
static boolean[] prime;
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
public void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j=i*i; j<MAXN; j+=i)
// marking spf[j] if it is not
// previously marked
if (spf[j]==j)
spf[j] = i;
}
}
}
void sieveOfEratosthenes(int n)
{
// Create a boolean array
// "prime[0..n]" and
// initialize all entries
// it as true. A value in
// prime[i] will finally be
// false if i is Not a
// prime, else true.
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] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// function to find first index >= x
public int lowerIndex(List<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
public int lowerIndex(int[] arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
public int upperIndex(List<Integer> arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
public int upperIndex(int[] arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
// function to count elements within given range
public int countInRange(List<Integer> arr, int n, int x, int y)
{
// initialize result
int count = 0;
count = upperIndex(arr, n, y) -
lowerIndex(arr, n, x) + 1;
return count;
}
public int _gcd(int a, int b)
{
if(b == 0) {
return a;
}
else {
return _gcd(b, a % b);
}
}
public int add(int a, int b){
a+=b;
if(a>=MOD) a-=MOD;
else if(a<0) a+=MOD;
return a;
}
public int mul(int a, int b){
long res= (long)a*(long)b;
return (int)(res%MOD);
}
public int power(int a, int b) {
int ans=1;
while(b>0){
if((b&1)!=0) ans= mul(ans,a);
b>>=1;
a= mul(a,a);
}
return ans;
}
int[] fact= new int[MAXN];
int[] inv= new int[MAXN];
public int Ckn(int n, int k){
if(k<0 || n<0) return 0;
return mul(mul(fact[n],inv[k]),inv[n-k]);
}
public int inverse(int a){
return power(a,MOD-2);
}
public void preprocess() {
fact[0]=1;
for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i);
inv[MAXN-1]= inverse(fact[MAXN-1]);
for(int i=MAXN-2;i>=0;i--){
inv[i]= mul(inv[i+1],i+1);
}
}
/**
* return VALUE of lower bound for unsorted array
*/
public int lowerBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.lower(x);
}
/**
* return VALUE of upper bound for unsorted array
*/
public int upperBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.higher(x);
}
public void debugArr(int[] arr){
for(int i: arr) out.print(i+" ");
out.println();
}
public int rand(){
int min=0, max= MAXN;
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
return random_int;
}
InputReader in; PrintWriter out;
static class fenwick{
int n;
int bit[];
public fenwick(int n){
bit = new int[n+1];
}
public void upd(int i, int d){
i++;
while (i < bit.length){
bit[i]+=d; i+=i&(-i);
}
}
int get(int i){
i++;
int r = 0;
while (i > 0){
r+=bit[i]; i-=i&-i;
}
return r;
}
}
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int lo[] = new int[n];
int hi[] = new int[n];
int pos[] = new int[n];
fenwick tree = new fenwick(n+m);
for (int i = 0; i < n; i++){
lo[i] = i+1;
hi[i] = i+1;
pos[i] = m + i;
tree.upd(pos[i], 1);
}
for (int i = 0; i < m; i++){
int message = in.nextInt()-1;
lo[message] = 1;
hi[message] = Math.max(hi[message], tree.get(pos[message]));
tree.upd(pos[message], -1);
pos[message] = m-i-1;
tree.upd(pos[message], 1);
}
for (int i = 0; i < n; i++){
hi[i] = Math.max(hi[i], tree.get(pos[i]));
}
for (int i = 0; i < n; i++){
out.println(lo[i] + " " + hi[i]);
}
}
class SEG {
int n;
int[] segs;
public SEG (int[] a){
this.n= a.length;
segs= new int[4*this.n];
build(a,0,0,this.n-1);
}
public void build(int[] a, int root, int l, int r){
if(l==r){
segs[root]=a[l];
return;
}
int m= (l+r)/2;
build(a,2*root+1,l,m);
build(a,2*root+2,m+1,r);
segs[root]= _gcd(segs[2*root+1], segs[2*root+2]);
}
public int query(int root, int l, int r, int lq, int rq){
if(lq<=l && rq>=r) return segs[root];
if(lq>r || rq<l) return 0;
int m= (l+r)/2;
int left= query(2*root+1, l, m, lq, rq);
int right= query(2*root+2, m+1, r, lq, rq);
return _gcd(left,right);
}
}
}
static class Venice{
public Map<Long,Long> m= new HashMap<>();
public long base=0;
public long totalValue=0;
private int M= 1000000007;
private long addMod(long a, long b){
a+=b;
if(a>=M) a-=M;
return a;
}
public void reset(){
m= new HashMap<>();
base=0;
totalValue=0;
}
public void update(long add){
base= base+ add;
}
public void add(long key, long val){
long newKey= key-base;
m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val));
}
}
static class Tuple implements Comparable<Tuple>{
int x, y, z;
public Tuple(int x, int y, int z){
this.x= x;
this.y= y;
this.z=z;
}
@Override
public int compareTo(Tuple o){
return this.x-o.x;
}
}
static class Pair implements Comparable<Pair>{
public int x;
public int y;
public Pair(int x, int y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Pair o) {
return this.x-o.x;
}
}
// public static class compareL implements Comparator<Tuple>{
// @Override
// public int compare(Tuple t1, Tuple t2) {
// return t2.l - t1.l;
// }
// }
// fast input reader class;
static class InputReader {
public BufferedReader br;
public StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public long nextLong(){
return Long.parseLong(nextToken());
}
public int[] nextIntArr(int n){
int[] arr= new int[n];
for(int i=0;i<n;i++) arr[i]= nextInt();
return arr;
}
public long[] nextLongArr(int n){
long[] arr= new long[n];
for(int i=0;i<n;i++) arr[i]= nextLong();
return arr;
}
public List<Integer> nextIntList(int n){
List<Integer> arr= new ArrayList<>();
for(int i=0;i<n;i++) arr.add(nextInt());
return arr;
}
public int[][] nextIntMatArr(int n, int m){
int[][] mat= new int[n][m];
for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt();
return mat;
}
public List<List<Integer>> nextIntMatList(int n, int m){
List<List<Integer>> mat= new ArrayList<>();
for(int i=0;i<n;i++){
List<Integer> temp= new ArrayList<>();
for(int j=0;j<m;j++) temp.add(nextInt());
mat.add(temp);
}
return mat;
}
public char[] nextStringCharArr(){
return nextToken().toCharArray();
}
}
} | java |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy 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 one of the two 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 say if it is possible to color the given string 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≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000
| [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | import java.util.Scanner;
public class StringColouring {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
int[] dp = new int[length];
dp[0] = 1;
String chars = scanner.next();
for (int i = 1; i < length; i++) {
for (int j = 0; j < i; j++) {
if (index(chars.charAt(j)) > index(chars.charAt(i))) dp[i] = Math.max(dp[i], dp[j]);
}
if (dp[i] + 1 >= 3) {
System.out.println("NO");
return;
}
dp[i]++;
}
int max = index(chars.charAt(0));
StringBuilder result = new StringBuilder().append(0);
for (int i = 1; i < chars.length(); i++) {
int ind = index(chars.charAt(i));
if (ind < max) result.append(1);
else {
if (ind > max) max = ind;
result.append(0);
}
}
System.out.println("YES");
System.out.println(result);
}
private static int index(char ch) {
return ch - 'a';
}
private static int lowBits(int n) {
return n & (-n);
}
} | java |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | // package Codeforce.cf615;
import java.io.PrintWriter;
import java.util.List;
import java.util.*;
public class F {
// MUST SEE BEFORE SUBMISSION
// check whether int part would overflow or not, especially when it is a * b!!!!
// check if top down dp would cause overflow or not !!!!!!!!!!!!!!!!!!!!!!
// ------------consider only if you running into mistake--------
// consider all the edge cases such as k > 0 or k >= 0
// consider some edge case such as extreme situation
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 int[] maxLen = new int[]{-1, Integer.MIN_VALUE};
static void solve(Scanner in, PrintWriter out){
int n = in.nextInt();
int[][] arr = new int[n - 1][2];
for(int i = 0; i < n - 1; i++){
arr[i] = new int[]{in.nextInt() - 1, in.nextInt() - 1};
}
Map<Integer, List<Integer>> mp = new HashMap<>();
for(int[] e : arr){
if (!mp.containsKey(e[0])) mp.put(e[0], new ArrayList<>());
if (!mp.containsKey(e[1])) mp.put(e[1], new ArrayList<>());
mp.get(e[1]).add(e[0]);
mp.get(e[0]).add(e[1]);
}
dfs1(mp, 0, -1, 0);
int start = maxLen[0];
maxLen = new int[]{-1, -1};
dfs1(mp, start, -1, 0);
int end = maxLen[0];
int len = maxLen[1];
LinkedList<Integer> q = new LinkedList<>();
maxLen = new int[]{-1, -1};
dfs2(mp, start, end, -1, q);
Set<Integer> set = new HashSet<>(q);
for(int v : q){
if (v == start || v == end) continue;
dfs3(mp, v, -1, set, 0);
}
int mx = len + maxLen[1];
out.println(mx);
out.println((start + 1) + " " + (end + 1) + " " + (maxLen[0] + 1));
}
static void dfs3(Map<Integer, List<Integer>> gra, int cur, int par, Set<Integer> set, int depth){
if (maxLen[1] < depth){
maxLen = new int[]{cur, depth};
}
for(int nxt : gra.get(cur)){
if (nxt == par || set.contains(nxt)) continue;
dfs3(gra, nxt, cur, set, depth + 1);
}
}
static void dfs1(Map<Integer, List<Integer>> gra, int cur, int par, int depth){
if (maxLen[1] < depth){
maxLen = new int[]{cur, depth};
}
for(int nxt : gra.get(cur)){
if (nxt == par) continue;
dfs1(gra, nxt, cur, depth + 1);
}
}
static boolean dfs2(Map<Integer, List<Integer>> gra, int cur, int tar, int par, LinkedList<Integer> q){
if (cur == tar){
q.add(tar);
return true;
}
for(int nxt : gra.get(cur)){
if (nxt == par){
continue;
}
if (dfs2(gra, nxt, tar, cur, q)){
q.add(cur);
return true;
}
}
return false;
}
}
| 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.*;
import java.util.*;
public class D {
static int dis(int l, int r, int[] a) {
HashSet<Integer> set = new HashSet();
for (int i = l; i < r; i++)
set.add(a[i]);
return set.size();
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), m = sc.nextInt();
int[] min = new int[n + 1], max = new int[n + 1];
ArrayList<Integer>[] occ = new ArrayList[n + 1], queries = new ArrayList[m];
for (int i = 1; i <= n; i++) {
min[i] = max[i] = i;
occ[i] = new ArrayList();
}
FenwickTree tree = new FenwickTree(n+m+2);
int[] a = new int[m];
for (int i = 0; i < m; i++) {
a[i] = sc.nextInt();
min[a[i]] = 1;
if (occ[a[i]].size() == 0) {
max[a[i]] += tree.query(a[i] + 1, n);
tree.update(a[i], 1);
}
occ[a[i]].add(i);
queries[i] = new ArrayList();
}
for (int i = 1; i <= n; i++) {
if (occ[i].size() == 0) {
max[i] += tree.query(i + 1, n);
continue;
}
occ[i].add(m);
for (int j = 0; j + 1 < occ[i].size(); j++) {
int l = occ[i].get(j), r = occ[i].get(j + 1) - 1;
// max[i] = Math.max(max[i], dis(l, r, a));
queries[r].add(l);
}
}
Arrays.fill(tree.bit, 0);
int[] last = new int[n + 1];
Arrays.fill(last, -1);
for (int r = 0; r < m; r++) {
if (last[a[r]] != -1) {
tree.update(last[a[r]] + 1, -1);
}
last[a[r]] = r;
tree.update(r + 1, 1);
for (int l : queries[r]) {
max[a[l]] = Math.max(max[a[l]], tree.query(l + 1, r + 1));
}
}
for (int i = 1; i <= n; i++) {
out.println(min[i] + " " + max[i]);
}
out.close();
}
static class FenwickTree {
int[] bit;
FenwickTree(int n) {
bit = new int[n + 1];
}
int query(int l, int r) {
return query(r) - query(l - 1);
}
int query(int idx) {
int ans = 0;
while (idx > 0) {
ans += bit[idx];
idx -= idx & -idx;
}
return ans;
}
void update(int idx, int v) {
while (idx < bit.length) {
bit[idx] += v;
idx += idx & -idx;
}
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
static void shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
}
} | 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 java.util.*;
public class P3{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int[] a=new int[n];
long mul=1;
for (int i=0;i<n;++i) {
a[i]=sc.nextInt();
}
if (n>m) {
System.out.println("0");
}
else{
for (int i=0;i<n-1;++i) {
for (int j=i+1;j<n;++j) {
mul= mul%m * Math.abs(a[i]-a[j])%m;
}
}
System.out.println(mul%m);
}
}
} | java |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.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 as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO". | [
"geometry",
"greedy",
"math",
"number theory"
] |
import java.math.BigInteger;
import java.sql.Array;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class A {
static FastScanner scan = new FastScanner();
static Scanner scanner = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static long MOD = 998244353;
static long MOD2 = MOD * MOD;
static int pInf = Integer.MAX_VALUE;
static int nInf = Integer.MIN_VALUE;
static long ded = (long)(1e17)+9;
public static void main(String[] args) {
int t = scan.nextInt();
while(t--!=0){
solve();
}
out.close();
}
public static void solve() {
int n = scan.nextInt();
int m = scan.nextInt();
if(n%m==0){
out.println("YES");
}
else{
out.println("NO");
}
}
static class Pair implements Comparable<Pair> {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
// this.idx = idx;
}
@Override
public int compareTo(Pair o){
if(this.y==o.y){
return this.x-o.x;
}
return this.y-o.y;
}
}
public static long mul(long a, long b) {
return ((a % MOD) * (b % MOD)) % MOD;
}
public static long add(long a, long b) {
return ((a % MOD) + (b % MOD)) % MOD;
}
public static long c2(long n) {
if ((n & 1) == 0) {
return mul(n / 2, n - 1);
} else {
return mul(n, (n - 1) / 2);
}
}
//Shuffle Sort
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); int temp= a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
//Brian Kernighans Algorithm
static long countSetBits(long n) {
if (n == 0) return 0;
return 1 + countSetBits(n & (n - 1));
}
//Euclidean Algorithm
static long gcd(long A, long B) {
if (B == 0) return A;
return gcd(B, A % B);
}
//Modular Exponentiation
static long fastExpo(long x, long n) {
if (n == 0) return 1;
if ((n & 1) == 0) return fastExpo((x * x) % MOD, n / 2) % MOD;
return ((x % MOD) * fastExpo((x * x) % MOD, (n - 1) / 2)) % MOD;
}
//AKS Algorithm
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 <= Math.sqrt(n); i += 6)
if (n % i == 0 || n % (i + 2) == 0) return false;
return true;
}
public static long modinv(long x) {
return modpow(x, MOD - 2);
}
public static long modpow(long a, long b) {
if (b == 0) {
return 1;
}
long x = modpow(a, b / 2);
x = (x * x) % MOD;
if (b % 2 == 1) {
return (x * a) % MOD;
}
return x;
}
/* public static void solve(){
int n = scan.nextInt();
int q = scan.nextInt();
int[] arr = new int[n];
int[] brr = new int[q];
for (int i =0;i<n;i++)arr[i]= scan.nextInt();
for (int i =0;i<q;i++)brr[i]= scan.nextInt();
int J=0;
while (q-->0){
int find = arr[J];
int l =0,r=arr.length;
while (l<=r){
int mid = (l + r ) / 2;
if(arr[mid]==find){
out.println(mid+1);
break;
}
else if(arr[mid]>find){
l = mid +1;
}
else{
r = mid-1;
}
}
J++;
}
}*/
//2 4 8 16 32 64
// 128 --
public static boolean isInteger(int n) {
return Math.sqrt(n) % 1 == 0;
}
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());
}
}
} | java |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good. | [
"math"
] |
import static java.lang.Math.*;
import java.awt.Point;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Exercise {
static Scanner sc = new Scanner(System.in);
//B. Composite Coloring
public static void solve() {
long l = sc.nextInt();
long g = sc.nextInt();
long b = sc.nextInt();
if(g >= l) {
System.out.println(l);
} else {
long tt = (long) ceil(l/2.0);
long res = tt % g;
long div = tt / g ;
long result = (div * g) + ((div - 1) * b);
if(res > 0) result += res + b;
if(result < l) System.out.println(l);
else System.out.println(result);
}
}
public static void main(String args[]) {
int test = sc.nextInt();
while(test-- != 0) solve();
}
}
| java |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.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 nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
| [
"greedy",
"math",
"number theory"
] | //package com.company;
import java.io.BufferedReader;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
//For submitting solution in KickStart change class name from C1 to Solution then submit it
//and for AtCoder class name should be Main
public class Solution{
public static void sieve(int n,ArrayList<Integer>l) {
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] == true)
{
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
l.add(i);
//System.out.print(i + " ");
}
}
public static long check(long x)
{
// check for the set bits
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
public static String sortString(String inputString)
{
// Converting input string to character array
char tempArray[] = inputString.toCharArray();
// Sorting temp array using
Arrays.sort(tempArray);
// Returning new sorted string
return new String(tempArray);
}
public static int isSubstring(
String s1, String s2)
{
int M = s1.length();
int N = s2.length();
for (int i = 0; i <= N - M; i++) {
int j;
for (j = 0; j < M; j++)
if (s2.charAt(i + j)
!= s1.charAt(j))
break;
if (j == M)
return i;
}
return -1;
}
public static class DSU{
// Declaring two arrays to hold
// information about the parent and
// rank of each node.
private int parent[];
private int rank[];
// Constructor
DSU(int n){
// Defining size of the arrays.
parent=new int[n];
rank=new int[n];
// Initializing their values
// by is and 0s.
for(int i=0;i<n;i++)
{
parent[i]=i;
rank[i]=0;
}
}
// Find function
public int find(int node){
// If the node is the parent of
// itself then it is the leader
// of the tree.
if(node==parent[node]) return node;
//Else, finding parent and also
// compressing the paths.
return parent[node]=find(parent[node]);
}
// Union function
public void union(int u,int v){
// Make u as a leader
// of its tree.
u=find(u);
// Make v as a leader
// of its tree.
v=find(v);
// If u and v are not equal,
// because if they are equal then
// it means they are already in
// same tree and it does not make
// sense to perform union operation.
if(u!=v)
{
// Checking tree with
// smaller depth/height.
if(rank[u]<rank[v])
{
int temp=u;
u=v;
v=temp;
}
// Attaching lower rank tree
// to the higher one.
parent[v]=u;
// If now ranks are equal
// increasing rank of u.
if(rank[u]==rank[v])
rank[u]++;
}
}
}
public static class pair implements Comparable<pair>{
int x;
int y;
pair(int x,int y){
this.x=x;
this.y=y;
}
@Override
public int compareTo(pair o) {
return this.y-o.y;
}
/* use when to compare two strings
if(this.y.compareTo(o.y)<0){
return o.y.compareTo(this.y);
}
else{
return o.y.compareTo(this.y);
}*/
}
static void printDivisors(int n,ArrayList<Integer>l,int check)
{
// Note that this loop runs till square root
for (int i=2; i<=Math.sqrt(n); i++)
{
if (n%i==0) {
// If divisors are equal, print only one
if (n / i == i && i!=check) {
l.add(i);
}
else {
l.add(i);
l.add(n/i);
}
}
}
}
static void printDivisors2(int n,ArrayList<Integer>l,int check)
{
// Note that this loop runs till square root
for (int i=2; i<=Math.sqrt(n); i++)
{
if (n%i==0) {
// If divisors are equal, print only one
if (n / i == i && i!=check) {
l.add(i);
}
else {
if(check!=i) {
l.add(i);
}
else if(check!=n/i){
l.add(n/i);
}
}
}
}
}
static long power(int x, int y, int p)
{
int res = 1; // Initialize result
while (y > 0) {
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = res * x;
// y must be even now
y = y >> 1; // y = y/2
x = x * x; // Change x to x^2
}
return res % p;
}
public static void main(String[] args) {
FastScanner sc=new FastScanner();
int t=sc.i();
while(t-->0){
int n=sc.i();
ArrayList<Integer> l=new ArrayList<>();
printDivisors(n,l,-1);
//System.out.println(l);
if(l.size()<=2){
System.out.println("NO");
}
else{
Collections.sort(l);
int n1=l.get(0);
l.clear();
printDivisors2(n/n1,l,n1);
//System.out.println(n1);
Collections.sort(l);
int n2=l.get(0);
int n3=n/(n1*n2);
//System.out.println(n1+" "+n2+" "+n3);
if(n1==n3 || n2==n3 || n1==n2 || n!=n1*n2*n3 || n1<2 || n2<2 || n3<2){
System.out.println("NO");
}
else{
System.out.println("YES");
System.out.println(n1+" "+n2+" "+n3);
}
}
}
}
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*b)/gcd(a,b);
}
static boolean isPrime(long n) {
if(n <=1 )return false;
if(n==2) return true;
if(n%2==0) return false;
for(int i=3;i<=Math.sqrt(n);i+=2)
if(n%i==0) return false;
return true;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
static boolean isPalindrome(String s,int start,int end) {
int i = start, j = end;
while (i < j) {
if (s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
}
class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String n() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int[] ia(int n) {
int[] arr = new int[n];
for(int i=0;i<n;i++)
arr[i] = i();
return arr;
}
String[] sa(int n) {
String[] arr = new String[n];
for(int i=0;i<n;i++)
arr[i] = n();
return arr;
}
long[] la(int n) {
long[] arr = new long[n];
for(int i=0;i<n;i++)
arr[i] = l();
return arr;
}
String nl()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
int i() {
return Integer.parseInt(n());
}
long l() {
return Long.parseLong(n());
}
} | 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.util.*;
import java.io.*;
public class A {
static class Pair {
long x;
long y;
public Pair(long x, long y) {
this.x = x;
this.y = y;
}
}
static long gcd(long n, long m) {
if (m == 0)
return n;
else
return gcd(m, n % m);
}
static long lcm(long n, long m) {
return (n * m) / gcd(n, m);
}
static void dfs(ArrayList<ArrayList<Integer>> adj, int s, int[] vis, int[] cnt) {
for (int i : adj.get(s)) {
if (vis[i] == 1) {
continue;
}
cnt[0]++;
vis[i] = 1;
dfs(adj, i, vis, cnt);
}
}
public static long solve(long a, long b, long x, long y, long n) {
if (a - n >= x) {
return ((a - n) * b);
} else {
n -= a - x;
a = x;
if (b - n >= y) {
return (a * (b - n));
} else {
b = y;
return (a * b);
}
}
}
static int high(int n) {
int p = (int) (Math.log(n) / Math.log(2));
return (int) Math.pow(2, p);
}
static void reverseandflip(char[] s1, int pos) {
int i = 0;
int j = pos;
while (i <= j) {
if (s1[i] == s1[j]) {
if (s1[i] == '1') {
s1[i] = '0';
s1[j] = '0';
} else {
s1[i] = '1';
s1[j] = '1';
}
}
i++;
j--;
}
}
static int bs(ArrayList<Long> pow, long target) {
int low = 0;
int idx = -1;
int high = pow.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (pow.get(mid) <= target) {
low = mid + 1;
idx = mid;
} else {
high = mid - 1;
}
}
return idx;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
StringBuilder str = new StringBuilder();
int t = sc.nextInt();
for (int xx = 0; xx < t; xx++) {
int n = sc.nextInt();
int k = sc.nextInt();
long[] arr = new long[n];
long max = 0;
for (int i = 0; i < n; i++) {
arr[i] = sc.nextLong();
max = Math.max(max, arr[i]);
}
ArrayList<Long> pow = new ArrayList<>();
pow.add(1L);
pow.add((long) k);
while (true) {
pow.add(pow.get(pow.size() - 1) * k);
if (pow.get(pow.size() - 1) >= max)
break;
}
boolean ok = true;
for (int i = 0; i < n; i++) {
if (arr[i] == 0)
continue;
while (arr[i] != 0) {
if (pow.size() == 0)
break;
int id = bs(pow, arr[i]);
if (id == -1)
break;
arr[i] -= pow.get(id);
pow.remove(id);
}
if (arr[i] != 0) {
ok = false;
break;
}
}
if (ok)
str.append("YES" + "\n");
else
str.append("NO" + "\n");
}
System.out.println(str);
sc.close();
}
} | 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.util.Scanner;
public class D {
public static void main(String [] args)
{
Scanner sc=new Scanner(System.in);
long u=sc.nextLong();
long v=sc.nextLong();
if(u>v||u%2!=v%2)
{
System.out.println(-1);
return;
}
if(u==v)
{
if(u!=0)
System.out.println(1);
System.out.println(u);
return;
}
long rem=(v-u)/2;
if((rem&u)==0)
{
System.out.println(2);
System.out.println((rem^u)+" "+rem);
}
else
{
System.out.println(3);
System.out.println(u+" "+(v-u)/2l+" "+(v-u)/2l);
}
}
}
| 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 static java.lang.System.out;
import static java.lang.Math.*;
import java.util.*;
import javax.naming.ContextNotEmptyException;
import javax.swing.ImageIcon;
import javax.swing.table.TableStringConverter;
import javax.swing.text.DefaultStyledDocument.ElementSpec;
import java.io.*;
import java.math.*;
import java.rmi.ConnectIOException;
public class Main {
static FastReader sc;
static long mod = ((long) 1e9) + 7;
static Tree tree;
static PrintWriter out, err;
static int imax = Integer.MAX_VALUE;
static int imin = Integer.MIN_VALUE;
static long lmax = Long.MAX_VALUE;
static long lmin = Long.MIN_VALUE;
static double dmax = Double.MAX_VALUE;
static double dmin = Double.MIN_VALUE;
private static void solve() throws IOException {
int n=sc.nextInt();
String s=sc.next();
Stack<Character> st=new Stack<>();
int open=0;
int close=0;
int ans=0;
for(int i=0;i<n;i++){
char ch=s.charAt(i);
if(ch==')'&&!st.isEmpty()&&st.peek()=='(')st.pop();
else st.add(ch);
if(ch=='(')open++;
else close++;
if(open==close){
if(!st.isEmpty()){
// debug(i+" "+);
ans+=open+close;
}
open=0;
close=open;
st=new Stack<>();
}
}
if(st.size()>0){
print(-1);
}else{
print(ans);
}
}
public static void main(String hi[]) throws IOException {
initializeIO();
out = new PrintWriter(System.out);
err = new PrintWriter(System.err);
sc = new FastReader();
long startTimeProg = System.currentTimeMillis();
long endTimeProg;
int testCase = 1;
// testCase = sc.nextInt();
while (testCase-- != 0) {
solve();
}
endTimeProg = System.currentTimeMillis();
debug("[finished : " + (endTimeProg - startTimeProg) + ".ms ]");
out.flush();
err.flush();
// System.out.println(String.format("%.9f", max));
}
private static class Pair {
int first = 0;
int sec = 0;
int[] arr;
char ch;
String s;
Map<Integer, Integer> map;
Pair(int first, int sec) {
this.first = first;
this.sec = sec;
}
Pair(int[] arr) {
this.map = new HashMap<>();
for (int x : arr)
this.map.put(x, map.getOrDefault(x, 0) + 1);
this.arr = arr;
}
Pair(char ch, int first) {
this.ch = ch;
this.first = first;
}
Pair(String s, int first) {
this.s = s;
this.first = first;
}
}
private static Set<Long> factors(long n) {
Set<Long> res = new HashSet<>();
// res.add(n);
for (long i = 1; i * i <= (n); i++) {
if (n % i == 0) {
res.add(i);
if (n / i != i) {
res.add(n / i);
}
}
}
return res;
}
private static long factorsCount(long n) {
long val = 0;
for (long i = 1; i * i <= (n); i++) {
if (n % i == 0) {
val++;
if (n / i != i) {
val++;
}
}
}
return val;
}
// geometrics
private static double areaOftriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
double[] mid_point = midOfaLine(x1, y1, x2, y2);
// debug(Arrays.toString(mid_point)+" "+x1+" "+y1+" "+x2+" "+y2+" "+x3+" "+"
// "+y3);
double height = distanceBetweenPoints(mid_point[0], mid_point[1], x3, y3);
double wight = distanceBetweenPoints(x1, y1, x2, y2);
// debug(height+" "+wight);
return (height * wight) / 2;
}
private static double distanceBetweenPoints(double x1, double y1, double x2, double y2) {
double x = x2 - x1;
double y = y2 - y1;
return (Math.pow(x, 2) + Math.pow(y, 2));
}
private static double[] midOfaLine(double x1, double y1, double x2, double y2) {
double[] mid = new double[2];
mid[0] = (x1 + x2) / 2;
mid[1] = (y1 + y2) / 2;
return mid;
}
/* Function to calculate x raised to the power y in O(logn) */
static long power(long x, long y) {
long temp;
if (y == 0)
return 1l;
temp = power(x, y / 2);
if (y % 2 == 0)
return (temp * temp);
else
return (x * temp * temp);
}
private static StringBuilder reverseString(String s) {
StringBuilder sb = new StringBuilder(s);
int l = 0, r = sb.length() - 1;
while (l <= r) {
char ch = sb.charAt(l);
sb.setCharAt(l, sb.charAt(r));
sb.setCharAt(r, ch);
l++;
r--;
}
return sb;
}
private static void swap(List<Integer> li, int i, int j) {
int t = li.get(i);
li.set(i, li.get(j));
li.set(j, t);
}
private static void swap(int[] arr, int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static boolean isPallindrome(String s, int l, int r) {
while (l < r) {
if (s.charAt(l) != s.charAt(r))
return false;
l++;
r--;
}
return true;
}
private static StringBuilder removeLeadingZero(StringBuilder sb) {
int i = 0;
while (i < sb.length() && sb.charAt(i) == '0')
i++;
// debug("remove "+i);
if (i == sb.length())
return new StringBuilder();
return new StringBuilder(sb.substring(i, sb.length()));
}
private static void print(int[][] arr) {
int n = arr.length;
int m = arr[0].length;
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
out.print(arr[i][j] + " ");
}
out.println();
}
}
private static StringBuilder removeEndingZero(StringBuilder sb) {
int i = sb.length() - 1;
while (i >= 0 && sb.charAt(i) == '0')
i--;
if (i < 0)
return new StringBuilder();
return new StringBuilder(sb.substring(0, i + 1));
}
private static void debug(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(long[][] arr) {
for (int i = 0; i < arr.length; i++) {
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(List<int[]> arr) {
for (int[] a : arr) {
err.println(Arrays.toString(a));
}
}
private static void debug(float[][] arr) {
for (int i = 0; i < arr.length; i++) {
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(double[][] arr) {
for (int i = 0; i < arr.length; i++) {
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(boolean[][] arr) {
for (int i = 0; i < arr.length; i++) {
err.println(Arrays.toString(arr[i]));
}
}
// private static void print() throws IOException {
// out.println(s);
// }
private static void debug(String s) throws IOException {
err.println(s);
}
private static void print(double s) throws IOException {
out.println(s);
}
private static void print(float s) throws IOException {
out.println(s);
}
private static void print(long s) throws IOException {
out.println(s);
}
private static void print(int s) throws IOException {
out.println(s);
}
private static void debug(double s) throws IOException {
err.println(s);
}
private static void debug(float s) throws IOException {
err.println(s);
}
private static void debug(long s) {
err.println(s);
}
private static void debug(int s) {
err.println(s);
}
private 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 (int i = 3; i * i <= n; i += 2) {
if (n % i == 0)
return false;
}
return true;
}
private static List<List<Integer>> readUndirectedGraph(int n) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
graph.get(x).add(y);
graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readUndirectedGraph(int[][] intervals, int n) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < intervals.length; i++) {
int x = intervals[i][0];
int y = intervals[i][1];
graph.get(x).add(y);
graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readDirectedGraph(int[][] intervals, int n) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < intervals.length; i++) {
int x = intervals[i][0];
int y = intervals[i][1];
graph.get(x).add(y);
// graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readDirectedGraph(int n) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
graph.get(x).add(y);
// graph.get(y).add(x);
}
return graph;
}
static String[] readStringArray(int n) {
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.next();
}
return arr;
}
private static Map<Character, Integer> freq(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
return map;
}
private static Map<Long, Integer> freq(long[] arr) {
Map<Long, Integer> map = new HashMap<>();
for (long x : arr) {
map.put(x, map.getOrDefault(x, 0) + 1);
}
return map;
}
private static Map<Integer, Integer> freq(int[] arr) {
Map<Integer, Integer> map = new HashMap<>();
for (int x : arr) {
map.put(x, map.getOrDefault(x, 0) + 1);
}
return map;
}
static boolean[] sieveOfEratosthenes(long n) {
boolean prime[] = new boolean[(int) n + 1];
for (int i = 2; 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] == true) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
static int[] sieveOfEratosthenesInt(long n) {
boolean prime[] = new boolean[(int) n + 1];
Set<Integer> li = new HashSet<>();
for (int i = 2; i <= n; i++) {
prime[i] = true;
}
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i += p) {
prime[i] = false;
}
}
}
for (int i = 0; i <= n; i++) {
if (prime[i])
li.add(i);
}
int[] arr = new int[li.size()];
int i = 0;
for (int x : li) {
arr[i++] = x;
}
return arr;
}
static boolean isMemberAC(int a, int d, int x) {
// If difference is 0, then x must
// be same as a.
if (d == 0)
return (x == a);
// Else difference between x and a
// must be divisible by d.
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
static boolean isMemberAC(long a, long d, long x) {
// If difference is 0, then x must
// be same as a.
if (d == 0)
return (x == a);
// Else difference between x and a
// must be divisible by d.
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
private static void sort(int[] arr) {
int n = arr.length;
List<Integer> li = new ArrayList<>();
for (int x : arr) {
li.add(x);
}
Collections.sort(li);
for (int i = 0; i < n; i++) {
arr[i] = li.get(i);
}
}
private static void sortReverse(int[] arr) {
int n = arr.length;
List<Integer> li = new ArrayList<>();
for (int x : arr) {
li.add(x);
}
Collections.sort(li, Collections.reverseOrder());
for (int i = 0; i < n; i++) {
arr[i] = li.get(i);
}
}
private static void sort(double[] arr) {
int n = arr.length;
List<Double> li = new ArrayList<>();
for (double x : arr) {
li.add(x);
}
Collections.sort(li);
for (int i = 0; i < n; i++) {
arr[i] = li.get(i);
}
}
private static void sortReverse(double[] arr) {
int n = arr.length;
List<Double> li = new ArrayList<>();
for (double x : arr) {
li.add(x);
}
Collections.sort(li, Collections.reverseOrder());
for (int i = 0; i < n; i++) {
arr[i] = li.get(i);
}
}
private static void sortReverse(long[] arr) {
int n = arr.length;
List<Long> li = new ArrayList<>();
for (long x : arr) {
li.add(x);
}
Collections.sort(li, Collections.reverseOrder());
for (int i = 0; i < n; i++) {
arr[i] = li.get(i);
}
}
private static void sort(long[] arr) {
int n = arr.length;
List<Long> li = new ArrayList<>();
for (long x : arr) {
li.add(x);
}
Collections.sort(li);
for (int i = 0; i < n; i++) {
arr[i] = li.get(i);
}
}
private static long sum(int[] arr) {
long sum = 0;
for (int x : arr) {
sum += x;
}
return sum;
}
private static long sum(long[] arr) {
long sum = 0;
for (long x : arr) {
sum += x;
}
return sum;
}
private static void initializeIO() {
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
System.setErr(new PrintStream(new FileOutputStream("error.txt")));
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
private static int maxOfArray(int[] arr) {
int max = Integer.MIN_VALUE;
for (int x : arr) {
max = Math.max(max, x);
}
return max;
}
private static long maxOfArray(long[] arr) {
long max = Long.MIN_VALUE;
for (long x : arr) {
max = Math.max(max, x);
}
return max;
}
private static int[][] readIntIntervals(int n, int m) {
int[][] arr = new int[n][m];
for (int j = 0; j < n; j++) {
for (int i = 0; i < m; i++) {
arr[j][i] = sc.nextInt();
}
}
return arr;
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int[] readIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
return arr;
}
private static double[] readDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextDouble();
}
return arr;
}
private static long[] readLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextLong();
}
return arr;
}
private static void print(int[] arr) throws IOException {
out.println(Arrays.toString(arr));
}
private static void print(long[] arr) throws IOException {
out.println(Arrays.toString(arr));
}
private static void print(String[] arr) throws IOException {
out.println(Arrays.toString(arr));
}
private static void print(double[] arr) throws IOException {
out.println(Arrays.toString(arr));
}
private static void debug(String[] arr) {
err.println(Arrays.toString(arr));
}
private static void debug(Boolean[][] arr) {
for (int i = 0; i < arr.length; i++)
err.println(Arrays.toString(arr[i]));
}
private static void debug(int[] arr) {
err.println(Arrays.toString(arr));
}
private static void debug(long[] arr) {
err.println(Arrays.toString(arr));
}
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 Tree {
List<List<Integer>> adj = new ArrayList<>();
int parent = 1;
int[] arr;
int n;
Map<Integer, Integer> node_parent;
List<Integer> leaf;
public Tree(int n) {
this.n = n;
leaf = new ArrayList<>();
node_parent = new HashMap<>();
arr = new int[n + 2];
for (int i = 0; i <= n + 1; i++) {
adj.add(new ArrayList<>());
}
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
node_parent.put(i + 1, arr[i]);
if ((i + 1) == arr[i])
parent = arr[i];
else
adj.get(arr[i]).add(i + 1);
}
}
private List<List<Integer>> getTree() {
return adj;
}
private void formLeaf(int v) {
boolean leaf = true;
for (int x : adj.get(v)) {
formLeaf(x);
leaf = false;
}
if (leaf)
this.leaf.add(v);
}
private List<Integer> getLeaf() {
return leaf;
}
private Map<Integer, Integer> getParents() {
return node_parent;
}
int[] getArr() {
return arr;
}
}
static class Dsu {
int[] parent, size;
Dsu(int n) {
parent = new int[n + 1];
size = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
private int findParent(int u) {
if (parent[u] == u)
return u;
return parent[u] = findParent(parent[u]);
}
private boolean union(int u, int v) {
// System.out.println("uf "+u+" "+v);
int pu = findParent(u);
// System.out.println("uf2 "+pu+" "+v);
int pv = findParent(v);
// System.out.println("uf3 " + u + " " + pv);
if (pu == pv)
return false;
if (size[pu] <= size[pv]) {
parent[pu] = pv;
size[pv] += size[pu];
} else {
parent[pv] = pu;
size[pu] += size[pv];
}
return true;
}
}
// ===================================================================================
public static int log2(int N) {
return (int) (Math.log(N) / Math.log(2));
}
private static long fact(long n) {
if (n <= 2)
return n;
return n * fact(n - 1);
}
private static void print(String s) throws IOException {
out.println(s);
}
public static boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
private static boolean isSorted(List<Integer> li) {
int n = li.size();
if (n <= 1)
return true;
for (int i = 0; i < n - 1; i++) {
if (li.get(i) > li.get(i + 1))
return false;
}
return true;
}
private static boolean isSorted(int[] arr) {
int n = arr.length;
if (n <= 1)
return true;
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1])
return false;
}
return true;
}
private static boolean ispallindromeList(List<Integer> res) {
int l = 0, r = res.size() - 1;
while (l < r) {
if (res.get(l) != res.get(r))
return false;
l++;
r--;
}
return true;
}
private static long ncr(long n, long r) {
return fact(n) / (fact(r) * fact(n - r));
}
private static void swap(char[] s, int i, int j) {
char t = s[i];
s[i] = s[j];
s[j] = t;
}
static boolean isPowerOfTwo(long x) {
return x != 0 && ((x & (x - 1)) == 0);
}
private static long gcd(long[] arr) {
long ans = 0;
for (long x : arr) {
ans = gcd(x, ans);
}
return ans;
}
private static int gcd(int[] arr) {
int ans = 0;
for (int x : arr) {
ans = gcd(x, ans);
}
return ans;
}
private static long power(long x, long y, long p) {
long res = 1;
x = x % p;
if (x == 0)
return 0;
while (y > 0) {
if ((y & 1) != 0)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
} | java |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | import java.util.Scanner;
public class Main{
private static Scanner in=new Scanner(System.in);
public static void solve(){
int n=in.nextInt();
int[] res=new int[n/2];
int idx=0;
if(n%2==0){
n/=2;
for(int i=0;i<n;i++)res[idx++]=1;
}else if(n%2==1){
res[idx++]=7;
n-=3;
n/=2;
for(int i=0;i<n;i++)res[idx++]=1;
}
for(int i=0;i<idx;i++)System.out.print(res[i]);
System.out.println();
}
public static void main(String[] args){
int t=in.nextInt();
while(t>0){t-=1;solve();}
}
} | java |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. | [
"data structures",
"greedy",
"implementation",
"math"
] | 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 D_MEX_maximizing {
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 q = f.nextInt();
int x = f.nextInt();
HashMap<Integer, Integer> hm = new HashMap<>();
int mex = 0;
for(int i = 0; i < q; i++) {
int num = f.nextInt();
int key = num%x;
hm.put(key, hm.getOrDefault(key, 0)+1);
int req = mex%x;
while(hm.containsKey(req) && (int)hm.get(req) > 0) {
hm.put(req, hm.get(req)-1);
mex++;
req = mex%x;
}
out.println(mex);
}
}
// 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 |
1304 | C | C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied. | [
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] | import java.util.*;
public class AirConditioner {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
outer:
while(t-->0) {
int n=sc.nextInt();
int temp=sc.nextInt();
long arr[][]=new long[n+1][3];
for(int i=1;i<=n;i++) {
arr[i][0]=sc.nextInt();
arr[i][1]=sc.nextInt();
arr[i][2]=sc.nextInt();
}
arr[0][0]=0;
arr[0][1]=temp;
arr[0][2]=temp;
long a=0,h=0,l=0;
for(int i=1;i<=n;i++) {
a=arr[i][0]-arr[i-1][0];
l=arr[i-1][1]-a;
h=arr[i-1][2]+a;
if(l<=arr[i][2] && h>=arr[i][1]) {
arr[i][1]=Math.max(arr[i][1],l);
arr[i][2]=Math.min(arr[i][2],h);
}
else {
System.out.println("NO");
continue outer;
}
}
// System.out.println(Arrays.deepToString(arr));
System.out.println("YES");
}
}
}
| java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.