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 |
---|---|---|---|---|---|
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.*;
public class Main {
static class data {
int x;
StringBuilder s = new StringBuilder();
data(int x, String s) {
this.x = x;
this.s.append(s);
}
}
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
if(k > 4 * m * n - 2 * n - 2 * m) {
System.out.println("NO");
return;
}
System.out.println("YES");
ArrayList<data> s = new ArrayList<>();
ArrayList<data> ans = new ArrayList<>();
if(m > 1) {
s.add(new data(m - 1, "R"));
s.add(new data(m - 1, "L"));
}
for(int i = 2; i <= n; ++i) {
s.add(new data(1, "D"));
if(m > 1) {
s.add(new data(m - 1, "R"));
s.add(new data(m - 1, "UDL"));
}
}
if(n > 1)
s.add(new data(n - 1, "U"));
for(int i = 0; k > 0; ++i) {
int cnt = s.get(i).x;
String ss = s.get(i).s.toString();
int y = ss.length();
if(y * cnt <= k) {
ans.add(new data(cnt, ss));
k -= cnt * y;
}
else {
int take = k / y;
k -= take * y;
if(take > 0)
ans.add(new data(take, ss));
if(k > 0)
ans.add(new data(1, ss.substring(0, k)));
k = 0;
}
}
int y = ans.size();
System.out.println(y);
for(int i = 0; i < y; ++i)
System.out.println(ans.get(i).x + " " + ans.get(i).s.toString());
}
} | java |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | import java.awt.Point;
import java.io.*;
import java.util.*;
public class Main {
public static void main (String[] args) throws java.lang.Exception {
Scanner sc= new Scanner(System.in);
int t= sc.nextInt();
int x=0,y=0,a=0,b=0;
for(int i=0; i<t; i++) {
a = sc.nextInt();
b = sc.nextInt();
x = sc.nextInt();
y = sc.nextInt();
int ans1 = 0, ans2 = 0, ans3 = 0, ans4 = 0;
ans1 = a * y;
ans2 = b * x;
ans3 = (a - 1 - x) * b;
ans4 = a * (b - 1 - y);
int ans = 0;
ans = Math.max(ans1, ans2);
ans = Math.max(ans, Math.max(ans3, ans4));
System.out.println(ans);
}
}} | java |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | //ღ(¯`◕‿◕´¯) ♫ ♪ ♫ YuSuF ♫ ♪ ♫ (¯`◕‿◕´¯)ღ
import java.util.*;
public class Angry_Students {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
char ar[] = in.next().toCharArray();
int counter = 0;
while (true) {
boolean hasAP = false;
for (int i = 0; i < n - 1; i++) {
if (ar[i] == 'A' && ar[i + 1] == 'P') {
hasAP = true;
ar[i + 1] = 'A';
i++;
}
}
if (!hasAP) {
break;
} else {
counter++;
}
}
System.out.println(counter);
}
}
}
| java |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class LetterA {
static class Point{
int x,y;
Point(int x, int y){
this.x=x;
this.y=y;
}
}
static class Segment{
Point p1,p2;
Segment(Point p1, Point p2){
this.p1=p1;
this.p2=p2;
}
}
static boolean acute(Point l, Point m, Point n){
long area=(long)(l.x-n.x)*(m.y-n.y)-(long)(l.y-n.y)*(m.x-n.x);
long a=(long)(l.x-n.x)*(l.x-n.x)+(long) (l.y-n.y)*(l.y-n.y);
long b=(long)(m.x-n.x)*(m.x-n.x)+(long) (m.y-n.y)*(m.y-n.y);
long c=(long)(m.x-l.x)*(m.x-l.x)+(long) (m.y-l.y)*(m.y-l.y);
return area!=0 && c<=a+b;
}
static boolean verticalSegment(Segment a, Segment b){
if(a.p1.x==b.p1.x && a.p1.y==b.p1.y){
return acute(a.p2,b.p2,a.p1);
}
if(a.p2.x==b.p2.x && a.p2.y==b.p2.y){
return acute(a.p1,b.p1,a.p2);
}
if(a.p1.x==b.p2.x && a.p1.y==b.p2.y){
return acute(a.p2,b.p1,a.p1);
}
if(a.p2.x==b.p1.x && a.p2.y==b.p1.y){
return acute(a.p1,b.p2,a.p2);
}
return false;
}
static boolean intersecting(Segment s,Point p){
if(p.x<Math.min(s.p1.x,s.p2.x) || p.x>Math.max(s.p1.x,s.p2.x) ||
p.y<Math.min(s.p1.y,s.p2.y)|| p.y>Math.max(s.p1.y,s.p2.y))
return false;
int x=Math.abs(s.p1.x-s.p2.x);
int y=Math.abs(s.p1.y-s.p2.y);
int xm=Math.min(Math.abs(s.p1.x-p.x),Math.abs(s.p2.x-p.x));
int ym=Math.min(Math.abs(s.p1.y-p.y),Math.abs(s.p2.y-p.y));
return x<=5*xm && y<=5*ym &&
(long)(p.x-s.p2.x)*(s.p1.y-s.p2.y)==(long)(p.y-s.p2.y)*(s.p1.x-s.p2.x);
}
static boolean check(Segment a, Segment b, Segment c){
return verticalSegment(a,b)&& (intersecting(a,c.p1)&&intersecting(b,c.p2)
|| intersecting(b,c.p1)&&intersecting(a,c.p2));
}
public static void main(String[] args) throws IOException {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(br.readLine());
Segment[][] segments= new Segment[n][3];
for(int i=0;i<n;i++) {
for(int j=0; j<3;j++){
StringTokenizer st= new StringTokenizer(br.readLine());
int x1 = Integer.parseInt(st.nextToken());
int y1 = Integer.parseInt(st.nextToken());
int x2 = Integer.parseInt(st.nextToken());
int y2 = Integer.parseInt(st.nextToken());
segments[i][j]= new Segment(new Point(x1,y1),new Point(x2,y2));
}
System.out.println(check(segments[i][0],segments[i][1],segments[i][2])
||check(segments[i][1],segments[i][2],segments[i][0])
||check(segments[i][2],segments[i][0],segments[i][1])?"YES":"NO");
}
}
}
| java |
1290 | B | B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105) — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram. | [
"binary search",
"constructive algorithms",
"data structures",
"strings",
"two pointers"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String s = input.readLine();
int[][] count = new int[s.length() + 1][26];
for (int i = 0; i < s.length(); ++i) {
count[i + 1] = count[i].clone();
count[i + 1][s.charAt(i) - 'a'] += 1;
}
int q = Integer.parseInt((new StringTokenizer(input.readLine())).nextToken());
while (q-- != 0) {
StringTokenizer tokenizer = new StringTokenizer(input.readLine());
int l = Integer.parseInt(tokenizer.nextToken()) - 1, r = Integer.parseInt(tokenizer.nextToken()) - 1;
int distinct = 0;
for (int i = 0; i < 26; ++i) {
distinct += (count[r + 1][i] != count[l][i] ? 1 : 0);
}
if (l != r && s.charAt(l) == s.charAt(r) && distinct < 3) {
System.out.println("No");
} else {
System.out.println("Yes");
}
}
}
}
| 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.io.FileNotFoundException;
import java.util.Scanner;
public class Task5 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
for (int k = 0; k < t; k++) {
int n = scn.nextInt();
boolean[] dp = new boolean[n];
boolean found = false;
for (int i = 0; i < n; i++) {
if(found){
scn.nextInt();
continue;
}
boolean isEven = scn.nextInt() % 2 == 0;
dp[i] = isEven;
if (isEven) {
System.out.println(1);
System.out.println(i+1);
found = true;
} else if (i != 0 && !dp[i - 1]) {
System.out.println(2);
System.out.println(i + " " + (i+1));
found=true;
}
}
if (!found) {
System.out.println(-1);
}
}
}
} | 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.util.*;
import java.io.*;
public class Main {
void solve() {
int n = in.nextInt();
int[] arr = new int[n + 1];
for (int i = 1; i <= n; i++) {
arr[i] = in.nextInt();
}
HashMap<Long, List<int[]>> map = new HashMap<>();
for (int i = 1; i <= n; i++) {
long sum = 0l;
for (int j = i; j <= n; j++) {
sum += arr[j];
map.computeIfAbsent(sum, k -> new ArrayList<>()).add(new int[] {i, j});
}
}
List<int[]> ans = new ArrayList<>();
for (List<int[]> x : map.values()) {
List<int[]> cur = x;
cur.sort((a, b) -> a[1] - b[1]);
List<int[]> temp = new ArrayList<>();
int prev = 0;
for (int[] y : cur) {
if (y[0] > prev) {
temp.add(y);
prev = y[1];
}
}
if (temp.size() > ans.size()) {
ans = temp;
}
}
out.println(ans.size());
for (int[] x : ans) {
out.println(x[0] + " " + x[1]);
}
}
FastScanner in;
PrintWriter out;
void run() {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
public static void main(String[] args) {
new Main().run();
}
} | java |
1320 | D | D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No
| [
"data structures",
"hashing",
"strings"
] | //package com.company;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static class Task {
String s;
class SegTree {
int n, mod, M, inv;
int[] pow;
Node[] nodes;
public SegTree() {
n = s.length();
nodes = new Node[4 * n];
pow = new int[n + 1];
mod = BigInteger.valueOf((new Random()).nextInt(1000000) + 1000000000).nextProbablePrime().intValue();
M = BigInteger.valueOf((new Random()).nextInt(100) + 100).nextProbablePrime().intValue();
pow[0] = 1;
inv = BigInteger.valueOf(M).modInverse(BigInteger.valueOf(mod)).intValue();
for (int i = 1; i <= n; i++) {
pow[i] = mul(pow[i - 1], M);
}
build(0, n, 1);
}
void build(int l, int r, int idx) {
if (l == r - 1) {
nodes[idx] = new Node();
nodes[idx].isStart1 = nodes[idx].isLast1 = s.charAt(l) == '1';
nodes[idx].len = 1;
nodes[idx].val = s.charAt(l) == '1' ? pow[0]: mul(2, pow[0]);
return;
}
int mid = (l + r) / 2;
build(l, mid, idx << 1);
build(mid, r, idx << 1 | 1);
nodes[idx] = new Node();
nodes[idx].fromChild(nodes[idx << 1], nodes[idx << 1 | 1]);
}
Node query(int l, int r, int idx, int L, int R) {
if (L <= l && r <= R) return nodes[idx];
if (L >= r || l >= R) return new Node();
int mid = (l + r) / 2;
Node left = query(l, mid, idx << 1, L, R);
Node right = query(mid, r, idx << 1 | 1, L, R);
Node me = new Node();
me.fromChild(left, right);
return me;
}
int add(int a, int b) {
int c = a + b;
if (c >= mod) return c - mod;
if (c < 0) return c + mod;
return c;
}
int mul(int a, int b) {
return (int)((long)a * b % mod);
}
boolean eq(int l1, int l2, int len) {
return query(0, n, 1, l1, l1 + len).val == query(0, n, 1, l2, l2 + len).val;
}
class Node {
boolean isStart1;
boolean isLast1;
int len, val;
public Node() {
}
void fromChild(Node left, Node right) {
if (left.len == 0) {
isStart1 = right.isStart1;
isLast1 = right.isLast1;
len = right.len;
val = right.val;
return;
}
if (right.len == 0) {
isStart1 = left.isStart1;
isLast1 = left.isLast1;
len = left.len;
val = left.val;
return;
}
isStart1 = left.isStart1;
isLast1 = right.isLast1;
len = left.len + right.len;
if (left.isLast1 && right.isStart1) {
if (left.len == 1) isStart1 = false;
if (right.len == 1) isLast1 = false;
len -= 2;
val = add(add(left.val, -pow[left.len - 1]), mul(mul(inv, add(right.val, -pow[0])), pow[left.len - 1]));
} else {
val = add(left.val, mul(right.val, pow[left.len]));
}
}
}
}
public void solve(Scanner sc, PrintWriter pw) throws IOException {
int n = sc.nextInt();
s = sc.next();
SegTree st1 = new SegTree();
SegTree st2 = new SegTree();
int q = sc.nextInt();
for (int i = 0; i < q; i++) {
int l1 = sc.nextInt() - 1;
int l2 = sc.nextInt() - 1;
int len = sc.nextInt();
if (st1.eq(l1, l2, len) && st2.eq(l1, l2, len)) {
pw.println("Yes");
} else {
pw.println("No");
}
}
}
}
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("nondec.in"));
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
// PrintWriter pw = new PrintWriter(new FileOutputStream("nondec.out"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);
System.err.println("Time used: " + (TIME_END - TIME_START) + ".");
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | java |
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 c1294;
//
// Codeforces Round #615 (Div. 3) 2020-01-22 06:35
// F. Three Paths on a Tree
// https://codeforces.com/contest/1294/problem/F
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected
// graph without cycles.
//
// Your task is to choose vertices a, b, c on this tree such that the number of edges which belong
// to one of the simple paths between a and b, b and c, or a and c 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.
//
// Input
//
// The first line contains one integer number n (3 <= n <= 2 * 10^5) -- the number of vertices in
// the tree.
//
// Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 <= a_i, b_i <= n, a_i !=
// b_i). It is guaranteed that given graph is a tree.
//
// Output
//
// In the first line print one integer res -- the maximum number of edges which belong to one of the
// simple paths between a and b, b and c, or a and c.
//
// In the second line print three integers a, b, c such that 1 <= a, b, c <= n and a !=, b != c, a
// != c.
//
// If there are several answers, you can print any.
//
// Example
/*
input:
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
output:
5
1 8 6
*/
// Note
//
// The picture corresponding to the first example (and ):
//
// https://espresso.codeforces.com/a14350f33ff1d0a53f558a037dbaf779e81c1ee9.png
//
// If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3),
// (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the
// path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2,
// 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer.
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.StringTokenizer;
public class C1294F {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int[] solve(int[][] edges) {
int n = edges.length + 1;
int[] ans = new int[4];
List<Integer>[] adjs = new ArrayList[n+1];
for (int i = 0; i < n + 1; i++) {
adjs[i] = new ArrayList<>();
}
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
adjs[u].add(v);
adjs[v].add(u);
}
int r = 1;
List<Integer>[] ca = new ArrayList[n+1];
for (int i = 0; i < n + 1; i++) {
ca[i] = new ArrayList<>();
}
int[] parent = new int[n+1];
int[] depth = new int[n+1];
Queue<Integer> q = new LinkedList<>();
q.add(r);
while (!q.isEmpty()) {
int v = q.poll();
for (int w : adjs[v]) {
if (w == parent[v]) {
continue;
}
ca[v].add(w);
parent[w] = v;
depth[w] = depth[v] + 1;
q.add(w);
}
}
if (test) System.out.format(" parent: %s\n", Arrays.toString(parent));
int[] degs = new int[n+1];
for (int i = 1; i <= n; i++) {
degs[i] = ca[i].size();
if (degs[i] == 0) {
q.add(i);
}
if (test && degs[i] != 0) {
Collections.sort(ca[i]);
System.out.format(" %2d: %s\n", i, ca[i].toString());
}
}
// dp[i][0][0]: the node with the maximal depth under the subtree
// dp[i][1][0]: pivot point depth of pair (x,y)
// dp[i][1][1]: x
// dp[i][1][2]: y
int[][][] dp = new int[n+1][2][3];
while (!q.isEmpty()) {
int v = q.poll();
if (ca[v].isEmpty()) {
dp[v][0][0] = v;
} else {
// sort children by descending depth
Collections.sort(ca[v], (x,y)->depth[dp[y][0][0]] - depth[dp[x][0][0]]);
int w0 = ca[v].get(0);
dp[v][0][0] = dp[w0][0][0];
if (test) System.out.format(" v:%2d %d %d dp[v][1]: %s ca[v]:%s ans0:%d\n",
v, w0, dp[w0][0][0], Arrays.toString(dp[v][1]), ca[v].toString(), ans[0]);
if (ca[v].size() == 1) {
if (dp[w0][1][0] == 0) {
// subtree is a stick
if (ans[0] < depth[dp[v][0][0]] - depth[v] && w0 != dp[v][0][0]) {
ans[0] = depth[dp[v][0][0]] - depth[v];
ans[1] = v;
ans[2] = w0;
ans[3] = dp[w0][0][0];
}
} else {
int p = dp[w0][1][0];
int a = dp[w0][1][1];
int b = dp[w0][1][2];
int score = depth[a] - depth[p] + depth[b] - depth[p] + depth[p] - depth[v];
if (test) System.out.format(" v:%2d p:%d a:%d b:%d score:%d\n", v, p, a, b, score);
dp[v][1][0] = p;
dp[v][1][1] = a;
dp[v][1][2] = b;
if (ans[0] < score) {
ans[0] = score;
ans[1] = v;
ans[2] = a;
ans[3] = b;
}
}
} else {
// 2+ children
// v
// / \
// w0 w1
// / \
// a b
int w1 = ca[v].get(1);
int a = dp[w0][0][0];
int b = dp[w1][0][0];
dp[v][1][0] = v;
dp[v][1][1] = a;
dp[v][1][2] = b;
int score = depth[a] + depth[b] - 2 * depth[v];
if (ans[0] < score) {
ans[0] = score;
ans[1] = v;
ans[2] = a;
ans[3] = b;
}
for (int i = 0; i < ca[v].size(); i++) {
int w = ca[v].get(i);
if (dp[w][1][0] > 0) {
// v
// |
// p
// / \
// a b
int p = dp[w][1][0];
a = dp[w][1][1];
b = dp[w][1][2];
int z = depth[a] + depth[b] - depth[p] - depth[v];
if (z > score) {
dp[v][1][0] = p;
dp[v][1][1] = a;
dp[v][1][2] = b;
score = z;
if (ans[0] < score) {
ans[0] = score;
ans[1] = v;
ans[2] = a;
ans[3] = b;
}
}
// v
// / \
// * p
// / / \
// u a b
int u = i == 0 ? dp[ca[v].get(1)][0][0] : dp[ca[v].get(0)][0][0];
z = depth[a] - depth[p] + depth[b] - depth[p] + depth[p] - depth[v] + depth[u] - depth[v];
if (ans[0] < z) {
ans[0] = z;
ans[1] = u;
ans[2] = a;
ans[3] = b;
}
}
}
if (ca[v].size() >= 3) {
// v
// / | \
// w0 w1 w2
// / | \
// a b c
int w2 = ca[v].get(2);
a = dp[w0][0][0];
b = dp[w1][0][0];
int c = dp[w2][0][0];
int x = depth[a] + depth[b] + depth[c] - 3 * depth[v];
if (ans[0] < x) {
ans[0] = x;
ans[1] = a;
ans[2] = b;
ans[3] = c;
}
}
}
}
if (test) System.out.format(" v:%2d dp[v][0]:%d dp[v][1]:%s\n", v, dp[v][0][0], Arrays.toString(dp[v][1]));
int p = parent[v];
if (p != 0) {
degs[p]--;
if (degs[p] == 0) {
q.add(p);
}
}
}
return ans;
}
static void test(int exp, int[][] edges) {
System.out.format("edges: %s\n", trace(edges));
int[] ans = solve(edges);
boolean ok = (exp == ans[0] && ans[1] != 0 && ans[2] != 0 && ans[3] != 0);
System.out.format(" => %d %d %d %d\n", ans[0], ans[1], ans[2], ans[3], ok ? "":"Expected " + exp);
myAssert(ok);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(99, new int[][] {{24,25},{57,58},{83,84},{81,80},{89,88},{34,33},{48,49},{58,59},{95,94},{28,27},
{98,99},{37,36},{77,76},{11,10},{8,9},{51,52},{49,50},{52,53},{92,91},{20,21},
{44,45},{65,66},{44,43},{78,79},{14,15},{48,47},{5,6},{28,29},{100,99},{84,85},
{42,41},{98,97},{40,39},{54,55},{82,83},{75,74},{56,57},{69,68},{11,12},{9,10},
{46,47},{13,12},{46,45},{93,94},{4,3},{77,78},{1,2},{54,53},{22,21},{87,86},
{59,60},{37,38},{15,16},{70,69},{29,30},{75,76},{61,62},{33,32},{62,63},{64,65},
{26,27},{22,23},{73,72},{42,43},{82,81},{66,67},{3,2},{67,68},{93,92},{31,30},
{71,72},{88,87},{86,85},{56,55},{4,5},{70,71},{40,41},{19,18},{25,26},{97,96},
{61,60},{90,91},{8,7},{73,74},{38,39},{50,51},{18,17},{35,34},{79,80},{96,95},
{90,89},{16,17},{20,19},{63,64},{24,23},{7,6},{36,35},{31,32},{14,13}});
test(20, new int[][] {{29,53},{2,1},{55,73},{89,66},{29,12},{18,1},{53,68},{8,60},{24,34},{10,6},
{28,44},{58,92},{87,30},{47,95},{11,5},{15,82},{40,91},{2,39},{20,35},{44,65},
{17,50},{19,33},{45,16},{6,4},{22,76},{26,56},{67,27},{2,9},{4,28},{98,19},
{27,20},{3,4},{3,88},{31,3},{25,24},{8,4},{44,69},{14,4},{68,80},{73,81},
{36,25},{30,27},{70,4},{4,5},{50,79},{78,3},{51,5},{3,15},{4,13},{24,6},
{15,17},{23,62},{1,3},{17,38},{19,54},{19,77},{47,20},{94,97},{34,99},{41,96},
{4,43},{74,54},{22,12},{100,82},{7,2},{46,71},{72,32},{86,59},{10,21},{35,37},
{40,19},{75,83},{9,20},{59,42},{16,9},{23,18},{38,41},{6,46},{49,9},{7,12},
{20,85},{17,90},{58,12},{58,61},{42,17},{19,7},{84,8},{91,93},{63,46},{31,64},
{32,8},{21,55},{26,21},{24,94},{75,11},{31,48},{26,52},{66,44},{57,10}});
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int n = in.nextInt();
int[][] edges = new int[n-1][2];
for (int i = 0; i < n - 1; i++) {
edges[i][0] = in.nextInt();
edges[i][1] = in.nextInt();
}
/*
if (n == 100 && edges[0][0] == 24 && edges[0][1] == 25) {
int[][] brr = new int[39][2];
for (int i = 60; i < n - 1; i++) {
brr[i-60][0] = edges[i][0];
brr[i-60][1] = edges[i][1];
}
throw new RuntimeException(trace(brr));
}
*/
int[] ans = solve(edges);
System.out.format("%d\n%d %d %d\n", ans[0], ans[1], ans[2], ans[3]);
}
static String trace(int[][] a) {
return Arrays.deepToString(a).replace(" ", "").replace('[', '{').replace(']', '}');
}
static String trace(int[] a) {
return Arrays.toString(a).replace(" ", "").replace('[', '{').replace(']', '}');
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 4000) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| java |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. | [
"dp",
"greedy",
"sortings"
] | import java.io.*;
import java.util.Scanner;
import java.util.*;
public class Solution {
static int mod = (int) 1e9 + 7;
static Kattio io = new Kattio();
static int h = (int) 1e5 * 2 + 2;
public static void main(String[] args) {
int n = io.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = io.nextInt();
}
new Solution().solve(n, arr);
io.close();
}
public void solve(int n, int[] arr) {
int len = (n + 1) / 2;
int[][] dp = new int[len + 2][2];
for (int[] t : dp) {
t[0] = Integer.MAX_VALUE / 2;
t[1] = Integer.MAX_VALUE / 2;
}
dp[0] = new int[]{0, 0};
for (int i = 0; i < n; i++) {
int[][] dp1 = new int[len + 2][2];
for (int[] t : dp1) {
t[0] = Integer.MAX_VALUE / 2;
t[1] = Integer.MAX_VALUE / 2;
}
for (int odd = 0; odd <= len; odd++) {
if (arr[i] == 0) {
if (odd > 0)
dp1[odd][0] = Math.min(dp[odd - 1][0], dp[odd - 1][1] + 1);
dp1[odd][1] = Math.min(dp[odd][0] + 1, dp[odd][1]);
} else if (arr[i] % 2 == 0) {
dp1[odd][1] = Math.min(dp[odd][0] + 1, dp[odd][1]);
} else {
if (odd > 0)
dp1[odd][0] = Math.min(dp[odd - 1][0], dp[odd - 1][1] + 1);
}
}
dp = dp1;
}
// for (int i = 0; i < n; i++) {
// int[][] dp1 = new int[len + 2][2];
// Arrays.fill(dp1, Integer.MAX_VALUE / 2);
// for (int odd = 0; odd <= len; odd++) {
// if (arr[i] == 0) {
// if (odd > 0)
// dp1[odd][0] = Math.min(dp[odd - 1][0], dp[odd - 1][1] + 1);
// dp1[odd][1] = Math.min(dp[odd][0] + 1, dp[odd][1]);
// } else if (arr[i] % 2 == 0) {
// dp1[odd][1] = Math.min(dp[odd][0] + 1, dp[odd][1]);
// } else {
// if (odd > 0)
// dp1[odd][0] = Math.min(dp[odd - 1][0], dp[odd - 1] + 1);
// }
// // if v == 0 {
// // f[i+1][j][1] = min(f[i][j][0]+1, f[i][j][1])
// // if j > 0
// // f[i+1][j][0] = min(f[i][j-1][0], f[i][j-1][1]+1)
// // } else if v % 2 == 0 {
// // if j > 0
// // f[i+1][j][0] = min(f[i][j-1][0], f[i][j-1][1]+1)
// // } else {
// // f[i+1][j][1] = min(f[i][j][0]+1, f[i][j][1])
// // }
// // if v == 0 {
// // f[j][1] = min(f[j][1], f[j][0]+1)
// // if (j > 0)
// // f[j][0] = min(f[j-1][0], f[j-1][1]+1)
// // else
// // f[j][0] = 1e9
// // } else if v % 2 == 0 {
// // f[j][1] = 1e9
// // if (j > 0)
// // f[j][0] = min(f[j-1][0], f[j-1][1]+1)
// // else
// // f[j][0] = 1e9
// // } else if v % 2 == 1 {
// // f[j][1] = min(f[j][1], f[j][0]+1)
// // f[j][0] = 1e9
// // }
// }
// }
io.println(Math.min(dp[len][0], dp[len][1]));
}
public int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public int countbit(long n) {
int count = 0;
for (int i = 0; i < 64; i++) {
if (((1L << i) & n) != 0) count++;
}
return count;
}
public int firstbit(int n) {
for (int i = 31; i >= 0; i--) {
if (((1 << i) & n) != 0) return i;
}
return -1;
}
}
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 |
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{
static int getSum(int i) {
return (i*(i+1))/2;
}
public static void main(String[] args) throws Exception{
MScanner sc=new MScanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
if(n==1) {
pw.println('?'+" "+1+" "+1);
pw.flush();
String x=sc.nextLine();
pw.println("! "+x);
pw.flush();
return;
}
HashMap<String, Integer>occ=new HashMap<String, Integer>();
pw.println("? "+1+" "+n);
pw.flush();
int substrings=getSum(n);
for(int i=0;i<substrings;i++) {
String x=sc.nextLine();
char[]xs=x.toCharArray();
Arrays.sort(xs);
StringBuilder sb=new StringBuilder();
for(char c:xs) {
sb.append(c);
}
x=sb.toString();
occ.put(x, occ.getOrDefault(x, 0)+1);
}
pw.println("? "+2+" "+n);
pw.flush();
substrings=getSum(n-1);
for(int i=0;i<substrings;i++) {
String x=sc.nextLine();
char[]xs=x.toCharArray();
Arrays.sort(xs);
StringBuilder sb=new StringBuilder();
for(char c:xs) {
sb.append(c);
}
x=sb.toString();
occ.put(x, occ.getOrDefault(x, 0)-1);
}
String[]prefixes=new String[n];
for(String x:occ.keySet()) {
if(occ.get(x)==1) {
prefixes[x.length()-1]=x;
}
}
StringBuilder ans=new StringBuilder();
for(int i=0;i<n;i++) {
int[]chars=new int[26];
for(int j=0;j<prefixes[i].length();j++) {
chars[prefixes[i].charAt(j)-'a']++;
}
for(int j=0;j<ans.length();j++) {
chars[ans.charAt(j)-'a']--;
}
for(int j=0;j<26;j++) {
if(chars[j]==1) {
char o=(char)('a'+j);
ans.append(o);
break;
}
}
}
pw.println("! "+ans);
pw.flush();
}
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] takearr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] takearrl(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public Integer[] takearrobj(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] takearrlobj(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | java |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — 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≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | import java.io.*;
import java.util.*;
public class cf {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void readArr(int[] ar, int n) {
for (int i = 0; i < n; i++) {
ar[i] = nextInt();
}
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static boolean binary_search(long[] a, long k) {
long low = 0;
long high = a.length - 1;
long mid = 0;
while (low <= high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == k) {
return true;
} else if (a[(int) mid] < k) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;
}
public static int bSearchDiff(long[] a, int low, int high) {
int mid = low + ((high - low) / 2);
int hight = high;
int lowt = low;
while (lowt < hight) {
mid = lowt + (hight - lowt) / 2;
if (a[high] - a[mid] <= 5) {
hight = mid;
} else {
lowt = mid + 1;
}
}
return lowt;
}
public static long lowerbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == ddp) {
return mid;
}
if (a[(int) mid] < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
if (low + 1 < a.length && a[(int) low + 1] <= ddp) {
low++;
}
if (low == a.length && low != 0) {
low--;
return low;
}
if (a[(int) low] > ddp && low != 0) {
low--;
}
return low;
}
public static long lowerbound(long a[], long ddp, long factor) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if ((a[(int) mid] + (mid * factor)) == ddp) {
return mid;
}
if ((a[(int) mid] + (mid * factor)) < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
if (low == a.length && low != 0) {
low--;
return low;
}
if (a[(int) low] > ddp - (low * factor) && low != 0) {
low--;
}
return low;
}
public static long lowerbound(List<Long> a, long ddp) {
long low = 0;
long high = a.size();
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
// if (a.get((int) mid) == ddp) {
// return mid;
// }
if (a.get((int) mid) < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
// if (low == a.size() && low != 0) {
// low--;
// return low;
// }
// if (a.get((int) low) >= ddp && low != 0) {
// low--;
// }
return low;
}
public static long lowerboundforpairs(pair a[], double pr) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid].w <= pr) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
// if(low == a.length && low != 0){
// low--;
// return low;
// }
// if(a[(int)low].w > pr && low != 0){
// low--;
// }
return low;
}
public static long upperbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == ddp) {
return mid;
}
if (a[(int) mid] < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if (low == a.length) {
// return a.length - 1;
// }
return low;
}
public static long upperbound(ArrayList<Long> a, long ddp) {
long low = 0;
long high = a.size();
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a.get((int) mid) <= ddp) {
low = mid + 1;
} else {
high = mid;
}
}
if (low == a.size()) {
return a.size() - 1;
}
// System.out.println(a.get((int) low) + " " + ddp);
if (low + 1 < a.size() && a.get((int) low) <= ddp) {
low++;
}
return low;
}
// public static class pair implements Comparable<pair> {
// long w;
// long h;
// public pair(long w, long h) {
// this.w = w;
// this.h = h;
// }
// public int compareTo(pair b) {
// if (this.w != b.w)
// return (int) (this.w - b.w);
// else
// return (int) (this.h - b.h);
// }
// }
public static class pairs {
char w;
int h;
public pairs(char w, int h) {
this.w = w;
this.h = h;
}
}
public static class pair {
long w;
long h;
public pair(long w, long h) {
this.w = w;
this.h = h;
}
@Override
public int hashCode() {
return Objects.hash(w, h);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof pair)) {
return false;
}
pair c = (pair) o;
return Long.compare(this.w, c.w) == 0 && Long.compare(this.h, h) == 0;
}
}
public static class trinary {
long a;
long b;
long c;
public trinary(long a, long b, long c) {
this.a = a;
this.b = b;
this.c = c;
}
}
public static class fourthary {
long a;
long b;
long c;
long d;
public fourthary(long a, long b, long c, long d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
}
public static pair[] sortpair(pair[] a) {
Arrays.sort(a, new Comparator<pair>() {
public int compare(pair p1, pair p2) {
if (p1.w != p2.w) {
return (int) (p1.w - p2.w);
}
return (int) (p1.h - p2.h);
}
});
return a;
}
public static trinary[] sortpair(trinary[] a) {
Arrays.sort(a, new Comparator<trinary>() {
public int compare(trinary p1, trinary p2) {
if (p1.b != p2.b) {
return (int) (p1.b - p2.b);
} else if (p1.a != p2.a) {
return (int) (p1.a - p2.a);
}
return (int) (p1.c - p2.c);
}
});
return a;
}
public static fourthary[] sortpair(fourthary[] a) {
Arrays.sort(a, new Comparator<fourthary>() {
public int compare(fourthary p1, fourthary p2) {
if (p1.b != p2.b) {
return (int) (p1.b - p2.b);
} else if (p1.a != p2.a) {
return (int) (p1.a - p2.a);
}
return (int) (p1.c - p2.c);
}
});
return a;
}
public static void sort(long[] arr) {
ArrayList<Long> a = new ArrayList<>();
for (long i : arr) {
a.add(i);
}
Collections.sort(a);
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
public static void sortForObjecttypes(pair[] arr) {
ArrayList<pair> a = new ArrayList<>();
for (pair i : arr) {
a.add(i);
}
Collections.sort(a, new Comparator<pair>() {
@Override
public int compare(pair a, pair b) {
return (int) (a.h - b.h);
}
});
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
public static boolean ispalindrome(String s) {
long i = 0;
long j = s.length() - 1;
boolean is = false;
while (i < j) {
if (s.charAt((int) i) == s.charAt((int) j)) {
is = true;
i++;
j--;
} else {
is = false;
return is;
}
}
return is;
}
public static long power(long base, long pow, long mod) {
long result = base;
long temp = 1;
while (pow > 1) {
if (pow % 2 == 0) {
result = ((result % mod) * (result % mod)) % mod;
pow /= 2;
} else {
temp = temp * base;
pow--;
}
}
result = ((result % mod) * (temp % mod));
// System.out.println(result);
return result;
}
public static long sqrt(long n) {
long res = 1;
long l = 1, r = (long) 10e9;
while (l <= r) {
long mid = (l + r) / 2;
if (mid * mid <= n) {
res = mid;
l = mid + 1;
} else
r = mid - 1;
}
return res;
}
public static boolean is[] = new boolean[1000000];
public static int a[] = new int[1000000];
public static Vector<Integer> seiveOfEratosthenes() {
Vector<Integer> listA = new Vector<>();
for (int i = 2; i * i <= a.length; i++) {
if (a[i] != 1) {
for (long j = i * i; j < a.length; j += i) {
a[(int) j] = 1;
}
}
}
for (int i = 2; i < a.length; i++) {
if (a[i] == 0) {
is[i] = true;
listA.add(i);
}
}
return listA;
}
public static Vector<Integer> ans = seiveOfEratosthenes();
public static long sumOfDigits(long n) {
long ans = 0;
while (n != 0) {
ans += n % 10;
n /= 10;
}
return ans;
}
public static long gcdTotal(long a[]) {
long t = a[0];
for (int i = 1; i < a.length; i++) {
t = gcd(t, a[i]);
}
return t;
}
public static ArrayList<Long> al = new ArrayList<>();
public static void makeArr() {
long t = 1;
while (t <= 10e17) {
al.add(t);
t *= 2;
}
}
public static boolean isBalancedBrackets(String s) {
if (s.length() == 1) {
return false;
}
Stack<Character> sO = new Stack<>();
int id = 0;
while (id < s.length()) {
if (s.charAt(id) == '(') {
sO.add('(');
}
if (s.charAt(id) == ')') {
if (!sO.isEmpty()) {
sO.pop();
} else {
return false;
}
}
id++;
}
if (sO.isEmpty()) {
return true;
}
return false;
}
public static long kadanesAlgo(long a[], int start, int end) {
long maxSoFar = Long.MIN_VALUE;
long maxEndingHere = 0;
for (int i = start; i < end; i++) {
maxEndingHere += a[i];
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
}
if (maxEndingHere < 0) {
maxEndingHere = 0;
}
}
return maxSoFar;
}
public static Vector<Integer> prime = new Vector<>();
public static int components = 0;
public static void search(HashMap<Integer, Integer> hm, int max, int start, int high) {
if (start == 0) {
components++;
return;
}
int t = max;
boolean is = false;
for (int i = start; i < high; i++) {
if (hm.get(t) >= start) {
t--;
is = true;
} else {
// System.out.println(start + " " + high + " " + hm.get(t) + " " + hm.get(max));
is = false;
break;
}
}
// System.out.println(max + " " + is + " " + t);
if (is) {
search(hm, t, hm.get(t), start);
components++;
} else {
// System.out.println(t);
search(hm, max, hm.get(t), high);
}
}
public static void helper(String s, Stack<Character> left, Stack<Character> right) {
int id = 0;
while (id < s.length()) {
if (s.charAt(id) == '(') {
left.add('(');
}
if (s.charAt(id) == ')') {
right.add(')');
if (left.size() > 0) {
left.pop();
right.pop();
}
}
id++;
}
}
public static long helperCounterFactor(long n, int fac, long m) {
long max = (long) 10e9;
long min = 0;
long mid = max + (max - min) / 2;
while (min < max) {
mid = max + (max - min) / 2;
if (n * mid > m) {
max = mid;
} else {
min = mid + 1;
}
}
return min;
}
public static long helperBS(long a[], long pref[], long d, long c) {
long start = 0;
long end = d;
long mid = 0;
long earn = 0;
long ct = 0;
long ans = 0;
while (start < end) {
mid = start + (end - start) / 2;
earn = 0;
ct = (d / (mid + 1));
if (mid >= a.length) {
earn = ct * (pref[pref.length - 1]);
earn += pref[(int) Math.min(a.length, (d % (mid + 1)))];
} else {
earn = ct * pref[(int) mid + 1];
earn += pref[(int) (d % (mid + 1))];
}
if (earn >= c) {
start = mid + 1;
ans = mid;
} else {
end = mid;
}
}
return ans;
}
public static void helper(int[][] hel, int max) {
for (int i = 0; i < Integer.toBinaryString(max).length(); i++) {
for (int j = 1; j <= max; j++) {
if (((j >> i) & 1) == 0) {
hel[j][i] = hel[j - 1][i] + 1;
} else {
hel[j][i] = hel[j - 1][i];
}
}
}
}
public static void solve(FastReader sc, PrintWriter w, StringBuilder sb) throws Exception {
int n = sc.nextInt();
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
}
int st = -1;
int en = n;
for (int i = 0; i < n; i++) {
if (a[i] < i) {
break;
}
st = i;
}
for (int i = n - 1; i >= 0; i--) {
if (a[i] < n - i - 1) {
break;
}
en = i;
}
if (en <= st) {
sb.append("YES\n");
} else {
sb.append("NO\n");
}
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter w = new PrintWriter(System.out);
StringBuilder sb = new StringBuilder();
// prime = seiveOfEratosthenes();
// int max = 200000;
// int[][] hel = new int[max + 1][Integer.toBinaryString(max).length()];
// helper(hel, max);
long o = sc.nextLong();
// makeArr();
while (o > 0) {
solve(sc, w, sb);
o--;
}
System.out.print(sb.toString());
w.close();
}
} | java |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all. | [
"implementation"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
public final class CFPS {
static FastReader fr = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static final int gigamod = 1000000007;
static final int mod = 998244353;
static int t = 1;
static boolean[] isPrime;
static int[] smallestFactorOf;
static final int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3;
static int cmp;
@SuppressWarnings({"unused"})
public static void main(String[] args) throws Exception {
OUTER:
for (int tc = 0; tc < t; tc++) {
int n = fr.nextInt();
int[] arr = fr.nextIntArray(n);
for (int i = 0; i < n; i++)
arr[i] = 1 - arr[i];
ArrayList<Integer> list = new ArrayList<>();
for (int k = 0; k < 5; k++) {
for (int i = 0; i < n; i++)
list.add(arr[i]);
}
int len = list.size();
int[] newArr = new int[len];
for (int i = 0; i < len; i++)
newArr[i] = list.get(i);
arr = newArr;
n = len;
int maxAns = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 1) continue;
int j = i;
while (j < n - 1 && arr[j + 1] == 0)
j++;
// [i, j]
maxAns = Math.max(maxAns, j + 1 - i);
i = j;
}
out.println(maxAns);
}
out.close();
}
static boolean isPalindrome(char[] s) {
char[] rev = s.clone();
reverse(rev);
return Arrays.compare(s, rev) == 0;
}
static class Segment implements Comparable<Segment> {
int size;
long val;
int stIdx;
Segment left, right;
Segment(int ss, long vv, int ssii) {
size = ss;
val = vv;
stIdx = ssii;
}
@Override
public int compareTo(Segment that) {
cmp = size - that.size;
if (cmp == 0)
cmp = stIdx - that.stIdx;
if (cmp == 0)
cmp = Long.compare(val, that.val);
return cmp;
}
}
static class Pair implements Comparable<Pair> {
int first, second;
int idx;
Pair() { first = second = 0; }
Pair (int ff, int ss) {first = ff; second = ss;}
Pair (int ff, int ss, int ii) { first = ff; second = ss; idx = ii; }
public int compareTo(Pair that) {
cmp = first - that.first;
if (cmp == 0)
cmp = second - that.second;
return (int) cmp;
}
}
// (range add - segment min) segTree
static int nn;
static int[] arr;
static int[] tree;
static int[] lazy;
static void build(int node, int leftt, int rightt) {
if (leftt == rightt) {
tree[node] = arr[leftt];
return;
}
int mid = (leftt + rightt) >> 1;
build(node << 1, leftt, mid);
build(node << 1 | 1, mid + 1, rightt);
tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]);
}
static void segAdd(int node, int leftt, int rightt, int segL, int segR, int val) {
if (lazy[node] != 0) {
tree[node] += lazy[node];
if (leftt != rightt) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
}
lazy[node] = 0;
}
if (segL > rightt || segR < leftt) return;
if (segL <= leftt && rightt <= segR) {
tree[node] += val;
if (leftt != rightt) {
lazy[node << 1] += val;
lazy[node << 1 | 1] += val;
}
lazy[node] = 0;
return;
}
int mid = (leftt + rightt) >> 1;
segAdd(node << 1, leftt, mid, segL, segR, val);
segAdd(node << 1 | 1, mid + 1, rightt, segL, segR, val);
tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]);
}
static int minQuery(int node, int leftt, int rightt, int segL, int segR) {
if (lazy[node] != 0) {
tree[node] += lazy[node];
if (leftt != rightt) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
}
lazy[node] = 0;
}
if (segL > rightt || segR < leftt) return Integer.MAX_VALUE / 10;
if (segL <= leftt && rightt <= segR)
return tree[node];
int mid = (leftt + rightt) >> 1;
return Math.min(minQuery(node << 1, leftt, mid, segL, segR),
minQuery(node << 1 | 1, mid + 1, rightt, segL, segR));
}
static void compute_automaton(String s, int[][] aut) {
s += '#';
int n = s.length();
int[] pi = prefix_function(s.toCharArray());
for (int i = 0; i < n; i++) {
for (int c = 0; c < 26; c++) {
int j = i;
while (j > 0 && 'A' + c != s.charAt(j))
j = pi[j-1];
if ('A' + c == s.charAt(j))
j++;
aut[i][c] = j;
}
}
}
static void timeDFS(int current, int from, UGraph ug,
int[] time, int[] tIn, int[] tOut) {
tIn[current] = ++time[0];
for (int adj : ug.adj(current))
if (adj != from)
timeDFS(adj, current, ug, time, tIn, tOut);
tOut[current] = ++time[0];
}
static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) {
// we will check if c3 lies on line through (c1, c2)
long a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return a == 0;
}
static int[] treeDiameter(UGraph ug) {
int n = ug.V();
int farthest = -1;
int[] distTo = new int[n];
diamDFS(0, -1, 0, ug, distTo);
int maxDist = -1;
for (int i = 0; i < n; i++)
if (maxDist < distTo[i]) {
maxDist = distTo[i];
farthest = i;
}
distTo = new int[n + 1];
diamDFS(farthest, -1, 0, ug, distTo);
distTo[n] = farthest;
return distTo;
}
static void diamDFS(int current, int from, int dist, UGraph ug, int[] distTo) {
distTo[current] = dist;
for (int adj : ug.adj(current))
if (adj != from)
diamDFS(adj, current, dist + 1, ug, distTo);
}
static class TreeDistFinder {
UGraph ug;
int n;
int[] depthOf;
LCA lca;
TreeDistFinder(UGraph ug) {
this.ug = ug;
n = ug.V();
depthOf = new int[n];
depthCalc(0, -1, ug, 0, depthOf);
lca = new LCA(ug, 0);
}
TreeDistFinder(UGraph ug, int a) {
this.ug = ug;
n = ug.V();
depthOf = new int[n];
depthCalc(a, -1, ug, 0, depthOf);
lca = new LCA(ug, a);
}
private void depthCalc(int current, int from, UGraph ug, int depth, int[] depthOf) {
depthOf[current] = depth;
for (int adj : ug.adj(current))
if (adj != from)
depthCalc(adj, current, ug, depth + 1, depthOf);
}
public int dist(int a, int b) {
int lc = lca.lca(a, b);
return (depthOf[a] - depthOf[lc] + depthOf[b] - depthOf[lc]);
}
}
public static long[][] GCDSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
} else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = gcd(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeGCDQ(long[][] table, int l, int r)
{
// [a,b)
if(l > r)return 1;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return gcd(table[t][l], table[t][r-(1<<t)]);
}
static class Trie {
TrieNode root;
Trie(char[][] strings) {
root = new TrieNode('A', false);
construct(root, strings);
}
public Stack<String> set(TrieNode root) {
Stack<String> set = new Stack<>();
StringBuilder sb = new StringBuilder();
for (TrieNode next : root.next)
collect(sb, next, set);
return set;
}
private void collect(StringBuilder sb, TrieNode node, Stack<String> set) {
if (node == null) return;
sb.append(node.character);
if (node.isTerminal)
set.add(sb.toString());
for (TrieNode next : node.next)
collect(sb, next, set);
if (sb.length() > 0)
sb.setLength(sb.length() - 1);
}
private void construct(TrieNode root, char[][] strings) {
// we have to construct the Trie
for (char[] string : strings) {
if (string.length == 0) continue;
root.next[string[0] - 'a'] = put(root.next[string[0] - 'a'], string, 0);
if (root.next[string[0] - 'a'] != null)
root.isLeaf = false;
}
}
private TrieNode put(TrieNode node, char[] string, int idx) {
boolean isTerminal = (idx == string.length - 1);
if (node == null) node = new TrieNode(string[idx], isTerminal);
node.character = string[idx];
node.isTerminal |= isTerminal;
if (!isTerminal) {
node.isLeaf = false;
node.next[string[idx + 1] - 'a'] = put(node.next[string[idx + 1] - 'a'], string, idx + 1);
}
return node;
}
class TrieNode {
char character;
TrieNode[] next;
boolean isTerminal, isLeaf;
boolean canWin, canLose;
TrieNode(char c, boolean isTerminallll) {
character = c;
isTerminal = isTerminallll;
next = new TrieNode[26];
isLeaf = true;
}
}
}
static class Edge implements Comparable<Edge> {
int from, to;
long weight, ans;
int id;
// int hash;
Edge(int fro, int t, long wt, int i) {
from = fro;
to = t;
id = i;
weight = wt;
// hash = Objects.hash(from, to, weight);
}
/*public int hashCode() {
return hash;
}*/
public int compareTo(Edge that) {
return Long.compare(this.id, that.id);
}
}
public static long[][] minSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeMinQ(long[][] table, int l, int r)
{
// [a,b)
if(l >= r)return Integer.MAX_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.min(table[t][l], table[t][r-(1<<t)]);
}
public static long[][] maxSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.max(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeMaxQ(long[][] table, int l, int r)
{
// [a,b)
if(l >= r)return Integer.MIN_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.max(table[t][l], table[t][r-(1<<t)]);
}
static class LCA {
int[] height, first, segtree;
ArrayList<Integer> euler;
boolean[] visited;
int n;
LCA(UGraph ug, int root) {
n = ug.V();
height = new int[n];
first = new int[n];
euler = new ArrayList<>();
visited = new boolean[n];
dfs(ug, root, 0);
int m = euler.size();
segtree = new int[m * 4];
build(1, 0, m - 1);
}
void dfs(UGraph ug, int node, int h) {
visited[node] = true;
height[node] = h;
first[node] = euler.size();
euler.add(node);
for (int adj : ug.adj(node)) {
if (!visited[adj]) {
dfs(ug, adj, h + 1);
euler.add(node);
}
}
}
void build(int node, int b, int e) {
if (b == e) {
segtree[node] = euler.get(b);
} else {
int mid = (b + e) / 2;
build(node << 1, b, mid);
build(node << 1 | 1, mid + 1, e);
int l = segtree[node << 1], r = segtree[node << 1 | 1];
segtree[node] = (height[l] < height[r]) ? l : r;
}
}
int query(int node, int b, int e, int L, int R) {
if (b > R || e < L)
return -1;
if (b >= L && e <= R)
return segtree[node];
int mid = (b + e) >> 1;
int left = query(node << 1, b, mid, L, R);
int right = query(node << 1 | 1, mid + 1, e, L, R);
if (left == -1) return right;
if (right == -1) return left;
return height[left] < height[right] ? left : right;
}
int lca(int u, int v) {
int left = first[u], right = first[v];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
return query(1, 0, euler.size() - 1, left, right);
}
}
static class FenwickTree {
long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates
public FenwickTree(int size) {
array = new long[size + 1];
}
public long rsq(int ind) {
assert ind > 0;
long sum = 0;
while (ind > 0) {
sum += array[ind];
//Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number
ind -= ind & (-ind);
}
return sum;
}
public long rsq(int a, int b) {
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, long value) {
assert ind > 0;
while (ind < array.length) {
array[ind] += value;
//Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number
ind += ind & (-ind);
}
}
public int size() {
return array.length - 1;
}
}
static class Point implements Comparable<Point> {
long x;
long y;
long z;
long id;
// private int hashCode;
Point() {
x = z = y = 0;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(Point p) {
this.x = p.x;
this.y = p.y;
this.z = p.z;
this.id = p.id;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(long x, long y, long z, long id) {
this.x = x;
this.y = y;
this.z = z;
this.id = id;
// this.hashCode = Objects.hash(x, y, id);
}
Point(long a, long b) {
this.x = a;
this.y = b;
this.z = 0;
// this.hashCode = Objects.hash(a, b);
}
Point(long x, long y, long id) {
this.x = x;
this.y = y;
this.id = id;
}
@Override
public int compareTo(Point o) {
if (this.x < o.x)
return -1;
if (this.x > o.x)
return 1;
if (this.y < o.y)
return -1;
if (this.y > o.y)
return 1;
if (this.z < o.z)
return -1;
if (this.z > o.z)
return 1;
return 0;
}
@Override
public boolean equals(Object that) {
return this.compareTo((Point) that) == 0;
}
}
static class BinaryLift {
// FUNCTIONS: k-th ancestor and LCA in log(n)
int[] parentOf;
int maxJmpPow;
int[][] binAncestorOf;
int n;
int[] lvlOf;
// How this works?
// a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}.
// b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we
// lift level in the tree.
public BinaryLift(UGraph tree) {
n = tree.V();
maxJmpPow = logk(n, 2) + 1;
parentOf = new int[n];
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
parentConstruct(0, -1, tree, 0);
binConstruct();
}
// TODO: Implement lvlOf[] initialization
public BinaryLift(int[] parentOf) {
this.parentOf = parentOf;
n = parentOf.length;
maxJmpPow = logk(n, 2) + 1;
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
UGraph tree = new UGraph(n);
for (int i = 1; i < n; i++)
tree.addEdge(i, parentOf[i]);
binConstruct();
parentConstruct(0, -1, tree, 0);
}
private void parentConstruct(int current, int from, UGraph tree, int depth) {
parentOf[current] = from;
lvlOf[current] = depth;
for (int adj : tree.adj(current))
if (adj != from)
parentConstruct(adj, current, tree, depth + 1);
}
private void binConstruct() {
for (int node = 0; node < n; node++)
for (int lvl = 0; lvl < maxJmpPow; lvl++)
binConstruct(node, lvl);
}
private int binConstruct(int node, int lvl) {
if (node < 0)
return -1;
if (lvl == 0)
return binAncestorOf[node][lvl] = parentOf[node];
if (node == 0)
return binAncestorOf[node][lvl] = -1;
if (binAncestorOf[node][lvl] != -1)
return binAncestorOf[node][lvl];
return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1);
}
// return ancestor which is 'k' levels above this one
public int ancestor(int node, int k) {
if (node < 0)
return -1;
if (node == 0)
if (k == 0) return node;
else return -1;
if (k > (1 << maxJmpPow) - 1)
return -1;
if (k == 0)
return node;
int ancestor = node;
int highestBit = Integer.highestOneBit(k);
while (k > 0 && ancestor != -1) {
ancestor = binAncestorOf[ancestor][logk(highestBit, 2)];
k -= highestBit;
highestBit = Integer.highestOneBit(k);
}
return ancestor;
}
public int lca(int u, int v) {
if (u == v)
return u;
// The invariant will be that 'u' is below 'v' initially.
if (lvlOf[u] < lvlOf[v]) {
int temp = u;
u = v;
v = temp;
}
// Equalizing the levels.
u = ancestor(u, lvlOf[u] - lvlOf[v]);
if (u == v)
return u;
// We will now raise level by largest fitting power of two until possible.
for (int power = maxJmpPow - 1; power > -1; power--)
if (binAncestorOf[u][power] != binAncestorOf[v][power]) {
u = binAncestorOf[u][power];
v = binAncestorOf[v][power];
}
return ancestor(u, 1);
}
}
static class DFSTree {
// NOTE: The thing is made keeping in mind that the whole
// input graph is connected.
UGraph tree;
UGraph backUG;
int hasBridge;
int n;
Edge backEdge;
DFSTree(UGraph ug) {
this.n = ug.V();
tree = new UGraph(n);
hasBridge = -1;
backUG = new UGraph(n);
treeCalc(0, -1, new boolean[n], ug);
}
private void treeCalc(int current, int from, boolean[] marked, UGraph ug) {
if (marked[current]) {
// This is a backEdge.
backUG.addEdge(from, current);
backEdge = new Edge(from, current, 1, 0);
return;
}
if (from != -1)
tree.addEdge(from, current);
marked[current] = true;
for (int adj : ug.adj(current))
if (adj != from)
treeCalc(adj, current, marked, ug);
}
public boolean hasBridge() {
if (hasBridge != -1)
return (hasBridge == 1);
// We have to determine the bridge.
bridgeFinder();
return (hasBridge == 1);
}
int[] levelOf;
int[] dp;
private void bridgeFinder() {
// Finding the level of each node.
levelOf = new int[n];
levelDFS(0, -1, 0);
// Applying DP solution.
// dp[i] -> Highest level reachable from subtree of 'i' using
// some backEdge.
dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE / 100);
dpDFS(0, -1);
// Now, we will check each edge and determine whether its a
// bridge.
for (int i = 0; i < n; i++)
for (int adj : tree.adj(i)) {
// (i -> adj) is the edge.
if (dp[adj] > levelOf[i])
hasBridge = 1;
}
if (hasBridge != 1)
hasBridge = 0;
}
private void levelDFS(int current, int from, int lvl) {
levelOf[current] = lvl;
for (int adj : tree.adj(current))
if (adj != from)
levelDFS(adj, current, lvl + 1);
}
private int dpDFS(int current, int from) {
dp[current] = levelOf[current];
for (int back : backUG.adj(current))
dp[current] = Math.min(dp[current], levelOf[back]);
for (int adj : tree.adj(current))
if (adj != from)
dp[current] = Math.min(dp[current], dpDFS(adj, current));
return dp[current];
}
}
static class UnionFind {
// Uses weighted quick-union with path compression.
private int[] parent; // parent[i] = parent of i
private int[] size; // size[i] = number of sites in tree rooted at i
// Note: not necessarily correct if i is not a root node
private int count; // number of components
public UnionFind(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
// Number of connected components.
public int count() {
return count;
}
// Find the root of p.
public int find(int p) {
while (p != parent[p])
p = parent[p];
return p;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public int numConnectedTo(int node) {
return size[find(node)];
}
// Weighted union.
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
public static int[] connectedComponents(UnionFind uf) {
// We can do this in nlogn.
int n = uf.size.length;
int[] compoColors = new int[n];
for (int i = 0; i < n; i++)
compoColors[i] = uf.find(i);
HashMap<Integer, Integer> oldToNew = new HashMap<>();
int newCtr = 0;
for (int i = 0; i < n; i++) {
int thisOldColor = compoColors[i];
Integer thisNewColor = oldToNew.get(thisOldColor);
if (thisNewColor == null)
thisNewColor = newCtr++;
oldToNew.put(thisOldColor, thisNewColor);
compoColors[i] = thisNewColor;
}
return compoColors;
}
}
static class UGraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public UGraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
adj[to].add(from);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int degree(int v) {
return adj[v].size();
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static void dfsMark(int current, boolean[] marked, UGraph g) {
if (marked[current]) return;
marked[current] = true;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, marked, g);
}
public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) {
if (marked[current]) return;
marked[current] = true;
if (from != -1)
distTo[current] = distTo[from] + 1;
HashSet<Integer> adj = g.adj(current);
int alreadyMarkedCtr = 0;
for (int adjc : adj) {
if (marked[adjc]) alreadyMarkedCtr++;
dfsMark(adjc, current, distTo, marked, g, endPoints);
}
if (alreadyMarkedCtr == adj.size())
endPoints.add(current);
}
public static void bfsOrder(int current, UGraph g) {
}
public static void dfsMark(int current, int[] colorIds, int color, UGraph g) {
if (colorIds[current] != -1) return;
colorIds[current] = color;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, colorIds, color, g);
}
public static int[] connectedComponents(UGraph g) {
int n = g.V();
int[] componentId = new int[n];
Arrays.fill(componentId, -1);
int colorCtr = 0;
for (int i = 0; i < n; i++) {
if (componentId[i] != -1) continue;
dfsMark(i, componentId, colorCtr, g);
colorCtr++;
}
return componentId;
}
public static boolean hasCycle(UGraph ug) {
int n = ug.V();
boolean[] marked = new boolean[n];
boolean[] hasCycleFirst = new boolean[1];
for (int i = 0; i < n; i++) {
if (marked[i]) continue;
hcDfsMark(i, ug, marked, hasCycleFirst, -1);
}
return hasCycleFirst[0];
}
// Helper for hasCycle.
private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) {
if (marked[current]) return;
if (hasCycleFirst[0]) return;
marked[current] = true;
HashSet<Integer> adjc = ug.adj(current);
for (int adj : adjc) {
if (marked[adj] && adj != parent && parent != -1) {
hasCycleFirst[0] = true;
return;
}
hcDfsMark(adj, ug, marked, hasCycleFirst, current);
}
}
}
static class Digraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public Digraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public Digraph reversed() {
Digraph dg = new Digraph(V());
for (int i = 0; i < V(); i++)
for (int adjVert : adj(i)) dg.addEdge(adjVert, i);
return dg;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static int[] KosarajuSharirSCC(Digraph dg) {
int[] id = new int[dg.V()];
Digraph reversed = dg.reversed();
// Gotta perform topological sort on this one to get the stack.
Stack<Integer> revStack = Digraph.topologicalSort(reversed);
// Initializing id and idCtr.
id = new int[dg.V()];
int idCtr = -1;
// Creating a 'marked' array.
boolean[] marked = new boolean[dg.V()];
while (!revStack.isEmpty()) {
int vertex = revStack.pop();
if (!marked[vertex])
sccDFS(dg, vertex, marked, ++idCtr, id);
}
return id;
}
private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) {
marked[source] = true;
id[source] = idCtr;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id);
}
public static Stack<Integer> topologicalSort(Digraph dg) {
// dg has to be a directed acyclic graph.
// We'll have to run dfs on the digraph and push the deepest nodes on stack first.
// We'll need a Stack<Integer> and a int[] marked.
Stack<Integer> topologicalStack = new Stack<Integer>();
boolean[] marked = new boolean[dg.V()];
// Calling dfs
for (int i = 0; i < dg.V(); i++)
if (!marked[i])
runDfs(dg, topologicalStack, marked, i);
return topologicalStack;
}
static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) {
marked[source] = true;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex])
runDfs(dg, topologicalStack, marked, adjVertex);
topologicalStack.add(source);
}
}
static class FastReader {
private BufferedReader bfr;
private StringTokenizer st;
public FastReader() {
bfr = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bfr.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());
}
char nextChar() {
return next().toCharArray()[0];
}
String nextString() {
return next();
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
double[] nextDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextDouble();
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
int[][] nextIntGrid(int n, int m) {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
grid[i][j] = fr.nextInt();
}
return grid;
}
}
@SuppressWarnings("serial")
static class CountMap<T> extends TreeMap<T, Integer>{
CountMap() {
}
CountMap(Comparator<T> cmp) {
}
CountMap(T[] arr) {
this.putCM(arr);
}
public Integer putCM(T key) {
return super.put(key, super.getOrDefault(key, 0) + 1);
}
public Integer removeCM(T key) {
int count = super.getOrDefault(key, -1);
if (count == -1) return -1;
if (count == 1)
return super.remove(key);
else
return super.put(key, count - 1);
}
public Integer getCM(T key) {
return super.getOrDefault(key, 0);
}
public void putCM(T[] arr) {
for (T l : arr)
this.putCM(l);
}
}
static long dioGCD(long a, long b, long[] x0, long[] y0) {
if (b == 0) {
x0[0] = 1;
y0[0] = 0;
return a;
}
long[] x1 = new long[1], y1 = new long[1];
long d = dioGCD(b, a % b, x1, y1);
x0[0] = y1[0];
y0[0] = x1[0] - y1[0] * (a / b);
return d;
}
static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) {
g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0);
if (c % g[0] > 0) {
return false;
}
x0[0] *= c / g[0];
y0[0] *= c / g[0];
if (a < 0) x0[0] = -x0[0];
if (b < 0) y0[0] = -y0[0];
return true;
}
static long[][] prod(long[][] mat1, long[][] mat2) {
int n = mat1.length;
long[][] prod = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
// determining prod[i][j]
// it will be the dot product of mat1[i][] and mat2[][i]
for (int k = 0; k < n; k++)
prod[i][j] += mat1[i][k] * mat2[k][j];
return prod;
}
static long[][] matExpo(long[][] mat, long power) {
int n = mat.length;
long[][] ans = new long[n][n];
if (power == 0)
return null;
if (power == 1)
return mat;
long[][] half = matExpo(mat, power / 2);
ans = prod(half, half);
if (power % 2 == 1) {
ans = prod(ans, mat);
}
return ans;
}
static int KMPNumOcc(char[] text, char[] pat) {
int n = text.length;
int m = pat.length;
char[] patPlusText = new char[n + m + 1];
for (int i = 0; i < m; i++)
patPlusText[i] = pat[i];
patPlusText[m] = '^'; // Seperator
for (int i = 0; i < n; i++)
patPlusText[m + i] = text[i];
int[] fullPi = piCalcKMP(patPlusText);
int answer = 0;
for (int i = 0; i < n + m + 1; i++)
if (fullPi[i] == m)
answer++;
return answer;
}
static int[] piCalcKMP(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static boolean[] prefMatchesSuff(char[] s) {
int n = s.length;
boolean[] res = new boolean[n + 1];
int[] pi = prefix_function(s);
res[0] = true;
for (int p = n; p != 0; p = pi[p])
res[p] = true;
return res;
}
static int[] prefix_function(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static long hash(long key) {
long h = Long.hashCode(key);
h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4);
return h & (gigamod-1);
}
static void Yes() {out.println("Yes");}static void YES() {out.println("YES");}static void yes() {out.println("Yes");}static void No() {out.println("No");}static void NO() {out.println("NO");}static void no() {out.println("no");}
static int mapTo1D(int row, int col, int n, int m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static int[] mapTo2D(int idx, int n, int m) {
// Inverse of what the one above does.
int[] rnc = new int[2];
rnc[0] = idx / m;
rnc[1] = idx % m;
return rnc;
}
static long mapTo1D(long row, long col, long n, long m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static boolean[] primeGenerator(int upto) {
// Sieve of Eratosthenes:
isPrime = new boolean[upto + 1];
smallestFactorOf = new int[upto + 1];
Arrays.fill(smallestFactorOf, 1);
Arrays.fill(isPrime, true);
isPrime[1] = isPrime[0] = false;
for (long i = 2; i < upto + 1; i++)
if (isPrime[(int) i]) {
smallestFactorOf[(int) i] = (int) i;
// Mark all the multiples greater than or equal
// to the square of i to be false.
for (long j = i; j * i < upto + 1; j++) {
if (isPrime[(int) j * (int) i]) {
isPrime[(int) j * (int) i] = false;
smallestFactorOf[(int) j * (int) i] = (int) i;
}
}
}
return isPrime;
}
static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) {
if (smallestFactorOf == null)
primeGenerator(num + 1);
HashMap<Integer, Integer> fnps = new HashMap<>();
while (num != 1) {
fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1);
num /= smallestFactorOf[num];
}
return fnps;
}
static HashMap<Long, Integer> primeFactorization(long num) {
// Returns map of factor and its power in the number.
HashMap<Long, Integer> map = new HashMap<>();
while (num % 2 == 0) {
num /= 2;
Integer pwrCnt = map.get(2L);
map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1);
}
for (long i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
num /= i;
Integer pwrCnt = map.get(i);
map.put(i, pwrCnt != null ? pwrCnt + 1 : 1);
}
}
// If the number is prime, we have to add it to the
// map.
if (num != 1)
map.put(num, 1);
return map;
}
static HashSet<Long> divisors(long num) {
HashSet<Long> divisors = new HashSet<Long>();
divisors.add(1L);
divisors.add(num);
for (long i = 2; i * i <= num; i++) {
if (num % i == 0) {
divisors.add(num/i);
divisors.add(i);
}
}
return divisors;
}
static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) {
if (m > limit) return;
if (m <= limit && n <= limit)
coprimes.add(new Point(m, n));
if (coprimes.size() > numCoprimes) return;
coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes);
coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes);
coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes);
}
static long nCr(long n, long r, long[] fac) { long p = gigamod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; }
static long modInverse(long n, long p) { return power(n, p - 2, p); }
static long modDiv(long a, long b){return mod(a * power(b, mod - 2, mod), mod);}
static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; }
static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); }
static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double 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 sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); }
static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
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(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();}
static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();}
static long mod(long a, long m){return(a%m+1000000L*m)%m;}
}
/*
*
* int[] arr = new int[] {1810, 1700, 1710, 2320, 2000, 1785, 1780
, 2130, 2185, 1430, 1460, 1740, 1860, 1100, 1905, 1650};
int n = arr.length;
sort(arr);
int bel1700 = 0, bet1700n1900 = 0, abv1900 = 0;
for (int i = 0; i < n; i++)
if (arr[i] < 1700)
bel1700++;
else if (1700 <= arr[i] && arr[i] < 1900)
bet1700n1900++;
else if (arr[i] >= 1900)
abv1900++;
out.println("COUNT: " + n);
out.println("PERFS: " + toString(arr));
out.println("MEDIAN: " + arr[n / 2]);
out.println("AVERAGE: " + Arrays.stream(arr).average().getAsDouble());
out.println("[0, 1700): " + bel1700 + "/" + n);
out.println("[1700, 1900): " + bet1700n1900 + "/" + n);
out.println("[1900, 2400): " + abv1900 + "/" + n);
*
* */
// NOTES:
// ASCII VALUE OF 'A': 65
// ASCII VALUE OF 'a': 97
// Range of long: 9 * 10^18
// ASCII VALUE OF '0': 48
// Primes upto 'n' can be given by (n / (logn)). | 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.io.*;
import java.util.Arrays;
public class Gf {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
int numberSets = Integer.parseInt(br.readLine());
for (int nos = 0; nos < numberSets; nos++) {
int [] data = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int max = 0;
for (int i = 0; i < data.length-1; i++) {
max = Math.max(max, data[i]);
}
for (int i = 0; i < data.length-1; i++) {
data[3]-=(max-data[i]);
}
if (data[3]%3 != 0 || data[3] < 0) {
System.out.println("NO");
} else {
System.out.println("YES");
}
}
}
}
| 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 codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
static List<Integer> al[];
static int par[];
static int dist[];
static boolean vis[];
static int n;
static int bfs(int u) {
Queue<Integer> q=new LinkedList<>();
q.add(u);
par[u]=0;
vis[u]=true;
dist[u]=0;
while(!q.isEmpty()){
int cur=q.poll();
// System.out.println(cur);
for(int e:al[cur]){
if(!vis[e]) {
vis[e]=true;
dist[e]=dist[cur]+1;
par[e]=cur;
q.add(e);
}
}
}
// for(int e:dist)
// System.out.print(e+" ");
// System.out.println();
int max=0;
for(int i=1;i<=n;i++) {
if(dist[i]>dist[max]) max=i;
}
return max;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
n=sc.nextInt();
al=new ArrayList[n+1];
for(int i=0;i<=n;i++) al[i]=new ArrayList<>();
for(int i=0;i<n-1;i++) {
int u=sc.nextInt();
int v=sc.nextInt();
al[u].add(v);
al[v].add(u);
}
dist=new int[n+1];
par=new int[n+1];
vis=new boolean[n+1];
int firstNode=bfs(1);
dist=new int[n+1];
par=new int[n+1];
vis=new boolean[n+1];
int secondNode=bfs(firstNode);
// System.out.println(firstNode+" "+secondNode);
int ans=dist[secondNode];
if(ans==n-1){
out.println(ans);
out.println(secondNode+" "+par[secondNode]+" "+firstNode);
}
else {
int temp=secondNode;
Queue<Integer> q=new LinkedList<>();
boolean vis[]=new boolean[n+1];
while(secondNode!=firstNode){
q.add(secondNode);
vis[secondNode]=true;
secondNode=par[secondNode];
}
q.add(firstNode);
vis[firstNode]=true;
int dist[]=new int[n+1];
while(!q.isEmpty()) {
int cur=q.poll();
for(int e:al[cur]){
if(!vis[e]) {
vis[e]=true;
dist[e]=dist[cur]+1;
q.add(e);
}
}
}
int max=0;
for(int i=1;i<=n;i++) {
if(dist[i]>dist[max]) max=i;
}
out.println(ans+dist[max]);
out.println(temp+" "+max+" "+firstNode);
}
out.flush();
out.close();
}
}
| 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.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
short n, m;
n = sc.nextShort();
m = sc.nextShort();
String[] s = new String[n];
String[] t = new String[m];
for (short b = 0; b < n; b++)
s[b] = sc.next();
for (short b = 0; b < m; b++)
t[b] = sc.next();
int q = sc.nextInt();
long y;
while (q-- > 0) {
y = sc.nextLong();
short index1 = (short) ((y - 1) % n);
short index2 = (short) ((y - 1) % m);
System.out.println(s[index1] + t[index2]);
}
sc.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"
] | //package javaapplication3;
import java.util.Scanner;
public class JavaApplication3 {
static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
int t = scan.nextInt();
while (t-- > 0) {
long n = scan.nextLong();
long g = scan.nextLong();
long b = scan.nextLong();
long dis = (long) Math.ceil(n / 2.0);
long round = g + b;
long numOfRounds = dis / g;
long ans;
if (dis % g == 0) {
ans = (round * numOfRounds) - b;
} else {
ans = (round * numOfRounds) + (dis % g);
}
if (ans < n) {
ans = n;
}
System.out.println(ans);
}
}
}
| 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.*;
import java.lang.*;
import java.util.*;
public class Main {
public static int mod = (int)1e9 + 7;
// **** -----> Disjoint Set Union(DSU) Start **********
public static int findPar(int node, int[] parent) {
if (parent[node] == node)
return node;
return parent[node] = findPar(parent[node], parent);
}
public static boolean union(int u, int v, int[] rank, int[] parent) {
u = findPar(u, parent);
v = findPar(v, parent);
if(u == v) return false;
if (rank[u] < rank[v])
parent[u] = v;
else if (rank[u] > rank[v])
parent[v] = u;
else {
parent[u] = v;
rank[v]++;
}
return true;
}
// **** DSU Ends ***********
//Pair with int int
public static class Pair{
public int a;
public int b;
Pair(int a , int b){
this.a = a;
this.b = b;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
public static String toBinary(int n) {return Integer.toBinaryString(n);}
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 isPalindrome(int[] arr) {int i = 0, j = arr.length - 1;while (i < j) {if (arr[i] != arr[j])return false;}return true;}
public static int pow(int x, int y) {int res = 1;x = x % mod;if (x == 0)return 0;while (y > 0) {if ((y & 1) != 0)res = (res * x) % mod;y = y >> 1;x = (x * x) % mod;}return res;}
public static int gcd(int a, int b) {if (b == 0)return a;return gcd(b, a % b);}
public static long gcd(long a, long b) {if (b == 0)return a;return gcd(b, a % b);}
public static void sort(long[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);long temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);}
public static void reverse(int a[]) {int i, k, t, n = a.length;for (i = 0; i < n / 2; i++) {t = a[i];a[i] = a[n - i - 1];a[n - i - 1] = t;}}
public static void sort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);}
public static void revSort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);reverse(a);}
public static long LCM(long a, long b) {if (a > b) {long t = a;a = b;b = t;}a /= gcd(a, b);return (a * b);}
public static int findMax(int[] a, int left, int right) {int res = left;int max = a[left];for (int i = left + 1; i <= right; i++) {if (a[i] > max) {max = a[i];res = i;}}return res;}
public static long findClosest(long arr[], long target) {int n = arr.length;if (target <= arr[0])return arr[0];if (target >= arr[n - 1])return arr[n - 1];int i = 0, j = n, mid = 0;while (i < j) {mid = (i + j) / 2;if (arr[mid] == target)return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];}
public static long getClosest(long val1, long val2, long target) {if (target - val1 >= val2 - target)return val2;else return val1;}
public static int findClosest(int arr[], int target) { int n = arr.length; if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];}
public static int getClosest(int val1, int val2, int target) {if (target - val1 >= val2 - target)return val2;else return val1;}
public static String reverse(String str) {StringBuilder sb = new StringBuilder(str);sb.reverse();return sb.toString();}
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 int xorSum(int arr[], int n){int bits = 0;for (int i = 0; i < n; ++i)bits |= arr[i];int ans = bits * (int)Math.pow(2, n-1);return ans;}
public static ArrayList<Integer> primeFactors(int n) { ArrayList<Integer> res = new ArrayList<>();while (n%2 == 0) { res.add(2); n = n/2; } for (int i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;}
public static ArrayList<Long> primeFactors(long n) { ArrayList<Long> res = new ArrayList<>();while (n%2 == 0) { res.add(2L); n = n/2; } for (long i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;}
static int lower_bound(int array[], int low, int high, int key){
int mid;
while (low < high) {
mid = low + (high - low) / 2;
if (key <= array[mid]) high = mid;
else low = mid + 1;
}
if (low < array.length && array[low] < key) low++;
return low;
}
static long fastPower(long a, long b, long mod){
long ans = 1 ;
while (b > 0)
{
if ((b&1) != 0) ans = (ans%mod * a%mod) %mod;
b >>= 1 ;
a = (a%mod * a%mod)%mod ;
}
return ans ;
}
/********************************* Start Here ***********************************/
// int mod = 1000000007;
static HashMap<String, Integer> map;
static Set<Integer> set1, set2;
static boolean[] vis;
public static void main(String[] args) throws java.lang.Exception {
if (System.getProperty("ONLINE_JUDGE") == null) {
PrintStream ps = new PrintStream(new File("output.txt"));
System.setOut(ps);
}
FastScanner sc = new FastScanner("input.txt");
StringBuilder result = new StringBuilder();
// sieveOfEratosthenes(1000000);
// int T = sc.nextInt();
int T = 1;
for(int test = 1; test <= T; test++){
int n = sc.nextInt();
int[] arr = sc.readArray(n);
long maxsum = 0;
int[] ans = new int[n];
for(int i = 0; i < n; i++){
int[] cur = new int[n];
cur[i] = arr[i];
int max = arr[i];
long cursum = arr[i];
for(int j = i-1; j >= 0; j--){
cur[j] = Math.min(max, arr[j]);
max = cur[j];
cursum += cur[j];
}
max = arr[i];
for(int j = i+1; j < n; j++){
cur[j] = Math.min(max,arr[j]);
max = cur[j];
cursum += cur[j];
}
if(cursum > maxsum){
maxsum = cursum;
ans = cur;
}
}
for(int i = 0; i < n; i++)
result.append(ans[i]+" ");
result.append("\n");
}
System.out.println(result);
System.out.close();
}
// public static boolean solve(int[][] arr, int i, int[][]){
// if(i == arr.length) return true;
// if(arr[i][0] == arr[i][1]){
// return false;
// }
// boolean res = false;
// return res;
// }
// static void sieveOfEratosthenes(int n){
// 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)
// set.add(i);
// }
// }
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
if (st == null || !st.hasMoreTokens()) {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken("\n");
}
public String[] readStringArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = next();
}
return a;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
String next() {
return nextToken();
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
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;
}
int[][] read2dArray(int n, int m) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextInt();
}
}
return a;
}
long[][] read2dlongArray(int n, int m) {
long[][] a = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextLong();
}
}
return a;
}
}
}
| java |
1304 | A | A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward. | [
"math"
] | import java.util.*;
import java.io.*;
public class Practice {
static boolean multipleTC = true;
final static int mod = 1000000007;
final static int mod2 = 998244353;
final double E = 2.7182818284590452354;
final double PI = 3.14159265358979323846;
int MAX = 3001;
int N = 3001;
void pre() throws Exception {
}
// All the best
void solve(int TC) throws Exception {
int x = ni();
int y = ni();
int a = ni();
int b = ni();
if ((y - x) % (b + a) == 0)
pn((y - x) / (b + a));
else
pn(-1);
}
// 2 3 4 5 1
// 1 2 3 4 5
// 1 2 3 4
// 2 1 4 3
// 1 2 4 3
//
double dist(int x1, int y1, int x2, int y2) {
double a = x1 - x2, b = y1 - y2;
return Math.sqrt((a * a) + (b * b));
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(int arr[], int left, int right) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = left; i <= right; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = left; i <= right; i++)
arr[i] = list.get(i - left);
}
void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
String bin(long n) {
return Long.toBinaryString(n);
}
String bin(int n) {
return Integer.toBinaryString(n);
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
void p(Object o) {
out.print(o);
}
void pn(Object o) {
out.println(o);
}
void pni(Object o) {
out.println(o);
out.flush();
}
void pn(int[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
void pn(long[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
String n() throws Exception {
return in.next();
}
String nln() throws Exception {
return in.nextLine();
}
int ni() throws Exception {
return Integer.parseInt(in.next());
}
long nl() throws Exception {
return Long.parseLong(in.next());
}
double nd() throws Exception {
return Double.parseDouble(in.next());
}
public static void main(String[] args) throws Exception {
new Practice().run();
}
FastReader in;
PrintWriter out;
void run() throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++)
solve(t);
out.flush();
out.close();
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
} | java |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import javax.management.InstanceNotFoundException;
import javax.swing.*;
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
static class Boot {
int left;
int right;
Boot(int left, int right) {
this.left = left;
this.right = right;
}
}
static Map<Integer, List<Integer>> leftBootIndexMap;
static Map<Integer, List<Integer>> rightBootIndexMap;
static List<Boot> boots = new ArrayList<>();
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 1; t <= test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
char[] leftBootsColor = sc.next().toCharArray();
char[] rightBootsColor = sc.next().toCharArray();
int[] freqLeftBoots = getFreqOfBoots(leftBootsColor, n);
int[] freqRightBoots = getFreqOfBoots(rightBootsColor, n);
leftBootIndexMap = getIndexMappingOfBoots(leftBootsColor, n);
rightBootIndexMap = getIndexMappingOfBoots(rightBootsColor, n);
int totalPairsOfBoots = findMaxPairOfBoots(freqLeftBoots, freqRightBoots);
out.println(totalPairsOfBoots);
for (Boot boot : boots) {
out.println(boot.left + " " + boot.right);
}
}
private static Map<Integer, List<Integer>> getIndexMappingOfBoots(char[] bootsColor, int n) {
Map<Integer, List<Integer>> indexMappingOfBoots = new HashMap<>();
for (int i = 0; i < 27; i++) {
indexMappingOfBoots.put(i, new ArrayList<>());
}
for (int i = 0; i < n; i++) {
int colorIndex = bootsColor[i] == '?' ? 26 : bootsColor[i] - 'a';
indexMappingOfBoots.get(colorIndex).add(i + 1);
}
return indexMappingOfBoots;
}
private static int findMaxPairOfBoots(int[] freqLeftBoots, int[] freqRightBoots) {
int totalPairsOfBoots = 0, remainingLeftBoots = 0, remainingRightBoots = 0;
for (int i = 0; i < 26; i++) {
int matchingPairs = Math.min(freqLeftBoots[i], freqRightBoots[i]);
totalPairsOfBoots += matchingPairs;
freqLeftBoots[i] -= matchingPairs;
freqRightBoots[i] -= matchingPairs;
addPairsOfBoots(i, i, matchingPairs);
remainingLeftBoots += freqLeftBoots[i];
remainingRightBoots += freqRightBoots[i];
}
int indefiniteLeftMatches = Math.min(remainingLeftBoots, freqRightBoots[26]);
int indefiniteRightMatches = Math.min(remainingRightBoots, freqLeftBoots[26]);
freqLeftBoots[26] -= indefiniteRightMatches;
freqRightBoots[26] -= indefiniteLeftMatches;
List<Integer> leftBootsRemaining = getRemainingBoots(leftBootIndexMap);
for (int i = 0; i < indefiniteLeftMatches; i++) {
int size = leftBootsRemaining.size();
int leftBootIndex = leftBootsRemaining.get(size - 1);
leftBootsRemaining.remove(size - 1);
size = rightBootIndexMap.get(26).size();
int rightBootIndex = rightBootIndexMap.get(26).get(size - 1);
rightBootIndexMap.get(26).remove(size - 1);
boots.add(new Boot(leftBootIndex, rightBootIndex));
}
List<Integer> rightBootsRemaining = getRemainingBoots(rightBootIndexMap);
for (int i = 0; i < indefiniteRightMatches; i++) {
int size = leftBootIndexMap.get(26).size();
int leftBootIndex = leftBootIndexMap.get(26).get(size - 1);
leftBootIndexMap.get(26).remove(size - 1);
size = rightBootsRemaining.size();
int rightBootIndex = rightBootsRemaining.get(size - 1);
rightBootsRemaining.remove(size - 1);
boots.add(new Boot(leftBootIndex, rightBootIndex));
}
totalPairsOfBoots += indefiniteLeftMatches + indefiniteRightMatches;
int bothIndefinite = Math.min(freqLeftBoots[26], freqRightBoots[26]);
addPairsOfBoots(26, 26, bothIndefinite);
totalPairsOfBoots += bothIndefinite;
return totalPairsOfBoots;
}
private static List<Integer> getRemainingBoots(Map<Integer, List<Integer>> bootIndexMap) {
List<Integer> remaining = new ArrayList<>();
for (int color : bootIndexMap.keySet()) {
if (color == 26) {
continue;
}
remaining.addAll(bootIndexMap.get(color));
}
return remaining;
}
private static void addPairsOfBoots(int leftColor, int rightColor, int matchingPairs) {
for (int i = 0; i < matchingPairs; i++) {
int size = leftBootIndexMap.get(leftColor).size();
int leftBootIndex = leftBootIndexMap.get(leftColor).get(size - 1);
leftBootIndexMap.get(leftColor).remove(size - 1);
size = rightBootIndexMap.get(rightColor).size();
int rightBootIndex = rightBootIndexMap.get(rightColor).get(size - 1);
rightBootIndexMap.get(rightColor).remove(size - 1);
boots.add(new Boot(leftBootIndex, rightBootIndex));
}
}
private static int[] getFreqOfBoots(char[] bootsColor, int n) {
int[] freq = new int[27];
for (int i = 0; i < n; i++) {
if (bootsColor[i] == '?') {
freq[26]++;
}else {
freq[bootsColor[i] - 'a']++;
}
}
return freq;
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
} | java |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
| [
"bitmasks",
"greedy"
] | import java.io.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);
DFillTheBag solver = new DFillTheBag();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class DFillTheBag {
public void solve(int testNumber, InputReader in, OutputWriter out) {
long n = in.nextLong();
int m = in.nextInt();
int[] arr = in.nextIntArray(m);
long sum = 0;
for (int a : arr) sum += a;
if (sum < n) {
out.println(-1);
return;
}
long[] f = new long[64];
for (int i = 0; i < 32; i++) {
for (int a : arr) {
if ((a & (1 << i)) != 0) f[i]++;
}
}
int ans = 0;
for (int i = 0; i <= 60; i++) {
if (((1L << i) & n) != 0) {
if (f[i] > 0) {
f[i]--;
} else {
for (int j = i + 1; j <= 60; j++) {
if (f[j] > 0) {
ans += j - i;
f[j]--;
for (int k = j - 1; k >= i; k--) {
f[k]++;
}
break;
}
}
}
}
f[i + 1] += f[i] / 2;
}
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[] 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());
}
public long nextLong() {
return Long.parseLong(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 close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
| 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.io.*;
import java.util.*;
import static java.lang.Math.*;
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) {
long u = in.nextLong();
long v = in.nextLong();
// u>v || (u%2)^(v%2)!=0 -> ans = -1
// x=(v-u)/2 u^0=u x^x=0 max(ans)=3, [u,x,x]
// a^b=u && a+b=v => a+b=(a^b)+2*(a&b) => (a&b)=(v-u)/2=x
long x = (v - u) / 2;
if (u == v) {
if (u == 0) {
pw.println(0);
} else {
pw.println("1\n" + u);
}
pw.close();
return;
}
if (u > v || ((u % 2) ^ (v % 2)) != 0) {
pw.println(-1);
pw.close();
return;
} else {
for (int i = 63; i >= 0; i--) {
if (((x >> i) & (u >> i)) != 0) {
pw.println(3 + "\n" + u + " " + x + " " + x);
pw.close();
return;
}
}
}
pw.println(2 + "\n" + (u + x) + " " + x);
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;
}
private void reverse(int[] a) {
int n = a.length;
for (int i = 0; i < n / 2; i++) {
int tmp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = tmp;
}
}
private 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);
}
}
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 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 |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | import java.util.*;
public class CF {
public static void main(String[] args) {
Scanner cs = new Scanner(System.in);
int t = cs.nextInt();
while(t-- > 0) {
int n = cs.nextInt();
int m = cs.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++) {
arr[i] = cs.nextInt();
}
boolean[] pr = new boolean[n];
for(int i=0;i<m;i++) {
int loc = cs.nextInt();
pr[loc-1] = true;
}
for(int i=0;i<n;i++) {
if(pr[i]) {
int loc = i;
for(i+=1;i<n;i++) {
if(!pr[i]) {
break;
}
}
Arrays.sort(arr, loc, i+1);
}
}
int now = arr[0];
int i=1;
for(;i<n;i++) {
if(now > arr[i]) {
break;
}
now = arr[i];
}
if(i == n) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
} | java |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00. | [
"math",
"number theory"
] | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scn = new Scanner(System.in);
OutputWriter out = new OutputWriter(System.out);
// Always print a trailing "\n" and close the OutputWriter as shown at the end of your output
// example;
ArrayList<Integer> arr1=new ArrayList<Integer>();
prime(arr1);
int t=scn.nextInt();
for(int i1=0;i1<t;i1++){
long a=scn.nextLong();long m=scn.nextLong();
long g=gcd1(m,a);a=a/g;m=m/g;
long ans=m;
for(int p:arr1){
if(m%p==0){
while(m%p==0){
m=m/p;
}
ans=ans*(p-1)/p;
}
}
if(m>1){
ans=(ans/m)*(m-1);
}
out.print(Long.toString(ans)+"\n");
}
out.close();
}
public static long gcd1(long a,long b){
if(a>=b){
while(b>0){
long m=a%b;
a=b;
b=m;
}
return(a);
}
else{
return(gcd1(b,a));
}
}
public static void prime(ArrayList<Integer> arr1){
int[] arr=new int[100001];
for(int i=2;i<=100000;i++){
if(arr[i]==0){
arr1.add(i);
if(i>=1000){
continue;
}
for(int j=i*i;j<=100000;j=j+i){
arr[j]=1;
}
}
}
}
// fast input
static class Scanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Scanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String line = reader.readLine();
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
} catch (Exception e) {
throw(new RuntimeException());
}
}
return tokenizer.nextToken();
}
public int nextInt() { return Integer.parseInt(next()); }
public long nextLong() { return Long.parseLong(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
}
// fast output
static class OutputWriter {
BufferedWriter writer;
public OutputWriter(OutputStream stream) {
writer = new BufferedWriter(new OutputStreamWriter(stream));
}
public void print(int i) throws IOException { writer.write(i); }
public void print(String s) throws IOException { writer.write(s); }
public void print(char[] c) throws IOException { writer.write(c); }
public void close() throws IOException { writer.close(); }
}
} | 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.io.*;
import java.util.InputMismatchException;
public class E1285A {
public static void main(String[] args) {
FastIO io = new FastIO();
int n = io.nextInt();
io.next();
io.println(n + 1);
io.close();
}
private static class FastIO extends PrintWriter {
private final InputStream stream;
private final byte[] buf = new byte[1 << 16];
private int curChar, numChars;
// standard input
public FastIO() {
this(System.in, System.out);
}
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c;
do {
c = nextByte();
} while (c <= ' ');
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nextByte();
} while (c > ' ');
return res.toString();
}
public int nextInt() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
int res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
long res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| 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 Main{
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 |
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;
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 |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32. | [
"combinatorics",
"math"
] |
import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static int mod ;
static void solve() {
int n=i();
mod=i();
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; }
long ans=0;
ans=((n%mod) * (fact[n]%mod)) %mod;
for(int rml=1;rml<n;rml++){
int bx=rml+1;
int rem=(n-bx);
int tb=rem+1;
long for1=((fact[tb]%mod) *(fact[bx]%mod) )%mod;
long size=rml+1;
size=(n-size);
size++;
for1= ((for1%mod) * (size % mod)) %mod;
ans=((ans%mod)+(for1%mod))%mod;
}
sb.append(ans+"\n");
}
public static void main(String[] args) {
sb = new StringBuilder();
int test = 1;
while (test-- > 0) {
solve();
}
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) % 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] = 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> {
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 |
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.util.*;
import java.io.*;
import java.math.*;
import java.lang.*;
public class Hyperset {
// static int mod = 998244353;
static int mod = 1000000007;
private static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws Exception {
FastReader scn = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
int t = 1;
outer : while(t-->0){
int n = scn.nextInt();
int k = scn.nextInt();
HashMap<String, Integer> hm = new HashMap<>();
String[] arr = new String[n];
for(int i=0; i<n; i++){
arr[i] = scn.nextLine();
hm.put(arr[i], hm.getOrDefault(arr[i], 0) + 1);
}
long ans = 0L;
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
String s1 = arr[i];
String s2 = arr[j];
StringBuilder sb = new StringBuilder();
for(int q=0; q<k; q++){
char ch1 = s1.charAt(q);
char ch2 = s2.charAt(q);
if(ch1 == 'S'){
if(ch2 == 'S'){
sb.append("S");
}else if(ch2 == 'E'){
sb.append("T");
}else if(ch2 == 'T'){
sb.append("E");
}
}else if(ch1 == 'E'){
if(ch2 == 'E'){
sb.append("E");
}else if(ch2 == 'S'){
sb.append("T");
}else if(ch2 == 'T'){
sb.append("S");
}
}else if(ch1 == 'T'){
if(ch2 == 'T'){
sb.append("T");
}else if(ch2 == 'S'){
sb.append("E");
}else if(ch2 == 'E'){
sb.append("S");
}
}
}
String str = sb.toString();
if(hm.containsKey(str)){
ans += hm.get(str);
}
}
}
long fans = ans / 3L;
pw.println(fans);
}
pw.close();
}
public static class Pair{
int x;
int y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for(int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
// private static void sort(Pair[] arr) {
// List<Pair> list = new ArrayList<>();
// for(int i=0; i<arr.length; i++){
// list.add(arr[i]);
// }
// Collections.sort(list); // collections.sort uses nlogn in backend
// for (int i = 0; i < arr.length; i++){
// arr[i] = list.get(i);
// }
// }
private static void reverseSort(int[] arr){
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list, Collections.reverseOrder()); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void reverseSort(long[] arr){
List<Long> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list, Collections.reverseOrder()); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void reverseSort(ArrayList<Integer> list){
Collections.sort(list, Collections.reverseOrder());
}
private static int lowerBound(int[] arr, int x){
int n = arr.length, si = 0, ei = n - 1;
while(si <= ei){
int mid = si + (ei - si)/2;
if(arr[mid] == x){
if(mid-1 >= 0 && arr[mid-1] == arr[mid]){
ei = mid-1;
}else{
return mid;
}
}else if(arr[mid] > x){
ei = mid - 1;
}else{
si = mid+1;
}
}
return si;
}
private static int upperBound(int[] arr, int x){
int n = arr.length, si = 0, ei = n - 1;
while(si <= ei){
int mid = si + (ei - si)/2;
if(arr[mid] == x){
if(mid+1 < n && arr[mid+1] == arr[mid]){
si = mid+1;
}else{
return mid + 1;
}
}else if(arr[mid] > x){
ei = mid - 1;
}else{
si = mid+1;
}
}
return si;
}
private static int upperBound(ArrayList<Integer> list, int x){
int n = list.size(), si = 0, ei = n - 1;
while(si <= ei){
int mid = si + (ei - si)/2;
if(list.get(mid) == x){
if(mid+1 < n && list.get(mid+1) == list.get(mid)){
si = mid+1;
}else{
return mid + 1;
}
}else if(list.get(mid) > x){
ei = mid - 1;
}else{
si = mid+1;
}
}
return si;
}
// (x^y)%p in O(logy)
private static long power(long x, long y){
long res = 1;
x = x % mod;
while(y > 0){
if ((y & 1) == 1){
res = (res * x) % mod;
}
y = y >> 1;
x = (x * x) % mod;
}
return res;
}
public static boolean nextPermutation(int[] arr) {
if(arr == null || arr.length <= 1){
return false;
}
int last = arr.length-2;
while(last >= 0){
if(arr[last] < arr[last+1]){
break;
}
last--;
}
if (last < 0){
return false;
}
if(last >= 0){
int nextGreater = arr.length-1;
for(int i=arr.length-1; i>last; i--){
if(arr[i] > arr[last]){
nextGreater = i;
break;
}
}
swap(arr, last, nextGreater);
}
reverse(arr, last+1, arr.length-1);
return true;
}
private static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static void reverse(int[] arr, int i, int j){
while(i < j){
swap(arr, i++, j--);
}
}
private static String reverseStr(String s){
StringBuilder sb = new StringBuilder(s);
return sb.reverse().toString();
}
// TC- O(logmax(a,b))
private static int gcd(int a, int b) {
if(a == 0){
return b;
}
return gcd(b%a, a);
}
private static long gcd(long a, long b) {
if(a == 0L){
return b;
}
return gcd(b%a, a);
}
private static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
// TC- O(logmax(a,b))
private static int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
private static long inv(long x){
return power(x, mod - 2);
}
private static long summation(long n){
return (n * (n + 1L)) >> 1;
}
} | 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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class StringColoring {
int[] tree;
private void insert(int num, int index, int a, int b, int node) {
if (a == b) {
tree[node] = num;
return;
}
int mid = (a +b ) / 2;
if (index <= mid) {
insert(num, index, a, mid, node * 2);
} else {
insert(num, index, mid + 1, b, node * 2 + 1);
}
tree[node] = Math.max(tree[node * 2], tree[node * 2 + 1]);
}
private int get(int from, int to, int a, int b, int node) {
if (from <= a && b <= to) {
return tree[node];
}
int mid = (a + b) / 2;
int max = 0;
if (from <= mid) {
max = Math.max(max, get(from, to, a, mid, node * 2));
}
if (to > mid) {
max = Math.max(max, get(from, to, mid + 1, b, node * 2 + 1));
}
return max;
}
public static void main(String[] args) throws IOException {
new StringColoring().solve();
}
public void solve() throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(f.readLine());
char[] seq = f.readLine().toCharArray();
int[] values = new int[n];
for (int i = 0; i < n; i++) {
values[i] = seq[i] - 'a';
}
seq = null;
int[] color = new int[n];
tree = new int[26 * 4 + 5];
for (int i = 0; i < n; i++) {
if (values[i] == 25) {
color[i] = 1;
} else {
color[i] = get(values[i] + 1, 25, 0, 25, 1) + 1;
}
insert(color[i], values[i], 0, 25, 1);
/*
System.out.println(values[i] + " " + get(values[i], values[i], 0, 25, 1));
for (int j = 0; j < 26; j++) {
System.out.print(get(j, j, 0, 25, 1) + " ");
}
System.out.println(); */
}
int max = 0;
for (int i = 0; i < n; i++) max = Math.max(max, color[i]);
out.println(max);
out.print(color[0]);
for (int i = 1; i < n; i++) {
out.print(" ");
out.print(color[i]);
}
out.println();
out.close();
}
}
| java |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. | [
"data structures",
"dsu",
"implementation"
] |
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
public class codeee
{ //public static int mod=1000000007;
public static ArrayList<Integer> Factors(int n)
{
ArrayList<Integer> arr=new ArrayList<Integer>();
int k=0;
while (n%2==0)
{
k++;
n /=2;
arr.add(2);
}
int p=(int) Math.sqrt(n);
for (int i = 3; i <=p; i+= 2)
{ if(n==1)break;
while (n%i == 0)
{
k++;
arr.add(i);
n /= i;
}
}
if (n > 2)
{
arr.add(n);
}
//arr.add(1);
return arr;
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static long gcd(long x, long p)
{
if (x == 0)
return p;
return gcd(p%x, x);
}
public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<Integer, Integer> > list =
new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() {
public int compare(Map.Entry<Integer, Integer> o1,
Map.Entry<Integer, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// put data from sorted list to hashmap
HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
static int sieve = 1000000 ;
static boolean[] prime = new boolean[sieve + 1] ;
public static void sieveOfEratosthenes()
{
// FALSE == prime and 1 // TRUE == COMPOSITE
// time complexity = 0(NlogLogN)== o(N)
// gives prime nos bw 1 to N // size - 1e7(at max)
for(int i = 4; i<= sieve ; i++)
{
prime[i] = true ; i++ ;
}
for(int p = 3; p*p <= sieve; p++)
{
if(prime[p] == false)
{
for(int i = p*p; i <= sieve; i += p)
prime[i] = true;
}
p++ ;
}
}
public static void arrInpInt(int [] arr, int n) throws IOException
{
Reader reader = new Reader();
for(int i=0;i<n;i++)
{
arr[i]=reader.nextInt();
}
}
public static void arrInpLong(long [] arr, int n) throws IOException
{
Reader reader = new Reader();
for(int i=0;i<n;i++)
{
arr[i]=reader.nextLong();
}
}
public static void printArr(int[] arr)
{
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static int[] decSort(int[] arr)
{
int[] arr1 = Arrays.stream(arr).boxed().sorted(Collections.reverseOrder()).mapToInt(Integer::intValue).toArray();
return arr1;
}
//if present - return the first occurrence of the no
//not present- return the index of next greater value
//if greater than all the values return N(taking high=N-1)
//if smaller than all the values return 0(taking low =0)
static int lower_bound(int arr[], int low,int high, int X)
{
if (low > high) {
return low;
}
int mid = low + (high - low) / 2;
if (arr[mid] >= X) {
return lower_bound(arr, low,
mid - 1, X);
}
return lower_bound(arr, mid + 1,
high, X);
}
//if present - return the index of next greater value
//not present- return the index of next greater value
//if greater than all the values return N(taking high=N-1)
//if smaller than all the values return 0(taking low =0)\
static int upper_bound(int arr[], int low, int high, int X)
{
if (low > high)
return low;
int mid = low + (high - low) / 2;
if (arr[mid] <= X) {
return upper_bound(arr, mid + 1,
high, X);
}
return upper_bound(arr, low,
mid - 1, X);
}
public static class Pair {// comparator with class
int x;
int y;
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
}
public static void sortbyColumn(int arr[][], int col) // send 2d array and col no
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else if (entry1[col] < entry2[col])
return -1;
else return 0;
}
});
}
public static void sortbyColumn1(int arr[][], int col) // send 2d array and col no
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else if (entry1[col] < entry2[col])
return -1;
else if(entry1[col] == entry2[col])
{
if(entry1[col-1]>entry2[col-1])
return -1;
else if(entry1[col-1]<entry2[col-1])
return 1;
else return 0;
}
else return 0;
}
});
}
public static void print2D(int mat[][])
{
// Loop through all rows
for (int i = 0; i < mat.length; i++)
{ // Loop through all elements of current row
{
for (int j = 0; j < mat[i].length; j++)
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
public static int biggestFactor(int num) {
int result = 1;
for(int i=2; i*i <=num; i++){
if(num%i==0){
result = num/i;
break;
}
}
return result;
}
public static class p
{
int no;
int h;
public p(int no, long h)
{
this.no=no;
this.h=(int) h;
}
}
public static class k
{
boolean inc;
int min;
int max;
public k(boolean inc,int min, int max)
{
this.inc=inc;
this.min=min;
this.max=max;
}
}
static class com implements Comparator<p>{
public int compare(p s1, p s2) {
if (s1.h > s2.h)
return -1;
else if (s1.h < s2.h)
return 1;
else if(s1.h==s2.h)
{
if(s1.no>s2.no)return -1;
else return 1;
}
return 0;
}
}
static long hcf(long a,long b)
{
while (b > 0)
{
long temp = b;
b = a % b;
a = temp;
}
return a;
}
static int lower_bound_arr(ArrayList<Integer> arr, int low,
int high, int X)
{
if (low > high) {
return low;
}
int mid = low + (high - low) / 2;
if (arr.get(mid) >= X) {
return lower_bound_arr(arr, low,
mid - 1, X);
}
return lower_bound_arr(arr, mid + 1,
high, X);
}
public static void main(String args[]) throws NumberFormatException, IOException ,java.lang.Exception
{
Reader reader = new Reader();
//sieveOfEratosthenes();
//System.out.println(prime[0]+" "+prime[1]+" "+prime[2]+" "+prime[3]+" "+prime[4]);
//Scanner reader=new Scanner(System.in);
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// int cases=Integer.parseInt(br.readLine());
int cases=1;
//BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
// int cases=reader.nextInt();
while (cases-->0){
long V=reader.nextLong();
long C=reader.nextLong();
//long N=reader.nextLong();
//long M=reader.nextLong();
//int N=reader.nextInt();
//int G=reader.nextInt();
//int B=reader.nextInt();
//BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
// int P=reader.nextInt();
//int[][] arr=new int[N][N];
//int K=reader.nextInt();
//int X=reader.nextInt();
//int K=reader.nextInt();
//int S=reader.nextInt();
//int circum=reader.nextInt();
//int K=reader.nextInt();
// String[] firs=br.readLine().split(" ");
// int N=Integer.parseInt(firs[0]);
//char p=first[1].charAt(0);
//int P=Integer.parseInt(first[1]);
//int K=Integer.parseInt(first[2]);
//String[] first=br.readLine().split(" ");
//int N=Integer.parseInt(first[0]);
//int K=Integer.parseInt(first[1]);
//int X=reader.nextInt();
//int Y=reader.nextInt();
//String s2=br.readLine();
// String s3=br.readLine();
// char[] s11=s2.toCharArray();
// char[] s12=new char[s11.length];
//String[] first1=br.readLine().split(" ");
//int C=Integer.parseInt(first1[0]);
//int C1=Integer.parseInt(first1[1]);
//char[] s12=s3.toCharArray();
//int max=Integer.MIN_VALUE;
//int min=Integer.MAX_VALUE;
//int ind=-1;
HashMap<String,Integer> map=new HashMap<String,Integer>();
HashMap<String,Integer> map1=new HashMap<String,Integer>();
//HashMap<Character,Integer> path=new HashMap<Character,Integer>();
//TreeMap<Integer,Integer> map=new TreeMap<Integer,Integer>(Collections.reverseOrder());
//HashSet<Long> left =new HashSet<Long>();
// HashSet<Integer> right =new HashSet<Integer>();
//TreeSet<Integer> a =new TreeSet<Integer>();
//TreeSet<Long> b =new TreeSet<Long>();
//TreeSet<Integer> map=new TreeSet<Integer>();
// int[] arr=new int[N];
//Integer[] arr=new Integer[s11.length];
// Integer[] diff=new Integer[N];
// int[] diff=new int[N];
// int[] arr1= {2,3,5,7,11,13,17,19,23,29,31};
//Integer[] arr2=new Integer[N];
//boolean[]arr1=new boolean[N];
// long[] arr=new long[N];
// ArrayList<Integer> k=new ArrayList<Integer>();
//ArrayList<Integer> arr1=new ArrayList<Integer>();
//int [][] arr=new int[N][5];
//System.out.println(map);
//PriorityQueue<p> Q=new PriorityQueue<p>(new com());
//PriorityQueue<Long> w=new PriorityQueue<Long>();
//int min=Integer.MAX_VALUE;
//ArrayList<ArrayList<Integer>> arr1=new ArrayList<ArrayList<Ineteger>>();
//System.out.println();
//System.out.println(zero+" "+one);
//System.out.println(Arrays.toString(arr2));
for(int i=0;i<C;i++)
{
int x=reader.nextInt();
int y=reader.nextInt();
if(map.containsKey(x+","+y))
{
String p=x+","+y;
if(x==1)
{
String k1=p+"+2,"+(y-1);
String k2=p+"+2,"+y;
String k3=p+"+2,"+(y+1);
String k11="2,"+(y-1)+"+"+p;
String k12="2,"+y+"+"+p;
String k13="2,"+(y+1)+"+"+p;
if(map1.containsKey(k1))map1.remove(k1);
if(map1.containsKey(k2))map1.remove(k2);
if(map1.containsKey(k3))map1.remove(k3);
if(map1.containsKey(k11))map1.remove(k11);
if(map1.containsKey(k12))map1.remove(k12);
if(map1.containsKey(k13))map1.remove(k13);
}
else
{
String k1=p+"+1,"+(y-1);
String k2=p+"+1,"+y;
String k3=p+"+1,"+(y+1);
String k11="1,"+(y-1)+"+"+p;
String k12="1,"+y+"+"+p;
String k13="1,"+(y+1)+"+"+p;
if(map1.containsKey(k1))map1.remove(k1);
if(map1.containsKey(k2))map1.remove(k2);
if(map1.containsKey(k3))map1.remove(k3);
if(map1.containsKey(k11))map1.remove(k11);
if(map1.containsKey(k12))map1.remove(k12);
if(map1.containsKey(k13))map1.remove(k13);
}
map.remove(p);
}
else
{
map.put(x+","+y, 1);
String p=x+","+y;
if(x==1)
{
String k1="2,"+(y-1);
String k2="2,"+y;
String k3="2,"+(y+1);
String k11=p+"+2,"+(y-1);
String k21=p+"+2,"+y;
String k31=p+"+2,"+(y+1);
if(map.containsKey(k1))map1.put(k11,1);
if(map.containsKey(k2))map1.put(k21,1);
if(map.containsKey(k3))map1.put(k31,1);
}
else
{
String k1="1,"+(y-1);
String k2="1,"+y;
String k3="1,"+(y+1);
String k11=p+"+1,"+(y-1);
String k21=p+"+1,"+y;
String k31=p+"+1,"+(y+1);
if(map.containsKey(k1))map1.put(k11,1);
if(map.containsKey(k2))map1.put(k21,1);
if(map.containsKey(k3))map1.put(k31,1);
}
}
// System.out.println(map1);
// System.out.println(map);
if(map1.isEmpty())System.out.println("YES");
else System.out.println("NO");
}
}
}
}
| 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;
import java.util.Spliterator;
public class Book {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
while (n-- > 0) {
int a = scan.nextInt(), b= scan.nextInt();
int count = 0;
if(a>b){
if((a-b)%2==1) count =2;
else count = 1;
}
else if(a<b){
if((b-a)%2==1) count = 1;
else count = 2;
}
else if(a==b) count = 0;
System.out.println(count);
}
}
} | java |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | import java.util.*;
import java.lang.*;
import java.io.*;
public class GradeAllocation {
public static void main(String[] args)throws java.lang.Exception{
Scanner scn=new Scanner(System.in);
int a=scn.nextInt();
while(a-->0){
int b=scn.nextInt();
int d=scn.nextInt();
int f=0;
int[] arr=new int[b];
for(int i=0;i<arr.length;i++){
arr[i]=scn.nextInt();
f+=arr[i];
}
System.out.println(Math.min(d,f));
}
}
}
| 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 DisplayTheNumbers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int p = 0; p < t; p++){
int n = in.nextInt();
if ( n % 2 == 0){
for ( int i = 0; i < n/2 - 1; i++){
System.out.print(1);
}
System.out.println(1);
}
else if ( n == 3){
System.out.println(7);
}
else{
System.out.print(7);
for (int i = 0; i < n / 2 - 2; i++) {
System.out.print(1);
}
System.out.println(1);
}
}
}
} | java |
1316 | B | B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. | [
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
//import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
public class B {
static int mod= 998244353;
public static void main(String[] args) throws Exception {
PrintWriter out=new PrintWriter(System.out);
FastScanner fs=new FastScanner();
int t=fs.nextInt();
outer:while(t-->0) {
int n=fs.nextInt();
char arr[]=fs.next().toCharArray();
StringBuilder ans= new StringBuilder(String.valueOf(arr));
int min=1;
for(int k=2;k<=n;k++) {
int r= n-k+1;
StringBuilder cur=new StringBuilder();
for(int i=k-1;i<n;i++) cur.append(arr[i]);
if(r%2==0) for(int i=0;i<k-1;i++) cur.append(arr[i]);
else for(int i=k-2;i>=0;i--) cur.append(arr[i]);
if(cur.compareTo(ans)<0) {
ans= cur;
min=k;
}
// System.out.println(cur);
}
out.println(ans);
out.println(min);
}
out.close();
}
static long pow(long a,long b) {
if(b<0) return 1;
long res=1;
while(b!=0) {
if((b&1)!=0) {
res*=a;
res%=mod;
}
a*=a;
a%=mod;
b=b>>1;
}
return res;
}
static int gcd(int a,int b) {
if(b==0) return a;
return gcd(b,a%b);
}
static long nck(int n,int k) {
if(k>n) return 0;
long res=1;
res*=fact(n);
res%=mod;
res*=modInv(fact(k));
res%=mod;
res*=modInv(fact(n-k));
res%=mod;
return res;
}
static long fact(long n) {
// return fact[(int)n];
long res=1;
for(int i=2;i<=n;i++) {
res*=i;
res%=mod;
}
return res;
}
static long modInv(long n) {
return pow(n,mod-2);
}
static void sort(int[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long[] lreadArray(int n) {
long a[]=new long[n];
for(int i=0;i<n;i++) a[i]=nextLong();
return a;
}
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 |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — 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≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int inc = 0;
int dec = n - 1;
for (int i = 0; i < n; i++) {
if (arr[i] >= i) {
inc = i;
} else {
break;
}
}
int cnt = 0;
for(int i = n -1; i>= 0; i--){
if(arr[i] >= cnt){
dec = i;
} else {
break;
}
cnt++;
}
if (inc >= dec) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| 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.*;
import java.util.*;
public class A {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
if (n % 2 == 1) {
System.out.println("NO");
return;
}
boolean ok = true;
int[] x = new int[n], y = new int[n];
for (int i = 0; i < n; i++) {
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
int a = x[0] + x[n / 2], b = y[0] + y[n / 2];
for (int i = 0; i < n / 2; i++)
if (x[i] + x[i + n / 2] != a || y[i] + y[i + n / 2] != b)
ok = false;
out.println(ok ? "YES" : "NO");
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
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 |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | /*package whatever //do not write package name here */
import java.util.Scanner;
import java.util.Arrays;
public class code{
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while(t-->0){
int n = s.nextInt();
int[] arr = new int[n];
int count_zero = 0;
int sum = 0;
for(int i = 0;i<n;i++){
arr[i] = s.nextInt();
if(arr[i]==0){
arr[i] = 1;
count_zero +=1;
}
sum+=arr[i];
}
if(sum!=0){
System.out.println(count_zero);
}else{
// find the smallest number and make it non-negative
// Arrays.sort(arr);
System.out.println(1+count_zero);
}
}
}
} | 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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
public class Codeforces {
public static void main(String[] args) {
FastReader fastReader = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int tt = 1;
while(tt-- > 0) {
int n = fastReader.nextInt();
int a[] = fastReader.ria(n);
HashMap<Integer,Long> map = new HashMap<>();
long ans = 0;
for(int i = 0; i < n; i++){
int temp = a[i] - (i+1);
map.put(temp,map.getOrDefault(temp, 0L)+a[i]);
ans = max(ans , map.getOrDefault(temp,0L));
}
out.println(ans);
}
out.close();
}
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
static Random __r = new Random();
// math util
static int minof(int a, int b, int c) {
return min(a, min(b, c));
}
static int minof(int... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return min(x[0], x[1]);
if (x.length == 3)
return min(x[0], min(x[1], x[2]));
int min = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] < min)
min = x[i];
return min;
}
static long minof(long a, long b, long c) {
return min(a, min(b, c));
}
static long minof(long... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return min(x[0], x[1]);
if (x.length == 3)
return min(x[0], min(x[1], x[2]));
long min = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] < min)
min = x[i];
return min;
}
static int maxof(int a, int b, int c) {
return max(a, max(b, c));
}
static int maxof(int... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return max(x[0], x[1]);
if (x.length == 3)
return max(x[0], max(x[1], x[2]));
int max = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] > max)
max = x[i];
return max;
}
static long maxof(long a, long b, long c) {
return max(a, max(b, c));
}
static long maxof(long... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return max(x[0], x[1]);
if (x.length == 3)
return max(x[0], max(x[1], x[2]));
long max = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] > max)
max = x[i];
return max;
}
static int powi(int a, int b) {
if (a == 0)
return 0;
int ans = 1;
while (b > 0) {
if ((b & 1) > 0)
ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static long powl(long a, int b) {
if (a == 0)
return 0;
long ans = 1;
while (b > 0) {
if ((b & 1) > 0)
ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static int fli(double d) {
return (int) d;
}
static int cei(double d) {
return (int) ceil(d);
}
static long fll(double d) {
return (long) d;
}
static long cel(double d) {
return (long) ceil(d);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static int[] exgcd(int a, int b) {
if (b == 0)
return new int[] { 1, 0 };
int[] y = exgcd(b, a % b);
return new int[] { y[1], y[0] - y[1] * (a / b) };
}
static long[] exgcd(long a, long b) {
if (b == 0)
return new long[] { 1, 0 };
long[] y = exgcd(b, a % b);
return new long[] { y[1], y[0] - y[1] * (a / b) };
}
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static long mix(long x) {
x += 0x9e3779b97f4a7c15L;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
return x ^ (x >> 31);
}
public static boolean[] findPrimes(int limit) {
assert limit >= 2;
final boolean[] nonPrimes = new boolean[limit];
nonPrimes[0] = true;
nonPrimes[1] = true;
int sqrt = (int) Math.sqrt(limit);
for (int i = 2; i <= sqrt; i++) {
if (nonPrimes[i])
continue;
for (int j = i; j < limit; j += i) {
if (!nonPrimes[j] && i != j)
nonPrimes[j] = true;
}
}
return nonPrimes;
}
// array util
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] ria(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = Integer.parseInt(next());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] rla(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = Long.parseLong(next());
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| java |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | import java.util.*;
import java.io.*;
public class Codeforces_Nonzero {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
in.nextLine();
for(int i=0; i<t; i++) {
int n = in.nextInt();
in.nextLine();
int[] arr = new int[n];
int sum = 0;
int numZero = 0;
for(int j=0; j<n; j++) {
arr[j] = in.nextInt();
sum+=arr[j];
if(arr[j]==0)
numZero++;
}
in.nextLine();
if(sum!=0 && numZero==0)
System.out.println(0);
else if(numZero>0) {
sum+=numZero;
if(sum!=0)
System.out.println(numZero);
else
System.out.println(numZero+1);
}
else { //sum==0 and numZero==0
System.out.println(1);
}
}
}
}
| java |
1304 | B | B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0
InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string. | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class Main {
static long M = (long) (1e9 + 7);
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 = (int) 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);
}
static boolean isSquare(int n) {
int v = (int) Math.sqrt(n);
return v * v == n;
}
static boolean PowerOfTwo(int n) {
if (n == 0) return false;
return (int) (Math.ceil((Math.log(n) / Math.log(2)))) ==
(int) (Math.floor(((Math.log(n) / Math.log(2)))));
}
static int power(long a, long b) {
long res = 1;
while (b > 0) {
if (b % 2 == 1) {
res = (res * a) % M;
}
a = ((a * a) % M);
b = b / 2;
}
return (int) res;
}
public static boolean isPrime(int n) {
for (int i = 2; i * i <= n; i++)
if (n % i == 0) {
return false;
}
return true;
}
static int pown(long n){
if(n==0)
return 1;
if(n==1)
return 1;
if((n&(~(n-1)))==n)
return 0;
return 1;
}
static long computeXOR(long n) {
// If n is a multiple of 4
if (n % 4 == 0)
return n;
// If n%4 gives remainder 1
if (n % 4 == 1)
return 1;
// If n%4 gives remainder 2
if (n % 4 == 2)
return n + 1;
// If n%4 gives remainder 3
return 0;
}
static long binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
long result = 0;
for (int i = numbers.length - 1; i >= 0; i--)
if (numbers[i] == '1')
result += Math.pow(2, (numbers.length - i - 1));
return result;
}
static String reverseString(String str){
char ch[]=str.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
int n = sc.nextInt();
int m = sc.nextInt();
HashSet<String> set = new HashSet<String>();
String s1="", s2="", pal="";
for(int i=0; i<n; i++){
String s = sc.next();
String rev = reverseString(s);
if(s.equals(rev))//لو الحروف شبه بعضها
pal = s;
else if(set.contains(rev)){
set.remove(rev);
s1 += rev;
s2 = s + s2;
}else{
set.add(s);
}
}
String s = s1 + pal + s2;
System.out.println(s.length() + "\n" + s);
}
} | java |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | import java.util.Scanner;
public class FirstChallenge
{
public static void main(String [ ] args)
{
Scanner in = new Scanner(System.in);
int number = in.nextInt();
for(int t=0;t<number;t++){
int n=in.nextInt();//time to do it 3
int d=in.nextInt();//time it takes to do 4
boolean isPossible=false;
if(n==d){
isPossible=true;
}
for(int i=0;i<=n;i++){
int temp=0;
double value=(double)d/(double)(i+1);
int gone=d/(i+1);
if(value!=gone){
gone++;
}
temp=i+gone;
if(temp<=n){
isPossible=true;
break;
}
}
if(isPossible){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
| 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.util.*;
import java.io.*;
import java.math.*;
public class Main{
public static void main(String[]args){
long s = System.currentTimeMillis();
new Solver().run();
System.err.println(System.currentTimeMillis()-s+"ms");
}
}
class Solver{
final long mod = (long)1e9+7l;
final boolean DEBUG = true, MULTIPLE_TC = true;
final int oo = (int)1e9 + 7;
FastReader sc;
PrintWriter out;
int N, M, K;
int arr[];
void init(){
N = ni();
M = ni();
K = ni();
arr = new int[N + 1];
for(int i = 1; i <= N; i++){
arr[i] = ni();
}
}
void process(int testNumber){
init();
int numberOfPeopleThatCanBeControlled = Math.min(M - 1, K),
numberOfPeopleThatCannotBeControlled = M - numberOfPeopleThatCanBeControlled - 1;
int res = 0;
for(int i = 0; i <= numberOfPeopleThatCanBeControlled; i++){
int bestInThisScenario = oo,
remPeopleThatCanBeControlled = numberOfPeopleThatCanBeControlled - i;
for(int j = 0; j <= numberOfPeopleThatCannotBeControlled; j++){
int remPeopleThatCannotBeControlled = numberOfPeopleThatCannotBeControlled - j;
int eleAtFront = arr[i + j + 1],
eleAtBack = arr[N - (remPeopleThatCanBeControlled + remPeopleThatCannotBeControlled)];
bestInThisScenario = Math.min(bestInThisScenario,
Math.max(eleAtFront, eleAtBack)
);
}
res = Math.max(res, bestInThisScenario);
}
pn(res);
}
void run(){
sc = new FastReader();
out = new PrintWriter(System.out);
int t = MULTIPLE_TC ? ni() : 1;
for(int test = 1; test <= t; test++){
process(test);
}
out.flush();
}
void trace(Object... o){ if(!DEBUG) return; System.err.println(Arrays.deepToString(o)); };
void pn(Object o){ out.println(o); }
void p(Object o){ out.print(o); }
int ni(){ return Integer.parseInt(sc.next()); }
long nl(){ return Long.parseLong(sc.next()); }
double nd(){ return Double.parseDouble(sc.next()); }
String nln(){ return sc.nextLine(); }
long gcd(long a, long b){ return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){ return (b==0)?a:gcd(b,a%b); }
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();
}
String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}
}
}
class pair implements Comparable<pair> {
int first, second;
public pair(int first, int second){
this.first = first;
this.second = second;
}
@Override
public int compareTo(pair ob){
if(this.first != ob.first)
return this.first - ob.first;
return this.second - ob.second;
}
@Override
public String toString(){
return this.first + " " + this.second;
}
static public pair from(int f, int s){
return new pair(f, s);
}
} | 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.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static int mod = (int) (1e9 + 7);
static long get(int idx,int rem,int dis){
if(rem ==0||idx==dis-1) return 1;
long ans=0;
for(int i=0;i<=rem;i++){
ans=( (ans%mod) + (get(idx+1,rem-i,dis)%mod) )%mod;
}
return ans;
}
static void solve() {
int n=i();
int m=i();
long ans=0;
for(int dis=1;dis<=Math.min(2*m,n);dis++){
long f1=ncr(n,dis)%mod;
f1=((f1 %mod )* (get(0,(2*m)-dis,dis)%mod))%mod;
// System.out.println(f1+" "+dis);
ans=((ans%mod) +(f1%mod)) %mod;
}
sb.append(ans+"\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; }
while (test-- > 0) {
solve();
}
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) % 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] = 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> {
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 |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32. | [
"combinatorics",
"math"
] | import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
public class Main
{
static class Pair
{
long a,b;
public Pair(long a,long b)
{
this.a=a;
this.b=b;
}
// @Override
// public int compareTo(Pair p) {
// return Long.compare(l, p.l);
// }
}
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 long[][] enumFIF(int n, long mod) {
long[] f = new long[n + 1];
long[] invf = new long[n + 1];
f[0] = 1;
for (int i = 1; i <= n; i++) {
f[i] = (long) ((long) f[i - 1] * i % mod);
}
long a = f[n];
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
invf[n] = (long) (p < 0 ? p + mod : p);
for (int i = n - 1; i >= 0; i--) {
invf[i] = (long) ((long) invf[i + 1] * (i + 1) % mod);
}
return new long[][] { f, invf };
}
public static void solve(int testNumber, InputReader in, OutputWriter out)
{
//int t = in.ni();
int t=1;
while (t-->0)
{
int n=in.ni();
long m=in.nextLong();
long[] fact=CP.facts(n+2,m);
//long[][] f=enumFIF(n,m);
long ans=0;
for(int i=1;i<=n;++i)
{
long places=(long)((n-i+1)%m*(n-i+1)%m)%m;
long steps=(fact[i]%m*fact[n-i]%m)%m;
long tp=(places%m*steps%m)%m;
ans=(ans+tp%m)%m;
}
out.printLine(ans%m);
}
}
}
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 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 digit(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);
}
static ArrayList<Integer> bitWiseSieve(int n) {
ArrayList<Integer> al = new ArrayList<>();
int prime[] = new int[n / 64 + 1];
for (int i = 3; i * i <= n; i += 2) {
if (ifnotPrime(prime, i) == 0)
for (int j = i * i, k = i << 1;
j < n; j += k)
makeComposite(prime, j);
}
al.add(2);
for (int i = 3; i <= n; i += 2)
if (ifnotPrime(prime, i) == 0)
al.add(i);
return al;
}
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)
{
// Reverse the sub-array
while (left < right)
{
int temp = data.get(left);
data.set(left++,
data.get(right));
data.set(right--, temp);
}
// Return the updated array
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 boolean[] sieve1(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 prime;
}
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 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;
}
// ==================== LIS & LNDS ================================
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 ArrayList<StringBuilder> permutations(StringBuilder s)
{
int n=s.length();
ArrayList<StringBuilder> al=new ArrayList<>();
getpermute(s,al,0,n);
return al;
}
// static String longestPalindrome(String s)
// {
// int st=0,ans=0,len=0;
//
//
// }
static void getpermute(StringBuilder s,ArrayList<StringBuilder> al,int l, int r)
{
if(l==r)
{
al.add(s);
return;
}
for(int i=l+1;i<r;++i)
{
char c=s.charAt(i);
s.setCharAt(i,s.charAt(l));
s.setCharAt(l,c);
getpermute(s,al,l+1,r);
c=s.charAt(i);
s.setCharAt(i,s.charAt(l));
s.setCharAt(l,c);
}
}
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 void reverse_ruffle_sort(int a[]) {
shuffle(a);
Arrays.sort(a);
for (int l = 0, r = a.length - 1; l < r; ++l, --r)
fast_swap(a, l, r);
}
static void ruffle_sort(int a[]) {
shuffle(a);
Arrays.sort(a);
}
static int getMax(int arr[], int n) {
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
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<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 lcm(int... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = lcm(ret, array[i]);
return ret;
}
public static int min(int a, int b) {
return a < b ? a : b;
}
public static int min(int... array) {
int ret = array[0];
for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]);
return ret;
}
public static long min(long a, long b) {
return a < b ? a : b;
}
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 int max(int a, int b) {
return a > b ? a : b;
}
public static int max(int... array) {
int ret = array[0];
for (int i = 1; i < array.length; ++i) ret = max(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(int... array) {
long ret = 0;
for (int i : array) ret += 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);
}
public static int lcs(String s, String t) {
int n = s.length(), m = t.length();
int dp[][] = new int[n + 1][m + 1];
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= m; ++j) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[n][m];
}
}
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 |
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"
] | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
static class Segment {
int start;
int end;
Segment(int start, int end) {
this.start = start;
this.end = end;
}
}
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 1; t <= test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// divide into max subarray-blocks, such that each have same sum.
Map<Long, List<Segment>> segmentsWithParticularSum = new HashMap<>();
// for each possible subarray-sum
for (int end = 0; end < n; end++) {
long blockSum = 0;
for (int start = end; start >= 0; start--) {
blockSum += arr[start];
if (!segmentsWithParticularSum.containsKey(blockSum)) {
segmentsWithParticularSum.put(blockSum, new ArrayList<>());
}
segmentsWithParticularSum.get(blockSum).add(new Segment(start + 1, end + 1));
}
}
List<Segment> bestSegmentsChosen = new ArrayList<>();
int maxTotalBlocks = 0;
for (long blockSum : segmentsWithParticularSum.keySet()) {
// greedily choose the blocks, since blocks are sorted by their right end
List<Segment> blocksTaken = new ArrayList<>();
int lastBlockEnd = -1, totalBlocks = 0;
for (Segment segment : segmentsWithParticularSum.get(blockSum)) {
if (segment.start > lastBlockEnd) { // can take this block
totalBlocks++;
blocksTaken.add(segment);
lastBlockEnd = segment.end;
}
}
if (totalBlocks > maxTotalBlocks) { // maximize the total blocks taking
maxTotalBlocks = totalBlocks;
bestSegmentsChosen = new ArrayList<>(blocksTaken);
}
}
out.println(maxTotalBlocks);
for (Segment segment : bestSegmentsChosen) {
out.println(segment.start + " " + segment.end);
}
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
} | 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; // set for o(1) removal
static HashSet<Integer> leaves;
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 s = graph.get(i).size();
if(s==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==v||w==u){
System.out.println("! "+(w+1));
System.out.flush();
return;
}
delete(u,-1,w);
delete(v,-1,w);
if(graph.get(w).size()<=1) leaves.add(w);
}
int ans = leaves.iterator().next();
System.out.println("! "+(ans+1));
System.out.flush();
}
static int query(int u,int v){
u++;
v++;
System.out.println("? "+u+" "+v);
System.out.flush();
int lca = i()-1;
return lca;
}
static void delete(int u,int p,int lca){
leaves.remove(u);
for(int e : graph.get(u)){
if(e==p) continue;
if(e==lca){
graph.get(lca).remove(u);
}else delete(e,u,lca);
}
graph.get(u).clear();
}
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 |
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.Scanner;
public class Collecting_Coins {
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();
int c = sc.nextInt();
int p = sc.nextInt();
int add = a+b+c+p;
int max = Math.max(a, Math.max(b, c));
int div = add/3;
if(add%3==0 && div>=max) {
System.out.println("YES");
}else {
System.out.println("NO");
}
}
}
} | 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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;
public class MaximumWhiteSubtree {
boolean[] isWhite;
int[] max;
ArrayList<Integer> adj[];
//ArrayList<HashSet<Integer>> containsThem;
public static void main(String[] args) throws IOException {
new MaximumWhiteSubtree().solve();
}
public void solve() throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(f.readLine());
StringTokenizer tokenizer = new StringTokenizer(f.readLine());
this.isWhite = new boolean[n];
for (int i = 0; i < n; i++) {
if (Integer.parseInt(tokenizer.nextToken()) == 1) {
isWhite[i] = true;
}
}
this.adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
this.adj[i] = new ArrayList<>();
//this.containsThem.add(new HashSet<Integer>());
}
for (int i = 0; i < n - 1; i++) {
tokenizer = new StringTokenizer(f.readLine());
int a = Integer.parseInt(tokenizer.nextToken()) - 1;
int b = Integer.parseInt(tokenizer.nextToken()) - 1;
adj[a].add(b);
adj[b].add(a);
}
this.max = new int[n];
dfs(0, -1);
dfs2(0, -1);
PrintWriter out = new PrintWriter(System.out);
out.print(this.max[0]);
for (int i = 1; i < n; i++) {
out.print(" ");
out.print(this.max[i]);
}
out.println();
out.close();
}
private void dfs(int node, int parent) {
if (this.isWhite[node]) {
this.max[node]++;
} else {
this.max[node]--;
}
for (int adjacent : this.adj[node]) {
if (adjacent == parent) {
continue;
}
dfs(adjacent, node);
if (this.max[adjacent] > 0) {
this.max[node] += this.max[adjacent];
// this.containsThem.get(node).add(adjacent);
}
}
}
private void dfs2(int node, int parent) {
for (int adjacent : adj[node]) {
if (adjacent == parent) {
continue;
}
if (this.max[adjacent] > 0) {
this.max[adjacent] = Math.max(this.max[adjacent], this.max[node]);
} else {
this.max[adjacent] = Math.max(this.max[adjacent], this.max[node] + this.max[adjacent]);
}
dfs2(adjacent, node);
}
}
} | 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.*;
import java.nio.file.FileStore;
import java.util.*;
public class zia
{
static void BFS(ArrayList<ArrayList<Integer>> adj,int s, boolean[] visited)
{
Queue<Integer> q=new LinkedList<>();
visited[s] = true;
q.add(s);
while(q.isEmpty()==false)
{
int u = q.poll();
for(int v:adj.get(u)){
if(visited[v]==false){
visited[v]=true;
q.add(v);
}
}
}
}
// static int BFS(ArrayList<ArrayList<Integer>> adj,pair s, boolean[] visited,int ar[],int m)
// {
// Queue<pair> q=new LinkedList<>();
// visited[s.a] = true;
// q.add(s);
// int count=0;
// while(q.isEmpty()==false)
// {
// pair u = q.poll();
// // if(adj.get(u.a).size()==0)
// // count++;
// boolean end=true;
// for(int v:adj.get(u.a)){
// if(visited[v]==false){
// visited[v]=true;
// end=false;
// int cat=ar[v]==0?0:ar[v]+u.b;
// if(cat>m)
// continue;
// q.add(new pair(v, cat));
// // System.out.print("--"+v+" "+cat+"--");
// }
// }
// if(end)
// count++;
// // System.out.println(u.a+" "+adj.get(u.a).size()+" count "+count);
// }
// return count;
// }
static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v)
{
adj.get(u).add(v);
adj.get(v).add(u);
}
static void ruffleSort(long[] a) {
int n=a.length;
Random random = new Random();
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a) {
int n=a.length;
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 Lcm(int a,int b)
{ int max=Math.max(a,b);
for(int i=1;;i++)
{
if((max*i)%a==0&&(max*i)%b==0)
return (max*i);
}
}
static void sieve(int n,boolean prime[])
{
// 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 =i+ p)
prime[i] = false;
}
}
}
// public static String run(int ar[],int n)
// {
// }
public static int upperbound(int s,int e, long ar[],long x)
{
int res=-1;
while(s<=e)
{ int mid=((s-e)/2)+e;
if(ar[mid]>x)
{e=mid-1;res=mid;}
else if(ar[mid]<x)
{s=mid+1;}
else
{e=mid-1;res=mid;
if(mid>0&&ar[mid]==ar[mid-1])
e=mid-1;
else
break;
}
}
return res;
}
public static long lowerbound(int s,int e, long ar[],long x)
{
long res=-1;
while(s<=e)
{ int mid=((s-e)/2)+e;
if(ar[mid]>x)
{e=mid-1;}
else if(ar[mid]<x)
{s=mid+1;res=mid;}
else
{res=mid;
if(mid+1<ar.length&&ar[mid]==ar[mid+1])
s=mid+1;
else
break;}
}
return res;
}
static long modulo=1000000007;
public static long power(long a, long b)
{
if(b==0) return 1;
long temp=power(a,b/2)%modulo;
if((b&1)==0)
return (temp*temp)%modulo;
else
return (((temp*temp)%modulo)*a)%modulo;
}
public static long powerwithoutmod(long a, long b)
{
if(b==0) return 1;
long temp=power(a,b/2);
if((b&1)==0)
return (temp*temp);
else
return ((temp*temp)*a);
}
public static double log2(long a)
{ double d=Math.log(a)/Math.log(2);
return d;
}
public static int log10(long a)
{ double d=Math.log(a)/Math.log(10);
return (int)d;
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public static void tree(int s,int e,int ar[],int c)
{
if(s<=e)
{
int max=s;
for(int i=s;i<=e;i++)
if(ar[i]>ar[max])
max=i;
ar[max]=c++;
tree(s,max-1,ar,c);
tree(max+1,e,ar,c);
}
}
static int resturant=0;
static void DFS(ArrayList<ArrayList<Integer>> al,boolean visited[],int s,int max,int curr,int ar[])
{
visited[s]=true;
if(al.get(s).size()==1&&visited[al.get(s).get(0)]==true)
{resturant++;return;}
// System.out.println(s+" "+curr);
for(int x:al.get(s))
{
if(visited[x]==false)
{
if(ar[x]==0)
DFS(al, visited, x, max, 0, ar);
else if(curr+ar[x]<=max)
DFS(al, visited, x, max, curr+ar[x], ar);
}
}
}
public static void main(String[] args) throws Exception
{
FastIO sc = new FastIO();
//sc.println();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
int test=sc.nextInt();
// // double c=Math.log(10);
// boolean prime[]=new boolean[233334];
// sieve(233334, prime);
// HashMap<Character,Integer> hm=new HashMap<>(9);
// char c='1';
// for(int i=1;i<=9;i++)
// hm.put(c++,i);
while(test-->0)
{
long n=sc.nextLong();
long g=sc.nextLong();
long b=sc.nextLong();
long r=(n+1)/2;
long res=0,x=r/g,gh=0,bh=0;
if(r%g==0)
{
gh=x*g;
if(x>=1)
bh=(x-1)*b;
}
else
{
gh=x*g+(r-x*g);
bh=x*b;
}
res=gh+bh;
if(res<n)
res+=(n-res);
// long gHighWay=(n+1)/2,res=0,x=gHighWay/g;
// if(gHighWay%g==0)
// res=x*g+(x-1)*b;
// else
// res=x*g+x*b+(gHighWay-x*g);
// if(res<n)
// res+=(n-);
sc.println(res);
}
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sc.close();
}
}
class pair implements Comparable<pair>{
int a;
int b;
pair(int a,int b)
{this.a=a;
this.b=b;
}
public int compareTo(pair p)
{
return (this.b-p.b);
}
}
class triplet implements Comparable<triplet>{
int first,second,third;
triplet(int first,int second,int third)
{this.first=first;
this.second=second;
this.third=third;
}
public int compareTo(triplet p)
{ if(this.third-p.third==0)
return this.first-p.first;
else
return -this.third+p.third;
}
}
// class triplet
// {
// int x1,x2,i;
// triplet(int a,int b,int c)
// {x1=a;x2=b;i=c;}
// }
class FastIO extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1<<16];
private int curChar, numChars;
// standard input
public FastIO() { this(System.in,System.out); }
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
public String nextLine() {
int c; do { c = nextByte(); } while (c <= '\n');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n');
return res.toString();
}
public String next() {
int c; do { c = nextByte(); } while (c <= ' ');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');
return res.toString();
}
public int nextInt() {
int c; do { c = nextByte(); } while (c <= ' ');
int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() {
int c; do { c = nextByte(); } while (c <= ' ');
long sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() { return Double.parseDouble(next()); }
} | java |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232. | [
"math",
"strings"
] | import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static int mod = (int) (1e9 + 7);
static void solve() {
int n = i();
int k =i();
String str = s();
int cnt0 = 0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)=='0') cnt0++;
}
int ans = 0;
int obal = 2*cnt0-n;
int cbal = 0;
for(int i =0;i<str.length();i++){
if(obal==0&&cbal==k){
sb.append(-1).append("\n");
return;
}
int num = Math.abs(k-cbal);
int denom = Math.abs(obal);
if((denom!=0)&&(num%denom==0)&&((k-cbal)/(obal)>=0)){
ans++;
}
if(str.charAt(i)=='0') cbal++;
else cbal--;
}
sb.append(ans).append("\n");
}
public static void main(String[] args) {
sb = new StringBuilder();
int test =i();
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 |
1313 | D | D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third. | [
"bitmasks",
"dp",
"implementation"
] | import java.io.*;
import java.util.*;
public class Sol{
static class event implements Comparable<event>{
int type;
int pos;
int id;
int bit;
public event(int type, int pos, int id) {
this.type = type;
this.pos = pos;
this.id = id;
bit = 0;
}
public int compareTo(event e) {
if(e.pos==this.pos) {
return Integer.compare(this.type,e.type);
}else {
return Integer.compare(this.pos, e.pos);
}
}
}
public static int n, m, k;
public static event arr[];
public static int dp[][];
public static int parity[];
public static TreeMap<Integer, Integer> mp = new TreeMap<>();
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
dp = new int[1<<8][2*n];
parity = new int[1<<8];
arr = new event [2*n];
for(int i=0; i<1<<8; ++i) {
Arrays.fill(dp[i], -1);
parity[i] = Integer.bitCount(i)%2;
}
boolean used[] = new boolean[8];
for(int i=0; i<n; ++i) {
int l = sc.nextInt();
int r = sc.nextInt();
arr[2*i] = new event(0, l, i);
arr[2*i+1] = new event(1, r, i);
}
Arrays.sort(arr);
for(int i=0; i<2*n; ++i) {
if(arr[i].type==0) {
while(used[arr[i].bit]) {
arr[i].bit++;
}
used[arr[i].bit]= true;
mp.put(arr[i].id, arr[i].bit);
}else {
arr[i].bit = mp.get(arr[i].id);
used[arr[i].bit] = false;
}
}
out.println(go(0, 0));
out.close();
}
public static int go(int msk, int idx) {
//System.out.println(msk + " " + idx);
if(idx>=2*n) return 0;
if(dp[msk][idx]!=-1) return dp[msk][idx];
int ans = 0;
if(arr[idx].type==1) {
int nxt = idx;
int nxtmsk = msk;
while(nxt<2*n&&arr[nxt].pos==arr[idx].pos) {
nxtmsk&=~(1<<arr[nxt++].bit);
}
int dist = 0;
if(nxt<2*n) {
dist = arr[nxt].pos-arr[idx].pos-1;
}
//System.out.println(dist);
//System.out.println(nxtmsk);
ans = parity[msk] + dist*parity[nxtmsk] + go(nxtmsk, nxt);
}else {
int dist = 0;
if(idx+1<2*n) {
dist = arr[idx+1].pos-arr[idx].pos;
}
ans = parity[msk|(1<<arr[idx].bit)]*dist + go(msk|(1<<arr[idx].bit), idx+1);
ans = Math.max(ans, parity[msk]*dist + go(msk, idx+1));
}
//System.out.println(ans);
return dp[msk][idx] = ans;
}
static class FastIO {
// Is your Fast I/O being bad?
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0;
public FastIO(String fileName) throws IOException {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws IOException {
dis = is;
}
int nextInt() throws IOException {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
long nextLong() throws IOException {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
byte nextByte() throws IOException {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
String next() throws IOException {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
}
} | java |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| [
"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 C_Restoring_Permutation {
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = f.nextInt();
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
int n = f.nextInt();
int arr[] = new int[n];
HashSet<Integer> hs = new HashSet<>();
for(int i = 0; i < n; i++) {
arr[i] = f.nextInt();
hs.add(arr[i]);
}
ArrayList<Point> arrli = new ArrayList<>();
for(int i = 0; i < n; i++) {
int x = -1;
for(int j = arr[i]+1; j <= 2*n; j++) {
if(!hs.contains(j)) {
x = j;
hs.add(x);
break;
}
}
if(arr[i] > x) {
out.println(-1);
return;
}
arrli.add(new Point(arr[i], x));
}
for(int i = 0; i < n; i++) {
out.print(arrli.get(i).i + " " + arrli.get(i).j + " ");
}
out.println();
}
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;
}
}
}
class Point {
int i;
int j;
public Point(int i, int j) {
this.i = i;
this.j = j;
}
}
/**
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 |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
| [
"dp",
"strings"
] | import java.io.*;
import java.util.*;
public class CF1303E extends PrintWriter {
CF1303E() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1303E o = new CF1303E(); o.main(); o.flush();
}
static final int A = 26;
void main() {
int[] ii = new int[A];
int t = sc.nextInt();
while (t-- > 0) {
byte[] ss = sc.next().getBytes();
byte[] tt = sc.next().getBytes();
int n = ss.length;
int m = tt.length;
for (int i = 0; i < n; i++)
ss[i] -= 'a';
for (int i = 0; i < m; i++)
tt[i] -= 'a';
int[][] next = new int[n][A];
Arrays.fill(ii, n);
for (int i = n - 1; i >= 0; i--) {
ii[ss[i]] = i;
for (int a = 0; a < A; a++)
next[i][a] = ii[a];
}
int[][] dp = new int[m + 1][m + 1];
boolean yes = false;
for (int l = 0; l <= m; l++) {
for (int i = 0; i <= l; i++)
for (int j = l; j <= m; j++)
dp[i][j] = n + 1;
dp[0][l] = 0;
for (int i = 0; i <= l; i++)
for (int j = l; j <= m; j++) {
int h = dp[i][j];
if (h >= n)
continue;
if (i < l)
dp[i + 1][j] = Math.min(dp[i + 1][j], next[h][tt[i]] + 1);
if (j < m)
dp[i][j + 1] = Math.min(dp[i][j + 1], next[h][tt[j]] + 1);
}
if (dp[l][m] <= n) {
yes = true;
break;
}
}
println(yes ? "YES" : "NO");
}
}
}
| 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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.HashMap;
public class Hyperset {
public static char[] values = new char[]{'S', 'E', 'T'};
public static void main(String[] args) {
FastReader fr = new FastReader();
int n = fr.nextInt();
int k = fr.nextInt();
HashMap<String, Integer> cards = new HashMap<>();
String[] cardsArray = new String[n];
for (int i = 0; i < n; i++) {
cardsArray[i] = fr.nextLine();
cards.put(cardsArray[i], i);
}
int result = 0;
for (int i = 0; i < n - 2; i++) {
String cardOne = cardsArray[i];
for (int j = i + 1; j < n - 1; j++) {
String cardTwo = cardsArray[j];
String neededCard = calcNeededCard(cardOne, cardTwo);
if (cards.containsKey(neededCard) && cards.get(neededCard) > j) {
result++;
}
}
}
System.out.println(result);
}
public static String calcNeededCard(String c1, String c2) {
StringBuilder sbr = new StringBuilder();
for (int i = 0; i < c1.length(); i++) {
if (c1.charAt(i) == c2.charAt(i)) {
sbr.append(c1.charAt(i));
} else if (c1.charAt(i) == 'S' || c2.charAt(i) == 'S'){
if (c1.charAt(i) == 'E' || c2.charAt(i) == 'E') {
sbr.append('T');
} else {
sbr.append('E');
}
} else {
sbr.append("S");
}
}
return sbr.toString();
}
/** HELPER */
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
int[] nextLineAsIntArray(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = nextInt();
}
return result;
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| java |
1141 | 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.io.*;
import java.util.*;
public class Polycarp_Restores_Permutation {
static FastScanner fs;
static FastWriter fw;
static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null;
private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}};
private static final int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
private static final int iMax = (int) (1e9 + 100), iMin = (int) (-1e9 - 100);
private static final long lMax = (long) (1e18 + 100), lMin = (long) (-1e18 - 100);
private static final int mod1 = (int) (1e9 + 7);
private static final int mod2 = 998244353;
public static void main(String[] args) throws IOException {
fs = new FastScanner();
fw = new FastWriter();
int t = 1;
//t = fs.nextInt();
while (t-- > 0) {
solve();
}
fw.out.close();
}
private static void solve() {
int n = fs.nextInt();
int[] q = readIntArray(n - 1);
int[] ans = new int[n];
ans[1] = 0;
ans[0] = -q[0];
for (int i = 2; i < n; i++) {
ans[i] = ans[i - 1] + q[i - 1];
}
int min = iMax;
for (int i = 0; i < n; i++) min = Math.min(min, ans[i]);
int x = 1 - min;
int[] vis = new int[n + 1];
for (int i = 0; i < n; i++) {
ans[i] = x + ans[i];
if (ans[i] < 1 || ans[i] > n || vis[ans[i]] == 1) {
fw.out.println(-1);
return;
}
vis[ans[i]] = 1;
}
for (int num : ans) fw.out.print(num + " ");
}
private static class UnionFind {
private final int[] parent;
private final int[] rank;
UnionFind(int n) {
parent = new int[n + 5];
rank = new int[n + 5];
for (int i = 0; i <= n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
private int find(int i) {
if (parent[i] == i)
return i;
return parent[i] = find(parent[i]);
}
private void union(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (rank[a] < rank[b]) {
int temp = a;
a = b;
b = temp;
}
parent[b] = a;
if (rank[a] == rank[b])
rank[a]++;
}
}
}
private static class Calc_nCr {
private final long[] fact;
private final long[] invfact;
private final int p;
Calc_nCr(int n, int prime) {
fact = new long[n + 5];
invfact = new long[n + 5];
p = prime;
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (i * fact[i - 1]) % p;
}
invfact[n] = pow_with_mod(fact[n], p - 2, p);
for (int i = n - 1; i >= 0; i--) {
invfact[i] = (invfact[i + 1] * (i + 1)) % p;
}
}
private long nCr(int n, int r) {
if (r > n || n < 0 || r < 0) return 0;
return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;
}
}
private static long gcd(long a, long b) {
return (b == 0 ? a : gcd(b, a % b));
}
private static long lcm(long a, long b) {
return ((a * b) / gcd(a, b));
}
private static long pow(long a, long b) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a);
}
a = (a * a);
b >>= 1;
}
return result;
}
private static long pow_with_mod(long a, long b, int mod) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long ceilDiv(long a, long b) {
return ((a + b - 1) / b);
}
private static long getMin(long... args) {
long min = lMax;
for (long arg : args)
min = Math.min(min, arg);
return min;
}
private static long getMax(long... args) {
long max = lMin;
for (long arg : args)
max = Math.max(max, arg);
return max;
}
private static boolean isPalindrome(String s, int l, int r) {
int i = l, j = r;
while (j - i >= 1) {
if (s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
private static List<Integer> primes(int n) {
boolean[] primeArr = new boolean[n + 5];
Arrays.fill(primeArr, true);
for (int i = 2; (i * i) <= n; i++) {
if (primeArr[i]) {
for (int j = i * i; j <= n; j += i) {
primeArr[j] = false;
}
}
}
List<Integer> primeList = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (primeArr[i])
primeList.add(i);
}
return primeList;
}
private static int noOfSetBits(long x) {
int cnt = 0;
while (x != 0) {
x = x & (x - 1);
cnt++;
}
return cnt;
}
private static int sumOfDigits(long num) {
int cnt = 0;
while (num > 0) {
cnt += (num % 10);
num /= 10;
}
return cnt;
}
private static int noOfDigits(long num) {
int cnt = 0;
while (num > 0) {
cnt++;
num /= 10;
}
return cnt;
}
private static boolean isPerfectSquare(long num) {
long sqrt = (long) Math.sqrt(num);
return ((sqrt * sqrt) == num);
}
private static class Pair<U, V> {
private final U first;
private final V second;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return first.equals(pair.first) && second.equals(pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
private Pair(U ff, V ss) {
this.first = ff;
this.second = ss;
}
}
private static void randomizeIntArr(int[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swapInIntArr(arr, i, j);
}
}
private static void randomizeLongArr(long[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swapInLongArr(arr, i, j);
}
}
private static void swapInIntArr(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
private static void swapInLongArr(long[] arr, int a, int b) {
long temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
private static int[] readIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextInt();
return arr;
}
private static long[] readLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextLong();
return arr;
}
private static List<Integer> readIntList(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(fs.nextInt());
return list;
}
private static List<Long> readLongList(int n) {
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(fs.nextLong());
return list;
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws IOException {
if (checkOnlineJudge)
this.br = new BufferedReader(new FileReader("src/input.txt"));
else
this.br = new BufferedReader(new InputStreamReader(System.in));
this.st = new StringTokenizer("");
}
public String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException err) {
err.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
if (st.hasMoreTokens()) {
return st.nextToken("").trim();
}
try {
return br.readLine().trim();
} catch (IOException err) {
err.printStackTrace();
}
return "";
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
private static class FastWriter {
PrintWriter out;
FastWriter() throws IOException {
if (checkOnlineJudge)
out = new PrintWriter(new FileWriter("src/output.txt"));
else
out = new PrintWriter(System.out);
}
}
}
| java |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all. | [
"dp",
"greedy"
] | // Problem: E. Array Shrinking
// Contest: Codeforces - Educational Codeforces Round 83 (Rated for Div. 2)
// URL: https://codeforces.com/contest/1312/problem/E
// Memory Limit: 256 MB
// Time Limit: 2000 ms
import java.io.*;
import java.util.*;
public class Main {
static IntReader in;
static FastWriter out;
static String INPUT = "";
static final int N = 505, INF = 0x3f3f3f3f;
static int[][] dp = new int[N][N], f = new int[N][N];
static int n;
static void solve() {
n = ni();
for (int i = 1; i <= n; i++) {
dp[i][i] = 1;
f[i][i] = ni();
}
for (int len = 2; len <= n; len++) {
for (int i = 1; i + len - 1 <= n; i++) {
int j = i + len - 1;
dp[i][j] = INF;
for (int k = i; k < j; k++) {
if (dp[i][k] + dp[k + 1][j] < dp[i][j]) {
dp[i][j] = dp[i][k] + dp[k + 1][j];
if (dp[i][k] == 1 && dp[k + 1][j] == 1 && f[i][k] == f[k + 1][j]) {
dp[i][j] = 1;
f[i][j] = f[i][k] + 1;
}
}
}
}
}
out.println(dp[1][n]);
}
public static void main(String[] args) throws Exception {
in = INPUT.isEmpty() ? new IntReader(System.in) : new IntReader(new ByteArrayInputStream(INPUT.getBytes()));
out = new FastWriter(System.out);
solve();
out.flush();
}
public static class IntReader {
private InputStream is;
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
public IntReader(InputStream is) {
this.is = is;
}
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 int ni() {
return (int) nl();
}
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();
}
}
}
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
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;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
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;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map) write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
static int ni() {
return in.ni();
}
static long nl() {
return in.nl();
}
static String ns() {
return in.ns();
}
static double nd() {
return Double.parseDouble(in.ns());
}
}
| java |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | import java.io.*;
import java.util.*;
public class ProblemB {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
StringBuilder sb = new StringBuilder();
int test = in.readInt();
while(test-->0){
int n = in.readInt();
ArrayList<Pair>list = new ArrayList<>();
list.add(new Pair(0,0));
for(int i = 0;i<n;i++){
String line[] = in.readLine().split(" ");
list.add(new Pair(Integer.parseInt(line[0]),Integer.parseInt(line[1])));
}
Comparator<Pair>cmp = new Comparator<Pair>(){
@Override
public int compare(Pair a, Pair b) {
return a.x == b.x? a.y - b.y: a.x - b.x;
}
};
Collections.sort(list,cmp);
StringBuilder res = new StringBuilder();
boolean ok = true;
for(int i=1;i<=n;i++){
//System.out.println(list.get(i).x+" "+list.get(i).y);
if(list.get(i-1).x<=list.get(i).x && list.get(i-1).y<=list.get(i).y){
int x = list.get(i).x - list.get(i-1).x;
int y = list.get(i).y - list.get(i-1).y;
if(x>0)res.append(String.join("", Collections.nCopies(x, "R")));
if(y>0)res.append(String.join("", Collections.nCopies(y, "U")));
}else ok = false;
}
if(ok){
sb.append("YES");
sb.append("\n");
sb.append(res);
}else sb.append("NO");
sb.append("\n");
}
System.out.println(sb);
}
static class Pair{
int x,y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
}
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String read()
{
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int readInt() { return Integer.parseInt(read()); }
public long readLong() { return Long.parseLong(read()); }
public double readDouble(){return Double.parseDouble(read());}
public String readLine() throws IOException{ return br.readLine(); }
}
}
| 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.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.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
Output out = new Output(outputStream);
CWorldOfDarkraftBattleForAzathoth solver = new CWorldOfDarkraftBattleForAzathoth();
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 CWorldOfDarkraftBattleForAzathoth {
private final int iinf = 1_000_000_000;
private final long linf = 4_000_000_000_000_000_000L;
public CWorldOfDarkraftBattleForAzathoth() {
}
public void solve(int kase, InputReader in, Output pw) {
int n = in.nextInt(), m = in.nextInt(), p = in.nextInt(), mn = (int) 1e6;
SegmentTree st = new SegmentTree(mn+1);
int[][] arr = in.nextInt(n, 2);
{
int[][] tmp = in.nextInt(m, 2);
Arrays.sort(tmp, Comparator.comparingInt(o -> -o[0]));
int min = iinf;
st.add(tmp[0][0], mn, -linf);
for(int i = 0; i<m; i++) {
st.add(i==m-1 ? 0 : tmp[i+1][0], tmp[i][0]-1, -(min = Math.min(min, tmp[i][1])));
}
}
Arrays.sort(arr, Comparator.comparingInt(o -> o[0]));
int[][] mon = in.nextInt(p, 3);
Arrays.sort(mon, Comparator.comparingInt(o -> o[0]));
long ans = -linf;
int j = 0;
for(int i = 0; i<n; i++) {
while(j<p&&mon[j][0]<arr[i][0]) {
st.add(mon[j][1], mn, mon[j++][2]);
}
ans = Math.max(ans, st.max(0, mn)-arr[i][1]);
}
pw.println(ans);
}
}
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 println(long l) {
println(String.valueOf(l));
}
public void println(String s) {
sb.append(s);
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 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++];
}
}
static interface InputReader {
int nextInt();
default int[] nextInt(int n) {
int[] ret = new int[n];
for(int i = 0; i<n; i++) {
ret[i] = nextInt();
}
return ret;
}
default int[][] nextInt(int n, int m) {
int[][] ret = new int[n][m];
for(int i = 0; i<n; i++) {
ret[i] = nextInt(m);
}
return ret;
}
}
static class SegmentTree {
public long[] arr;
public long[] sumv;
public long[] minv;
public long[] maxv;
public long[] addv;
public long[] setv;
public long _sum;
public long _min;
public long _max;
public long y1;
public long y2;
public long v;
public int n;
public boolean[] setc;
public boolean add;
public SegmentTree(int n) {
arr = new long[n];
this.n = n;
sumv = new long[n<<2];
minv = new long[n<<2];
maxv = new long[n<<2];
addv = new long[n<<2];
setv = new long[n<<2];
setc = new boolean[n<<2];
build0(1, 0, n-1);
}
public SegmentTree(long[] arr) {
this.arr = arr.clone();
n = arr.length;
sumv = new long[n<<2];
minv = new long[n<<2];
maxv = new long[n<<2];
addv = new long[n<<2];
setv = new long[n<<2];
setc = new boolean[n<<2];
build(1, 0, n-1);
}
private void build0(int o, int l, int r) {
if(l==r) {
setc[o] = true;
}else {
int m = l+r >> 1;
build0(o<<1, l, m);
build0(o<<1|1, m+1, r);
}
}
private void build(int o, int l, int r) {
if(l==r) {
setc[o] = true;
setv[o] = minv[o] = maxv[o] = sumv[o] = arr[l];
}else {
int lc = o<<1, rc = o<<1|1;
int m = l+r >> 1;
build(lc, l, m);
build(rc, m+1, r);
sumv[o] = sumv[lc]+sumv[rc];
minv[o] = Math.min(minv[lc], minv[rc]);
maxv[o] = Math.max(maxv[lc], maxv[rc]);
}
}
public void query(int o, int l, int r, long add) {
if(setc[o]) {
long v = setv[o]+add+addv[o];
_sum += v*(Math.min(r, y2)-Math.max(l, y1)+1);
_min = Math.min(_min, v);
_max = Math.max(_max, v);
}else if(y1<=l&&y2>=r) {
_sum += sumv[o]+add*(r-l+1);
_min = Math.min(_min, minv[o]+add);
_max = Math.max(_max, maxv[o]+add);
}else {
int m = (l+r) >> 1;
if(y1<=m) {
query(o<<1, l, m, add+addv[o]);
}
if(y2>m) {
query(o<<1|1, m+1, r, add+addv[o]);
}
}
}
public void update(int o, int l, int r) {
int lc = o<<1, rc = o<<1|1;
if(y1<=l&&y2>=r) {
if(add) {
addv[o] += v;
}else {
setv[o] = v;
setc[o] = true;
addv[o] = 0;
}
}else {
pushdown(o);
int m = (l+r) >> 1;
if(y1<=m) {
update(lc, l, m);
}else {
maintain(lc, l, m);
}
if(y2>m) {
update(rc, m+1, r);
}else {
maintain(rc, m+1, r);
}
}
maintain(o, l, r);
}
private void maintain(int o, int l, int r) {
int lc = o<<1, rc = o<<1|1;
if(r>l) {
sumv[o] = sumv[lc]+sumv[rc];
minv[o] = Math.min(minv[lc], minv[rc]);
maxv[o] = Math.max(maxv[lc], maxv[rc]);
}
if(setc[o]) {
minv[o] = maxv[o] = setv[o];
sumv[o] = setv[o]*(r-l+1);
}
if(addv[o]!=0) {
minv[o] += addv[o];
maxv[o] += addv[o];
sumv[o] += addv[o]*(r-l+1);
}
}
private void pushdown(int o) {
int lc = o<<1, rc = o<<1|1;
if(setc[o]) {
setv[lc] = setv[rc] = setv[o];
addv[lc] = addv[rc] = 0;
setc[o] = false;
setc[lc] = setc[rc] = true;
}
if(addv[o]!=0) {
addv[lc] += addv[o];
addv[rc] += addv[o];
addv[o] = 0;
}
}
public void add(int l, int r, long v) {
y1 = l;
y2 = r;
this.v = v;
add = true;
update(1, 0, n-1);
}
public void query(int l, int r) {
y1 = l;
y2 = r;
_sum = 0;
_max = Long.MIN_VALUE;
_min = Long.MAX_VALUE;
query(1, 0, n-1, 0);
}
public long max(int l, int r) {
query(l, r);
return _max;
}
}
}
| java |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — 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≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | import java.util.*;
public class ArraySharpening {
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 arr[]=new int[n];
for(int i=0;i<n;i++) {
arr[i]=sc.nextInt();
}
int pos=0;
for(int i=0;i<n;i++) {
if(arr[i]<i) {
break;
}
pos=i;
}
int k=0;
for(int i=n-1;i>=pos;i--) {
if(arr[i]<n-1-i) {
System.out.println("No");
continue outer;
}
k++;
}
System.out.println("Yes");
}
}
}
| java |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
import java.io.*;
public class Main {
// Graph
// prefix sums
//inputs
public static void main(String args[])throws Exception{
Input sc=new Input();
precalculates p=new precalculates();
StringBuilder sb=new StringBuilder();
int t=sc.readInt();
for(int f=0;f<t;f++){
int d[]=sc.readArray();
int a,b,c;
a=d[0];b=d[1];c=d[2];
int ans=Integer.MAX_VALUE;
for(int i=1;i<=2*a;i++){
for(int j=i;j<=2*b;j+=i){
if(j%i==0){
int temp=ans;
ans=Math.min(ans,Math.abs(a-i)+Math.abs(b-j)+Math.abs(c-j));
if(ans<temp){
d[0]=i;
d[1]=j;
d[2]=j;
}
temp=ans;
if(c-c%j>0) {// same -
ans = Math.min(ans, Math.abs(a - i) + Math.abs(b - j) + Math.abs(c % j));//-
if(ans<temp){
d[0]=i;
d[1]=j;
d[2]=c-c%j;
}
temp=ans;
}
if(c%j==0) {
if(c-j>0) {
ans = Math.min(ans, Math.abs(a - i) + Math.abs(b - j) + Math.abs((j)));
if (ans < temp) {
d[0] = i;
d[1] = j;
d[2] = c - (j);
}
temp = ans;
}
ans=Math.min(ans,Math.abs(a-i)+Math.abs(b-j)+Math.abs(j));
if(ans<temp){
d[0]=i;
d[1]=j;
d[2]=c+j;
}
temp=ans;
}
if(c+(j-c%j)>0) {
ans = Math.min(ans, Math.abs(a - i) + Math.abs(b - j) + Math.abs((j-c%j)));//-
if(ans<temp){
d[0]=i;
d[1]=j;
d[2]=c+(j-c%j);
}
temp=ans;
}
}
}
}
sb.append(ans+"\n");
sb.append(d[0]+" "+d[1]+" "+d[2]+"\n");
}
System.out.print(sb);
}
}
class Input{
BufferedReader br;
StringTokenizer st;
Input(){
br=new BufferedReader(new InputStreamReader(System.in));
st=new StringTokenizer("");
}
public int[] readArray() throws Exception{
st=new StringTokenizer(br.readLine());
int a[]=new int[st.countTokens()];
for(int i=0;i<a.length;i++){
a[i]=Integer.parseInt(st.nextToken());
}
return a;
}
public long[] readArrayLong() throws Exception{
st=new StringTokenizer(br.readLine());
long a[]=new long[st.countTokens()];
for(int i=0;i<a.length;i++){
a[i]=Long.parseLong(st.nextToken());
}
return a;
}
public int readInt() throws Exception{
st=new StringTokenizer(br.readLine());
return Integer.parseInt(st.nextToken());
}
public long readLong() throws Exception{
st=new StringTokenizer(br.readLine());
return Long.parseLong(st.nextToken());
}
public String readString() throws Exception{
return br.readLine();
}
public int[][] read2dArray(int n,int m)throws Exception{
int a[][]=new int[n][m];
for(int i=0;i<n;i++){
st=new StringTokenizer(br.readLine());
for(int j=0;j<m;j++){
a[i][j]=Integer.parseInt(st.nextToken());
}
}
return a;
}
}
class precalculates{
public long gcd(long p, long q) {
if (q == 0) return p;
else return gcd(q, p % q);
}
public int[] prefixSumOneDimentional(int a[]){
int n=a.length;
int dp[]=new int[n];
for(int i=0;i<n;i++){
if(i==0)
dp[i]=a[i];
else
dp[i]=dp[i-1]+a[i];
}
return dp;
}
public int[] postSumOneDimentional(int a[]) {
int n = a.length;
int dp[] = new int[n];
for (int i = n - 1; i >= 0; i--) {
if (i == n - 1)
dp[i] = a[i];
else
dp[i] = dp[i + 1] + a[i];
}
return dp;
}
public int[][] prefixSum2d(int a[][]){
int n=a.length;int m=a[0].length;
int dp[][]=new int[n+1][m+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
dp[i][j]=a[i-1][j-1]+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1];
}
}
return dp;
}
public long pow(long a,long b){
long mod=1000000007;
long ans=1;
if(b<=0)
return 1;
if(b%2==0){
ans=pow(a,b/2)%mod;
return ((ans%mod)*(ans%mod))%mod;
}else{
ans=pow(a,b-1)%mod;
return ((a%mod)*(ans%mod))%mod;
}
}
}
class GraphInteger{
HashMap<Integer,vertex> vtces;
class vertex{
HashMap<Integer,Integer> children;
public vertex(){
children=new HashMap<>();
}
}
public GraphInteger(){
vtces=new HashMap<>();
}
public void addVertex(int a){
vtces.put(a,new vertex());
}
public void addEdge(int a,int b,int cost){
if(!vtces.containsKey(a)){
vtces.put(a,new vertex());
}
if(!vtces.containsKey(b)){
vtces.put(b,new vertex());
}
vtces.get(a).children.put(b,cost);
// vtces.get(b).children.put(a,cost);
}
public boolean isCyclicDirected(){
boolean isdone[]=new boolean[vtces.size()+1];
boolean check[]=new boolean[vtces.size()+1];
for(int i=1;i<=vtces.size();i++) {
if (!isdone[i] && isCyclicDirected(i,isdone, check)) {
return true;
}
}
return false;
}
private boolean isCyclicDirected(int i,boolean isdone[],boolean check[]){
if(check[i])
return true;
if(isdone[i])
return false;
check[i]=true;
isdone[i]=true;
Set<Integer> set=vtces.get(i).children.keySet();
for(Integer ii:set){
if(isCyclicDirected(ii,isdone,check))
return true;
}
check[i]=false;
return false;
}
}
class union_find {
int n;
int[] sz;
int[] par;
union_find(int nval) {
n = nval;
sz = new int[n + 1];
par = new int[n + 1];
for (int i = 0; i <= n; i++) {
par[i] = i;
sz[i] = 1;
}
}
int root(int x) {
if (par[x] == x)
return x;
return par[x] = root(par[x]);
}
boolean find(int a, int b) {
return root(a) == root(b);
}
int union(int a, int b) {
int ra = root(a);
int rb = root(b);
if (ra == rb)
return 0;
if(a==b)
return 0;
if (sz[a] > sz[b]) {
int temp = ra;
ra = rb;
rb = temp;
}
par[ra] = rb;
sz[rb] += sz[ra];
return 1;
}
}
| 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 Codeforces{
static long mod = 1000000007L;
// map.put(a[i],map.getOrDefault(a[i],0)+1);
// map.putIfAbsent;
static MyScanner sc = new MyScanner();
//<----------------------------------------------WRITE HERE------------------------------------------->
static void solve(){
long n = sc.nextLong();
long a = 1;
long b = n;
for(long i=2;i*i<=n;i++) {
if(n%i == 0 && i != n/i) {
if(gcd(i,n/i) == 1) {
a = i;
b = n/i;
}
}
}
out.print(a+" "+b);
}
private static void sieve(boolean[] a, int n) {
a[1] = true;
for(int i=2;i*i<=n;i++) {
if(!a[i]) {
for(int j=i*i;j<=n;j+=i)
a[j] = true;
}
}
}
static boolean isPrime(long n) {
for(int i=2;i*i<=n;i++) {
if(n%i == 0) {
return false;
}
}
return true;
}
static long modInv(long x,long mod) {
return expo(x,mod-2,mod)%mod;
}
static long expo(long x,long k,long mod) {
long res = 1;
while(k>0) {
if(k%2 != 0) {
res = (res*x)%mod;
k--;
}
x = (x*x)%mod;
k /= 2;
}
return res%mod;
}
//<----------------------------------------------WRITE HERE------------------------------------------->
static void swap(int[] a,int i,int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void priArr(int[] a) {
for(int i=0;i<a.length;i++) {
out.print(a[i] + " ");
}
out.println();
}
static long gcd(long a,long b){
if(b==0) return a;
return gcd(b,a%b);
}
static class Pair implements Comparable<Pair>{
Integer val;
Integer ind;
Pair(int v,int f){
val = v;
ind = f;
}
public int compareTo(Pair p){
int s1 = this.ind-this.val;
int s2 = p.ind-p.val;
if(s1 != s2) return s1-s2;
return this.val - p.val;
}
}
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
// int t = sc.nextInt();
int t= 1;
while(t-- >0){
solve();
}
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int[] readIntArray(int n){
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = Integer.parseInt(next());
}
return arr;
}
int[] reverse(int arr[]){
int n= arr.length;
int i = 0;
int j = n-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;i++;
}
return arr;
}
long[] readLongArray(int n){
long arr[] = new long[n];
for(int i = 0;i<n;i++){
arr[i] = Long.parseLong(next());
}
return arr;
}
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;
}
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
} | 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 CF_13A {
static int a,sum;
public static int gcd(int x, int y)
{
int max = 0;
int r = 0;
if (x == y)
{
return x;
}
if (x < y)
{
x = r;
x = y;
y = r;
}
while (true)
{
max = x%y;
x = y;
y = max;
if (max == 0)
{
return x;
}
}
}
public static void add(int x, int y)
{
while (x>0)
{
sum += x%y;
x = x/y;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
sum = 0;
for (int i = 2; i<a; i++)
{
add(a,i);
}
int g = gcd(sum,(a-2));
System.out.print((sum/g)+"/"+((a-2)/g));
}
} | java |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| [
"greedy"
] | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Scanner sc=new Scanner(System.in);
// String testcases[]=br.readLine().split(" ");
// int t=Integer.parseInt(testcases[0]);
PrintWriter pw=new PrintWriter(System.out);
int t=sc.nextInt();
for(int i=0;i<t;i++)
{
int n=sc.nextInt();
int a[]=new int[n];
for(int j=0;j<n;j++)
a[j]=sc.nextInt();
int b[]=new int[2*n];
int taken[]=new int[2*n];
Arrays.fill(taken,0);
int f=0;
inner :
for(int j=0;j<n;j++)
{
if(a[j]>2*n||taken[a[j]-1]==1)
{
f=1;
break inner;
}
else
taken[a[j]-1]=1;
}
if(f==1)
{
pw.write("-1\n");
continue;
}
int index=0;
outer :
for(int j=0;j<n;j++)
{
b[index++]=a[j];
int found=0;
inner :
for(int k=a[j];k<2*n;k++)
{
if(taken[k]==0)
{
found=1;
taken[k]=1;
b[index++]=k+1;
break inner;
}
}
if(found==0)
{
f=1;
break outer;
}
}
if(f==1)
{
pw.write("-1\n");
continue;
}
for(int j=0;j<2*n;j++)
pw.write(b[j]+" ");
pw.write("\n");
}
pw.flush();
pw.close();
}
// static int[][] getBitMap(int[] a)
// {
// int n=a.length;
// int[][] bit_map=new int[n][32];
// for(int j=0;j<n;j++)
// Arrays.fill(bit_map[j],0);
// for(int j=0;j<n;j++)
// {
// int counter=0;
// while(a[j]!=0)
// {
// bit_map[j][counter]=a[j]%2;
// a[j]/=2;
// counter++;
// }
// }
// return bit_map;
// }
// static ArrayList<Integer> sieveOfEratosthenes(int n)
// {
// boolean prime[]=new boolean[n+1];
// for(int j=0;j<=n;j++)
// prime[j]=true;
// for(long p=2;p*p<=n;p++)
// {
// if(prime[(int)p]==true)
// {
// for(long j=p*p;j<=n;j+=p)
// prime[(int)j]=false;
// }
// }
// ArrayList<Integer> al=new ArrayList<>();
// for(int j=2;j<=n;j++)
// {
// if(prime[j]==true)
// al.add(j);
// }
// return al;
// }
// static boolean sortedIncreasing(long[] a)
// {
// int f=0;
// for(int j=1;j<a.length;j++)
// {
// if(a[j]<a[j-1])
// f=1;
// }
// return f==0?true:false;
// }
// static boolean sortedDecreasing(long[] a)
// {
// int f=0;
// for(int j=1;j<a.length;j++)
// {
// if(a[j]>a[j-1])
// f=1;
// }
// return f==0?true:false;
// }
// static ArrayList<Long> getFactors(long n)
// {
// ArrayList<Long> al=new ArrayList<>();
// for(long i=1;i<=Math.sqrt(n);i++)
// {
// if(n%i==0)
// {
// al.add(i);
// if(n/i!=i)
// al.add(n/i);
// }
// }
// return al;
// }
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
// static int gcd(int a, int b)
// {
// return b==0?a:gcd(b,a%b);
// }
// static int lcm(int a, int b)
// {
// return ((a/gcd(a,b))*b);
// }
// static boolean checkCoprime(int a, int b)
// {
// if(a==1||b==1)
// return true;
// if (gcd(a,b)==1)
// return true;
// else
// return false;
// }
// static boolean checkSquare(long n)
// {
// if (Math.ceil((double)Math.sqrt(n)) ==
// Math.floor((double)Math.sqrt(n)))
// return true;
// else
// return false;
// }
// static long floorSqrt(long x)
// {
// if (x == 0 || x == 1)
// return x;
// long start = 1, end = x / 2, ans = 0;
// while (start <= end) {
// long mid = (start + end) / 2;
// if (mid * mid == x)
// return (int)mid;
// if (mid * mid < x) {
// start = mid + 1;
// ans = mid;
// }
// else
// end = mid - 1;
// }
// return (long)ans;
// }
}
// class Pair
// {
// int h=0;
// int p=0;
// Pair(int x, int y)
// {
// h=x;
// p=y;
// }
// }
// class NewComparator implements Comparator<Pair>
// {
// public int compare(Pair p1, Pair p2)
// {
// if (p1.p < p2.p)
// return 1;
// else if (p1.p > p2.p)
// return -1;
// return 0;
// }
// }
| 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.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);
BSkyscrapersEasyVersion solver = new BSkyscrapersEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class BSkyscrapersEasyVersion {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] arr = in.nextIntArray(n);
int[] ans = new int[n];
long val = 0;
for (int id = 0; id < n; id++) {
long s = 0;
int[] temp = arr.clone();
for (int i = id + 1; i < n; i++) {
temp[i] = Math.min(temp[i], temp[i - 1]);
}
for (int i = id - 1; i >= 0; i--) {
temp[i] = Math.min(temp[i], temp[i + 1]);
}
for (int a : temp) s += a;
if (s > val) {
val = s;
ans = temp.clone();
}
}
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 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();
}
}
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 |
1141 | G | G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1 | [
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.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);
GPrivatizationOfRoadsInTreeland solver = new GPrivatizationOfRoadsInTreeland();
solver.solve(1, in, out);
out.close();
}
static class GPrivatizationOfRoadsInTreeland {
int N = 200010;
int M = N * 2;
int[] h = new int[N];
int[] e = new int[M];
int[] ne = new int[M];
int idx;
int n;
int k;
int[] deg;
int res;
int[] ans = new int[N];
public void solve(int testNumber, InputReader in, OutputWriter out) {
Arrays.fill(h, -1);
idx = 0;
n = in.nextInt();
k = in.nextInt();
deg = new int[n];
for (int i = 0; i < n - 1; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
add(a, b);
add(b, a);
deg[a]++;
deg[b]++;
}
Arrays.sort(deg);
res = deg[n - k - 1];
out.println(res);
dfs(0, 0, 0);
for (int i = 0; i < n - 1; i++) {
out.print(ans[i] + 1, "");
}
}
private void dfs(int u, int p, int c) {
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (j == p) {
continue;
}
c++;
ans[i / 2] = c % res;
dfs(j, u, c);
}
}
void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
| java |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] | import java.io.*;
import java.util.*;
public class Practice
{
// static final long mod=7420738134811L;
static int mod=998244353;//1000000007;
static int size=(int)2e5+1;
static FastReader sc=new FastReader(System.in);
// static Reader sc=new Reader();
// static Scanner sc=new Scanner(System.in);
static PrintWriter out=new PrintWriter(System.out);
static long[] factorialNumInverse;
static long[] naturalNumInverse;
static int[] sp;
static long[] fact;
static ArrayList<Integer> pr;
public static void main(String[] args) throws IOException, CloneNotSupportedException
{
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream("output.txt"));
factorial(mod);
InverseofNumber(mod);
InverseofFactorial(mod);
// make_seive();
int t=1;
// t=sc.nextInt();
for(int i=1;i<=t;i++)
solve(i);
out.close();
out.flush();
// System.out.flush();
// System.exit(0);
}
static void solve(int CASENO) throws IOException, CloneNotSupportedException
{
int n=sc.nextInt(),m=sc.nextInt();
long ans=((Binomial(m, n-1)*(n-2))%mod*((power(2,n-3))%mod))%mod;
out.println(ans);
}
static class Pair implements Cloneable, Comparable<Pair>
{
int x,y;
Pair(int a,int b)
{
this.x=a;
this.y=b;
}
@Override
public boolean equals(Object obj)
{
if(obj instanceof Pair)
{
Pair p=(Pair)obj;
return p.x==this.x && p.y==this.y;
}
return false;
}
@Override
public int hashCode()
{
return (int)Math.abs(x)+500*Math.abs(y);
}
@Override
public String toString()
{
return "("+x+" "+y+")";
}
@Override
protected Pair clone() throws CloneNotSupportedException {
return new Pair(this.x,this.y);
}
@Override
public int compareTo(Pair a)
{
long t=(this.x-a.x);
if(t!=0)
return t>0?1:-1;
else
return (int)(this.y-a.y);
}
public void swap()
{
this.y=this.y+this.x;
this.x=this.y-this.x;
this.y=this.y-this.x;
}
}
static class Tuple implements Cloneable, Comparable<Tuple>
{
int x,y,z;
Tuple(int a,int b,int c)
{
this.x=a;
this.y=b;
this.z=c;
}
public boolean equals(Object obj)
{
if(obj instanceof Tuple)
{
Tuple p=(Tuple)obj;
return p.x==this.x && p.y==this.y && p.z==this.z;
}
return false;
}
@Override
public int hashCode()
{
return (this.x+501*this.y);
}
@Override
public String toString()
{
return "("+x+","+y+" "+z+")";
}
@Override
protected Tuple clone() throws CloneNotSupportedException {
return new Tuple(this.x,this.y,this.z);
}
@Override
public int compareTo(Tuple a)
{
int x=this.y-a.y;
if(x!=0)
return x;
int X= this.x-a.x;
return X;
}
}
static void arraySort(int arr[])
{
ArrayList<Integer> a=new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
a.add(arr[i]);
}
Collections.sort(a);
// Collections.sort(a,Comparator.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i]=a.get(i);
}
}
static void arraySort(long arr[])
{
ArrayList<Long> a=new ArrayList<Long>();
for (int i = 0; i < arr.length; i++) {
a.add(arr[i]);
}
Collections.sort(a);
for (int i = 0; i < arr.length; i++) {
arr[i]=a.get(i);
}
}
static HashMap<Integer,Integer> primeFactors(int n)
{
int c=0;
HashMap<Integer,Integer> ans=new HashMap<Integer, Integer>();
while((n&1)==0)
{
ans.put(2,ans.getOrDefault(2, 0)+1);
n=n>>1;
c++;
}
for(int i=3;i*i<=n;i+=2)
{
while(n%i==0)
{
ans.put(i,ans.getOrDefault(i, 0)+1);
n=n/i;
c++;
}
}
if(n!=1)
{
ans.put(n,ans.getOrDefault(n, 0)+1);
c++;
}
// return c;
return ans;
}
static ArrayList<Integer> findAllFactors(int n)
{
ArrayList<Integer> ans=new ArrayList<Integer>();
for(int i=1;i*i<=n;i++)
{
ans.add(i);
if(n!=i*i)
ans.add(n/i);
}
return ans;
}
static class sparseTable{
int n;
int[][]dp;
int log2[];
int P;
void buildTable(int[] arr)
{
n=arr.length;
P=(int)Math.floor(Math.log(n)/Math.log(2));
log2=new int[n+1];
log2[0]=log2[1]=0;
for(int i=2;i<=n;i++)
log2[i]=log2[i/2]+1;
dp=new int[P+1][n];
for(int i=0;i<n;i++)
dp[0][i]=arr[i];
for(int p=1;p<=P;p++)
{
for(int i=0;i+(1<<p)<=n;i++)
{
int left=dp[p-1][i];
int right=dp[p-1][i+(1<<(p-1))];
dp[p][i]=gcd(left, right);
}
}
}
int query(int l,int r)
{
int len=r-l+1;
int p=(int)Math.floor(log2[len]);
int left=dp[p][l];
int right=dp[p][r-(1<<p)+1];
return gcd(left,right);
}
}
static void make_seive()
{
sp=new int[size];
pr=new ArrayList<Integer>();
for (int i=2; i<size; ++i) {
if (sp[i] == 0) {
sp[i] = i;
pr.add(i);
}
for (int j=0; j<(int)pr.size() && pr.get(j)<=sp[i] && i*pr.get(j)<size; ++j)
sp[i * pr.get(j)] = pr.get(j);
}
}
public static void InverseofNumber(int p)
{
naturalNumInverse=new long[size];
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i < size; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
public static void InverseofFactorial(int p)
{
factorialNumInverse=new long[size];
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// pre-compute inverse of natural numbers
for(int i = 2; i < size; i++)
factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p;
}
// Function to calculate factorial of 1 to 200001
public static void factorial(int p)
{
fact=new long[size];
fact[0] = 1;
for(int i = 1; i < size; i++)
fact[i] = (fact[i - 1] * (long)i) % p;
}
// Function to return nCr % p in O(1) time
public static long Binomial(int N, int R)
{
if(R<0)
return 1;
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) % mod * factorialNumInverse[N - R]) % mod;
return ans;
}
static int findXOR(int x) //from 0 to x
{
if(x<0)
return 0;
if(x%4==0)
return x;
if(x%4==1)
return 1;
if(x%4==2)
return x+1;
return 0;
}
static boolean isPrime(long x)
{
if(x==1)
return false;
if(x<=3)
return true;
if(x%2==0 || x%3==0)
return false;
for(int i=5;i<=Math.sqrt(x);i+=2)
if(x%i==0)
return false;
return true;
}
static long gcd(long a,long b)
{
return (b==0)?a:gcd(b,a%b);
}
static int gcd(int a,int b)
{
return (b==0)?a:gcd(b,a%b);
}
static class Node
{
int vertex,ind;
ArrayList<Node> adj;
Node(int ver)
{
vertex=ver;
ind=0;
adj=new ArrayList<Node>();
}
@Override
public String toString()
{
return vertex+" ";
}
}
static class Edge
{
Node to;
int cost;
Edge(Node t,int c)
{
this.to=t;
this.cost=c;
}
@Override
public String toString() {
return "("+to.vertex+","+cost+") ";
}
}
static long power(long x, long y)
{
if(x<=0)
return 1;
long res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res%mod;
}
static long binomialCoeff(long n, long k)
{
if(n<k)
return 0;
long res = 1;
// Since C(n, k) = C(n, n-k)
if (k > n - k)
k = n - k;
// Calculate value of
// [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
for (long i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static class FastReader
{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is)
{
in = is;
}
int scan() throws IOException
{
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException
{
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException
{
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException
{
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
public void printarray(int arr[])
{
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
public void printarray(int arr[])
{
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
}
| 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 |
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"
] | /***** ---> :) Vijender Srivastava (: <--- *****/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static FastReader sc =new FastReader();
static PrintWriter out=new PrintWriter(System.out);
static long mod=(long)998244353;
static StringBuilder sb = new StringBuilder();
/* start */
public static void main(String [] args)
{
int testcases = 1;
testcases = i();
// calc();
while(testcases-->0)
{
solve();
}
out.flush();
out.close();
}
static void solve()
{
long n = l(),m = l();
// if(m==0)
// {
// pl(0);
// return ;
// }
long ans = n*(n+1)/2;
long space = m+1,zero = n-m;
long val = zero/space,rem = zero%space;
ans-=(((val+1)*(val+2)/2)*rem);
ans-=((val*(val+1)/2)*(space-rem));
pl(ans);
}
/* end */
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;
}
}
// print code start
static void p(Object o)
{
out.print(o);
}
static void pl(Object o)
{
out.println(o);
}
static void pl()
{
out.println("");
}
// print code end //
static int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static char[] inputC()
{
String s = sc.nextLine();
return s.toCharArray();
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static long[] putL(long a[]) {
long A[]=new long[a.length];
for(int i=0;i<a.length;i++) {
A[i]=a[i];
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int min(int a,int b) {
return Math.min(a, b);
}
static int min(int a,int b,int c) {
return Math.min(a, Math.min(b, c));
}
static int min(int a,int b,int c,int d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static int max(int a,int b) {
return Math.max(a, b);
}
static int max(int a,int b,int c) {
return Math.max(a, Math.max(b, c));
}
static int max(int a,int b,int c,int d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long min(long a,long b) {
return Math.min(a, b);
}
static long min(long a,long b,long c) {
return Math.min(a, Math.min(b, c));
}
static long min(long a,long b,long c,long d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static long max(long a,long b) {
return Math.max(a, b);
}
static long max(long a,long b,long c) {
return Math.max(a, Math.max(b, c));
}
static long max(long a,long b,long c,long d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static long mod(long x) {
return ((x%mod + mod)%mod);
}
static long sum_mod(long x,long y)
{
return mod(mod(x)+mod(y));
}
public static long ncr_mod(long n,long r){
long top=fac_mod(n);
long bottom=mul_mod(fac_mod(r),fac_mod(n-r));
long ans=mul_mod(top,power_mod(bottom,mod-2));
return ans;
}
public static long power_mod(long a,long b){
if(b==0)return 1;
if(b==1)return a;
long res=1;
while(b>0){
if((b&1)==1) res=mul_mod(res,a);
a=mul_mod(a,a);
b/=2;
}
return res;
}
public static long fac_mod(long n){
if(n==0)return 1;
return mul_mod(fac_mod(n-1),n);
}
static long mul_mod(long x,long y)
{
return mod(mod(x)*mod(y));
}
static long power(long x, long y)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) ;
y = y >> 1;
x = (x * x);
}
return res;
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static long[] sort(long a[]) {
ArrayList<Long> arr = new ArrayList<>();
for(long i : a) {
arr.add(i);
}
Collections.sort(arr);
for(int i = 0; i < arr.size(); i++) {
a[i] = arr.get(i);
}
return a;
}
static int[] sort(int a[])
{
ArrayList<Integer> arr = new ArrayList<>();
for(Integer i : a) {
arr.add(i);
}
Collections.sort(arr);
for(int i = 0; i < arr.size(); i++) {
a[i] = arr.get(i);
}
return a;
}
static int[] sortInd(int a[])
{
int n = a.length;
int ii[] = new int[n];
for(int i=0;i<n;i++)ii[i] = i;
ii = Arrays.stream(ii).boxed().sorted((i,j)->a[i]-a[j]).mapToInt($->$).toArray();
return ii;
}
//pair class
private static class Pair implements Comparable<Pair> {
long first, second;
public Pair(long f, long s) {
first = f;
second = s;
}
@Override
public int compareTo(Pair p) {
if (first < p.first)
return 1;
else if (first > p.first)
return -1;
else {
if (second > p.second)
return 1;
else if (second < p.second)
return -1;
else
return 0;
}
}
}
// segment t start
static long seg[] ;
static void build(long a[], int v, int tl, int tr) {
if (tl == tr) {
seg[v] = a[tl];
} else {
int tm = (tl + tr) / 2;
build(a, v*2, tl, tm);
build(a, v*2+1, tm+1, tr);
seg[v] = Math.min(seg[v*2] , seg[v*2+1]);
}
}
static long query(int v, int tl, int tr, int l, int r) {
if (l > r || tr < tl)
return Integer.MAX_VALUE;
if (l == tl && r == tr) {
return seg[v];
}
int tm = (tl + tr) / 2;
return (query(v*2, tl, tm, l, min(r, tm))+ query(v*2+1, tm+1, tr, max(l, tm+1), r));
}
static void update(int v, int tl, int tr, int pos, long new_val) {
if (tl == tr) {
seg[v] = new_val;
} else {
int tm = (tl + tr) / 2;
if (pos <= tm)
update(v*2, tl, tm, pos, new_val);
else
update(v*2+1, tm+1, tr, pos, new_val);
seg[v] = Math.min(seg[v*2] , seg[v*2+1]);
}
}
// segment t end //
}
| 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.*;
public class ProblemA {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
int n = in.readInt();
int a[] = new int[n];
for(int i = 0;i<n;i++)a[i] = in.readInt();
ArrayList<Pair>res = new ArrayList<>();
HashMap<Long,ArrayList<Pair>>mp = new HashMap<>();
long t = 0;
for(int i = 0;i<n;i++){
long sum =0;
for(int j = i;j>=0;j--){
sum+=a[j];
ArrayList<Pair>l = mp.getOrDefault(sum,new ArrayList<Pair>());
l.add(new Pair(j+1,i+1));
mp.put(sum, l);
}
}
for(Map.Entry<Long, ArrayList<Pair>>m:mp.entrySet()){
ArrayList<Pair> temp = m.getValue();
ArrayList<Pair>cur = new ArrayList<>();
int r = -1;
for(int i = 0;i<temp.size();i++){
if(temp.get(i).x>r){
cur.add(temp.get(i));
r = temp.get(i).y;
}
}
if(cur.size()>res.size()){
res = cur;
}
}
System.out.println(res.size());
for(Pair it:res)System.out.println(it.x+" "+it.y);
}
public static void build(int seg[],int ind,int l,int r,int a[]){
if(l == r){
seg[ind] = a[l];
return;
}
int mid = (l+r)/2;
build(seg,(2*ind)+1,l,mid,a);
build(seg,(2*ind)+2,mid+1,r,a);
seg[ind] = Math.min(seg[(2*ind)+1],seg[(2*ind)+2]);
}
public static long gcd(long a, long b){
return b ==0 ?a:gcd(b,a%b);
}
public static long nearest(TreeSet<Long> list,long target){
long nearest = -1,sofar = Integer.MAX_VALUE;
for(long it:list){
if(Math.abs(it - target)<sofar){
sofar = Math.abs(it - target);
nearest = it;
}
}
return nearest;
}
public static ArrayList<Long> factors(long n){
ArrayList<Long>l = new ArrayList<>();
for(long i = 1;i*i<=n;i++){
if(n%i == 0){
l.add(i);
if(n/i != i)l.add(n/i);
}
}
Collections.sort(l);
return l;
}
public static void swap(int a[],int i, int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static boolean isSorted(long a[]){
for(int i =0;i<a.length;i++){
if(i+1<a.length && a[i]>a[i+1])return false;
}
return true;
}
public static int first(ArrayList<Long>list,long target){
int index = -1;
int l = 0,r = list.size()-1;
while(l<=r){
int mid = (l+r)/2;
if(list.get(mid) == target){
index = mid;
r = mid-1;
}else if(list.get(mid)>target){
r = mid-1;
}else l = mid+1;
}
return index;
}
public static int last(ArrayList<Long>list,long target){
int index = -1;
int l = 0,r = list.size()-1;
while(l<=r){
int mid = (l+r)/2;
if(list.get(mid) == target){
index= mid;
l = mid+1;
}else if(list.get(mid)<target){
l = mid+1;
}else r = mid-1;
}
return index;
}
public static void sort(int arr[]){
ArrayList<Integer>list = new ArrayList<>();
for(int it:arr)list.add(it);
Collections.sort(list);
for(int i = 0;i<arr.length;i++)arr[i] = list.get(i);
}
static class Pair{
int x,y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
}
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String read()
{
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int readInt() { return Integer.parseInt(read()); }
public long readLong() { return Long.parseLong(read()); }
public double readDouble(){return Double.parseDouble(read());}
public String readLine() throws Exception { return br.readLine(); }
}
}
| java |
1284 | D | D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2
1 2 3 6
3 4 7 8
OutputCopyYES
InputCopy3
1 3 2 4
4 5 6 7
3 4 5 5
OutputCopyNO
InputCopy6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
OutputCopyYES
NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist. | [
"binary search",
"data structures",
"hashing",
"sortings"
] | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
// editorial:
public class cf1284d {
public static void main(String[] args) throws IOException {
int n = ri(), a[][] = new int[n][2], b[][] = new int[n][2];
for (int i = 0; i < n; ++i) {
int sa = rni(), ea = ni(), sb = ni(), eb = ni();
a[i][0] = sa;
a[i][1] = ea;
b[i][0] = sb;
b[i][1] = eb;
}
prYN(check(a, b) && check(b, a));
close();
}
static boolean check(int[][] a, int[][] b) {
int n = a.length;
// [time, delete, ind]
PriorityQueue<int[]> events = new PriorityQueue<>((x, y) -> x[0] == y[0] ? y[1] - x[1] : x[0] - y[0]);
for (int i = 0; i < n; ++i) {
events.offer(new int[] {a[i][0], 0, i});
events.offer(new int[] {a[i][1] + 1, 1, i});
flush();
}
TreeMap<Integer, Integer> start_set = new TreeMap<>((x, y) -> y - x), end_set = new TreeMap<>();
while (!events.isEmpty()) {
int[] event = events.poll();
int action = event[1], ind = event[2];
if (action == 0) {
if (!end_set.isEmpty() && end_set.firstKey() < b[ind][0]) {
return false;
}
if (!start_set.isEmpty() && start_set.firstKey() > b[ind][1]) {
return false;
}
start_set.put(b[ind][0], start_set.getOrDefault(b[ind][0], 0) + 1);
end_set.put(b[ind][1], end_set.getOrDefault(b[ind][1], 0) + 1);
} else {
start_set.put(b[ind][0], start_set.get(b[ind][0]) - 1);
if (start_set.get(b[ind][0]) == 0) {
start_set.remove(b[ind][0]);
}
end_set.put(b[ind][1], end_set.get(b[ind][1]) - 1);
if (end_set.get(b[ind][1]) == 0) {
end_set.remove(b[ind][1]);
}
}
}
return true;
}
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 |
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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.List;
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
static int n;
static int[] a;
static List<Integer>[] adjacents;
static int[] parent;
static int[] answer;
public static void main(String[] args) throws IOException {
Reader input = new Reader();
n = input.nextInt();
a = new int[n];
for(int i = 0; i < n; ++i) a[i] = input.nextInt();
adjacents = new List[n];
for(int i = 0; i < n; ++i) adjacents[i] = new ArrayList<Integer>();
int u, v;
for(int i = 1; i < n; ++i) {
u = input.nextInt()-1;
v = input.nextInt()-1;
adjacents[u].add(v);
adjacents[v].add(u);
}
parent = new int[n];
answer = new int[n];
dfs(0, -1);
dfs(0);
solve();
StringBuilder output = new StringBuilder();
for(int i = 0; i < n; ++i) {
output.append(answer[i]);
output.append(" ");
}
System.out.print(output);
}
static void solve() {
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(0);
while(! queue.isEmpty()) {
int node = queue.poll();
for(int adjacent : adjacents[node]) {
if(adjacent != parent[node]) {
int v = answer[node]-(answer[adjacent] > 0 ? answer[adjacent] : 0);
answer[adjacent] = answer[adjacent]+(v > 0 ? v : 0);
queue.add(adjacent);
}
}
}
}
static void dfs(int node) {
int best = a[node] == 0 ? -1 : 1;
for(int adjacent : adjacents[node]) {
if(adjacent != parent[node]) {
dfs(adjacent);
if(answer[adjacent] > 0) {
best += answer[adjacent];
}
}
}
answer[node] = best;
}
static void dfs(int node, int p) {
parent[node] = p;
for(int adjacent : adjacents[node]) {
if(adjacent != parent[node]) {
dfs(adjacent, node);
}
}
}
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 |
1304 | F1 | F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp"
] | import java.util.*;
import java.io.*;
public class Animals{
static int lim=20050;
static int n,m,k,temp,max;
static int[][] M = new int[55][lim];
static int[][] DP = new int[55][lim];
static Deque<tuple> mono = new LinkedList<>();
public static void insert(tuple e){
while(!mono.isEmpty()&& e.v>mono.peekLast().v){mono.removeLast();}
mono.addLast(e);
}
public static void drop(int i){
if(mono.peekFirst().i==i){mono.removeFirst();}
}
public static int sum(int l,int p,int q){
return M[l][q]-M[l][p-1];
}
public static int lpun(int l, int x){
return DP[l-1][x]-M[l][x+k-1];
}
public static int rpun(int l, int x){
return DP[l-1][x]+M[l][x-1];
}
public static void main(String[] args) throws IOException{
Reader in = new Reader();
n = in.nextInt();m = in.nextInt();k = in.nextInt();
for (int i = 1; i <=n; i++) {
for (int j = 1; j <=m; j++) {
M[i][j]=in.nextInt()+M[i][j-1];
}
}
for (int i = 1; i <= m-k+1; i++) {
DP[1][i]=sum(1,i,i+k-1)+sum(2,i,i+k-1);
}
tuple tem;
for (int i = 2; i <= n; i++) {
//left
max=0;mono.clear();
for (int j = 1; j <= m-k+1; j++) {
if(j>k){drop(j-k);max = Math.max(max,DP[i-1][j-k]);}
insert(new tuple(j, lpun(i,j)));
tem = mono.peekFirst();
DP[i][j] = Math.max(DP[i-1][tem.i]+sum(i,tem.i+k,j+k-1), max+sum(i,j,j+k-1));
}
//right
max=0;mono.clear();
for (int j = m-k+1; j >= 1; j--) {
if(j+k<= m-k+1){drop(j+k);max = Math.max(max,DP[i-1][j+k]);}
insert(new tuple(j, rpun(i,j)));
tem = mono.peekFirst();
DP[i][j] = Math.max(DP[i][j],Math.max(DP[i-1][tem.i]+sum(i,j,tem.i-1), max+sum(i,j,j+k-1)));
}
for(int j=1;j<=m+k-1;j++){DP[i][j]+=sum(i+1,j,j+k-1);}
}
int ans=0;
for (int i = 1; i <= m-k+1; i++) {
ans = Math.max(DP[n][i],ans);
}
System.out.println(ans);
in.close();
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}
class tuple{
int i,v;
public tuple(int a,int b){
this.i=a;this.v=b;
}
}
| java |
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.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
in = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
try {
int t = in.nextInt(); while(t-- > 0) { solve(); out.println();}
// solve();
} finally {
out.close();
}
return;
}
public static void solve() {
int n = in.nextInt();
int m = in.nextInt();
if(n == m) {
out.print("YES");
return;
}
if(m < 3) {
out.print("NO");
return;
}
if(n % m == 0) {
out.print("YES");
} else {
out.print("NO");
}
return;
}
static void print(char[][] a) {
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a.length; j++) {
out.print(a[i][j]);
}
out.println();
}
}
//-------------- Helper methods-------------------
public static int[] fillArray(int n) {
int[] array = new int[n];
for(int i = 0; i < n; i++) {
array[i] = in.nextInt();
}
return array;
}
public static char[] fillArray() {
char[] array = in.next().toCharArray();
return array;
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
public static MyScanner in;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
} | java |
1324 | E | E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good. | [
"dp",
"implementation"
] |
/*
It's always like another kick for me to make sure I get what I want to get done,
because honestly you never know.
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main extends PrintWriter {
Main() { super(System.out); }
static boolean cases = false;
// Solution
int l, h, r, a[];
int dp[][];
void solve() {
int n = sc.nextInt();
h = sc.nextInt();
l = sc.nextInt();
r = sc.nextInt();
a = sc.readIntArray(n);
this.dp = new int[n + 1][h + 1];
for (int d[] : dp) Arrays.fill(d, -1);
int ans = solve(0, 0);
System.out.println(ans);
}
int solve(int i, int x) {
if (i >= a.length) return 0;
if (dp[i][x] != -1) return dp[i][x];
int d1 = (x + a[i]) % h;
int d2 = (x + (a[i] - 1)) % h;
int ans = 0;
ans = max((d1 >= l && d1 <= r ? 1 : 0) + solve(i + 1, d1), ans);
ans = max((d2 >= l && d2 <= r ? 1 : 0) + solve(i + 1, d2), ans);
return dp[i][x] = ans;
}
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);
}
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();
obj.solve();
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 |
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.io.*;
import java.util.*;
/*
@author : sanskarXrawat
@date : 4/18/2022
@time : 4:49 PM
*/
@SuppressWarnings("ALL")
public class Demo {
public static void main(String[] args) throws Throwable {
Thread thread = new Thread (null, new TaskAdapter (), "", 1 << 29);
thread.start ();
thread.join ();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput (inputStream);
FastOutput out = new FastOutput (outputStream);
Solution solver = new Solution ();
try {
solver.solve (1, in, out);
} catch (Exception e) {
e.printStackTrace ();
}
in.close ();
out.close ();
}
}
@SuppressWarnings("unused")
static class Solution {
static final Debug debug = new Debug (true);
public void solve(int testNumber, FastInput in, FastOutput out) throws Exception {
int n=in.ri();
long[] arr=new long[n];
for(int i=0;i<n;i++){
arr[i]=in.rl ();
}
HashMap<Long,Long> m=new HashMap<> ();
for(int i=0;i<n;i++){
if(!m.containsKey (i-arr[i])){
m.put (i-arr[i],arr[i]);
}else{
m.put(i-arr[i],m.get(i-arr[i])+arr[i]);
}
}
long ans=Collections.max (m.values ());
if(ans<0) ans=0;
out.prtl (ans);
}
static int gcd(int a,int b){
return b==0?a:gcd (b,a%b);
}
static void sort(int[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n); int temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private final StringBuilder cache = new StringBuilder (THRESHOLD * 2);
private static final int THRESHOLD = 32 << 10;
private final Writer os;
public FastOutput append(CharSequence csq) {
cache.append (csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append (csq, start, end);
return this;
}
private void afterWrite() {
if (cache.length () < THRESHOLD) {
return;
}
flush ();
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this (new OutputStreamWriter (os));
}
public FastOutput append(char c) {
cache.append (c);
afterWrite ();
return this;
}
public FastOutput append(String c) {
cache.append (c);
afterWrite ();
return this;
}
public FastOutput println(String c) {
return append (c).println ();
}
public FastOutput println() {
return append ('\n');
}
final <T> void prt(T a) {
append (a + " ");
}
final <T> void prtl(T a) {
append (a + "\n");
}
public FastOutput flush() {
try {
os.append (cache);
os.flush ();
cache.setLength (0);
} catch (IOException e) {
throw new UncheckedIOException (e);
}
return this;
}
public void close() {
flush ();
try {
os.close ();
} catch (IOException e) {
throw new UncheckedIOException (e);
}
}
public String toString() {
return cache.toString ();
}
public FastOutput printf(String format, Object... args) {
return append (String.format (format, args));
}
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;
}
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;
}
}
static class FastInput {
private final StringBuilder defaultStringBuf = new StringBuilder (1 << 13);
private final ByteBuffer tokenBuf = new ByteBuffer ();
private final byte[] buf = new byte[1 << 13];
private SpaceCharFilter filter;
private final InputStream is;
private int bufOffset;
private int bufLen;
private int next;
private int ptr;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read (buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read ();
}
}
public String next() {
return readString ();
}
public int ri() {
return readInt ();
}
public int readInt() {
boolean rev = false;
skipBlank ();
if (next == '+' || next == '-') {
rev = next == '-';
next = read ();
}
int val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read ();
}
return rev ? val : -val;
}
public long readLong() {
boolean rev = false;
skipBlank ();
if (next == '+' || next == '-') {
rev = next == '-';
next = read ();
}
long val = 0L;
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read ();
}
return rev ? val : -val;
}
public long rl() {
return readLong ();
}
public String readString(StringBuilder builder) {
skipBlank ();
while (next > 32) {
builder.append ((char) next);
next = read ();
}
return builder.toString ();
}
public String readString() {
defaultStringBuf.setLength (0);
return readString (defaultStringBuf);
}
public int rs(char[] data, int offset) {
return readString (data, offset);
}
public char[] rsc() {
return readString ().toCharArray ();
}
public int rs(char[] data) {
return rs (data, 0);
}
public int readString(char[] data, int offset) {
skipBlank ();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read ();
}
return offset - originalOffset;
}
public char rc() {
return readChar ();
}
public char readChar() {
skipBlank ();
char c = (char) next;
next = read ();
return c;
}
public double rd() {
return nextDouble ();
}
public double nextDouble() {
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read ();
}
double res = 0;
while (!isSpaceChar (c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow (10, readInt ());
if (c < '0' || c > '9')
throw new InputMismatchException ();
res *= 10;
res += c - '0';
c = read ();
}
if (c == '.') {
c = read ();
double m = 1;
while (!isSpaceChar (c)) {
if (c == 'e' || c == 'E')
return res * Math.pow (10, readInt ());
if (c < '0' || c > '9')
throw new InputMismatchException ();
m /= 10;
res += (c - '0') * m;
c = read ();
}
}
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar (c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public final int readByteUnsafe() {
if (ptr < bufLen) return buf[ptr++];
ptr = 0;
try {
bufLen = is.read (buf);
if (bufLen > 0) {
return buf[ptr++];
} else {
return -1;
}
} catch (IOException e) {
throw new UncheckedIOException (e);
}
}
public final int readByte() {
if (ptr < bufLen) return buf[ptr++];
ptr = 0;
try {
bufLen = is.read (buf);
if (bufLen > 0) {
return buf[ptr++];
} else {
throw new java.io.EOFException ();
}
} catch (IOException e) {
throw new UncheckedIOException (e);
}
}
public final String nextLine() {
tokenBuf.clear ();
for (int b = readByte (); b != '\n'; b = readByteUnsafe ()) {
if (b == -1) break;
tokenBuf.append (b);
}
return new String (tokenBuf.getRawBuf (), 0, tokenBuf.size ());
}
public final String nl() {
return nextLine ();
}
public final boolean hasNext() {
for (int b = readByteUnsafe (); b <= 32 || b >= 127; b = readByteUnsafe ()) {
if (b == -1) return false;
}
--ptr;
return true;
}
public final void close() {
try {
is.close ();
} catch (IOException e) {
throw new UncheckedIOException (e);
}
}
private static final class ByteBuffer {
private static final int DEFAULT_BUF_SIZE = 1 << 12;
private byte[] buf;
private int ptr = 0;
private ByteBuffer(int capacity) {
this.buf = new byte[capacity];
}
private ByteBuffer() {
this (DEFAULT_BUF_SIZE);
}
private ByteBuffer append(int b) {
if (ptr == buf.length) {
int newLength = buf.length << 1;
byte[] newBuf = new byte[newLength];
System.arraycopy (buf, 0, newBuf, 0, buf.length);
buf = newBuf;
}
buf[ptr++] = (byte) b;
return this;
}
private char[] toCharArray() {
char[] chs = new char[ptr];
for (int i = 0; i < ptr; i++) {
chs[i] = (char) buf[i];
}
return chs;
}
private byte[] getRawBuf() {
return buf;
}
private int size() {
return ptr;
}
private void clear() {
ptr = 0;
}
}
}
static class Debug {
private final boolean offline;
private final PrintStream out = System.err;
static int[] empty = new int[0];
public Debug(boolean enable) {
offline = enable && System.getSecurityManager () == null;
}
public Debug debug(String name, Object x) {
return debug (name, x, empty);
}
public Debug debug(String name, long x) {
if (offline) {
debug (name, "" + x);
}
return this;
}
public Debug debug(String name, String x) {
if (offline) {
out.printf ("%s=%s", name, x);
out.println ();
}
return this;
}
public Debug debug(String name, Object x, int... indexes) {
if (offline) {
if (x == null || !x.getClass ().isArray ()) {
out.append (name);
for (int i : indexes) {
out.printf ("[%d]", i);
}
out.append ("=").append ("" + x);
out.println ();
} else {
indexes = Arrays.copyOf (indexes, indexes.length + 1);
if (x instanceof byte[]) {
byte[] arr = (byte[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof short[]) {
short[] arr = (short[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof boolean[]) {
boolean[] arr = (boolean[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof char[]) {
char[] arr = (char[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof int[]) {
int[] arr = (int[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof float[]) {
float[] arr = (float[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof double[]) {
double[] arr = (double[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else if (x instanceof long[]) {
long[] arr = (long[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
} else {
Object[] arr = (Object[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug (name, arr[i], indexes);
}
}
}
}
return this;
}
}
} | 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.*;
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();
while(t-->0) {
long n=sc.nextLong();
long a=sc.nextLong();
long b=sc.nextLong();
if(a>=n){
System.out.println(n);
}else{
long minreq=(n+1)/2;
long ans=0;
if(minreq%a==0){
ans+=((minreq/a)*a);
ans+=(((minreq/a)-1)*b);
}else{
ans+=((((minreq/a))*a));
ans+=(minreq%a);
ans+=((minreq/a)*b);
}
if(ans>=n){
System.out.println(ans);
}else{
long gfg=n-ans;
System.out.println(ans+gfg);
}
}
}
}catch(Exception e){
return;
}
}
public static long bfs(int [][] arr,int i,int j,int num){
Queue<Pair> queue=new LinkedList<>();
long ans=0;
int count=1;
queue.add(new Pair(i,j));
int [] ff={-1,0,0,1};
int [] ss={0,1,-1,0};
boolean [][] gfg=new boolean [arr.length][arr[0].length];
gfg[i][j]=true;
while(!queue.isEmpty()){
int n=queue.size();
while(n-->0){
Pair p=queue.remove();
int a=p.a;
int b=p.b;
for(int ij=0;ij<4;ij++){
int ind1=ff[ij]+a;
int ind2=ss[ij]+b;
if(ok(ind1,ind2,arr) && !gfg[ind1][ind2]){
gfg[ind1][ind2]=true;
if(arr[ind1][ind2]==num){
ans+=count;
}
queue.add(new Pair(ind1,ind2));
}
}
}
count++;
}
//System.out.println(ans);
return ans;
}
private static boolean ok(int ind1, int ind2, int[][] arr) {
return ind1>=0 && ind1<arr.length && ind2>=0 && ind2<arr[0].length;
}
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 |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications. | [
"data structures",
"greedy",
"sortings"
] |
import java.util.*;
import java.io.*;
public class Main {
static FastReader in=new FastReader();
static StringBuilder Sd=new StringBuilder();
static List<Integer>Gr[];
static long Mod=998244353;
static Map<Integer,Integer>map=new HashMap<>();
public static void main(String [] args) {
//Dir by MohammedElkady
int n=in.nextInt();
int a[]=fillint(n);
node[]node=new node[n];
long ans=0L;
for(int i=0;i<n;i++){
int t=in.nextInt();
node[i]=(new node(a[i],t));
}
Sorting.bucketSort((node),n);
for(int i=n-1;i>=0;i--) {
int x=node[(i)].x,t=node[i].t;
if(!map.containsKey(x)) {map.put(x, x+1);}
else {
int z=MakeHash(x);
int lol=z-1-x;
ans+=((long)lol*(long)t);
}
}
Soutln(ans+"");
Sclose();
}
static int MakeHash(int z) {
if(map.containsKey(z)) {
int w=map.get(z);
w=MakeHash(w);
map.put(z, w);
return w;
}
else {
map.put(z, z+1);
return z+1;
}
}
static long power(long x, long y, long p)
{
// Initialize result
long res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static long modInverse(long n, long p)
{
return power(n, p-2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static long nCrModPFermat(int n, int r,
long p)
{
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
long[] fac = new long[n+1];
fac[0] = 1;
for (int i = 1 ;i <= n; i++)
fac[i] = fac[i-1] * i % p;
return (fac[n]* modInverse(fac[r], p)
% p * modInverse(fac[n-r], p)
% p) % p;
}
static long fac(int n , int m,int l) {
long res=1;
for(int i=l,u=1;i<=n||u<=m;i++,u++) {
if(i<=n) {res*=i;}
if(u<=m) {res/=u;}
while(res>Mod)
res-=Mod;
}
return res;
}
static long posation(int n) {
long res=1;
for(int i=0;i<n-3;i++) {res*=2L;
while(res>Mod)
res-=Mod;
while(res<=0)res+=Mod;}
return res;
}
static long gcd(long g,long x){
if(x<1)return g;
else return gcd(x,g%x);
}
//array fill
static long[]filllong(int n){long a[]=new long[n];for(int i=0;i<n;i++)a[i]=in.nextLong();return a;}
static int[]fillint(int n){int a[]=new int[n];for(int i=0;i<n;i++)a[i]=in.nextInt();return a;}
//OutPut Line
static void Sout(String S) {Sd.append(S);}
static void Soutln(String S) {Sd.append(S+"\n");}
static void Soutf(String S) {Sd.insert(0, S);}
static void Sclose() {System.out.println(Sd);}
static void Sclean() {Sd=new StringBuilder();}
}
class node implements Comparable<node>{
int x,t;
node(int x,int p){
this.x=x;
this.t=p;
}
@Override
public int compareTo(node o) {
return (t-o.t);
}
}
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;
}
}
class Sorting{
public static node[] bucketSort(node[] array, int bucketCount) {
if (bucketCount <= 0) throw new IllegalArgumentException("Invalid bucket count");
if (array.length <= 1) return array; //trivially sorted
int high = array[0].t;
int low = array[0].t;
for (int i = 1; i < array.length; i++) { //find the range of input elements
if (array[i].t > high) high = array[i].t;
if (array[i].t < low) low = array[i].t;
}
double interval = ((double)(high - low + 1))/bucketCount; //range of one bucket
ArrayList<node> buckets[] = new ArrayList[bucketCount];
for (int i = 0; i < bucketCount; i++) { //initialize buckets
buckets[i] = new ArrayList();
}
for (int i = 0; i < array.length; i++) { //partition the input array
buckets[(int)((array[i].t - low)/interval)].add(array[i]);
}
int pointer = 0;
for (int i = 0; i < buckets.length; i++) {
Collections.sort(buckets[i]); //mergeSort
for (int j = 0; j < buckets[i].size(); j++) { //merge the buckets
array[pointer] = buckets[i].get(j);
pointer++;
}
}
return array;
}
} | 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"
] | // package codeforce.cf617;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class E {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
// int t = sc.nextInt();
int t = 1;
for (int i = 0; i < t; i++) {
solve(sc, pw);
}
pw.close();
}
static void solve(Scanner in, PrintWriter out){
int n = in.nextInt();
String s = in.next();
char[] cs = s.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
boolean find = false;
for (int j = i - 1; j >= 0; j--) {
if (sb.charAt(j) == '1' && cs[j] > cs[i]){
out.println("NO");
return;
}else if (cs[j] > cs[i]){
find = true;
}
}
if (find){
sb.append("1");
}else{
sb.append("0");
}
}
out.println("YES");
out.println(sb.toString());
}
// Use this instead of Arrays.sort() on an array of ints. Arrays.sort() is n^2
// worst case since it uses a version of quicksort. Although this would never
// actually show up in the real world, in codeforces, people can hack, so
// this is needed.
static void ruffleSort(int[] a) {
//ruffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n), temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
}
| java |
1296 | 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.io.*;
import java.util.*;
public class StringColoring {
public static void main(String[] args) throws Exception {
FastIO in = new FastIO();
int n = in.nextInt();
String s = in.next();
int prev0 = -1;
int prev1 = -1;
int[] ans = new int[n];
boolean works = true;
for (int i=0; i<n; i++) {
int c = s.charAt(i)-'a';
if (c<prev0 && c<prev1) {
works = false;
break;
}
else if (c<prev0 && c>=prev1) {
prev1 = c;
ans[i] = 1;
}
else if (c>=prev0 && c<prev1) {
prev0 = c;
ans[i] = 0;
}
else {
if (prev1<prev0) {
prev0 = c;
ans[i] = 0;
}
else {
prev1 = c;
ans[i] = 1;
}
}
}
if (!works) System.out.println("NO");
else {
System.out.println("YES");
for (int i: ans) System.out.print(i);
System.out.println();
}
}
static class FastIO {
BufferedReader br;
StringTokenizer st;
PrintWriter pr;
public FastIO() throws IOException
{
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); }
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public String nextLine() throws IOException
{
String str = br.readLine();
return str;
}
}
}
| java |
1141 | E | E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1
| [
"math"
] | import java.io.*;
import java.util.*;
public class Main {
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream)
{
reader = new BufferedReader(new InputStreamReader(stream),32768);
tokenizer = null;
}
String next()
{
while (tokenizer == null||!tokenizer.hasMoreTokens())
{
try
{
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
static InputReader r = new InputReader(System.in);
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args)
{
long H = r.nextLong();
int n = r.nextInt();
long[] d = new long[n];
long[] ps = new long[n+1];
for (int i = 0; i < n; i ++)
{
d[i] = r.nextInt();
ps[i+1] = ps[i] + d[i];
}
long min = Integer.MAX_VALUE;
for (int i = 0; i < n + 1; i ++)
{
min = Math.min(min,ps[i]);
}
if (ps[n] >= 0 && H + min > 0)
{
pw.println(-1);
}
else if (H + min <= 0)
{
int hi = 0;
for (int i = n; i >= 0; i --)
{
if (H+ps[i] <= 0)
{
hi = i;
}
}
pw.println(hi);
}
else
{
long x = ps[n];
//y rounds --> H+min-x*y <= 0
long y = ((H+min+(-x-1))/(-x));
H = H + x*y;
int hi = 0;
for (int i = n; i>=0; i --)
{
if (H+ps[i]<= 0)
{
hi = i;
}
}
pw.println(n*y+hi);
}
pw.close();
}
} | java |
1304 | B | B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0
InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string. | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import org.w3c.dom.NamedNodeMap;
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.*;
import java.util.Collections;
public class div {
static PrintWriter output = new PrintWriter(System.out);
public static void main(String[] args) throws java.lang.Exception {
div.FastReader sc =new FastReader();
int n = sc.nextInt(); int m = sc.nextInt();String arr[]= new String [n];
for(int e =0;e<n;e++)arr[e]=sc.next();
String s = ""; String ss ="";int w=0;
String arr1[]= new String [n];
for(int e =0;e<n;e++) {
StringBuilder q = new StringBuilder(arr[e]); q.reverse();String h = q.toString();
if(h.equals(arr[e])&&!arr[e].equals("")) {
String a = "";
for(int ee =0;ee<n;ee++) {
if(arr[ee].equals(h)&&!arr[ee].equals("")) {
a=a+""+arr[ee];
arr[ee]="";
}
}
if(ss.length()<a.length())ss=a;
}
else {
for(int ee=0;ee<n;ee++) {
if(arr[ee].equals(h)&&!arr[ee].equals("")) {
s=s+""+arr[e];
arr1[w]=arr[ee];
arr[ee]="";
w++;
break;
}
}
}
}
s=s+""+ss;
for(int e =w-1;e>=0;e--) {
s=s+arr1[e];
}
System.out.println(s.length());
System.out.println(s);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
float nextFloat()
{
return Float.parseFloat(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readArrayLong(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
public static int[] radixSort2(int[] a)
{
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for(int v : a) {
c0[(v&0xff)+1]++;
c1[(v>>>8&0xff)+1]++;
c2[(v>>>16&0xff)+1]++;
c3[(v>>>24^0x80)+1]++;
}
for(int i = 0;i < 0xff;i++) {
c0[i+1] += c0[i];
c1[i+1] += c1[i];
c2[i+1] += c2[i];
c3[i+1] += c3[i];
}
int[] t = new int[n];
for(int v : a)t[c0[v&0xff]++] = v;
for(int v : t)a[c1[v>>>8&0xff]++] = v;
for(int v : a)t[c2[v>>>16&0xff]++] = v;
for(int v : t)a[c3[v>>>24^0x80]++] = v;
return a;
}
static void reverse_sorted(int[] arr)
{
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<arr.length;i++)
{
list.add(arr[i]);
}
Collections.sort(list , Collections.reverseOrder());
for(int i=0;i<arr.length;i++)
{
arr[i] = list.get(i);
}
}
static int LowerBound(int a[], int x) { // x is the target value or key
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int UpperBound(ArrayList<Integer> list, int x) {// x is the key or target value
int l=-1,r=list.size();
while(l+1<r) {
int m=(l+r)>>>1;
if(list.get(m)<=x) l=m;
else r=m;
}
return l+1;
}
public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<String, Integer> > list =
new LinkedList<Map.Entry<String, Integer> >(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() {
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// put data from sorted list to hashmap
HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
static class Queue_Pair implements Comparable<Queue_Pair> {
int first , second;
public Queue_Pair(int first, int second) {
this.first=first;
this.second=second;
}
public int compareTo(Queue_Pair o) {
return Integer.compare(o.first, first);
}
}
static void leftRotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
leftRotatebyOne(arr, n);
}
static void leftRotatebyOne(int arr[], int n)
{
int i, temp;
temp = arr[0];
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[n-1] = temp;
}
static boolean isPalindrome(String str)
{
// Pointers pointing to the beginning
// and the end of the string
int i = 0, j = str.length() - 1;
// While there are characters to compare
while (i < j) {
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;
// Increment first pointer and
// decrement the other
i++;
j--;
}
// Given string is a palindrome
return true;
}
static boolean palindrome_array(char arr[], int n)
{
// Initialise flag to zero.
int flag = 0;
// Loop till array size n/2.
for (int i = 0; i <= n / 2 && n != 0; i++) {
// Check if first and last element are different
// Then set flag to 1.
if (arr[i] != arr[n - i - 1]) {
flag = 1;
break;
}
}
// If flag is set then print Not Palindrome
// else print Palindrome.
if (flag == 1)
return false;
else
return true;
}
static boolean allElementsEqual(long[] arr,int n)
{
int z=0;
for(int i=0;i<n-1;i++)
{
if(arr[i]==arr[i+1])
{
z++;
}
}
if(z==n-1)
{
return true;
}
else
{
return false;
}
}
static boolean allElementsDistinct(int[] arr,int n)
{
int z=0;
for(int i=0;i<n-1;i++)
{
if(arr[i]!=arr[i+1])
{
z++;
}
}
if(z==n-1)
{
return true;
}
else
{
return false;
}
}
public static void reverse(int[] array)
{
// Length of the array
int n = array.length;
// Swaping the first half elements with last half
// elements
for (int i = 0; i < n / 2; i++) {
// Storing the first half elements temporarily
int temp = array[i];
// Assigning the first half to the last half
array[i] = array[n - i - 1];
// Assigning the last half to the first half
array[n - i - 1] = temp;
}
}
public static void reverse_Long(long[] array)
{
// Length of the array
int n = array.length;
// Swaping the first half elements with last half
// elements
for (int i = 0; i < n / 2; i++) {
// Storing the first half elements temporarily
long temp = array[i];
// Assigning the first half to the last half
array[i] = array[n - i - 1];
// Assigning the last half to the first half
array[n - i - 1] = temp;
}
}
static boolean isSorted(int[] a)
{
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
static boolean isReverseSorted(int[] a)
{
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] < a[i + 1]) {
return false;
}
}
return true;
}
static int[] rearrangeEvenAndOdd(int arr[], int n)
{
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(arr[i]%2==0)
{
list.add(arr[i]);
}
}
for(int i=0;i<n;i++)
{
if(arr[i]%2!=0)
{
list.add(arr[i]);
}
}
int len = list.size();
int[] array = list.stream().mapToInt(i->i).toArray();
return array;
}
static long[] rearrangeEvenAndOddLong(long arr[], int n)
{
ArrayList<Long> list = new ArrayList<>();
for(int i=0;i<n;i++)
{
if(arr[i]%2==0)
{
list.add(arr[i]);
}
}
for(int i=0;i<n;i++)
{
if(arr[i]%2!=0)
{
list.add(arr[i]);
}
}
int len = list.size();
long[] array = list.stream().mapToLong(i->i).toArray();
return array;
}
static boolean isPrime(long n)
{
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (long i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
static long getSum(long n)
{
long sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = n/10;
}
return sum;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcdLong(long a, long b)
{
if (b == 0)
return a;
return gcdLong(b, a % b);
}
static void swap(int i, int j)
{
int temp = i;
i = j;
j = temp;
}
static int countDigit(int n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
/*
Arrays.sort(arr, Comparator.comparingDouble(o -> o[0]));
q.replace(i, i+1, "4");
StringBuilder q = new StringBuilder(s);
List arr1 = new ArrayList();
String.format("%.2f",arr[ee][0])
*/
/*
*/
}
| java |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | import java.util.*;
import java.io.*;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public final class Main{
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() { this(System.in, System.out); }
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(new FileWriter(problemName + ".out"));
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
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()); }
}
static Kattio sc = new Kattio();
static long mod = (long)1e9+7;
static PrintWriter out =new PrintWriter(System.out);
public static void buildHeap(int arr[], int n) {
for(int i = n/2-1;i>=0;i--) {
heapify(arr,n,i);
}
}
//Heapify function to maintain heap property.
public static void heapify(int arr[], int n, int i) {
int l = i*2 + 1 , r = i*2 + 2;
int small = l;
if(r<n&& arr[r]<arr[small]) {
small = r;
}
if(l>=n || arr[i]< arr[small]) return;
if(small != i)swap(small, i, arr);
heapify(arr,n,small);
}
public static void swap(int i,int j,int arr[]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void heapSort(int arr[], int n) {
buildHeap(arr,n);
System.out.println(Arrays.toString(arr));
int ans[] = new int[n];
int l = 0 , r = n-1;
while(l<=r) {
swap(l,r,arr);
r--;
heapify(arr,r + 1,0);
}
}
public static long getInversion(String a) {
long zero =0;
for(char ch : a.toCharArray()) {
if(ch=='0') zero++;
}
long ans = 0;
for(char ch : a.toCharArray()) {
if(ch=='1') {
ans += zero;
}
else zero--;
}
return ans;
}
public static List<Integer> getAllParent (int node) {
List<Integer> list = new ArrayList<>();
while(node >= 1) {
list.add(node);
node /= 2;
}
return list;
}
public static boolean isSubsequence(String small, String big) {
// System.out.println( small + " " + big);
int i =0 , j = 0;
while(i< small.length() && j < big.length()) {
if(small.charAt(i) == big.charAt(j)) {
i++;
j++;
}
else {
j++;
}
}
if(i >= small.length()) return true;
else return false;
}
static long arr[][] = new long[1005][1005];
public static void main(String[] args)throws IOException {
int t = sc.nextInt();
while(t-->0) {
solve();
}
out.close();
}
public static void solve() throws IOException {
int n = sc.nextInt() , x = sc.nextInt();
int arr[] = new int[n];
int sum =0;
for(int i = 0;i<n;i++) {
arr[i] = sc.nextInt();
sum += arr[i];
}
System.out.println(Math.min(x , sum));
}
public static long getx(long num) {
for(long i =0;i<=64;i++) {
if((1l<<i) == num) return i;
}
return 64;
}
public static long pow(long a , long b) {
long mod = (long)1e9+7;
if(b == 1) return a;
if(b == 0) return 1;
long ans = pow(a , b/2)%mod;
if(b%2 == 0) {
return (ans*ans)%mod;
}
else {
return ((ans*ans)%mod*a)%mod;
}
}
public static long getAns(int len) {
long mod = 998244353l;
if(len == 1) return 45;
else {
long min = pow(10 , len -1);
long max = pow(10 , len) -1;
long ans = (max - min + 1)%mod;
ans = ((ans*(ans + 1))%mod)/2;
return (ans + getAns(len -1))%mod;
}
}
public static int maxLen(int[] arr, int n) {
for(int i =0;i<n;i++) {
if(arr[i] == 0)arr[i] = -1;
}
for(int i =1;i<n;i++) {
arr[i] += arr[i-1];
}
System.out.println(Arrays.toString(arr));
HashMap<Integer , Integer> map = new HashMap<>();
map.put(0 ,-1);
int ans = 0;
for(int i = 0;i<n;i++) {
if(map.containsKey(arr[i]*-1)) {
ans = Math.max(ans ,i - map.get(arr[i]*-1));
}
map.putIfAbsent(arr[i] , i);
}
return ans;
}
public static int getDifference(char a[] , char b[] , int l1 , int r1,int l2,int r2) {
int ans = 0;
while(l1<=r1 && l2 <= r2) {
if(a[l1] != b[l2]) ans++;
l1++;
l2++;
}
return ans;
}
public static long callfun(int x1 , int y1,int x2,int y2,long arr[][] , long memo[][]) {
if(x1 == x2 && y1 == y2) return arr[x1][y1];
if(x1 > x2) return Integer.MIN_VALUE;
if(y1 > y2) return Integer.MIN_VALUE;
if(memo[x1][y1] != -1) return memo[x1][y1];
else {
return memo[x1][y1] = arr[x1][y1] + Math.max(callfun(x1 + 1 ,y1 ,x2,y2,arr , memo ),callfun(x1 ,y1 + 1 ,x2,y2,arr , memo ));
}
}
public static boolean isVowel(char ch) {
if(ch == 'a' || ch == 'e'||ch == 'i' || ch == 'o' || ch == 'u') return true;
return false;
}
public static String getAns(int i,int j,String s) {
if(j>=s.length()) return s.charAt(i) + "";
while(i>=0 && j<s.length() && s.charAt(i) == s.charAt(j)) {
i--;
j++;
}
return s.substring(i +1, j);
}
public static int getFactor(int num) {
if(num==1) return 1;
int ans = 2;
int k = num/2;
for(int i = 2;i<=k;i++) {
if(num%i==0) ans++;
}
return Math.abs(ans);
}
public static int geti(char ch) {
if(ch=='R') return 2;
if(ch=='L') return 3;
if(ch=='U') return 1;
else return 0;
}
public static int[] readarr()throws IOException {
int n = sc.nextInt();
int arr[] = new int[n];
for(int i =0;i<n;i++) {
arr[i] = sc.nextInt();
}
return arr;
}
public static boolean isPowerOfTwo (long x) {
return x!=0 && ((x&(x-1)) == 0);
}
public static boolean isPrime(long num) {
if(num==1) return false;
if(num<=3) return true;
if(num%2==0||num%3==0) return false;
for(long i =5;i*i<=num;i+=6) {
if(num%i==0) return false;
}
return true;
}
public static boolean isPrime(int num) {
if(num==1) return false;
if(num<=3) return true;
if(num%2==0||num%3==0) return false;
for(int i =5;i*i<=num;i+=6) {
if(num%i==0) return false;
}
return true;
}
public static long gcd(long a , long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static long get_gcd(long a , long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static long fac(long num) {
long ans = 1;
int mod = (int)1e9+7;
for(long i = 2;i<=num;i++) {
ans = (ans*i)%mod;
}
return ans;
}
} | java |
1325 | C | C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample: | [
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | //package com.company;//Read minute details if coming wrong for no idea questions
import com.sun.source.tree.ArrayAccessTree;
import javax.swing.*;
import java.beans.IntrospectionException;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Main {
static class pair implements Comparable<pair> {
long a = 0;
long b = 0;
// int cnt;
pair(long b, long a) {
this.a = b;
this.b = a;
// cnt = x;
}
@Override
public int compareTo(pair o) {
if(this.a != o.a)
return (int) (this.a - o.a);
else
return (int) (this.b - o.b);
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.a == a && p.b == b;
}
return false;
}
public int hashCode() {
return (Long.valueOf(a).hashCode()) * 31 + (Long.valueOf(b).hashCode());
}
}
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 prlong(Object object) throws IOException {
bw.append("" + object);
}
public void prlongln(Object object) throws IOException {
prlong(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
//HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS
// HashSet<Long> set = new HashSet<>();
// for(int i = 0; i < s.length(); i++){
// int b = 0;
// long h = 1;
// for(int j=i; j<s.length(); j++){
// h = 131*h + (int)s.charAt(j);
// b += bad[(int)(s.charAt(j)-'a')];
// if(b<=k){
// set.add(h);
// }
// }
// }
// System.out.println(set.size());
//dsu
static int[] par, rank;
public static void dsu(int n) {
par = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
par[i] = i;
rank[i] = 1;
}
}
static int find(int u) {
return par[u] == -1 ? -1 : par[u] == u ? u : (par[u] = find(par[u]));
}
static void union(int u, int v) {
int a = find(u), b = find(v);
if (a != b && a != -1 && b != -1) {
par[b] = a;
rank[a] += rank[b];
}
}
static void disunion(int u, int v) {
int a = find(u), b = find(v);
if (a != -1 && a == b) {
par[a] = -1;
}
}
static class Calc_nCr {
private final long[] fact;
private final long[] invfact;
private final int p;
Calc_nCr(int n, int prime) {
fact = new long[n + 5];
invfact = new long[n + 5];
p = prime;
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (i * fact[i - 1]) % p;
}
invfact[n] = pow(fact[n], p - 2, p);
for (int i = n - 1; i >= 0; i--) {
invfact[i] = (invfact[i + 1] * (i + 1)) % p;
}
}
private long nCr(int n, int r) {
if (r > n || n < 0 || r < 0) return 0;
return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;
}
private static long pow(long a, long b, int mod) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return result;
}
}
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);
}
}
public static void main(String[] args) {
try {
FastReader in = new FastReader();
FastWriter out = new FastWriter();
// int mx=10000000;
// boolean isPrime[] = new boolean[mx+5]; int primeDiv[] = new int[mx+5];
// for (int i = 0; i <= mx; i++) {
// isPrime[i] = true;
// }
// for(int i =0;i<primeDiv.length;i++)
// primeDiv[i]=i;
// isPrime[0] = isPrime[1] = false;
// for (long i = 2; i <= mx; i++) {
// if (isPrime[(int)i]) {
// for (long j = i*i; j <= mx; j += i) {
// if (primeDiv[(int)j] == j) {
// primeDiv[(int)j] = (int)i;
// }
// isPrime[(int)j] = false;
// }
// }
// }
// System.out.println(
// String.format("%.12f", x));
int testCases=1;
// int n =in.nextInt();
// long arr[]=new long[n];
// ArrayList<Long>ans=new ArrayList<>();
// for(int i =0;i<n;i++)
//
//
// } ans.add(in.nextLong());
// Collections.sort(ans);
// for(int i =0;i<n;i++)
// arr[i]=ans.get(i);
int mod =1000000007;
fl:
while (testCases-- > 0) {
int n =in.nextInt();
ArrayList<ArrayList<Integer>>adj=new ArrayList<>();
int q[][]=new int[n][3];
for(int i =0;i<n;i++)
adj.add(new ArrayList<>());
for(int i =0;i<n-1;i++)
{
int a =in.nextInt();
int b =in.nextInt();
a--;b--; int temp=a;
a=Math.min(a,b);
b=Math.max(temp,b);
q[i][0]=a;
q[i][1]=b;
adj.get(a).add(b);
adj.get(b).add(a);
}
// System.out.println(adj);
int x =0;
int y =-1; int x2 =0;
int y2 =-1;
boolean yes=true;
int count =0;
int a[][]=new int[3][2];
HashMap<Integer,Integer>map=new HashMap<>();
for(int i =0;i<n;i++)
{
if(adj.get(i).size()>=3)
{
yes=false;
a[0][0]=(i);a[0][1]=adj.get(i).get(0);
a[1][0]=(i);a[1][1]=adj.get(i).get(1); a[2][0]=(i);a[2][1]=adj.get(i).get(2);
break ;
}
}
HashMap<pair,Integer>b=new HashMap<>();
for(int i =0;i<3;i++)
{
pair p =new pair(a[i][0],a[i][1]);
b.put(p,0);}
Stack<Integer>ans=new Stack<>() ;
// System.out.println(x+" "+y+" "+x2+" "+y2);
for(int i =3;i<n-1;i++)
ans.push(i);
if(yes)
{
ans.push(2);
ans.push(1);
ans.push(0);
}
int aa=0;
for(int i =0;i<n-1;i++)
{
int aaa =q[i][0];
int bbb =q[i][1];
// System.out.println(aaa+" "+bbb);
pair p =new pair(aaa,bbb);
pair p1 =new pair(bbb,aaa);
if(b.containsKey(p))
{
out.prlongln(aa);
aa++;
}
else if(b.containsKey(p1))
{
out.prlongln(aa);
aa++;
}
else out.prlongln(ans.pop());
}
}
out.close();
} catch (Exception e) {
return;
}
}
public static double dfs(ArrayList<ArrayList<Integer>>adj, int curr, int par) {
double len = 0;
for(int child: adj.get(curr)) {
if(child == par)
continue;
len += dfs(adj, child, curr)+1;
}
//System.out.println(curr+" "+len);
if(len == 0) // leaf node
return 0;
if(par == -1) // root node
return len/adj.get(curr).size();
return len/(adj.get(curr).size()-1);
}
static long comb(int r, int n)
{
long result;
result = factorial(n)/(factorial(r)*factorial(n-r));
return result;
}
static long factorial(int n) {
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
static void LongestPalindromicPrefix(String str,int lps[]){
// String temp = str + '/';
// str = reverse(str);
// temp += str;
String temp =str;
int n = temp.length();
for(int i = 1; i < n; i++)
{
int len = lps[i - 1];
while (len > 0 && temp.charAt(len) !=
temp.charAt(i))
{
len = lps[len - 1];
}
if (temp.charAt(i) == temp.charAt(len))
{
len++;
}
lps[i] = len;
}
// return temp.substring(0, lps[n - 1]);
}
static String reverse(String input)
{
char[] a = input.toCharArray();
int l, r = a.length - 1;
for(l = 0; l < r; l++, r--)
{
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.valueOf(a);
}
}
/*
*
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ JACKS PET FROM ANOTHER WORLD
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓-------
* ┃ ┏┛-------
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/
//RULES
//TAKE INPUT AS LONG IN CASE OF SUM OR MULITPLICATION OR CHECK THE CONTSRaint of the array
//Always use stringbuilder of out.println for strinof out.println for string or high level output
// IMPORTANT TRs1 TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROs1 OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN
//Read minute details if coming wrong for no idea questions | 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"
] | import java.util.*;
import java.io.*;
public class F_1311 {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
Pair[] array = new Pair[n];
for(int i = 0; i < n; i++)
array[i] = new Pair(sc.nextInt(), 0);
for(int i = 0; i < n; i++)
array[i].v = sc.nextInt();
Arrays.sort(array);
long sum = 0;
long[] sumNeg = new long[n];
int[] cntNeg = new int[n];
for(int i = 0; i < n; i++)
if(array[i].v < 0) {
sumNeg[i] = array[i].x + (i == 0 ? 0 : sumNeg[i - 1]);
cntNeg[i] = 1 + (i == 0 ? 0 : cntNeg[i - 1]);
} else if(array[i].v > 0) {
sumNeg[i] = i == 0 ? 0 : sumNeg[i - 1];
cntNeg[i] = i == 0 ? 0 : cntNeg[i - 1];
sum += 1l * cntNeg[i] * array[i].x - sumNeg[i];
} else {
sumNeg[i] = i == 0 ? 0 : sumNeg[i - 1];
cntNeg[i] = i == 0 ? 0 : cntNeg[i - 1];
sum += 1l * cntNeg[i] * array[i].x - sumNeg[i];
sumNeg[i] += array[i].x;
cntNeg[i] += 1;
}
TreeSet<Integer> set = new TreeSet<>();
for(int i = 0; i < n; i++)
if(array[i].v < 0)
set.add(-array[i].v);
TreeMap<Integer, Integer> map = new TreeMap<>();
int index = 1;
for(int i : set)
map.put(i, index++);
int N = 1;
while(N < index)
N <<= 1;
SegmentTree sumTree = new SegmentTree(new long[N + 1]);
SegmentTree cntTree = new SegmentTree(new long[N + 1]);
for(int i = 0; i < n; i++)
if(array[i].v < 0) {
int ind = map.get(-array[i].v);
sum += 1l * array[i].x * cntTree.query(1, ind) - sumTree.query(1, ind);
sumTree.update_point(1, array[i].x);
sumTree.update_point(ind + 1, -array[i].x);
cntTree.update_point(1, 1);
cntTree.update_point(ind + 1, -1);
}
set = new TreeSet<>();
for(int i = 0; i < n; i++)
if(array[i].v > 0)
set.add(array[i].v);
map = new TreeMap<>();
index = 1;
for(int i : set)
map.put(i, index++);
N = 1;
while(N < index)
N <<= 1;
sumTree = new SegmentTree(new long[N + 1]);
cntTree = new SegmentTree(new long[N + 1]);
for(int i = n - 1; i >= 0; i--)
if(array[i].v > 0) {
int ind = map.get(array[i].v);
sum += 1l * sumTree.query(1, ind) - 1l * array[i].x * cntTree.query(1, ind);
sumTree.update_point(1, array[i].x);
sumTree.update_point(ind + 1, -array[i].x);
cntTree.update_point(1, 1);
cntTree.update_point(ind + 1, -1);
}
pw.println(sum);
pw.flush();
}
public static class Pair implements Comparable<Pair> {
int x, v;
public Pair(int x, int v) {
this.x = x;
this.v = v;
}
public int compareTo(Pair p) {
return this.x - p.x;
}
}
public static class SegmentTree {
int N;
long[] in, sTree;
public SegmentTree(long[] array) {
in = array;
N = array.length - 1;
sTree = new long[N<<1];
build(1, 1, N);
}
public void build(int node, int b, int e) {
if(b == e) {
sTree[node] = in[b];
return;
}
int left = node<<1, right = node<<1|1;
int mid = (b + e)>>1;
build(left, b, mid);
build(right, mid + 1, e);
sTree[node] = sTree[left] + sTree[right];
}
public long query(int l, int r) {
return query(1, 1, N, l, r);
}
public long query(int node, int b, int e, int l, int r) {
if(r < b || l > e)
return 0;
if(b >= l && e <= r)
return sTree[node];
int left = node<<1, right = node<<1|1;
int mid = (b + e)>>1;
return query(left, b, mid, l, r) + query(right, mid + 1, e, l, r);
}
public void update_point(int n, int v) {
n += N - 1;
sTree[n] += v;
while(n > 1) {
n /= 2;
sTree[n] = sTree[n<<1] + sTree[n<<1|1];
}
}
}
public 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[] nextIntArray(int n) throws IOException {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++)
array[i] = new Integer(nextInt());
return array;
}
public long[] nextLongArray(int n) throws IOException {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
public static int[] 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;
}
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
| java |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | import java.util.Scanner;
public class Nonzero {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int j = 0; j < t; j++) {
int n= sc.nextInt();
int[] arr = new int[n];
int ans =0;
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
if (arr[i] == 0){
ans++;
arr[i] =1;
}
}
int sum =0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
if (sum == 0){
ans = ans+1;
}
System.out.println(ans);
}
}
}
| 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.*;
import java.io.*;
import static java.lang.Math.*;
public class Main { public static void main(String[] args) { new MainClass().execute(); } }
class MainClass extends PrintWriter {
MainClass() { super(System.out, true); }
boolean cases = true;
// Solution
void solveIt(int testCaseNo) {
int n = sc.nextInt();
long m = sc.nextLong();
List<long[]> al = new ArrayList<>();
for(int i=0;i<n;i++){
long time = sc.nextLong();
long lb = sc.nextLong();
long rb = sc.nextLong();
al.add(new long[]{time,lb,rb});
}
long max = m, min = m, prev = 0;
for(long x[] : al){
max += (x[0]-prev);
min -= (x[0]-prev);
if(max < x[1] || min > x[2]) {
println("NO");
return;
}
max = min(max,x[2]);
min = max(min,x[1]);
prev = x[0];
}
println("YES");
}
void solve() {
int caseNo = 1;
if (cases) for (int T = sc.nextInt(); T > 1; T--, caseNo++) { solveIt(caseNo); }
solveIt(caseNo);
}
void execute() {
long S = System.currentTimeMillis();
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
this.sc = new FastIO();
solve();
out.flush();
long G = System.currentTimeMillis();
sc.tr(G - S + "ms");
}
class FastIO {
private boolean endOfFile() {
if (bufferLength == -1) return true;
int lptr = ptrbuf;
while (lptr < bufferLength) {
// __
if (!spaceChar(inputBuffer[lptr++])) return false;
}
try {
is.mark(1000);
while (true) {
int b = is.read();
if (b == -1) {
is.reset();
return true;
} else if (!spaceChar(b)) {
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private byte[] inputBuffer = new byte[1024];
int bufferLength = 0, ptrbuf = 0;
private int readByte() {
if (bufferLength == -1) throw new InputMismatchException();
if (ptrbuf >= bufferLength) {
ptrbuf = 0;
try {
bufferLength = is.read(inputBuffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (bufferLength <= 0) return -1;
}
return inputBuffer[ptrbuf++];
}
private boolean spaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skipIt() {
int b;
while ((b = readByte()) != -1 && spaceChar(b));
return b;
}
private double nextDouble() { return Double.parseDouble(next()); }
private char nextChar() { return (char) skipIt(); }
private String next() {
int b = skipIt();
StringBuilder sb = new StringBuilder();
while (!(spaceChar(b))) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] readCharArray(int n) {
char[] buf = new char[n];
int b = skipIt(), p = 0;
while (p < n && !(spaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private 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 int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
private long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
private int nextInt() {
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 nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) {
if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o));
}
}
InputStream is;
PrintWriter out;
String INPUT = "";
final int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
final long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
final long mod = (long) 1e9 + 7;
FastIO sc;
} | java |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6
| [
"greedy",
"sortings"
] | import java.util.*;
public class FightwithMonsters {
public static void main(String args[])
{
int i,j,t,n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
long ap=sc.nextInt();
long bp=sc.nextInt();
long k=sc.nextInt();
int a[]=new int[n];
long z=ap+bp;
PriorityQueue<Long> fina=new PriorityQueue<>();
int count=0;
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
long mod=a[i]%z;
if(mod==0)
{
fina.add(bp);
}
else if(mod<=ap)
{
count++;
}
else
{
fina.add(mod-ap);
}
}
while(fina.size()>0)
{
long pq=fina.remove();
pq=(int)Math.ceil((double)pq/ap);
k=k-pq;
if(k<0)
{
break;
}
count++;
}
System.out.println(count);
}
}
| java |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] | import java.io.*;
import java.lang.*;
import java.util.*;
public class ComdeFormces {
static int x[]= {0,-1,1,1,1,1,-1,-1};
static int y[]= {-1,0,0,0,1,-1,1,-1};
// static int dp[][][];
static int seg[];
static int E;
static class Trie{
Trie a[];
int ind;
public Trie() {
this.a=new Trie[3];
this.ind=-1;
}
}
static long ncr[][];
static int cst;
static HashMap<Integer,Integer> hm;
static int dp[][];
static ArrayList<Integer> tp;
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
FastReader sc=new FastReader();
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
// OutputStream out = new BufferedOutputStream ( System.out );
// int t=sc.nextInt();
int tc=1;
InverseofNumber(m);
InverseofFactorial(m);
factorial(m);
while(tc--!=0) {
int n=sc.nextInt();
int mm=sc.nextInt();
if(n==2)log.write("0\n");
else {
long bn=Binomial(mm,n-1,m);
bn=mul(bn,n-2);
long tw=2;
bn=mul(bn,pow(tw,(long)(n-3)));
log.write(bn+"\n");
}
log.flush();
}
}
static int N = 1000001;
// Array to store inverse of 1 to N
static long[] factorialNumInverse = new long[N + 1];
// Array to precompute inverse of 1! to N!
static long[] naturalNumInverse = new long[N + 1];
// Array to store factorial of first N numbers
static long[] fact = new long[N + 1];
// Function to precompute inverse of numbers
public static void InverseofNumber(int p)
{
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i <= N; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] *
(long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
public static void InverseofFactorial(int p)
{
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// Precompute inverse of natural numbers
for(int i = 2; i <= N; i++)
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p;
}
// Function to calculate factorial of 1 to N
public static void factorial(int p)
{
fact[0] = 1;
// Precompute factorials
for(int i = 1; i <= N; i++)
{
fact[i] = (fact[i - 1] * (long)i) % p;
}
}
// Function to return nCr % p in O(1) time
public static long Binomial(int N, int R, int p)
{
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) %
p * factorialNumInverse[N - R]) % p;
return ans;
}
public static int m=(int)(998244353);
public static int mul(int a, int b) {
return ((a%m)*(b%m))%m;
}
public static long mul(long a, long b) {
return ((a%m)*(b%m))%m;
}
public static int add(int a, int b) {
return ((a%m)+(b%m))%m;
}
public static long add(long a, long b) {
return ((a%m)+(b%m))%m;
}
public static long sub(long a,long b) {
return ((a%m)-(b%m)+m)%m;
}
static long gcd(long a,long b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static int gcd(int a,int b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static long ncr(int n, int r){
if(r>n-r)r=n-r;
long ans=1;
long m=(int)(1e9+7);
for(int i=0;i<r;i++){
ans=ans*(n-i);
ans/=i+1;
}
return ans;
}
public static class num{
long v;
}
static long gcd(long a,long b,num x,num y) {
if(b==0) {
x.v=1;
y.v=0;
return a;
}
num x1=new num();
num y1=new num();
long ans=gcd(b,a%b,x1,y1);
x.v=y1.v;
y.v=x1.v-(a/b)*y1.v;
return ans;
}
static long inverse(long b,long m) {
num x=new num();
num y=new num();
long gc=gcd(b,m,x,y);
if(gc!=1) {
return -1;
}
return (x.v%m+m)%m;
}
static long div(long a,long b,long m) {
a%=m;
if(inverse(b,m)==-1)return a/b;
return (inverse(b,m)*a)%m;
}
public static class trip{
int a;
int b;
long c;
int d;
public trip(int a,int b,long c,int d) {
this.a=a;
this.b=b;
this.c=c;
this.d=d;
}
}
static void mergesort(int[] a,int start,int end) {
if(start>=end)return ;
int mid=start+(end-start)/2;
mergesort(a,start,mid);
mergesort(a,mid+1,end);
merge(a,start,mid,end);
}
static void merge(int[] a, int start,int mid,int end) {
int ptr1=start;
int ptr2=mid+1;
int b[]=new int[end-start+1];
int i=0;
while(ptr1<=mid && ptr2<=end) {
if(a[ptr1]<=a[ptr2]) {
b[i]=a[ptr1];
ptr1++;
i++;
}
else {
b[i]=a[ptr2];
ptr2++;
i++;
}
}
while(ptr1<=mid) {
b[i]=a[ptr1];
ptr1++;
i++;
}
while(ptr2<=end) {
b[i]=a[ptr2];
ptr2++;
i++;
}
for(int j=start;j<=end;j++) {
a[j]=b[j-start];
}
}
public static class FastReader {
BufferedReader b;
StringTokenizer s;
public FastReader() {
b=new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(s==null ||!s.hasMoreElements()) {
try {
s=new StringTokenizer(b.readLine());
}
catch(IOException e) {
e.printStackTrace();
}
}
return s.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str="";
try {
str=b.readLine();
}
catch(IOException e) {
e.printStackTrace();
}
return str;
}
boolean hasNext() {
if (s != null && s.hasMoreTokens()) {
return true;
}
String tmp;
try {
b.mark(1000);
tmp = b.readLine();
if (tmp == null) {
return false;
}
b.reset();
} catch (IOException e) {
return false;
}
return true;
}
}
public static class pair{
int a;
int b;
public pair(int a,int b) {
this.a=a;
this.b=b;
}
@Override
public String toString() {
return "{"+this.a+" "+this.b+"}";
}
}
static long pow(long a, long pw) {
long temp;
if(pw==0)return 1;
temp=pow(a,pw/2);
if(pw%2==0)return mul(temp,temp);
return mul(a,mul(temp,temp));
}
public static int md=998244353;
static int pow(int a, int pw) {
int temp;
if(pw==0)return 1;
temp=pow(a,pw/2);
if(pw%2==0)return temp*temp;
return a*temp*temp;
}
} | 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 static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class C_2_Skyscrapers_hard_version {
static long mod = Long.MAX_VALUE;
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 arr[] = f.nextArray(n);
ArrayDeque<Integer> stack = new ArrayDeque<>();
long l[] = new long[n];
for(int i = 0; i < n; i++) {
while(!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
stack.poll();
}
long curr = 0;
if(stack.isEmpty()) {
curr = (i+1) * (long)arr[i];
} else {
curr = l[stack.peek()] + (i-stack.peek()) * (long)arr[i];
}
stack.push(i);
l[i] = curr;
}
// for(long x: l) {
// out.print(x + " ");
// }
// out.println();
stack.clear();
long r[] = new long[n];
for(int i = n-1; i >= 0; i--) {
while(!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
stack.poll();
}
long curr = 0;
if(stack.isEmpty()) {
curr = (n-i) * (long)arr[i];
} else {
curr = r[stack.peek()] + (stack.peek()-i) * (long)arr[i];
}
stack.push(i);
r[i] = curr;
}
long maxFloor = 0;
int ind = -1;
for(int i = 0; i < n; i++) {
long currFloor = (l[i]+r[i]-arr[i]);
if(currFloor > maxFloor) {
maxFloor = currFloor;
ind = i;
}
}
int ans[] = new int[n];
ans[ind] = arr[ind];
int min = arr[ind];
for(int i = ind+1; i < n; i++) {
min = min(min, arr[i]);
ans[i] = min;
}
min = arr[ind];
for(int i = ind-1; i >= 0; i--) {
min = min(min, arr[i]);
ans[i] = min;
}
for(int i: ans) {
out.print(i + " ");
}
}
// 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 |
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"
] | /**
* ******* Created on 25/2/20 8:03 PM*******
*/
import java.io.*;
import java.util.*;
public class ED81E implements Runnable {
private static final int MAX = 2*(int) (1E5 + 5);
private static final int MOD = (int) (1E9 + 7);
private static final long Inf = (long) (1E14 + 10);
int n;
private void solve() throws IOException {
n = reader.nextInt();
int[] p = new int[MAX];
int[] rp = new int[MAX];
int[] a = new int[MAX];
for(int i=0;i<n;i++){
p[i] = reader.nextInt();
p[i]--;
rp[p[i]]=i;
}
for(int i=0;i<n;i++)
a[i] = reader.nextInt();
b[0] = a[0];
for(int i=1;i<n;i++)
b[i] = a[i] + b[i-1];
build(0,0,n);
long res = b[0];
for(int i = 0; i < n; ++i){
int pos = rp[i];
upd(pos, n, -a[pos]);
upd(0, pos, a[pos]);
res = Math.min(res, get(0, n - 1));
}
writer.println(res);
}
long[] b = new long[MAX];
long[] t = new long[4*MAX];
long[] add = new long[4*MAX];
private void build(int v, int l, int r) {
if(r-l ==1){
t[v] = b[l];
return;
}
int mid = (l+r)/2;
build(v*2 +1, l, mid);
build(2*v+2, mid,r);
t[v] = Math.min(t[2*v+1], t[2*v+2]);
}
void push(int v, int l, int r){
if(add[v] != 0){
if(r - l > 1)
for(int i = v+v+1; i < v+v+3; ++i){
add[i] += add[v];
t[i] += add[v];
}
add[v] = 0;
}
}
void upd(int v, int l, int r, int L, int R, int x){
if(L >= R) return;
if(l == L && r == R){
add[v] += x;
t[v] += x;
push(v, l, r);
return;
}
push(v, l, r);
int mid = (l + r) / 2;
upd(v * 2 + 1, l, mid, L, Math.min(mid, R), x);
upd(v * 2 + 2, mid, r, Math.max(mid, L), R, x);
t[v] = Math.min(t[v * 2 + 1], t[v * 2 + 2]);
}
void upd(int l, int r, int x){
upd(0, 0, n, l, r, x);
}
long get(int v, int l, int r, int L, int R){
if(L >= R) return Inf;
push(v, l, r);
if(l == L && r == R)
return t[v];
int mid = (l + r) / 2;
return Math.min(get(v * 2 + 1, l, mid, L, Math.min(R, mid)),
get(v * 2 + 2, mid, r, Math.max(L, mid), R));
}
long get(int l, int r){
return get(0, 0, n, l, r);
}
public static void main(String[] args) throws IOException {
try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
new ED81E().run();
}
}
StandardInput reader;
PrintWriter writer;
@Override
public void run() {
try {
reader = new StandardInput();
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
interface Input extends Closeable {
String next() throws IOException;
default int nextInt() throws IOException {
return Integer.parseInt(next());
}
default long nextLong() throws IOException {
return Long.parseLong(next());
}
default double nextDouble() throws IOException {
return Double.parseDouble(next());
}
default int[] readIntArray() throws IOException {
return readIntArray(nextInt());
}
default int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextInt();
}
return array;
}
default long[] readLongArray(int size) throws IOException {
long[] array = new long[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextLong();
}
return array;
}
}
private static class StandardInput implements Input {
private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer stringTokenizer;
@Override
public void close() throws IOException {
reader.close();
}
@Override
public String next() throws IOException {
if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
}
}
| 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.io.*;
import java.util.*;
public class Main {
static long u, v;
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
u = sc.nextLong();
v = sc.nextLong();
solve();
out.close();
}
/*
1. 不可行
1.1 u > v, 相加的值必然大于等于所有数异或
1.2 u 和 v 奇偶不同, 所有数相加和所有数相异或奇偶应该相同。
2. 可行
长度为3: [u, x, x] u ^ x ^ x = u, u + x + x = v, x = (v-u)/2
长度为2: [a, b] a ^ b = u, a + b = v, 已知 a + b = a ^ b + 2(a&b),可得 a&b = (v-u)/2 = x
x有一位为1,u对应二进制位为0
x有一位为0,u对应二进制位任意
那么可知道若存在这样的a,b, 那么x & u = 0,即 x ^ u = x + u
那么数组位[u + x, x]
长度为1: [u], u = v != 0
*/
static void solve() {
if (u > v || (u % 2 != v % 2)) {
out.println("-1");
return;
}
long x = (v - u) / 2; // 由于u,v奇偶相同,那么必然能被2整除
if (u == v) {
if (u == 0) out.println(0);
else out.println(1 + "\n" + u);
} else {
if ((x & u) == 0) out.println(2 + "\n" + (u + x) + " " + x);
else out.println(3 + "\n" + u + " " + x + " " + x);
}
}
} | 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"
] | import java.io.*;
import java.util.*;
public class Tournament {
static FastScanner sc = new FastScanner();
public static void main(String[] args){
int t = sc.nextInt();
// sc.nextLine();
// int t = 1;
while( t--> 0){
solve();
}
}
public static void solve(){
long n = sc.nextLong();
long a=0, b=0;
for (int i=2;(i*i)<n;i++) {
if (n%i==0){
n/=i;
if(a==0) a = i;
else{
b = i;
break;
}
}
}
if(a!=0 && b!=0 && n>b){
System.out.println("YES");
System.out.println(a + " " + b + " " + n);
}else System.out.println("NO");
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
| java |
1141 | G | G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1 | [
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
static class Pair {
int to;
int index;
Pair(int to, int index) {
this.to = to;
this.index = index;
}
}
static int MAX = 200005;
static List<Pair>[] graph = new List[MAX];
static int[] degree = new int[MAX];
static int[] colorAssigned = new int[MAX];
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 1; t <= test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
int k = sc.nextInt();
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
graph[u].add(new Pair(v, i));
graph[v].add(new Pair(u, i));
degree[u]++;
degree[v]++;
}
TreeMap<Integer, Integer> freqMap = new TreeMap<>();
for (int i = 0; i < n; i++) {
freqMap.put(degree[i], freqMap.getOrDefault(degree[i], 0) + 1);
}
int minColorsNeeded = 0, remainingNodes = n;
for (int key : freqMap.keySet()) {
if (remainingNodes > k) {
minColorsNeeded = key;
remainingNodes -= freqMap.get(key);
}else {
break;
}
}
dfs(minColorsNeeded, 0, -1, -1);
out.println(minColorsNeeded);
for (int i = 0; i < n - 1; i++) {
out.print((colorAssigned[i] + 1) + " ");
}
out.println();
}
private static void dfs(int minColorsNeeded, int currNode, int parent, int parentEdgeColor) {
int color = 0;
for (Pair adjacentPair : graph[currNode]) {
if (adjacentPair.to == parent) {
continue;
}
if (color == parentEdgeColor) {
color = (color + 1) % minColorsNeeded;
parentEdgeColor = -1;
}
colorAssigned[adjacentPair.index] = color;
dfs(minColorsNeeded, adjacentPair.to, currNode, color);
color = (color + 1) % minColorsNeeded;
}
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.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.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
//
public class cf1295e {
public static void main(String[] args) throws IOException {
int n = ri(), p[] = riam1(n), c[] = ria(n);
int pos[] = new int[n];
for (int i = 0; i < n; ++i) {
pos[p[i]] = i;
}
long[] pre = new long[n];
pre[0] = c[0];
for (int i = 1; i < n; ++i) {
pre[i] = pre[i - 1] + c[i];
}
sgt sgt = new sgt(pre, Long::sum, Math::min, LMAX);
long ans = c[0];
// prln(pre);
for (int i = 0; i < n; ++i) {
sgt.upd(0, pos[i], c[pos[i]]);
sgt.upd(pos[i], n, -c[pos[i]]);
ans = min(ans, sgt.qry(0, n - 1));
// long[] arr = new long[n];
// for (int j = 0; j < n; ++j) {
// arr[j] = sgt.qry(j, j + 1);
// }
// prln(arr);
}
prln(ans);
close();
}
@FunctionalInterface
interface LongOperator {
long merge(long a, long b);
}
static class sgt {
LongOperator upd_op, qry_op;
int n;
long sgt[], lazy[], id;
sgt(int sz, LongOperator operator, long identity) {
n = sz;
sgt = new long[4 * n + 5];
upd_op = qry_op = operator;
id = identity;
}
sgt(int sz, LongOperator update_operator, LongOperator query_operator, long identity) {
n = sz;
sgt = new long[4 * n + 5];
upd_op = update_operator;
qry_op = query_operator;
id = identity;
}
sgt(long[] a, LongOperator operator, long identity) {
n = a.length;
sgt = new long[4 * n + 5];
upd_op = qry_op = operator;
id = identity;
build(1, a, 0, n - 1);
}
sgt(long[] a, LongOperator update_operator, LongOperator query_operator, long identity) {
n = a.length;
sgt = new long[4 * n + 5];
lazy = new long[4 * n + 5];
upd_op = update_operator;
qry_op = query_operator;
id = identity;
build(1, a, 0, n - 1);
}
void set(int i, long x) {
set(1, i, x, 0, n - 1);
}
void upd(int i, long x) {
upd(1, i, x, 0, n - 1);
}
void upd(int i, int j, long x) {
upd(1, i, j - 1, x, 0, n - 1);
}
long qry(int l, int r) {
return qry(1, l, r - 1, 0, n - 1);
}
void set(int node, int i, long x, int l, int r) {
if (l == r) {
sgt[node] = x;
} else {
int m = l + (r - l) / 2;
if (i <= m) {
set(node << 1, i, x, l, m);
} else {
set(node << 1 | 1, i, x, m + 1, r);
}
pull(node);
}
}
void upd(int node, int i, long x, int l, int r) {
if (l == r) {
sgt[node] = upd_op.merge(sgt[node], x);
} else {
int m = l + (r - l) / 2;
if (i <= m) {
upd(node << 1, i, x, l, m);
} else {
upd(node << 1 | 1, i, x, m + 1, r);
}
pull(node);
}
}
void upd(int node, int i, int j, long x, int l, int r) {
if (r < i || j < l) {
return;
} else if (i <= l && r <= j) {
lazy[node] += x;
push(node, l, r);
} else {
push(node, l, r);
int m = l + (r - l) / 2;
upd(node << 1, i, j, x, l, m);
upd(node << 1 | 1, i, j, x, m + 1, r);
pull(node);
}
}
long qry(int node, int i, int j, int l, int r) {
if (r < i || j < l) {
return id;
} else if (i <= l && r <= j) {
push(node, l, r);
return sgt[node];
} else {
push(node, l, r);
int m = l + (r - l) / 2;
return qry_op.merge(qry(node << 1, i, j, l, m), qry(node << 1 | 1, i, j, m + 1, r));
}
}
void build(int node, long[] a, int l, int r) {
if (l == r) {
sgt[node] = a[l];
} else {
int m = l + (r - l) / 2;
build(node << 1, a, l, m);
build(node << 1 | 1, a, m + 1, r);
pull(node);
}
}
void pull(int node) {
sgt[node] = qry_op.merge(sgt[node << 1], sgt[node << 1 | 1]);
}
void push(int node, int l, int r) {
if (lazy[node] != 0) {
if (l < r) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
}
sgt[node] += lazy[node];
lazy[node] = 0;
}
}
}
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 |
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.io.*;
import java.util.*;
public class A {
static class Program {
int val;
int index;
Program(int i, int val) {
this.index = i;
this.val = val;
}
}
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int t = 1;
while (t-- > 0) {
int n = sc.nextInt();
String s = sc.next();
int r = 0, l = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'R')
r++;
else
l++;
}
System.out.println(r + l + 1);
}
// min
// mid
// max
// max + min
// max + mid
// min + max + mid
}
/*
* 5 4
* 9 4
* 9 13
* 22 13
* 22 35
* 57 35
* 57 92
* +100
*/
static boolean IsPowerOfTwo(int x) {
return (x & (x - 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 |
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.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
// ???
public class cf1305e {
public static void main(String[] args) throws IOException {
int n = rni(), m = ni(), ans[] = new int[n];
if (m > (n / 2) * ((n - 1) / 2)) {
prln(-1);
close();
return;
}
int k = n;
while (m < (k / 2) * ((k - 1) / 2)) {
--k;
}
for (int i = 0; i < k; ++i) {
ans[i] = i + 1;
}
if (k < n) {
ans[k] = 2 * k + 1 - 2 * (m - (k / 2) * ((k - 1) / 2));
for (int i = k + 1; i < n; ++i) {
ans[i] = 100000001 + i * 10000;
}
}
prln(ans);
close();
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// graph util
static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static void pryesno(boolean b) {prln(b ? "yes" : "no");};
static void pryn(boolean b) {prln(b ? "Yes" : "No");}
static void prYN(boolean b) {prln(b ? "YES" : "NO");}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}} | 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"
] |
// Imports
import java.util.*;
import java.io.*;
public class D1305 {
/**
* @param args the command line arguments
* @throws IOException, FileNotFoundException
*/
public static void main(String[] args) throws IOException, FileNotFoundException {
// TODO UNCOMMENT WHEN ALGORITHM CORRECT
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
// TODO code application logic here
int N = Integer.parseInt(f.readLine());
ArrayList<Integer>[] edges = new ArrayList[N];
int[] degree = new int[N];
ArrayList<Integer> deg1 = new ArrayList<>();
for(int i = 0; i < N; i++) {
edges[i] = new ArrayList<>();
}
for(int i = 0; i < N - 1; i++) {
StringTokenizer st = new StringTokenizer(f.readLine());
int a = Integer.parseInt(st.nextToken()) - 1;
int b = Integer.parseInt(st.nextToken()) - 1;
degree[a]++;
degree[b]++;
if(degree[a] == 1) {
deg1.add(a);
}
else if(degree[a] == 2) {
deg1.remove((Integer)a);
}
if(degree[b] == 1) {
deg1.add(b);
}
else if(degree[b] == 2) {
deg1.remove((Integer)b);
}
edges[a].add(b);
edges[b].add(a);
}
while(1 == 1) {
if(deg1.size() == 1) {
System.out.println("! " + (deg1.remove(0) + 1));
break;
}
else {
int first = deg1.remove(0) + 1;
int second = deg1.remove(0) + 1;
System.out.println("? " + first + " " + second);
System.out.flush();
int l = Integer.parseInt(f.readLine());
if(l == first) {
// System.out.println(l + " " + first);
System.out.println("! " + first);
break;
}
if(l == second) {
// System.out.println(l + " " + second);
System.out.println("! " + second);
break;
}
for(int i : edges[first - 1]) {
if(degree[i] == 2) {
degree[i] = 1;
deg1.add(i);
}
else {
degree[i]--;
}
}
for(int i : edges[second - 1]) {
if(degree[i] == 2) {
degree[i] = 1;
deg1.add(i);
}
else {
degree[i]--;
}
}
}
}
}
}
| 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"
] | /******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.*;
public class Main
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int t = sc.nextInt();
for(int i = 0 ; i < t;i++)
{
String a = sc.next();
String b =sc.next();
String c = sc.next();
check(a,b,c);
}
}
static void check(String a, String b , String c)
{
int[]freq =new int[26];
String ans = "YES";
for(int i = 0 ; i < a.length();i++)
{
if(a.charAt(i)==b.charAt(i)&&c.charAt(i)!=a.charAt(i)){
ans="NO";
break;
}
if(a.charAt(i)!=b.charAt(i))
{
if(c.charAt(i)!=b.charAt(i)&&c.charAt(i)!=a.charAt(i)){
ans = "NO";
break;
}
}
}
System.out.println(ans);
}
}
| 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.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
BAromasSearch solver = new BAromasSearch();
solver.solve(1, in, out);
out.close();
}
static class BAromasSearch {
ArrayList<long[]> data;
long cx;
long cy;
long ax;
long bx;
long ay;
long by;
long[][] dis;
boolean canAdd() {
double x = ((double) cx * ax) + bx;
double y = ((double) cy * ay) + by;
return (x <= 2e17) && (y <= 2e17);
}
long[] newData() {
long x = (cx * ax) + bx;
long y = (cy * ay) + by;
cx = x;
cy = y;
return new long[]{x, y};
}
public void solve(int testNumber, ScanReader in, PrintWriter out) {
data = new ArrayList<>();
long x0 = in.scanLong();
long y0 = in.scanLong();
ax = in.scanLong();
ay = in.scanLong();
bx = in.scanLong();
by = in.scanLong();
cx = x0;
cy = y0;
data.add(new long[]{x0, y0});
while (canAdd()) data.add(newData());
long sx = in.scanLong();
long sy = in.scanLong();
long t = in.scanLong();
dis = new long[data.size()][data.size()];
for (int i = 0; i < data.size(); i++) {
for (int j = i + 1; j < data.size(); j++) {
dis[i][j] = dis[j][i] = makeEdge(i, j);
}
}
long ans = Long.MIN_VALUE;
for (int i = 0; i < data.size(); i++) {
long tt = t - dist(sx, sy, data.get(i)[0], data.get(i)[1]);
ans = Math.max(ans, findIt(i, tt));
}
out.println(ans);
}
long dist(long x, long y, long xx, long yy) {
return (long) Math.abs(x - xx) + Math.abs(y - yy);
}
long findIt(int node, long t) {
if (t < 0) return 0;
int n = data.size();
long ans = 1;
for (int l = 0; l < n; l++) {
for (int r = l; r < n; r++) {
if (dis[l][r] + Math.min(dis[node][l], dis[node][r]) <= t) ans = Math.max(ans, r - l + 1);
}
}
return ans;
}
long makeEdge(int i, int j) {
long xx = Math.abs(data.get(i)[0] - data.get(j)[0]);
long yy = Math.abs(data.get(i)[1] - data.get(j)[1]);
return xx + yy;
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
}
}
| java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.