contest_id
stringclasses 33
values | problem_id
stringclasses 14
values | statement
stringclasses 181
values | tags
listlengths 1
8
| code
stringlengths 21
64.5k
| language
stringclasses 3
values |
---|---|---|---|---|---|
1296
|
A
|
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
|
[
"math"
] |
import java.math.BigInteger;
import java.sql.Array;
import java.util.*;
public class leet {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
for (int i = 0; i < x; i++) {
int y = scan.nextInt();
int[] arr = new int[y];
for (int j = 0; j < arr.length; j++) {
arr[j]= scan.nextInt();
}
int c = 0;
for (int j = 0; j < arr.length; j++) {
if(arr[j]%2!=0){
c++;
}
}
if(c==y && y%2!=0){
System.out.println("YES");
}
else if(c!=y && c>0){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
|
java
|
1301
|
A
|
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.
|
[
"implementation",
"strings"
] |
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class LRUD {
public static void main(String... strings) {
try (Scanner sc = new Scanner(System.in)) {
int testCase = sc.nextInt();
Set<Character> chars;
while (testCase-- > 0) {
char a[] = sc.next().toCharArray();
char b[] = sc.next().toCharArray();
char c[] = sc.next().toCharArray();
String result = "YES";
for (int i = 0; i < a.length; i++) {
// c is different
if (a[i] == b[i] && a[i] != c[i]) {
result = "NO";
break;
}
chars = new HashSet<>(3);
chars.add(a[i]);
chars.add(b[i]);
chars.add(c[i]);
if (chars.size() == 3) {
result = "NO";
break;
}
}
System.out.println(result);
}
}
}
}
|
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.*;
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();
HashMap<String,Integer> hm=new HashMap<>();
String[]arr=new String[n];
HashSet<String>ans=new HashSet<>();
for(int i=0;i<n;i++){
String s=s();
arr[i]=s;
hm.put(s,i);
}
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
String s1=arr[i];
String s2=arr[j];
char[]arr1=new char[k];
String make="";
for(int l=0;l<k;l++){
char c1=s1.charAt(l);
char c2=s2.charAt(l);
if(c1==c2)arr1[l]=c1;
else{
if(c1!='S'&&c2!='S'){
arr1[l]='S';
}
else if(c1!='T'&&c2!='T'){
arr1[l]='T';
}
else{
arr1[l]='E';
}
}
make+=arr1[l];
}
if(hm.containsKey(make)){
int ti=hm.get(make);
ArrayList<Integer> temp=new ArrayList<>();
temp.add(i);
temp.add(j);
temp.add(ti);
Collections.sort(temp);
String add="";
for(int x:temp){
add+=x+"#";
}
ans.add(add);
}
}
}
sb.append(ans.size());
}
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
|
1316
|
E
|
E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.
|
[
"bitmasks",
"dp",
"greedy",
"sortings"
] |
import java.util.*;
import java.io.*;
public class TeamBuilding {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int poolSize = Integer.parseInt(st.nextToken());
int teamSize = Integer.parseInt(st.nextToken());
int audSize = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
Pair[] audContrib = new Pair[poolSize];
for (int i = 0; i < poolSize; i++) {
audContrib[i] = new Pair(i, Integer.parseInt(st.nextToken()));
}
Arrays.sort(audContrib);
int[][] skill = new int[poolSize][teamSize];
for (int i = 0; i < poolSize; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < teamSize; j++) {
skill[i][j] = Integer.parseInt(st.nextToken());
}
}
long[][] dp = new long[poolSize + 1][(1 << teamSize)];
for (int i = 0; i <= poolSize; i++) {
Arrays.fill(dp[i], -1);
}
dp[0][0] = 0;
for (int i = 1; i <= poolSize; i++) {
int ind = audContrib[i - 1].idx;
for (int m = 0; m < (1 << teamSize); m++) {
int bits = Integer.bitCount(m);
// Try adding the player to the audience.
int numAud = i - 1 - bits;
if (numAud < audSize) {
if (dp[i - 1][m] != -1) {
dp[i][m] = dp[i - 1][m] + audContrib[i - 1].val;
}
} else {
if (dp[i - 1][m] != -1) {
dp[i][m] = dp[i - 1][m];
}
}
// Try adding the player to the team.
for (int j = 0; j < teamSize; j++) {
if ((m & (1 << j)) != 0 && (dp[i - 1][m ^ (1 << j)]) != -1) {
dp[i][m] = Math.max(
dp[i][m],
dp[i - 1][m ^ (1 << j)] + skill[ind][j]
);
}
}
}
}
System.out.println(dp[poolSize][(1 << teamSize) - 1]);
}
}
class Pair implements Comparable<Pair> {
int idx;
int val;
public Pair(int idx, int val) {
this.idx = idx;
this.val = val;
}
public int compareTo(Pair other) {
return other.val - val;
}
}
|
java
|
13
|
C
|
C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1
|
[
"dp",
"sortings"
] |
import java.util.*;
public class Sequence {
static void solve() {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong(), k=0;
// Max queue
Queue<Long> p = new PriorityQueue<Long>((int)n, new Comparator<Long>(){
public int compare (Long a, Long b) {
return b-a>0 ? 1 : b-a==0 ? 0 : -1 ;
}
});
while (n-->0) {
long c = sc.nextLong();
p.add(c);
if (p.peek()>c) {
k+=p.poll()-c;
p.add(c);
}
}
System.out.println(k);
sc.close();
}
public static void main(String[] args) {
solve();
}
}
|
java
|
1285
|
B
|
B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.
|
[
"dp",
"greedy",
"implementation"
] |
/* 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 class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
int binary(int arr[], int x)
{
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x)
return m;
if (arr[m] < x)
l = m + 1;
else
r = m - 1;
}
return -1;
}
static int[] segment,parent,rank;
static void constructSt(int n, int[] arr){
segment = new int[n*4+1];
formSt(arr, 1,0,n-1);
}
public static void formSt(int[] arr, int node, int s, int e){
if(s==e){
segment[node]= arr[s];
return;
}
formSt(arr, node*2,s,s+(e-s)/2);
formSt(arr, node*2+1,s+(e-s)/2+1,e);
segment[node]=Math.max(segment[node*2],segment[node*2+1]);
}
public static int findMax( int node, int s, int e,int l , int r){
if(l>e||s>r) return -1;
if(s==e) return segment[node];
if(l<=s&&r>=e) return segment[node];
int mid = s+(e-s)/2;
return Math.max(findMax(node*2,s,mid,l,r),findMax(node*2+1,mid+1,e,l,r));
}
public static void dsu(int n){
parent = new int[n]; rank = new int[n];
for(int i =0;i<n;i++) parent[i]=i;
}
public static int find(int i){
if(i==parent[i] ) return i;
return parent[i]=find(parent[i]);
}
public static void merge(int i, int j){
if(rank[i]>=rank[j]){
rank[i]+=rank[j];
parent[j]=i;
}
else {
rank[j]+=rank[i];
parent[i]=j;
}
}
public static long kadane(long[] a, int n){
long max =0L,prev =0L;
long l =0L,r=0L;
for(int i =0;i<n-1;i++){
prev+=a[i];
if(max<prev){
max=prev;
r=i+1;
}
if(prev<0){
prev=0;
l=i+1;
}
}
prev=0;
for(int i =1;i<n;i++){
prev+=a[i];
if(max<prev){
max=prev;
r=i+1;
}
if(prev<0){
prev=0;
l=i+1;
}
}
return max;
}
public static void main (String[] args) throws java.lang.Exception
{
OutputStream outputStream =System.out;
PrintWriter out =new PrintWriter(outputStream);
FastReader sc =new FastReader();
int t =sc.nextInt();
while(t-->0){
int n = sc.nextInt();
long sum =0;
long[] a = new long[n];
for(int i =0;i<n;i++){
a[i]= sc.nextLong(); sum+=a[i];
}
// out.println(sum);
out.print(sum>kadane(a,n)?"YES":"NO");
out.print("\n");
}
out.close();
// your code goes here"
}
}
class pair
{
long r;
long d;
public pair(long r , long d)
{
this.r= r;
this.d= d;
}
}
class solution{
}
|
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.*;
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);
int max = 0;
int cnt = 0;
for(int i = 0 ; i < n; i++){
if(a[i] == 1){
cnt++;
max = max(cnt,max);
}else{
max = max(cnt,max);
cnt = 0;
}
}
if(a[n-1] == 1){
int index= 0;
int count = 0;
while(index < n-1 && a[index] == 1){
count++;
index++;
}
index = n-2;
while(index >= 0 && a[index] == 1){
index--;
count++;
}
max = max(max,count+1);
}
out.println(max);
}
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
|
1295
|
A
|
A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
|
[
"greedy"
] |
import java.util.Scanner;
public class MAin
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
StringBuilder sb=new StringBuilder();
int n,t=s.nextInt(),i;
while(t-->0)
{
n=s.nextInt();
if(n%2==0)
{
for(i=0;i<(n/2);i++)
sb.append(1);
}
else
{
sb.append(7);
for(i=0;i<(n-3)/2;i++)
sb.append(1);
}
sb.append("\n");
}
System.out.print(sb);
}
}
|
java
|
1325
|
F
|
F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:
|
[
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.HashSet;
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);
PrintWriter out = new PrintWriter(outputStream);
FEhabsLastTheorem solver = new FEhabsLastTheorem();
solver.solve(1, in, out);
out.close();
}
static class FEhabsLastTheorem {
PrintWriter out;
InputReader in;
ArrayList<Integer>[] graph;
HashSet<Integer>[] tset;
int[] par;
int[] dep;
int max_cycle = 0;
int start = 0;
int end = 0;
DSU ob;
boolean[] visited;
int[] tin;
int[] low;
void dfs(int v, int p, int h) {
dep[v] = h;
for (int u : graph[v]) {
if (dep[u] == -1) {
par[u] = v;
dfs(u, v, h + 1);
} else if (u != par[v]) {
if (dep[v] - dep[u] + 1 > max_cycle) {
max_cycle = dep[v] - dep[u] + 1;
start = v;
end = u;
}
}
}
}
TreeSet<Integer> MIS(int n) {
TreeSet<Integer> is = new TreeSet<>();
TreeSet<Pair> set = new TreeSet<>();
int deg[] = new int[n + 1];
for (int i = 0; i < n; ++i) {
set.add(new Pair(graph[i].size(), i));
deg[i] = graph[i].size();
}
while (!set.isEmpty()) {
Pair v = set.pollFirst();
for (int e : graph[v.y]) {
if (set.contains(new Pair(deg[e], e))) {
for (int f : graph[e]) {
if (set.contains(new Pair(deg[f], f))) {
set.remove(new Pair(deg[f], f));
set.add(new Pair(--deg[f], f));
}
}
set.remove(new Pair(deg[e], e));
}
}
is.add(v.y);
}
return is;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
this.out = out;
this.in = in;
int n = ni();
int m = ni();
visited = new boolean[n];
low = new int[n];
tin = new int[n];
ob = new DSU(n);
graph = new ArrayList[n];
tset = new HashSet[n];
par = new int[n];
dep = new int[n];
int sq = (int) Math.sqrt(n);
if (sq * sq != n)
sq++;
int i = 0;
for (i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
tset[i] = new HashSet<>();
}
Arrays.fill(dep, -1);
for (i = 0; i < m; i++) {
int u = ni() - 1;
int v = ni() - 1;
graph[u].add(v);
graph[v].add(u);
}
dfs(0, -1, 0);
if (max_cycle >= sq) {
pn(2);
pn(max_cycle);
ArrayList<Integer> ans = new ArrayList<>();
for (i = start; i != end; i = par[i])
ans.add(i);
ans.add(end);
for (int x : ans)
p(x + 1 + " ");
return;
}
TreeSet<Integer> mis = MIS(n);
pn(1);
int c = 0;
for (int x : mis) {
p(x + 1 + " ");
c++;
if (c == sq)
break;
}
}
int ni() {
return in.nextInt();
}
void pn(long zx) {
out.println(zx);
}
void p(Object o) {
out.print(o);
}
class DSU {
int[] par;
int[] sz;
DSU(int n) {
par = new int[n];
sz = new int[n];
int i = 0;
for (i = 0; i < n; i++) {
par[i] = i;
sz[i] = 1;
}
}
}
class Pair implements Comparable<Pair> {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair other) {
if (this.x != other.x)
return this.x - other.x;
return this.y - other.y;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
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.Scanner;
public class CF1209{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
while(testCases>0){
int arrayLength = scan.nextInt();
int maxPossibleScore = scan.nextInt();
int totalSumOfScores = 0;
for(int i=0; i<arrayLength; i++){
totalSumOfScores += scan.nextInt();
}
if(totalSumOfScores<=maxPossibleScore){
System.out.println(totalSumOfScores);
}else{
System.out.println(maxPossibleScore);
}
testCases--;
}
}
}
|
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.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
for (int tc = 0; tc < q; ++tc) {
int n = sc.nextInt();
int m = sc.nextInt();
int[] t = new int[n];
int[] l = new int[n];
int[] h = new int[n];
for (int i = 0; i < n; ++i) {
t[i] = sc.nextInt();
l[i] = sc.nextInt();
h[i] = sc.nextInt();
}
System.out.println(solve(t, l, h, m) ? "YES" : "NO");
}
sc.close();
}
static boolean solve(int[] t, int[] l, int[] h, int m) {
int lower = m;
int upper = m;
for (int i = 0; i < t.length; ++i) {
int delta = t[i] - (i == 0 ? 0 : t[i - 1]);
int nextLower = Math.max(lower - delta, l[i]);
int nextUpper = Math.min(upper + delta, h[i]);
if (nextLower > nextUpper) {
return false;
}
lower = nextLower;
upper = nextUpper;
}
return true;
}
}
|
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.Arrays;
import java.util.Scanner;
import java.util.Comparator;
public class MovingPoints {
private static long sumaj(long[] arr,int index) {
long result=0;
while (index>=0) {
result+=arr[index];
index=(index&(index+1))-1;
}
return result;
}
private static void apdejt (long[] t,int index,int vv) {
while (index<t.length) {
t[index]+=vv;
index=index|(index + 1);
}
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int[][] pm=new int[n][2];
int[][] vm=new int[n][2];
for (int i=0;i<n;i++)
pm[i][0]=in.nextInt();
for (int i=0;i<n;i++) {
pm[i][1]=in.nextInt();
vm[i][0]=pm[i][1];
vm[i][1]=i;
}
in.close();
Arrays.sort(vm, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
int nss=0;
int[][] finar=new int[n][2];
for (int i=0;i<n;i++) {
if (i>0 && vm[i][0]!=vm[i-1][0])
nss++;
finar[i][0]=nss;
finar[i][1]=vm[i][1];
}
Arrays.sort(finar,new Comparator<int[]>() {
public int compare(int[] a,int[] b) {
return a[1]-b[1];
}});
for (int i=0; i<n;i++) {
pm[i][1] = finar[i][0];
}
Arrays.sort(pm,new Comparator<int[]>() {
public int compare(int[] a,int[] b) {
return a[0]-b[0];
}});
long[] c=new long[n];
long[] pts=new long[n];
long totalsum=0;
for (int i=0;i<n;i++) {
int index=pm[i][1];
totalsum+=sumaj(pts,index)*pm[i][0]-sumaj(c,index);
apdejt(pts,index,1);
//System.out.println();
//System.out.println(totalsum);
//System.out.println();
//System.out.println("coordtsum");
//for (int j=0;j<c.length;j++) {
//System.out.print(c[j]);
//}
apdejt(c, index, pm[i][0]);
//System.out.println();
//System.out.println("pointsum");
//for (int j=0;j<pts.length;j++) {
//System.out.print(pts[j]);
//}
}
//System.out.println();
System.out.println(totalsum);
}
}
|
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 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_1_Skyscrapers_easy_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);
long maxFloor = 0;
int maxFloors[] = new int[n];
int currFloors[] = new int[n];
for(int i = 0; i < n; i++) {
long currFloor = arr[i];
currFloors[i] = arr[i];
int min = arr[i];
for(int j = i+1; j < n; j++) {
min = min(min, arr[j]);
currFloors[j] = min;
currFloor += min;
}
min = arr[i];
for(int j = i-1; j >= 0; j--) {
min = min(min, arr[j]);
currFloors[j] = min;
currFloor += min;
}
if(currFloor > maxFloor) {
maxFloor = currFloor;
for(int j = 0; j < n; j++) {
maxFloors[j] = currFloors[j];
}
}
}
for(int i: maxFloors) {
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
|
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.*;
import java.util.*;
public class B {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
//int tst = Integer.parseInt(br.readLine());
int tst = 1;
while(tst-->0){
String[] str = br.readLine().split(" ");
long x0 = Long.parseLong(str[0]), y0 = Long.parseLong(str[1]);
long ax = Long.parseLong(str[2]), ay = Long.parseLong(str[3]);
long bx = Long.parseLong(str[4]), by = Long.parseLong(str[5]);
String[] s = br.readLine().split(" ");
long xs = Long.parseLong(s[0]), ys = Long.parseLong(s[1]), t = Long.parseLong(s[2]);
long[] x = new long[65];
long[] y = new long[65];
long lim = ((long)1<<56)-1;
int n = 1;
x[0] = x0;
y[0] = y0;
int bonus = (xs == x0 && ys == y0)?1:0;
while((lim-bx)/ax>=x[n-1] && (lim-by)/ay>=y[n-1]){
x[n] = ax*x[n-1] + bx;
y[n] = ay*y[n-1] + by;
bonus = Math.max((xs == x[n] && ys == y[n])?1:0, bonus);
n++;
}
int max = 0;
for(int l = 0; l<n; l++){
for(int r = l; r<n; r++){
//check if this range is poss!
long dist_x = Math.abs(x[l]-x[r]);
long dist_y = Math.abs(y[l]-y[r]);
long shrt = Math.min((Math.abs(x[r]-xs) + Math.abs(y[r]-ys)), (Math.abs(x[l]-xs)+Math.abs(y[l]-ys)));
if(dist_x+dist_y+shrt<=t){
//System.err.println(dist_x+dist_y+shrt + " "+l+" "+r+" "+(r-l+1+bonus));
max = Math.max(max, r-l+1);
}
}
}
sb.append(max).append('\n');
}
System.out.println(sb);
}
}
|
java
|
1301
|
D
|
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
|
[
"constructive algorithms",
"graphs",
"implementation"
] |
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef {
static class Pair{
int n;
String direction;
Pair(int n, String direction) {
this.n = n;
this.direction = direction;
}
}
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 0; t < test; t++) {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int total_distance = 0;
List<Pair> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
list.add(new Pair(m - 1, "R"));
total_distance += m - 1;
if (i == 1) {
list.add(new Pair(m - 1, "L"));
total_distance += m - 1;
}else {
list.add(new Pair(m - 1, "UDL"));
total_distance += 3 * (m - 1);
}
if (i == n) {
list.add(new Pair(n - 1, "U"));
total_distance += n - 1;
}else {
list.add(new Pair(1, "D"));
total_distance += 1;
}
}
if (total_distance < k ) {
out.println("NO");
continue;
}
String temp = "";
int curr = 0;
while (total_distance > k) {
temp = list.get(list.size() - 1).direction;
curr = list.get(list.size() - 1).n * temp.length();
list.remove(list.get(list.size() - 1));
total_distance -= curr;
if (total_distance > k) {
continue;
}
curr = k - total_distance;
if (curr / temp.length() > 0) {
list.add(new Pair(curr / temp.length(), temp));
}
if (curr % temp.length() > 0){
temp = temp.substring(0, curr % temp.length());
list.add(new Pair(1, temp));
}
total_distance = k;
}
out.println("YES");
int count = 0;
for (Pair p : list) {
if (p.n == 0) count++;
}
out.println(list.size() - count);
for(Pair p : list) {
if (p.n == 0) {
continue;
}
out.println(p.n + " " + p.direction);
}
}
out.close();
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
java
|
1286
|
B
|
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2
|
[
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] |
import java.io.*;
import java.math.*;
import java.util.*;
// @author : Dinosparton
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static int dfs(int src,int par,ArrayList<Integer> adj[],int child[]) {
int node = 1;
for(int i : adj[src]) {
if( i == par) {
continue;
}
node += dfs(i,src,adj,child);
}
child[src] = node - 1;
return node;
}
static int get(int pos,ArrayList<Integer> list) {
int ans = list.get(pos);
for(int i=pos;i<list.size()-1;i++) {
list.set(i, list.get(i+1));
}
list.remove(list.size()-1);
return ans;
}
static void dfs(int src,int par,ArrayList<Integer> adj[],int ans[],int c[],ArrayList<Integer> list) {
ans[src] = get(c[src],list);
for(int i : adj[src]) {
if(i == par) {
continue;
}
dfs(i,src,adj,ans,c,list);
}
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuilder res = new StringBuilder();
int tc = 1;
while(tc-->0) {
int n = sc.nextInt();
ArrayList<Integer> adj[] = new ArrayList[n];
for(int i=0;i<n;i++) {
adj[i] = new ArrayList<>();
}
int root = -1;
int c[] = new int[n];
for(int i=0;i<n;i++) {
int par = sc.nextInt();
int val = sc.nextInt();
if(par != 0) {
par--;
adj[par].add(i);
adj[i].add(par);
}
else {
root = i;
}
c[i] = val;
}
int child[] = new int[n];
dfs(root,-1,adj,child);
// for(int i=0;i<n;i++) {
// System.out.print(child[i]+" ");
// }
// System.out.println();
boolean ok = true;
for(int i=0;i<n;i++) {
if(child[i] < c[i]) {
ok = false;
break;
}
}
if(!ok) {
res.append("NO"+"\n");
continue;
}
int ans[] = new int[n];
ArrayList<Integer> list = new ArrayList<>();
for(int i = 1;i<=n;i++) {
list.add(i);
}
dfs(root,-1,adj,ans,c,list);
res.append("YES"+"\n");
for(int i=0;i<n;i++) {
res.append(ans[i]+" ");
}
}
System.out.println(res);
}
}
|
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.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);
CEhabTheXorcist solver = new CEhabTheXorcist();
solver.solve(1, in, out);
out.close();
}
static class CEhabTheXorcist {
public void solve(int testNumber, InputReader in, OutputWriter out) {
long u = in.nextLong(), v = in.nextLong();
if (v % 2 == 1 && u % 2 == 0 || (v % 2 == 0 && u % 2 == 1)) {
out.println(-1);
return;
}
if (u == 0 && v == 0) {
out.println(0);
} else if (u == v) {
out.println(1);
out.println(u);
} else if (u > v) {
out.println(-1);
} else {
long x = (v - u) / 2;
if ((x & u) == 0) {
out.println(2);
out.println((x + u) + " " + x);
} else {
out.println(3);
out.println(u + " " + x + " " + x);
}
}
}
}
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 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 print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
public void println(int i) {
writer.println(i);
}
}
}
|
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 ArraySharpening {
private static String solve(int n, long[] arr){
int leftIndex=-1,rightIndex=-1;
for(int i=0;i<n;i++){
if(arr[i]<i){
leftIndex = i-1;
break;
}
}
for(int i=n-1;i>=0;i--){
if(arr[i]<n-i-1){
rightIndex=i+1;
break;
}
}
// System.out.println(leftIndex +" "+rightIndex);
if(leftIndex==-1 || rightIndex==-1 || (leftIndex>=rightIndex))
return "Yes";
return "No";
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while(t>0){
int n = scanner.nextInt();
long[] arr = new long[n];
for(int i=0;i<n;i++){
arr[i] = scanner.nextLong();
}
System.out.println(solve(n,arr));
t--;
}
}
}
|
java
|
1322
|
C
|
C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.
|
[
"graphs",
"hashing",
"math",
"number theory"
] |
//package round626;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.Random;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
for(int T = ni();T > 0;T--){
go();
}
}
class Datum
{
int[] row;
int id;
public Datum(int[] row, int id) {
this.row = row;
this.id = id;
}
}
void go()
{
int n = ni(), m = ni();
long[] a = new long[n];
for(int i = 0;i < n;i++)a[i] = nl();
int[] from = new int[m];
int[] to = new int[m];
for(int i = 0;i < m;i++){
from[i] = ni()-1;
to[i] = ni()-1;
}
int[][] ig = packD(n, to, from);
Random gen = new Random();
for(int[] row : ig){
shuffle(row, gen);
Arrays.sort(row);
}
Datum[] ds = new Datum[n];
for(int i = 0;i < n;i++){
ds[i] = new Datum(ig[i], i);
}
Arrays.sort(ds, new Comparator<Datum>() {
public int compare(Datum x, Datum y) {
int[] a = x.row;
int[] b = y.row;
for(int i = 0;i < a.length && i < b.length;i++){
if(a[i] != b[i])return a[i] - b[i];
}
return a.length - b.length;
}
});
long ans = 0;
for(int i = 0;i < n;){
int j = i;
while(j < n && Arrays.equals(ds[i].row, ds[j].row))j++;
if(ds[i].row.length > 0){
long s = 0;
for(int k = i;k < j;k++){
s += a[ds[k].id];
}
ans = gcd(ans, s);
}
i = j;
}
out.println(ans);
}
public static int[] shuffle(int[] a, Random gen){ for(int i = 0, n = a.length;i < n;i++){ int ind = gen.nextInt(n-i)+i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; }
public static long gcd(long a, long b) {
while (b > 0) {
long c = a;
a = b;
b = c % b;
}
return a;
}
static int[][] packD(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int i = 0; i < n; i++)
g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) {
g[from[i]][--p[from[i]]] = to[i];
}
return g;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new C().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
java
|
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"
] |
// Problem: F2. Same Sum Blocks (Hard)
// Contest: Codeforces - Codeforces Round #547 (Div. 3)
// URL: https://codeforces.com/problemset/problem/1141/F2
// Memory Limit: 256 MB
// Time Limit: 3000 ms
// author: zdkk
import java.io.*;
import java.util.*;
public class Main {
static IntReader in;
static FastWriter out;
static String INPUT = "";
static final int N = 1510;
static int[] a = new int[N];
static int n;
static void solve() {
n = ni();
for (int i = 1; i <= n; i++) a[i] = ni();
Map<Integer, List<int[]>> map = new HashMap<>();
for (int i = 1; i <= n; i++) {
int s = 0;
for (int j = i; j >= 1; j--) {
s += a[j];
map.computeIfAbsent(s, key -> new ArrayList<>()).add(new int[]{j, i});
}
}
List<int[]> res = new ArrayList<>();
for (int key : map.keySet()) {
List<int[]> t = map.get(key);
if (t.size() <= res.size()) continue;
int pre = Integer.MIN_VALUE;
List<int[]> list = new ArrayList<>();
for (int[] p : t) {
if (p[0] > pre) {
list.add(p);
pre = p[1];
}
}
if (list.size() > res.size()) {
res = list;
}
}
out.println(res.size());
for (int[] p : res) {
out.println(p[0] + " " + p[1]);
}
}
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
|
1293
|
B
|
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.
|
[
"combinatorics",
"greedy",
"math"
] |
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner dp=new Scanner(System.in);
int x,y;double sum=0;
int n=dp.nextInt();
for(int i=n;i>=1;i--){
sum+=1/(double)i;
}
System.out.println(String.format("%.12f",sum));
}
}
|
java
|
1304
|
E
|
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
|
[
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1304e_3 {
static int euler[], first[], dep[], p = 0;
static sptb rmq;
public static void main(String[] args) throws IOException {
int n = ri();
euler = new int[2 * n - 1];
first = new int[n];
dep = new int[n];
List<List<Integer>> g = rg(n, n - 1);
dfs(g, 0, -1);
rmq = new sptb(euler, (a, b) -> first[a] < first[b] ? a : b);
int q = ri();
while (q --> 0) {
int x = rni() - 1, y = ni() - 1, a = ni() - 1, b = ni() - 1, k = ni(), d;
d = dist(a, b);
if (k >= d && (k - d) % 2 == 0) {
prY();
continue;
}
d = dist(a, x) + 1 + dist(y, b);
if (k >= d && (k - d) % 2 == 0) {
prY();
continue;
}
d = dist(a, y) + 1 + dist(x, b);
if (k >= d && (k - d) % 2 == 0) {
prY();
continue;
}
prN();
}
close();
}
static int dist(int a, int b) {
int lca = lca(a, b);
return (dep[a] - dep[lca]) + (dep[b] - dep[lca]);
}
static int lca(int a, int b) {
return rmq.qry(min(first[a], first[b]), max(first[a], first[b]) + 1);
}
@FunctionalInterface
interface IntOperator {
int merge(int a, int b);
}
// cannot use with summation
static class sptb {
IntOperator op;
int n, lg[], lookup[][];
sptb(int[] a, IntOperator operator) {
n = a.length;
lg = new int[n + 1];
int pow2 = 4;
for (int i = 2, ind = 1; i <= n; ++i) {
if (pow2 == i) {
++ind;
pow2 <<= 1;
}
lg[i] = ind;
}
op = operator;
lookup = new int[n][lg[n] + 1];
for (int i = 0; i < n; ++i) {
lookup[i][0] = a[i];
}
for (int j = 1; (1 << j) <= n; ++j) {
for (int i = 0; (i + (1 << j)) <= n; ++i) {
lookup[i][j] = op.merge(lookup[i][j - 1], lookup[i + (1 << (j - 1))][j - 1]);
}
}
}
int qry(int l, int r) {
int j = lg[r - l];
return op.merge(lookup[l][j], lookup[r - (1 << j)][j]);
}
}
static void dfs(List<List<Integer>> g, int i, int par) {
if (par == -1) {
dep[i] = 0;
} else {
dep[i] = dep[par] + 1;
}
euler[p] = i;
first[i] = p++;
for (int n : g.get(i)) {
if (n != par) {
dfs(g, n, i);
euler[p++] = i;
}
}
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int)d;}
static int cei(double d) {return (int)ceil(d);}
static long fll(double d) {return (long)d;}
static long cel(double d) {return (long)ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// graph util
static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for(int i = 0; i < n; ++i) a[i] = nl(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(double... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();}
static void h() {__out.println("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
}
|
java
|
1141
|
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()) {
List<Segment> blocksTaken = new ArrayList<>();
int lastBlockEnd = -1, totalBlocks = 0;
for (Segment segment : segmentsWithParticularSum.get(blockSum)) {
if (segment.start > lastBlockEnd) {
totalBlocks++;
blocksTaken.add(segment);
lastBlockEnd = segment.end;
}
}
if (totalBlocks > maxTotalBlocks) {
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
|
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.io.*;
import java.math.BigInteger;
import java.util.*;
/**
*
* @author eslam
*/
public class Solution {
// Beginning of the solution
static Kattio input = new Kattio();
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>();
static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>();
static ArrayList<LinkedList<String>> allprems = new ArrayList<>();
static ArrayList<Long> luc = new ArrayList<>();
static long mod = (long) (Math.pow(10, 9) + 7);
static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}};
static int dp[][];
static double cmp = 0.000000001;
public static void main(String[] args) throws IOException {
//Kattio input = new Kattio("input");
//BufferedWriter log = new BufferedWriter(new FileWriter("output.txt"));
int test = input.nextInt();
loop:
for (int o = 1; o <= test; o++) {
long x = input.nextInt();
long y = input.nextInt();
long a = input.nextInt();
long b = input.nextInt();
long max = (long) 1e9;
long min = 0;
long ans = -1;
while (max >= min) {
long mid = (max + min) / 2;
if (x + a * mid == y - b * mid) {
ans = mid;
break;
} else if (x + a * mid > y - b * mid) {
max = mid - 1;
} else {
min = mid + 1;
}
}
log.write(ans + "\n");
}
log.flush();
}
static int get(int x) {
int cnt = 0;
while (x > 0) {
cnt++;
x /= 10;
}
return cnt;
}
static Comparator<tri> cmpTri() {
Comparator<tri> c = new Comparator<tri>() {
@Override
public int compare(tri o1, tri o2) {
if (o1.x > o2.x) {
return 1;
} else if (o1.x < o2.x) {
return -1;
} else {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
if (o1.z > o2.z) {
return 1;
} else if (o1.z < o2.z) {
return -1;
} else {
return 0;
}
}
}
}
};
return c;
}
static Comparator<pair> cmpPair() {
Comparator<pair> c = new Comparator<pair>() {
@Override
public int compare(pair o1, pair o2) {
if (o1.x > o2.x) {
return 1;
} else if (o1.x < o2.x) {
return -1;
} else {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
return 0;
}
}
}
};
return c;
}
static class rec {
long x1;
long x2;
long y1;
long y2;
public rec(long x1, long y1, long x2, long y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public long getArea() {
return (x2 - x1) * (y2 - y1);
}
}
static int sumOfRange(int x1, int y1, int x2, int y2, int e, int a[][][]) {
return (a[e][x2][y2] - a[e][x1 - 1][y2] - a[e][x2][y1 - 1]) + a[e][x1 - 1][y1 - 1];
}
public static int[][] bfs(int i, int j, String w[]) {
Queue<pair> q = new ArrayDeque<>();
q.add(new pair(i, j));
int dis[][] = new int[w.length][w[0].length()];
for (int k = 0; k < w.length; k++) {
Arrays.fill(dis[k], -1);
}
dis[i][j] = 0;
while (!q.isEmpty()) {
pair p = q.poll();
int cost = dis[p.x][p.y];
for (int k = 0; k < 4; k++) {
int nx = p.x + grid[0][k];
int ny = p.y + grid[1][k];
if (isValid(nx, ny, w.length, w[0].length())) {
if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') {
q.add(new pair(nx, ny));
dis[nx][ny] = cost + 1;
}
}
}
}
return dis;
}
public static void dfs(int node, ArrayList<Integer> a[], boolean vi[]) {
vi[node] = true;
for (Integer ch : a[node]) {
if (!vi[ch]) {
dfs(ch, a, vi);
}
}
}
public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException {
for (int i = 0; i < a.length; i++) {
a[i] = new ArrayList<>();
}
while (q-- > 0) {
int x = input.nextInt();
int y = input.nextInt();
a[x].add(y);
a[y].add(x);
}
}
public static boolean isValid(int i, int j, int n, int m) {
return (i > -1 && i < n) && (j > -1 && j < m);
}
// present in the left and right indices
public static int[] swap(int data[], int left, int right) {
// Swap the data
int temp = data[left];
data[left] = data[right];
data[right] = temp;
// Return the updated array
return data;
}
// Function to reverse the sub-array
// starting from left to the right
// both inclusive
public static int[] reverse(int data[], int left, int right) {
// Reverse the sub-array
while (left < right) {
int temp = data[left];
data[left++] = data[right];
data[right--] = temp;
}
// Return the updated array
return data;
}
// Function to find the next permutation
// of the given integer array
public static boolean findNextPermutation(int data[]) {
// If the given dataset is empty
// or contains only one element
// next_permutation is not possible
if (data.length <= 1) {
return false;
}
int last = data.length - 2;
// find the longest non-increasing suffix
// and find the pivot
while (last >= 0) {
if (data[last] < data[last + 1]) {
break;
}
last--;
}
// If there is no increasing pair
// there is no higher order permutation
if (last < 0) {
return false;
}
int nextGreater = data.length - 1;
// Find the rightmost successor to the pivot
for (int i = data.length - 1; i > last; i--) {
if (data[i] > data[last]) {
nextGreater = i;
break;
}
}
// Swap the successor and the pivot
data = swap(data, nextGreater, last);
// Reverse the suffix
data = reverse(data, last + 1, data.length - 1);
// Return true as the next_permutation is done
return true;
}
public static pair[] dijkstra(int node, ArrayList<pair> a[]) {
PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() {
@Override
public int compare(tri o1, tri o2) {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
return 0;
}
}
});
q.add(new tri(node, 0, -1));
pair distance[] = new pair[a.length];
while (!q.isEmpty()) {
tri p = q.poll();
int cost = p.y;
if (distance[p.x] != null) {
continue;
}
distance[p.x] = new pair(p.z, cost);
ArrayList<pair> nodes = a[p.x];
for (pair node1 : nodes) {
if (distance[node1.x] == null) {
tri pa = new tri(node1.x, cost + node1.y, p.x);
q.add(pa);
}
}
}
return distance;
}
public static String revs(String w) {
String ans = "";
for (int i = w.length() - 1; i > -1; i--) {
ans += w.charAt(i);
}
return ans;
}
public static boolean isPalindrome(String w) {
for (int i = 0; i < w.length() / 2; i++) {
if (w.charAt(i) != w.charAt(w.length() - i - 1)) {
return false;
}
}
return true;
}
public static void getPowerSet(Queue<Integer> a) {
int n = a.poll();
if (!a.isEmpty()) {
getPowerSet(a);
}
int s = powerSet.size();
for (int i = 0; i < s; i++) {
ArrayList<Integer> ne = new ArrayList<>();
ne.add(n);
for (int j = 0; j < powerSet.get(i).size(); j++) {
ne.add(powerSet.get(i).get(j));
}
powerSet.add(ne);
}
ArrayList<Integer> p = new ArrayList<>();
p.add(n);
powerSet.add(p);
}
public static int getlo(int va) {
int v = 1;
while (v <= va) {
if ((va&v) != 0) {
return v;
}
v <<= 1;
}
return 0;
}
static long fast_pow(long a, long p, long mod) {
long res = 1;
while (p > 0) {
if (p % 2 == 0) {
a = (a * a) % mod;
p /= 2;
} else {
res = (res * a) % mod;
p--;
}
}
return res;
}
public static int countPrimeInRange(int n, boolean isPrime[]) {
int cnt = 0;
Arrays.fill(isPrime, true);
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * 2; j <= n; j += i) {
isPrime[j] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
cnt++;
}
}
return cnt;
}
public static void create(long num) {
luc.add(num);
if (num > power(10, 9)) {
return;
}
create(num * 10 + 4);
create(num * 10 + 7);
}
public static long ceil(long a, long b) {
return (a + b - 1) / b;
}
public static long round(long a, long b) {
if (a < 0) {
return (a - b / 2) / b;
}
return (a + b / 2) / b;
}
public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) {
if (l.size() == st.size()) {
allprems.add(l);
}
for (int i = 0; i < st.size(); i++) {
if (!visited[i]) {
visited[i] = true;
LinkedList<String> nl = new LinkedList<>();
for (String x : l) {
nl.add(x);
}
nl.add(st.get(i));
allPremutationsst(nl, visited, st);
visited[i] = false;
}
}
}
public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) {
if (l.size() == a.length) {
allprem.add(l);
}
for (int i = 0; i < a.length; i++) {
if (!visited[i]) {
visited[i] = true;
LinkedList<Integer> nl = new LinkedList<>();
for (Integer x : l) {
nl.add(x);
}
nl.add(a[i]);
allPremutations(nl, visited, a);
visited[i] = false;
}
}
}
public static int binarySearch(long[] a, long value) {
int l = 0;
int r = a.length - 1;
while (l <= r) {
int m = (l + r) / 2;
if (a[m] == value) {
return m;
} else if (a[m] > value) {
r = m - 1;
} else {
l = m + 1;
}
}
return -1;
}
public static void reverse(int l, int r, char ch[]) {
for (int i = 0; i < r / 2; i++) {
char c = ch[i];
ch[i] = ch[r - i - 1];
ch[r - i - 1] = c;
}
}
public static int logK(long v, long k) {
int ans = 0;
while (v > 1) {
ans++;
v /= k;
}
return ans;
}
public static long power(long a, long n) {
if (n == 1) {
return a;
}
long pow = power(a, n / 2);
pow *= pow;
if (n % 2 != 0) {
pow *= a;
}
return pow;
}
public static long get(long max, long x) {
if (x == 1) {
return max;
}
int cnt = 0;
while (max > 0) {
cnt++;
max /= x;
}
return cnt;
}
public static int numOF0(long v) {
long x = 1;
int cnt = 0;
while (x <= v) {
if ((x & v) == 0) {
cnt++;
}
x <<= 1;
}
return cnt;
}
public static int log2(double n) {
int cnt = 0;
while (n > 1) {
n /= 2;
cnt++;
}
return cnt;
}
public static int[] bfs(int node, ArrayList<Integer> a[]) {
Queue<Integer> q = new LinkedList<>();
q.add(node);
int distances[] = new int[a.length];
Arrays.fill(distances, -1);
distances[node] = 0;
while (!q.isEmpty()) {
int parent = q.poll();
ArrayList<Integer> nodes = a[parent];
int cost = distances[parent];
for (Integer node1 : nodes) {
if (distances[node1] == -1) {
q.add(node1);
distances[node1] = cost + 1;
}
}
}
return distances;
}
public static ArrayList<Integer> primeFactors(int n) {
ArrayList<Integer> a = new ArrayList<>();
while (n % 2 == 0) {
a.add(2);
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i == 0) {
a.add(i);
n /= i;
}
if (n < i) {
break;
}
}
if (n > 2) {
a.add(n);
}
return a;
}
public static ArrayList<Integer> printPrimeFactoriztion(int n) {
ArrayList<Integer> a = new ArrayList<>();
for (int i = 1; i < Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
if (isPrime(i)) {
a.add(i);
n /= i;
i = 0;
} else if (isPrime(n / i)) {
a.add(n / i);
n = i;
i = 0;
}
}
}
return a;
}
// end of solution
public static BigInteger f(long n) {
if (n <= 1) {
return BigInteger.ONE;
}
long t = n - 1;
BigInteger b = new BigInteger(t + "");
BigInteger ans = new BigInteger(n + "");
while (t > 1) {
ans = ans.multiply(b);
b = b.subtract(BigInteger.ONE);
t--;
}
return ans;
}
public static long factorial(long n) {
if (n <= 1) {
return 1;
}
long t = n - 1;
while (t > 1) {
n = mod((mod(n, mod) * mod(t, mod)), mod);
t--;
}
return n;
}
public static long rev(long n) {
long t = n;
long ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans;
}
public static boolean isPalindrome(int n) {
int t = n;
int ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans == n;
}
static class tri {
int x, y, z;
public tri(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public String toString() {
return x + " " + y + " " + z;
}
}
static boolean isPrime(long num) {
if (num == 1) {
return false;
}
if (num == 2) {
return true;
}
if (num % 2 == 0) {
return false;
}
if (num == 3) {
return true;
}
for (int i = 3; i <= Math.sqrt(num) + 1; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void prefixSum(int[] a) {
for (int i = 1; i < a.length; i++) {
a[i] = a[i] + a[i - 1];
}
}
public static void suffixSum(long[] a) {
for (int i = a.length - 2; i > -1; i--) {
a[i] = a[i] + a[i + 1];
}
}
static long mod(long a, long b) {
long r = a % b;
return r < 0 ? r + b : r;
}
public static long binaryToDecimal(String w) {
long r = 0;
long l = 0;
for (int i = w.length() - 1; i > -1; i--) {
long x = (w.charAt(i) - '0') * (long) Math.pow(2, l);
r = r + x;
l++;
}
return r;
}
public static String decimalToBinary(long n) {
String w = "";
while (n > 0) {
w = n % 2 + w;
n /= 2;
}
return w;
}
public static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] >= a[i + 1]) {
return false;
}
}
return true;
}
public static void print(int[] a) throws IOException {
for (int i = 0; i < a.length; i++) {
log.write(a[i] + " ");
}
log.write("\n");
}
public static void read(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = input.nextInt();
}
}
static class gepair {
long x;
long y;
public gepair(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
static class pair {
int x;
int y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
static class pai {
long x;
int y;
public pai(long x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
public static long LCM(long x, long y) {
return x / GCD(x, y) * y;
}
public static long GCD(long x, long y) {
if (y == 0) {
return x;
}
return GCD(y, x % y);
}
public static void simplifyTheFraction(int a, int b) {
long GCD = GCD(a, b);
System.out.println(a / GCD + " " + b / GCD);
}
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(problemName + ".out");
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
String nextLine() {
String str = "";
try {
str = r.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
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
|
1311
|
A
|
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.
|
[
"greedy",
"implementation",
"math"
] |
import java.util.*;
public class SolveJava{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int ts = in.nextInt();
while(ts-- > 0){
int a = in.nextInt(), b, x = 0, y = 0;
b = in.nextInt();
if(a % 2 == 1) x = 1;
if(b % 2 == 1) y = 1;
if(a == b) System.out.println(0);
else if(x == 1 && y == 1 && a > b) System.out.println(1);
else if(x == 0 && y == 1 && b > a) System.out.println(1);
else if(x == 1 && y == 0 && b > a) System.out.println(1);
else if(x == 0 && y == 0 && a > b) System.out.println(1);
else if(x == 1 && y == 0 && a > b) System.out.println(2);
else if(x == 1 && y == 1 && b > a) System.out.println(2);
else if(x == 0 && y == 1 && a > b) System.out.println(2);
else System.out.println(2);
}
}
}
|
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.math.*;
import java.util.*;
// @author : Dinosparton
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuilder res = new StringBuilder();
int tc = 1;
while(tc-->0) {
int n = sc.nextInt();
String s = sc.next();
char a[] = s.toCharArray();
Arrays.sort(a);
// System.out.println(a);
ArrayList<Integer> adj[] = new ArrayList[26];
for(int i=0;i<26;i++) {
adj[i] = new ArrayList<>();
}
for(int i=0;i<n;i++) {
adj[a[i]-'a'].add(i);
}
int dir[] = new int[n];
for(int i=0;i<n;i++) {
if(i < adj[s.charAt(i)-'a'].get(0)) {
dir[i] = 1;
adj[s.charAt(i)-'a'].remove(0);
}
else if(i > adj[s.charAt(i)-'a'].get(0)) {
dir[i] = -1;
adj[s.charAt(i)-'a'].remove(0);
}
}
boolean ok = true;
int min = -1;
for(int i=0;i<n;i++) {
if(dir[i] == 1) {
if(min > s.charAt(i) - 'a') {
// System.out.println(i + " " + min);
ok = false;
}
else {
min = s.charAt(i) - 'a';
}
}
}
min = 26;
for(int i=n-1;i>=0;i--) {
if(dir[i] == -1) {
if(min < s.charAt(i) - 'a') {
// System.out.println(i + " " + min+" second");
ok = false;
}
else {
min = s.charAt(i) - 'a';
}
}
}
for(int i=0;i<n;i++) {
if(dir[i] == 0) {
for(int j=i-1;j>=0;j--) {
if(s.charAt(j) > s.charAt(i)) {
ok = false;
break;
}
}
for(int j=i+1;j<n;j++) {
if(s.charAt(j) < s.charAt(i)) {
ok = false;
break;
}
}
}
}
if(ok) {
res.append("YES"+"\n");
for(int i=0;i<n;i++) {
if(dir[i]==1) {
res.append(1);
}
else {
res.append(0);
}
}
res.append("\n");
}
else {
res.append("NO"+"\n");
}
}
System.out.println(res);
}
}
|
java
|
1325
|
B
|
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].
|
[
"greedy",
"implementation"
] |
import java.util.*;
public class hello{
public static void main(String []args){
Scanner inp =new Scanner(System.in);
int t=inp.nextInt();
while(t-->0){
int n=inp.nextInt();
int []arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=inp.nextInt();
}
Arrays.sort(arr);
int uni=1; //find unique elements!!
for(int i=0;i<n-1;i++){
if(arr[i]!=arr[i+1]) uni++;
}
System.out.println(uni);
}
}
}
|
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"
] |
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Submit {
public static void main(String[] pojebaneArgumenty) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
FastReader reader = new FastReader()) {
int t = reader.nextInt();
int g;
String s;
while (t-- > 0) {
g = reader.nextInt();
s = reader.nextLine();
int counter = 0, max = 0;
if (s.indexOf('A') >= 0) {
for (int i = s.indexOf('A') + 1; i < g; i++) {
if (s.charAt(i) == 'P') {
counter++;
if (max < counter) {
max = counter;
}
} else {
counter = 0;
}
}
}
writer.append(max + System.lineSeparator());
writer.flush();
}
}
}
}
class FastReader implements AutoCloseable {
private BufferedReader reader;
private StringTokenizer tokenizer;
public FastReader() {
this.reader = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreElements()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
while (tokenizer == null || !tokenizer.hasMoreElements()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return Integer.parseInt(tokenizer.nextToken());
}
public String nextLine() {
String line = "";
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
public char nextChar() {
char character = ' ';
try {
character = (char) reader.read();
} catch (IOException ex) {
ex.printStackTrace();
}
return character;
}
@Override
public void close() {
try {
this.reader.close();
} catch (IOException closingEx) {
// ignore
}
}
}
|
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 javax.print.DocFlavor.INPUT_STREAM;
import java.io.*;
import java.math.*;
import java.sql.Array;
import java.sql.SQLIntegrityConstraintViolationException;
public class Main {
private static class MyScanner {
private static final int BUF_SIZE = 2048;
BufferedReader br;
private MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private boolean isSpace(char c) {
return c == '\n' || c == '\r' || c == ' ';
}
String next() {
try {
StringBuilder sb = new StringBuilder();
int r;
while ((r = br.read()) != -1 && isSpace((char)r));
if (r == -1) {
return null;
}
sb.append((char) r);
while ((r = br.read()) != -1 && !isSpace((char)r)) {
sb.append((char)r);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static long mod_mul( long... a) {
long ans = a[0]%mod;
for(int i = 1 ; i<a.length ; i++) {
ans = (ans * (a[i]%mod))%mod;
}
return ans;
}
static long mod_sum( long... a) {
long ans = 0;
for(long e:a) {
ans = (ans + e)%mod;
}
return ans;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void print(long[] arr) {
System.out.println("---print---");
for(long e:arr) System.out.print(e+" ");
System.out.println("-----------");
}
static void print(int[] arr) {
System.out.println("---print---");
for(long e:arr) System.out.print(e+" ");
System.out.println("-----------");
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2);
}
static long lcm(long a , long b) {
return (a*b)/gcd(a, b);
}
static int lcm(int a , int b) {
return (int)((a*b)/gcd(a, b));
}
static long power(long x, long y){
if(y<0) return 0;
long m = mod;
if (y == 0) return 1; long p = power(x, y / 2) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z; // factorial
private long[] z1; // inverse factorial
private long[] z2; // incerse number
private long mod;
public Combinations(long N , long mod) {
this.mod = mod;
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return z1[(int)n];
}
long ncr(long N, long R)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int max(int... a ) {
int max = a[0];
for(int e:a) max = Math.max(max, e);
return max;
}
static long max(long... a ) {
long max = a[0];
for(long e:a) max = Math.max(max, e);
return max;
}
static int min(int... a ) {
int min = a[0];
for(int e:a) min = Math.min(e, min);
return min;
}
static long min(long... a ) {
long min = a[0];
for(long e:a) min = Math.min(e, min);
return min;
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.min(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = gcd(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(0);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return gcd(left, right);
}
public void update(int index , int val) {
arr[index] = val;
// for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
/* ***************************************************************************************************************************************************/
// static MyScanner sc = new MyScanner(); // only in case of less memory
static Reader sc = new Reader();
static int TC;
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
// tc = sc.nextInt();
TC = 0;
for(int i = 1 ; i<=tc ; i++) {
TC++;
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.print(sb);
}
static class Pair implements Comparable<Pair>{
int p;
int t;
Pair(int p , int t){
this.p = p;
this.t = t;
}
public int compareTo(Pair o) {
return Integer.compare(o.t, this.t);
}
}
static void TEST_CASE() {
int n = sc.nextInt();
int[] p = new int[n];
int[] t = new int[n];
for(int i = 0 ;i<n ; i++)
p[i] = sc.nextInt();
for(int i = 0 ;i<n ; i++)
t[i] = sc.nextInt();
TreeMap<Integer , PriorityQueue<Integer>> map = new TreeMap<>();
for(int i = 0 ;i<n ; i++) {
if(!map.containsKey(p[i])) map.put(p[i], new PriorityQueue<>(Comparator.reverseOrder()));
map.get(p[i]).add(t[i]);
}
PriorityQueue<Pair> pq = new PriorityQueue<>();
long ans = 0;
long pow = 0;
while(!map.isEmpty()) {
int k = map.firstKey();
PriorityQueue<Integer> q = map.get(k);
map.pollFirstEntry();
if(pq.isEmpty()) {
q.poll();
while(!q.isEmpty()) {
pq.add(new Pair(k, q.poll()));
}
pow = k+1;
}else {
while(pow < k && !pq.isEmpty()) {
Pair pp = pq.poll();
ans += (pow-pp.p)*pp.t;
pow++;
}
while(!q.isEmpty()) {
pq.add(new Pair(k, q.poll()));
}
Pair pp = pq.poll();
ans += (k-pp.p)*pp.t;
pow = k+1;
}
}
while( !pq.isEmpty()) {
Pair pp = pq.poll();
ans += (pow-pp.p)*pp.t;
pow++;
}
System.out.println(ans);
}
}
/*******************************************************************************************************************************************************/
/**
*/
|
java
|
1307
|
E
|
E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000) — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n) — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n) — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2
1 1 1 1 1
1 2
1 3
OutputCopy2 2
InputCopy5 2
1 1 1 1 1
1 2
1 4
OutputCopy1 4
InputCopy3 2
2 3 2
3 1
2 1
OutputCopy2 4
InputCopy5 1
1 1 1 1 1
2 5
OutputCopy0 1
NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.
|
[
"binary search",
"combinatorics",
"dp",
"greedy",
"implementation",
"math"
] |
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.stream.IntStream;
public class Main {
static {
Locale.setDefault(Locale.ENGLISH);
}
private static DecimalFormat decimalFormat = new DecimalFormat("#0.00000000");
private static class Reader implements Closeable {
private BufferedReader reader;
private StringTokenizer tokenizer;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String fileName) {
try {
reader = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
throw new IllegalStateException("There is no file with given name");
}
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String nextLine = reader.readLine();
if (nextLine == null) {
return null;
}
tokenizer = new StringTokenizer(nextLine);
} catch (IOException e) {
throw new IllegalStateException("I/O Error");
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
@Override
public void close() throws IOException {
reader.close();
}
}
private static class Pair implements Comparable<Pair> {
private int x;
private int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public int compareTo(Pair o) {
if (this.x != o.x) return Integer.compare(this.x, o.x);
return Integer.compare(this.y, o.y);
}
}
private <T> ArrayList<T> createArrayList(int n, T value) {
ArrayList<T> result = new ArrayList<>();
IntStream.range(0, n).forEach(i -> result.add(value));
return result;
}
public static void main(String[] args) throws IOException {
Reader reader = new Reader();
//Reader reader = new Reader("input.txt");
PrintWriter writer = new PrintWriter(System.out);
new Main().solve(reader, writer);
reader.close();
writer.close();
}
private static class Cow {
private int l;
private int r;
public Cow(int l, int r) {
this.l = l;
this.r = r;
}
public int getL() {
return l;
}
public int getR() {
return r;
}
}
private void solve(Reader reader, PrintWriter writer) {
int n = reader.nextInt();
int m = reader.nextInt();
ArrayList<Integer> s = new ArrayList<>();
boolean[] s1 = new boolean[5001];
boolean[] s2 = new boolean[5001];
for (int i = 0; i < n; ++i) {
s.add(reader.nextInt());
s1[s.get(s.size() - 1)] = true;
}
ArrayList<Cow>[] cowsByF = new ArrayList[5001];
for (int i = 1; i <= n; ++i) {
cowsByF[i] = new ArrayList<>();
}
boolean[] used = new boolean[5000];
for (int i = 0; i < m; ++i) {
int f = reader.nextInt();
int h = reader.nextInt();
int l = -1;
int r = -1;
s2[f] = true;
int counter = 0;
for (int j = 0; j < n; ++j) {
if (s.get(j) == f) {
counter++;
if (counter == h) {
l = j;
break;
}
}
}
counter = 0;
for (int j = n - 1; j >= 0; --j) {
if (s.get(j) == f) {
counter++;
if (counter == h) {
r = j;
break;
}
}
}
if (l != -1) {
used[l] = true;
cowsByF[f].add(new Cow(l, r));
}
}
int bestResult = 0;
long bestCount = 0;
for (int i = -1; i < n; ++i) { //граница разделения
if (i > -1 && !used[i]) {
continue;
}
int result = 0;
long count = 1;
boolean usedProperCow = false;
for (int j = 1; j <= n; ++j) { //уровень сладости
if (!s1[j] && !s2[j]) {
continue;
}
boolean usedProperCowAtJ = false;
int l = 0;
int r = 0;
int mixed = 0;
for (Cow cow : cowsByF[j]) {
if (cow.l == i) {
usedProperCow = true;
usedProperCowAtJ = true;
continue;
}
if (cow.l <= i && cow.r <= i) {
l++;
}
if (cow.l > i && cow.r > i) {
r++;
}
if (cow.l <= i && cow.r > i) {
mixed++;
}
}
if (usedProperCowAtJ) {
if (r + mixed == 0) {
result += 1;
continue;
} else {
result += 2;
int mult = r + mixed;
count *= mult;
if (count > 1000000007) {
count %= 1000000007;
}
continue;
}
}
if (l + r + mixed == 0) {
continue;
}
if (mixed + (l > 0 ? 1 : 0) + (r > 0 ? 1 : 0) > 1) {
result += 2;
int mult = l * mixed + r * mixed + mixed * (mixed - 1);
count *= mult;
} else {
result += 1;
int mult = l + r + mixed * 2;
count *= mult;
}
if (count > 1000000007) {
count %= 1000000007;
}
}
if (result > bestResult) {
bestResult = result;
bestCount = count;
} else if (result == bestResult && (i == -1 || usedProperCow)) {
bestCount += count;
bestCount %= 1000000007;
}
}
writer.println(bestResult + " " + bestCount);
}
}
|
java
|
1299
|
C
|
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.
|
[
"data structures",
"geometry",
"greedy"
] |
import java.io.*;
import java.util.*;
public class WaterBalance_1299C {
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] a = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i ++) a[i] = Integer.parseInt(st.nextToken());
long[] sums = new long[n];
int[] starts = new int[n];
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < n; i ++) {
sums[i] = a[i];
starts[i] = i;
while(!stack.isEmpty()) {
int j = stack.peek();
if(sums[j] * (i - starts[j] + 1) <= (sums[i] + sums[j]) * (j - starts[j] + 1)) break;
stack.pop();
sums[i] += sums[j];
starts[i] = starts[j];
}
stack.push(i);
}
StringBuilder output = new StringBuilder();
for(int i : stack) {
double val = (double)sums[i] / (i - starts[i] + 1);
for(int j = starts[i]; j <= i; j ++) output.append(val + "\n");
}
System.out.println(output.toString());
}
}
|
java
|
1315
|
B
|
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
|
[
"binary search",
"dp",
"greedy",
"strings"
] |
/*
Created on = 08-Feb-2022 / 8:55:29 AM
*/
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws IOException {
try {
int t = sc.nextInt();
while (t-- > 0)
solve();
out.close();
} catch (Exception e) {
return;
}
}
// SOLUTION STARTS HERE
// :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
static void solve() {
long a = sc.nextLong(), b = sc.nextLong(), p = sc.nextLong();
char s[] = sc.next().toCharArray();
int n = s.length;
int l = 0, r = n - 1, ans = n;
while (l <= r) {
int mid = l + (r - l) / 2;
if (ok(mid, s, a, b, p)) {
ans = Math.min(ans, mid);
r = mid - 1;
} else {
l = mid + 1;
}
}
System.out.println(ans + 1);
}
static boolean ok(int mid, char[] s, long a, long b, long p) {
long sum = 0;
for (int i = mid; i < s.length - 1; i++) {
char curr = s[i];
while (i < s.length && s[i] == curr)
i++;
i--;
sum += curr == 'A' ? a : b;
}
return sum <= p;
}
// SOLUTION ENDS HERE
// :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
static long binPow(long a, long b, long mod) {
long ans = 1;
while (b != 0) {
if ((b & 1) == 1)
ans = (ans * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return ans;
}
static class DSU {
int rank[];
int parent[];
DSU(int n) {
rank = new int[n + 1];
parent = new int[n + 1];
for (int i = 1; i <= n; i++) {
parent[i] = i;
}
}
int findParent(int node) {
if (parent[node] == node)
return node;
return parent[node] = findParent(parent[node]);
}
boolean union(int x, int y) {
int px = findParent(x);
int py = findParent(y);
if (px == py)
return false;
if (rank[px] < rank[py]) {
parent[px] = py;
} else if (rank[px] > rank[py]) {
parent[py] = px;
} else {
parent[px] = py;
rank[py]++;
}
return true;
}
}
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
}
static boolean[] seiveOfEratosthenes(int n) {
boolean[] isPrime = new boolean[n + 1];
Arrays.fill(isPrime, true);
for (int i = 2; i * i <= n; i++) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
return isPrime;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean isPrime(long n) {
if (n < 2)
return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
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;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
private static final FastScanner sc = new FastScanner();
private static PrintWriter out = new PrintWriter(System.out);
}
|
java
|
1301
|
B
|
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.
|
[
"binary search",
"greedy",
"ternary search"
] |
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 B_Motarack_s_Birthday {
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 = f.nextInt();
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);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(int i = 0; i < n; i++) {
if(arr[i] == -1) {
if(i-1 >= 0 && arr[i-1] != -1) {
max = max(max, arr[i-1]);
min = min(min, arr[i-1]);
}
if(i+1 < n && arr[i+1] != -1) {
max = max(max, arr[i+1]);
min = min(min, arr[i+1]);
}
}
}
int k = (max+min)/2;
if(k == -1) {
out.println(0 + " " + 0);
return;
}
for(int i = 0; i < n; i++) {
if(arr[i] == -1) {
arr[i] = k;
}
}
int m = 0;
for(int i = 1; i < n; i++) {
m = max(m, abs(arr[i]-arr[i-1]));
}
out.println(m + " " + k);
}
// 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
|
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.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
public class weird_algrithm {
static BufferedWriter output = new BufferedWriter(
new OutputStreamWriter(System.out));
static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
static int mod = 1000000007;
static String toReturn = "";
static int steps = Integer.MAX_VALUE;
static int maxlen = 1000005;
/*MATHEMATICS FUNCTIONS START HERE
MATHS
MATHS
MATHS
MATHS*/
static long gcd(long a, long b) {
if(b == 0) return a;
else return gcd(b, a % b);
}
static long powerMod(long x, long y, int mod) {
if(y == 0) return 1;
long temp = powerMod(x, y / 2, mod);
temp = ((temp % mod) * (temp % mod)) % mod;
if(y % 2 == 0) return temp;
else return ((x % mod) * (temp % mod)) % mod;
}
static long modInverse(long n, int p) {
return powerMod(n, p - 2, p);
}
static long nCr(int n, int r, int mod, long [] fact, long [] ifact) {
return ((fact[n] % mod) * ((ifact[r] * ifact[n - r]) % mod)) % mod;
}
static boolean isPrime(long a) {
if(a == 1) return false;
else if(a == 2 || a == 3 || a== 5) return true;
else if(a % 2 == 0 || a % 3 == 0) return false;
for(int i = 5; i * i <= a; i = i + 6) {
if(a % i == 0 || a % (i + 2) == 0) return false;
}
return true;
}
static int [] seive(int a) {
int [] toReturn = new int [a + 1];
for(int i = 0; i < a; i++) toReturn[i] = 1;
toReturn[0] = 0;
toReturn[1] = 0;
toReturn[2] = 1;
for(int i = 2; i * i <= a; i++) {
if(toReturn[i] == 0) continue;
for(int j = 2 * i; j <= a; j += i) toReturn[j] = 0;
}
return toReturn;
}
static long [] fact(int a) {
long [] arr = new long[a + 1];
arr[0] = 1;
for(int i = 1; i < a + 1; i++) {
arr[i] = (arr[i - 1] * i) % mod;
}
return arr;
}
static ArrayList<Long> divisors(long n) {
ArrayList<Long> arr = new ArrayList<Long>();
for(long i = 2; i * i <= n; i++) {
if(n % i == 0) {
while(n % i == 0) {
n /= i;
}
arr.add(i);
}
}
if(n > 1) arr.add(n);
return arr;
}
static int euler(int n) {
int ans = n;
for(int i = 2; i * i <= n; i++) {
if(n % i == 0) {
while(n % i == 0) {
n /= i;
}
ans -= ans / i;
}
}
if(n > 1) ans -= ans / n;
return ans;
}
static long extendedEuclid(long a, long b, long [] arr) {
if(b == 0) {
arr[0] = 1;
arr[1] = 0;
return a;
}
long [] arr1 = new long[2];
long d = extendedEuclid(b, a % b, arr1);
arr[0] = arr1[1];
arr[1] = arr1[0] - arr1[1] * (a / b);
return d;
}
/*MATHS
MATHS
MATHS
MATHS
MATHEMATICS FUNCTIONS END HERE */
/*SWAP FUNCTION START HERE
SWAP
SWAP
SWAP
SWAP
*/
static void swap(int i, int j, long[] arr) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, int[] arr) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, String [] arr) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void swap(int i, int j, char [] arr) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/*SWAP
SWAP
SWAP
SWAP
SWAP FUNCTION END HERE*/
/*BINARY SEARCH METHODS START HERE
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
*/
static boolean BinaryCheck(long test, long [] arr, long health) {
for(int i = 0; i <= arr.length - 1; i++) {
if(i == arr.length - 1) health -= test;
else if(arr[i + 1] - arr[i] > test) {
health = health - test;
}else {
health = health - (arr[i + 1] - arr[i]);
}
if(health <= 0) return true;
}
return false;
}
/*-4 -2 0 1 4 5 6*/
static int binarySearch(int start, int end, long [] arr, long tar) {
while(start <= end) {
int mid = (start + end) / 2;
if(arr[mid] < tar) {
start = mid + 1;
}else if(arr[mid] == tar) {
if(mid - 1 >= 0 && arr[mid - 1] == tar) {
end = mid - 1;
}else return mid;
}else end = mid - 1;
}
return start;
}
static int upper(int start, int end, ArrayList<Integer> pairs, long val) {
while(start < end) {
int mid = (start + end) / 2;
if(pairs.get(mid) <= val) start = mid + 1;
else end = mid;
}
return start;
}
static int lower(int start, int end, ArrayList<Long> arr, long val) {
while(start < end) {
int mid = (start + end) / 2;
if(arr.get(mid) >= val) end = mid;
else start = mid + 1;
}
return start;
}
/*BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
* BINARY SEARCH
BINARY SEARCH METHODS END HERE*/
/*RECURSIVE FUNCTION START HERE
* RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
*/
static int recurse(int x, int y, int n, int steps1, Integer [][] dp) {
if(x > n || y > n) return 0;
if(dp[x][y] != null) {
return dp[x][y];
}
else if(x == n || y == n) {
return steps1;
}
return dp[x][y] = Math.max(recurse(x + y, y, n, steps1 + 1, dp), recurse(x, x + y, n, steps1 + 1, dp));
}
/*RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
* RECURSIVE
RECURSIVE FUNCTION END HERE*/
/*GRAPH FUNCTIONS START HERE
* GRAPH
* GRAPH
* GRAPH
* GRAPH
* */
static class edge{
int from, to;
long weight;
public edge(int x, int y, long weight2) {
this.from = x;
this.to = y;
this.weight = weight2;
}
}
static class sort implements Comparator<TreeNode>{
@Override
public int compare(TreeNode o1, TreeNode o2) {
// TODO Auto-generated method stub
if(o1.start >= o2.start) return -1;
return 1;
}
}
/*
* static class sort1 implements Comparator<TreeNode>{
*
*
* @Override public int compare(TreeNode a, TreeNode b) { // TODO Auto-generated
* method stub if(a.c.equals(b.c)) { return a.id - b.id; }else return
* a.c.compareTo(b.c); }
* }
*/
static void addEdge(ArrayList<ArrayList<edge>> graph, int from, int to, long weight) {
edge temp = new edge(from, to, weight);
edge temp1 = new edge(to, from, weight);
graph.get(from).add(temp);
//graph.get(to).add(temp1);
}
static int ans = 0;
static void topoSort(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, ArrayList<Integer> toReturn) {
if(visited[vertex]) return;
visited[vertex] = true;
for(int i = 0; i < graph.get(vertex).size(); i++) {
if(!visited[graph.get(vertex).get(i)]) topoSort(graph, graph.get(vertex).get(i), visited, toReturn);
}
toReturn.add(vertex);
}
static boolean isCyclicDirected(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, boolean [] reStack) {
if(reStack[vertex]) return true;
if(visited[vertex]) return false;
reStack[vertex] = true;
visited[vertex] = true;
for(int i = 0; i < graph.get(vertex).size(); i++) {
if(isCyclicDirected(graph, graph.get(vertex).get(i), visited, reStack)) return true;
}
reStack[vertex] = false;
return false;
}
static int e = 0;
static long mst(PriorityQueue<edge> pq, int nodes) {
long weight = 0;
int [] size = new int[nodes + 1];
Arrays.fill(size, 1);
while(!pq.isEmpty()) {
edge temp = pq.poll();
int x = parent(parent, temp.to);
int y = parent(parent, temp.from);
if(x != y) {
//System.out.println(temp.weight);
union(x, y, rank, parent, size);
weight += temp.weight;
e++;
}
}
return weight;
}
static void floyd(long [][] dist) { // to find min distance between two nodes
for(int k = 0; k < dist.length; k++) {
for(int i = 0; i < dist.length; i++) {
for(int j = 0; j < dist.length; j++) {
if(dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
}
static void dijkstra(ArrayList<ArrayList<edge>> graph, long [] dist, int src) {
for(int i = 0; i < dist.length; i++) dist[i] = Long.MAX_VALUE / 2;
dist[src] = 0;
boolean visited[] = new boolean[dist.length];
PriorityQueue<pair> pq = new PriorityQueue<>();
pq.add(new pair(src, 0));
while(!pq.isEmpty()) {
pair temp = pq.poll();
int index = (int)temp.a;
for(int i = 0; i < graph.get(index).size(); i++) {
if(dist[graph.get(index).get(i).to] > dist[index] + graph.get(index).get(i).weight) {
dist[graph.get(index).get(i).to] = dist[index] + graph.get(index).get(i).weight;
pq.add(new pair(graph.get(index).get(i).to, graph.get(index).get(i).weight));
}
}
}
}
static int parent1 = -1;
static boolean ford(ArrayList<ArrayList<edge>> graph1, ArrayList<edge> graph, long [] dist, int src, int [] parent) {
for(int i = 0; i < dist.length; i++) dist[i] = Long.MIN_VALUE / 2;
dist[src] = 0;
boolean hasNeg = false;
for(int i = 0; i < dist.length - 1; i++) {
for(int j = 0; j < graph.size(); j++) {
int from = graph.get(j).from;
int to = graph.get(j).to;
long weight = graph.get(j).weight;
if(dist[to] < dist[from] + weight) {
dist[to] = dist[from] + weight;
parent[to] = from;
}
}
}
for(int i = 0; i < graph.size(); i++) {
int from = graph.get(i).from;
int to = graph.get(i).to;
long weight = graph.get(i).weight;
if(dist[to] < dist[from] + weight) {
parent1 = from;
hasNeg = true;
/*
* dfs(graph1, parent1, new boolean[dist.length], dist.length - 1);
* //System.out.println(ans); dfs(graph1, 0, new boolean[dist.length], parent1);
*/
//System.out.println(ans);
if(ans == 2) break;
else ans = 0;
}
}
return hasNeg;
}
/*GRAPH FUNCTIONS END HERE
* GRAPH
* GRAPH
* GRAPH
* GRAPH
*/
/*disjoint Set START HERE
* disjoint Set
* disjoint Set
* disjoint Set
* disjoint Set
*/
static int [] rank;
static int [] parent;
static int parent(int [] parent, int x) {
if(parent[x] == x) return x;
else return parent[x] = parent(parent, parent[x]);
}
static boolean union(int x, int y, int [] rank, int [] parent, int [] setSize) {
if(parent(parent, x) == parent(parent, y)) {
return true;
}
if (rank[x] > rank[y]) {
parent[y] = x;
setSize[x] += setSize[y];
} else {
parent[x] = y;
setSize[y] += setSize[x];
if (rank[x] == rank[y]) rank[y]++;
}
return false;
}
/*disjoint Set END HERE
* disjoint Set
* disjoint Set
* disjoint Set
* disjoint Set
*/
/*INPUT START HERE
* INPUT
* INPUT
* INPUT
* INPUT
* INPUT
*/
static int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(sc.readLine());
}
static long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(sc.readLine());
}
static long [] inputLongArr() throws NumberFormatException, IOException{
String [] s = sc.readLine().split(" ");
long [] toReturn = new long[s.length];
for(int i = 0; i < s.length; i++) {
toReturn[i] = Long.parseLong(s[i]);
}
return toReturn;
}
static int max = 0;
static int [] inputIntArr() throws NumberFormatException, IOException{
String [] s = sc.readLine().split(" ");
//System.out.println(s.length);
int [] toReturn = new int[s.length];
for(int i = 0; i < s.length; i++) {
toReturn[i] = Integer.parseInt(s[i]);
}
return toReturn;
}
/*INPUT
* INPUT
* INPUT
* INPUT
* INPUT
* INPUT END HERE
*/
static long [] preCompute(int level) {
long [] toReturn = new long[level];
toReturn[0] = 1;
toReturn[1] = 16;
for(int i = 2; i < level; i++) {
toReturn[i] = ((toReturn[i - 1] % mod) * (toReturn[i - 1] % mod)) % mod;
}
return toReturn;
}
static class pair{
long a;
long b;
long d;
public pair(long in, long y) {
this.a = in;
this.b = y;
this.d = 0;
}
}
static int [] nextGreaterBack(char [] s) {
Stack<Integer> stack = new Stack<>();
int [] toReturn = new int[s.length];
for(int i = 0; i < s.length; i++) {
if(!stack.isEmpty() && s[stack.peek()] >= s[i]) {
stack.pop();
}
if(stack.isEmpty()) {
stack.push(i);
toReturn[i] = -1;
}else {
toReturn[i] = stack.peek();
stack.push(i);
}
}
return toReturn;
}
static int [] nextGreaterFront(char [] s) {
Stack<Integer> stack = new Stack<>();
int [] toReturn = new int[s.length];
for(int i = s.length - 1; i >= 0; i--) {
if(!stack.isEmpty() && s[stack.peek()] >= s[i]) {
stack.pop();
}
if(stack.isEmpty()) {
stack.push(i);
toReturn[i] = -1;
}else {
toReturn[i] = stack.peek();
stack.push(i);
}
}
return toReturn;
}
static int [] lps(String s) {
int [] lps = new int[s.length()];
lps[0] = 0;
int j = 0;
for(int i = 1; i < lps.length; i++) {
j = lps[i - 1];
while(j > 0 && s.charAt(i) != s.charAt(j)) j = lps[j - 1];
if(s.charAt(i) == s.charAt(j)) {
lps[i] = j + 1;
}
}
return lps;
}
static int [][] vectors = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static String dir = "DRUL";
static boolean check(int i, int j, boolean [][] visited) {
if(i >= visited.length || j >= visited[0].length) return false;
if(i < 0 || j < 0) return false;
return true;
}
static void selectionSort(long arr[], long [] arr1, ArrayList<ArrayList<Integer>> ans)
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
else if(arr[j] == arr[min_idx]) {
if(arr1[j] < arr1[min_idx]) min_idx = j;
}
if(i == min_idx) {
continue;
}
ArrayList<Integer> p = new ArrayList<Integer>();
p.add(min_idx + 1);
p.add(i + 1);
ans.add(new ArrayList<Integer>(p));
swap(i, min_idx, arr);
swap(i, min_idx, arr1);
}
}
static int saved = Integer.MAX_VALUE;
static String ans1 = "";
public static boolean isValid(int x, int y, String [] mat) {
if(x >= mat.length || x < 0) return false;
if(y >= mat[0].length() || y < 0) return false;
return true;
}
public static void recurse3(ArrayList<Character> arr, int index, String s, int max, ArrayList<String> toReturn) {
if(s.length() == max) {
toReturn.add(s);
return;
}
if(index == arr.size()) return;
recurse3(arr, index + 1, s + arr.get(index), max, toReturn);
recurse3(arr, index + 1, s, max, toReturn);
}
/*
if(arr[i] > q) return Math.max(f(i + 1, q - 1) + 1, f(i + 1, q);
else return f(i + 1, q) + 1
*/
static void dfsDP(ArrayList<ArrayList<Integer>> graph, int src, int [] dp1, int [] dp2, int parent) {
int sum1 = 0; int sum2 = 0;
for(int x : graph.get(src)) {
if(x == parent) continue;
dfsDP(graph, x, dp1, dp2, src);
sum1 += Math.min(dp1[x], dp2[x]);
sum2 += dp1[x];
}
dp1[src] = 1 + sum1;
dp2[src] = sum2;
System.out.println(src + " " + dp1[src] + " " + dp2[src]);
}
static int balanced = 0;
static void dfs(ArrayList<ArrayList<ArrayList<Long>>> graph, long src, int [] dist, long sum1, long sum2, long parent, ArrayList<Long> arr, int index) {
index = 0;//binarySearch(index, arr.size() - 1, arr, sum1);
if(index < arr.size() && arr.get(index) <= sum1) {
dist[(int)src] = index + 1;
}
else dist[(int)src] = index;
for(ArrayList<Long> x : graph.get((int)src)) {
if(x.get(0) == parent) continue;
if(arr.size() != 0) arr.add(arr.get(arr.size() - 1) + x.get(2));
else arr.add(x.get(2));
dfs(graph, x.get(0), dist, sum1 + x.get(1), sum2, src, arr, index);
arr.remove(arr.size() - 1);
}
}
static int compare(String s1, String s2) {
Queue<Character> q1 = new LinkedList<>();
Queue<Character> q2 = new LinkedList<Character>();
for(int i = 0; i < s1.length(); i++) {
q1.add(s1.charAt(i));
q2.add(s2.charAt(i));
}
int k = 0;
while(k < s1.length()) {
if(q1.equals(q2)) {
break;
}
q2.add(q2.poll());
k++;
}
return k;
}
static long pro = 0;
public static int len(ArrayList<ArrayList<Integer>> graph, int src, boolean [] visited
) {
visited[src] = true;
int max = 0;
for(int x : graph.get(src)) {
if(!visited[x]) {
visited[x] = true;
int len = len(graph, x, visited) + 1;
//System.out.println(len);
pro = Math.max(max * (len - 1), pro);
max = Math.max(len, max);
}
}
return max;
}
public static void recurse(int l, int [] ans) {
if(l < 0) return;
int r = (int)Math.sqrt(l * 2);
int s = r * r;
r = s - l;
recurse(r - 1, ans);
while(r <= l) {
ans[r] = l;
ans[l] = r;
r++;
l--;
}
}
static boolean isSmaller(String str1, String str2)
{
// Calculate lengths of both string
int n1 = str1.length(), n2 = str2.length();
if (n1 < n2)
return true;
if (n2 < n1)
return false;
for (int i = 0; i < n1; i++)
if (str1.charAt(i) < str2.charAt(i))
return true;
else if (str1.charAt(i) > str2.charAt(i))
return false;
return false;
}
// Function for find difference of larger numbers
static String findDiff(String str1, String str2)
{
// Before proceeding further, make sure str1
// is not smaller
if (isSmaller(str1, str2)) {
String t = str1;
str1 = str2;
str2 = t;
}
// Take an empty string for storing result
String str = "";
// Calculate length of both string
int n1 = str1.length(), n2 = str2.length();
// Reverse both of strings
str1 = new StringBuilder(str1).reverse().toString();
str2 = new StringBuilder(str2).reverse().toString();
int carry = 0;
// Run loop till small string length
// and subtract digit of str1 to str2
for (int i = 0; i < n2; i++) {
// Do school mathematics, compute difference of
// current digits
int sub
= ((int)(str1.charAt(i) - '0')
- (int)(str2.charAt(i) - '0') - carry);
// If subtraction is less than zero
// we add then we add 10 into sub and
// take carry as 1 for calculating next step
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += (char)(sub + '0');
}
// subtract remaining digits of larger number
for (int i = n2; i < n1; i++) {
int sub = ((int)(str1.charAt(i) - '0') - carry);
// if the sub value is -ve, then make it
// positive
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += (char)(sub + '0');
}
// reverse resultant string
return new StringBuilder(str).reverse().toString();
}
public static long check(long [] arr, long mid) {
long cost = 0;
for(int i = 0; i < arr.length; i++) {
cost += Math.abs(arr[i] - mid);
}
return cost;
}
/*
4, 8, 15, 16, 23
*/
static interactor test;
static boolean query(int x) throws NumberFormatException, IOException {
//System.out.println(x);
String to = test.interact(x);
if(to.equals("yes")) return true;
return false;
}
static int len(char [] s, int c, char s1) {
int j = 0;
int count = 0;
int max = 0;
for(int i = 0; i < s.length; i++) {
if(s[i] != s1) {
count++;
}
while(count > c) {
if(s[j] != s1) count--;
j++;
}
max = Math.max(max, i - j + 1);
}
return max;
}
static long ways(int i, int m, int len, int n, Long [][] dp) {
if(i == n) return 1;
if(len == 2 * m) return 1;
if(dp[i][len] != null) return dp[i][len];
return dp[i][len] = (ways(i, m, len + 1, n, dp) + ways(i + 1, m, len, n, dp)) % mod;
}
static void solve() throws IOException {
int [] n = inputIntArr();
Long [][] dp = new Long[n[0] + 1][2 * n[1] + 1];
output.write(ways(1, n[1], 0, n[0], dp) + "\n");
}
/*1 2 3 4 5 6*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//int t = Integer.parseInt(sc.readLine()); for(int i = 0; i < t; i++)
solve();
output.flush();
}
}
class interactor{
int [] arr;
int min = 2; int max = 100;
int n;
public interactor() {
n = (int)(Math.random()*(max-min+1)+min);
}
public String interact(int x) {
if(n % x == 0) return "yes";
return "no";
}
}
class TreeNode {
int start; int end;
public TreeNode(int start, int end) {
this.start = start;
this.end = end;
}
public String toString() {
return start + " " + end;
}
}
/*
1
10
6 10 85 84 11 99 9 20 88 31 1 0 1 1 1 0 0 1 1 1 1 0 0
*/
|
java
|
1325
|
A
|
A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100) — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.
|
[
"constructive algorithms",
"greedy",
"number theory"
] |
import java.util.Scanner;
public class CFR628D2 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t>0){
t--;
int x=sc.nextInt();
System.out.println(1+" "+(x-1));
}
}
}
|
java
|
1307
|
C
|
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
|
[
"brute force",
"dp",
"math",
"strings"
] |
//package com.company;
import java.beans.IntrospectionException;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Main {
static class pair {
String a;
String b;
pair(String x, String y) {
this.a = x;
this.b = y;
}
// 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);
}
//uppper bound code
// int beg =0;
// int end =n;
// while(beg<end)
// {
// int mid =(beg+end)/2;
// if(max[mid]>lim)
// {
// end=mid;
// }
// else beg=mid+1;
//
// }
//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;
}
}
public static int help(boolean[] v) {
HashSet<Integer> s = new HashSet<>();
for (int e = 1; e < v.length; e++) {
int i = find(e);
if (v[i]) s.add(i);
}
// System.out.print(Arrays.toString(parent));
return s.size();
}
public static void main(String[] args) {
try {
FastReader in = new FastReader();
FastWriter out = new FastWriter();
long testCases = 1;
fl:
while (testCases-- > 0) {
String s =in.next();
int n =s.length();
int arr[]=new int[n];
for(int i =0;i<n;i++)
{
arr[i]=s.charAt(i)-'a';
}
long ans =0;
long dp[][]=new long[30][30];
long fr[]=new long[30];
for(int i =0;i<n;i++)
{
for(int j =0;j<26;j++)
dp[j][arr[i]]+=fr[j];
fr[arr[i]]++;
}
for(long i :fr)
ans =Math.max(ans,i);
for(int i =0;i<26;i++)
for(int j =0;j<26;j++)
ans =Math.max(ans,dp[i][j]);
System.out.println(ans);
}
out.close();
} catch (Exception e) {
return;
}
}
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 TRY TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROY OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN
|
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.Arrays;
import java.util.Scanner;
import java.util.Comparator;
public class MovingPoints {
private static long sumaj(long[] arr,int index) {
long result=0;
while (index>=0) {
result+=arr[index];
index=(index&(index+1))-1;
}
return result;
}
private static void apdejt (long[] t,int index,int vv) {
while (index<t.length) {
t[index]+=vv;
index=index|(index + 1);
}
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int[][] pm=new int[n][2];
int[][] vm=new int[n][2];
for (int i=0;i<n;i++)
pm[i][0]=in.nextInt();
for (int i=0;i<n;i++) {
pm[i][1]=in.nextInt();
vm[i][0]=pm[i][1];
vm[i][1]=i;
}
in.close();
Arrays.sort(vm, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
int nss=0;
int[][] finar=new int[n][2];
for (int i=0;i<n;i++) {
if (i>0 && vm[i][0]!=vm[i-1][0])
nss++;
finar[i][0]=nss;
finar[i][1]=vm[i][1];
}
Arrays.sort(finar,new Comparator<int[]>() {
public int compare(int[] a,int[] b) {
return a[1]-b[1];
}});
for (int i=0; i<n;i++) {
pm[i][1] = finar[i][0];
}
Arrays.sort(pm,new Comparator<int[]>() {
public int compare(int[] a,int[] b) {
return a[0]-b[0];
}});
long[] c=new long[n];
long[] pts=new long[n];
long totalsum=0;
for (int i=0;i<n;i++) {
int index=pm[i][1];
totalsum+=sumaj(pts,index)*pm[i][0]-sumaj(c,index);
apdejt(pts,index,1);
apdejt(c, index, pm[i][0]);
}
System.out.println(totalsum);
}
}
|
java
|
1325
|
F
|
F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:
|
[
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] |
import java.io.*;
import java.util.*;
public class A {
static ArrayList<Integer>[] adj;
static int[] visited, par, level;
static int sqrt;
static boolean[] taken;
static ArrayList<Integer> cycle;
static boolean dfs(int u, int p) {
visited[u] = 1;
par[u] = p;
boolean can = true;
for (int v : adj[u]) {
if (v == p || visited[v] == 2) {
can &= !taken[v];
continue;
}
if (visited[v] == 0) {
level[v] = level[u] + 1;
if (dfs(v, u))
return true;
} else if (level[u] - level[v] + 1 >= sqrt) {
cycle = new ArrayList();
while (true) {
cycle.add(u);
if (u == v)
return true;
u = par[u];
}
}
can &= !taken[v];
}
if (can)
taken[u] = true;
visited[u] = 2;
return false;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), m = sc.nextInt();
adj = new ArrayList[n];
for (int i = 0; i < n; i++)
adj[i] = new ArrayList();
while (m-- > 0) {
int u = sc.nextInt() - 1, v = sc.nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
sqrt = (int) Math.ceil(Math.sqrt(n));
visited = new int[n];
par = new int[n];
level = new int[n];
taken = new boolean[n];
dfs(0, -1);
if (cycle == null) {
out.println(1);
for (int i = 0, j = 0; j < sqrt; i++)
if (taken[i]) {
out.print((i + 1) + " ");
j++;
}
} else {
out.println(2);
out.println(cycle.size());
for (int x : cycle)
out.print((x + 1) + " ");
}
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();
}
int[] nxtArr(int n) throws IOException {
int[] ans = new int[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
}
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
|
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 static java.lang.Math.*;
import java.awt.Point;
import java.io.*;
import java.util.*;
public class Exercise {
static StringTokenizer st;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static void solve() {
readLine();
int part = nextInt(); int ina = nextInt(); int time = 0; int inb = ina;
int a, b; boolean allPC = true;
for(int i = 0; i < part; i++) {
readLine();
int tm = nextInt(); int space = tm - time; time = tm;
a = nextInt(); b = nextInt();
if(min(a, b) > inb + space || max(a, b) < ina - space) {
allPC = false;
}
ina = min(a, b) <= ina - space ? ina - space : a;
inb = max(a, b) >= inb + space ? inb + space : b;
}
System.out.println(allPC ? "YES" : "NO");
}
public static void main(String args[]) {
readLine();
int testcases = nextInt();
while(testcases-- != 0) solve();
}
public static int nextInt() {
return Integer.parseInt(st.nextToken());
}
public static String nextLine() {
try {
st = new StringTokenizer(br.readLine());
} catch(Exception e) {}
return st.nextToken();
}
public static void readLine() {
try {
st = new StringTokenizer(br.readLine());
} catch(Exception e) {}
}
}
|
java
|
1312
|
A
|
A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO".
|
[
"geometry",
"greedy",
"math",
"number theory"
] |
import java.util.Scanner;
public class CodeForce {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int testCases = in.nextInt();
in.nextLine();
int a, b;
for(int t = 1; t <= testCases; t ++) {
a = in.nextInt();
b = in.nextInt();
in.nextLine();
if(a % b == 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
|
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.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.in;
import static java.lang.System.out;
public class Journey_Planning {
public static void main(String[] args) {
try {
FastReader in = new FastReader();
FastWriter out = new FastWriter();
int n = in.nextInt();
ArrayList<Integer> array = new ArrayList<>();
for (int i = 0; i < n; i++) {
array.add(in.nextInt());
}
calc(n, array);
out.close();
} catch (Exception e) {
return;
}
}
private static void calc(int n, ArrayList<Integer> array) {
long max = 0;
HashMap<Integer, Long> map = new HashMap();
for (int i = 0; i < n; i++) {
int temp = array.get(i) - i;
map.put(temp, map.getOrDefault(temp, 0l) + array.get(i));
max = Math.max(max, map.get(temp));
}
out.println(max);
}
private static long gcd(long a, long b) {
if (a == 0) {
return b;
} else {
return (gcd(b % a, a));
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(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 class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(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 parseInt(next());
}
long nextLong() {
return parseLong(next());
}
double nextDouble() {
return parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
}
|
java
|
1295
|
F
|
F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3
1 2
1 2
1 2
OutputCopy499122177
InputCopy2
42 1337
13 420
OutputCopy578894053
InputCopy2
1 1
0 0
OutputCopy1
InputCopy2
1 1
1 1
OutputCopy1
NoteThe real answer in the first test is 1212.
|
[
"combinatorics",
"dp",
"probabilities"
] |
import java.util.*;
import java.io.*;
public class Good {
public static void main(String [] args) {
Solver s = new Solver();
s.solve();
}
}
class Solver {
Reader in = new Reader ();
Writer out = new Writer ();
int l[], r[];
int n;
int b[], e[];
int range;
long invfac[];
final int inf = 1000000000;
final int mod = 998244353;
long power(long b, int e) {
if(e == 0) return 1;
if(e % 2 == 1) return (power(b, e - 1) * b) % mod;
long m = power(b, e >> 1);
return (m * m) % mod;
}
long nCr(int n, int k) {
long ans = invfac[k];
for(int i = n; i > n - k; i--) {
ans = (ans * i) % mod;
}
return ans;
}
class Data {
int value, type;
Data () {}
Data (int value, int type) {
this.value = value;
this.type = type;
}
boolean equalTo(Data t) {
return (value == t.value && type == t.type);
}
}
long mem[][];
long dp(int pos, int cur) {
if(pos == n + 1) return 1;
if(cur <= 0) return 0;
if(mem[pos][cur] != -1) return mem[pos][cur];
long ans = dp(pos, cur - 1);
for(int i = pos; i <= n; i++) {
int sz = (i - pos + 1);
if(l[i] <= b[cur] && e[cur] <= r[i]) {
ans += dp(i + 1, cur - 1) * nCr(e[cur] - b[cur] + sz, sz);
ans %= mod;
} else break;
}
return mem[pos][cur] = ans;
}
void solve () {
n = in.nextInt();
l = new int [n + 1];
r = new int [n + 1];
b = new int [5 * n + 1];
e = new int [5 * n + 1];
ArrayList <Data> arr = new ArrayList <> ();
arr.add(new Data(-inf, 0));
arr.add(new Data(inf, 1));
for(int i = 1; i <= n; i++) {
l[i] = in.nextInt();
r[i] = in.nextInt();
arr.add(new Data(l[i], 0)); arr.add(new Data(l[i] - 1, 1));
arr.add(new Data(r[i], 1)); arr.add(new Data(r[i] + 1, 0));
}
Collections.sort(arr, (p, q) -> {if(p.value == q.value) return p.type - q.type;
else return p.value - q.value; });
ArrayList <Integer> unq = new ArrayList <> ();
for(int i = 0; i < arr.size(); i++) {
if(i > 0 && arr.get(i - 1).equalTo(arr.get(i))) continue;
unq.add(arr.get(i).value);
}
range = 0;
for(int i = 0; i < unq.size(); i += 2) {
b[++range] = unq.get(i);
e[range] = unq.get(i + 1);
// System.out.println(b[range] + " " + e[range]);
}
invfac = new long [n + 1];
long fac = 1;
invfac[0] = fac;
for(int i = 1; i <= n; i++) {
fac = (fac * i) % mod;
invfac[i] = power(fac, mod - 2);
}
mem = new long [n + 1][range + 1];
for(int i = 0; i <= n; i++) {
for(int j = 0; j <= range; j++) {
mem[i][j] = -1;
}
}
long res = dp(1, range);
for(int i = 1; i <= n; i++) {
res = (res * power(r[i] - l[i] + 1, mod - 2)) % mod;
}
System.out.println(res);
}
}
class Reader {
private StringTokenizer a;
private BufferedReader b;
Reader () {
a = null;
try {
b = new BufferedReader (new InputStreamReader (System.in)); // for file IO, replace this with new FileReader ("in.txt")
} catch (Exception e) {
e.printStackTrace();
}
}
public String next () {
while(a == null || !a.hasMoreTokens()) {
try {
a = new StringTokenizer (b.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return a.nextToken();
}
public int nextInt() {
return Integer.parseInt(this.next());
}
public long nextLong () {
return Long.parseLong(this.next());
}
public double nextDouble () {
return Double.parseDouble(this.next());
}
public String nextLine() {
try {
return b.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
class Writer {
private PrintWriter a;
private StringBuffer b;
Writer () {
try {
a = new PrintWriter (System.out); // for file IO, replace this with new FileWriter ("out.txt")
} catch (Exception e) {
e.printStackTrace();
}
b = new StringBuffer ("");
}
public void write (Object s) {
b.append(s);
}
public void writeln(Object s) {
b.append(s).append('\n');
}
public void flush () {
a.print(b);
a.flush();
a.close();
}
}
|
java
|
1296
|
C
|
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
|
[
"data structures",
"implementation"
] |
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int tc = 0; tc < t; ++tc) {
sc.nextInt();
String path = sc.next();
System.out.println(solve(path));
}
sc.close();
}
static String solve(String path) {
int l = -1;
int r = -1;
int x = 0;
int y = 0;
Map<Point, Integer> pointToPos = new HashMap<>();
pointToPos.put(new Point(0, 0), 0);
for (int i = 0; i < path.length(); ++i) {
char move = path.charAt(i);
if (move == 'L') {
--x;
} else if (move == 'R') {
++x;
} else if (move == 'U') {
++y;
} else {
--y;
}
Point point = new Point(x, y);
if (pointToPos.containsKey(point) && (l == -1 || i - pointToPos.get(point) < r - l)) {
l = pointToPos.get(point) + 1;
r = i + 1;
}
pointToPos.put(point, i + 1);
}
return (l == -1) ? "-1" : String.format("%d %d", l, r);
}
}
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public boolean equals(Object obj) {
Point other = (Point) obj;
return x == other.x && y == other.y;
}
}
|
java
|
1305
|
D
|
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
|
[
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1305d {
public static void main(String[] args) throws IOException {
int n = ri(), sz[] = new int[n], par[] = new int[n];
List<List<Integer>> t = new ArrayList<>();
for(int i = 0; i < n; ++i) {
t.add(new ArrayList<>());
}
for(int i = 1; i < n; ++i) {
int u = rni() - 1, v = ni() - 1;
t.get(u).add(v);
t.get(v).add(u);
}
int centroid = 0, maxsz = 0, maxnei = -1;
dfs(t, 0, -1, sz);
for(int nei : t.get(0)) {
if(sz[nei] > maxsz) {
maxsz = sz[nei];
maxnei = nei;
}
}
while(maxsz > n / 2) {
sz[centroid] -= maxsz;
sz[maxnei] = n;
centroid = maxnei;
maxsz = 0;
for(int nei : t.get(centroid)) {
if(sz[nei] > maxsz) {
maxsz = sz[nei];
maxnei = nei;
}
}
}
assign(t, centroid, -1, par);
boolean[] no = new boolean[n];
while(true) {
int u = -1, v = centroid;
for(int nei : t.get(centroid)) {
if(nei != par[centroid] && !no[nei]) {
if(u == -1) {
u = nei;
while(t.get(u).size() > 1) {
for(int unei : t.get(u)) {
if(unei != par[u]) {
u = unei;
break;
}
}
}
} else {
v = nei;
while(t.get(v).size() > 1) {
for(int vnei : t.get(v)) {
if(vnei != par[v]) {
v = vnei;
break;
}
}
}
break;
}
}
}
if(u == -1) {
break;
} else {
pr("? ");
prln(u + 1, v + 1);
flush();
centroid = ri() - 1;
while(u != centroid && u >= 0) {
no[u] = true;
u = par[u];
}
while(v != centroid && v >= 0) {
no[v] = true;
v = par[v];
}
}
}
pr("! ");
prln(centroid + 1);
close();
}
static void assign(List<List<Integer>> g, int i, int p, int[] par) {
par[i] = p;
for(int n : g.get(i)) {
if(n != p) {
assign(g, n, i, par);
}
}
}
static void dfs(List<List<Integer>> g, int i, int par, int[] sz) {
sz[i] = 1;
for(int n : g.get(i)) {
if(n != par) {
dfs(g, n, i, sz);
sz[i] += sz[n];
}
}
}
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
// IRAND ~= 3e8
// IMAX ~= 2e10
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IRAND = 327859546;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// 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 floori(double d) {return (int)d;}
static int ceili(double d) {return (int)ceil(d);}
static long floorl(double d) {return (long)d;}
static long ceill(double d) {return (long)ceil(d);}
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 <T> void reverse(T[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {T 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 shuffle(char[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); char swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); Arrays.sort(a);}
static void rsort(long[] a) {shuffle(a); Arrays.sort(a);}
static void rsort(double[] a) {shuffle(a); Arrays.sort(a);}
static void rsort(char[] a) {shuffle(a); Arrays.sort(a);}
static <T> void rsort(T[] a) {shuffle(a); Arrays.sort(a);}
static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}
// input
static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
static long rl() throws IOException {return Long.parseLong(__in.readLine());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
static int ni() {return Integer.parseInt(input.nextToken());}
static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
static long nl() {return Long.parseLong(input.nextToken());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());}
static void h() {__out.println("hlfd");}
static void flush() {__out.flush();}
static void close() {__out.close();}
}
|
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.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class randoms {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
//segment tree + sweep line
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken());
int[] ys = new int[(int)(1e6)+5];
Arrays.fill(ys, Integer.MIN_VALUE);
int max = 0;
for(int i = 0; i<n; i++) {
st = new StringTokenizer(br.readLine());
int pos = Integer.parseInt(st.nextToken());
ys[pos] = Math.max(ys[pos], -Integer.parseInt(st.nextToken()));
max = Math.max(max, pos);
}
segtree tree = new segtree(ys, 0, ys.length-1);
int[][] xs = new int[m][2];
for(int i = 0; i<m; i++){
st = new StringTokenizer(br.readLine());
xs[i] = new int[]{Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())};
}
Arrays.sort(xs, (int[] a, int[] b) -> a[0] - b[0]);
int[][] coords = new int[p][3];
for(int i = 0; i<p; i++){
st = new StringTokenizer(br.readLine());
coords[i][1] = Integer.parseInt(st.nextToken());
coords[i][0] = Integer.parseInt(st.nextToken());
coords[i][2] = Integer.parseInt(st.nextToken());
}
Arrays.sort(coords, (int[] a, int[] b) -> a[0] - b[0]);
int idx = 0;
int ret = Integer.MIN_VALUE;
for(int i = 0; i<m; i++){
while(idx < p && coords[idx][0] < xs[i][0]){
if(max > coords[idx][1]){
tree.update(coords[idx][1]+1, ys.length-1, coords[idx][2]);
}
idx++;
}
// System.out.println(tree.get(0, ys.length-1));
ret = Math.max(ret, tree.get(0, ys.length-1) - xs[i][1]);
}
pw.println(ret);
pw.close();
br.close();
}
static class segtree {
private final int none = Integer.MIN_VALUE;
private final int updnone = 0;
private int gL;
private int gR;
private int mid;
public segtree left;
public segtree right;
public int val;
public int lazy = updnone;
public segtree(int[] nums, int l, int r) {
gL = l;
gR = r;
mid = (l + r) / 2;
if (l == r) {
val = nums[l];
return;
}
left = new segtree(nums, l, mid);
right = new segtree(nums, mid + 1, r);
val = comb(left.val, right.val);
}
public int get(int l, int r) {
if (l > gR || r < gL) {
return none;
}
push();
if (gL == l && gR == r) {
return val;
}
return comb(
left.get(l, Math.min(r, mid)),
right.get(Math.max(l, mid + 1), r)
);
}
public int update(int l, int r, int v) {
push();
if (l > gR || r < gL) {
return val;
}
if (gL == l && gR == r) {
compose(this, v);
push();
} else {
val = comb(
left.update(l, Math.min(r, mid), v),
right.update(Math.max(l, mid + 1), r, v)
);
}
return val;
}
private int comb(int a, int b) { //associative
return Math.max(a, b);
}
//push when you need the updated value
public void push() {
if (gL != gR) {
compose(left, lazy);
compose(right, lazy);
}
val += lazy; //modify: effect of lazy
lazy = updnone;
}
public void compose(segtree t, long v) {
t.lazy += v;
}
public String toString() {
return gL + " " + gR + " " + val + " " + lazy;
}
}
}
/*
2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
*/
|
java
|
1294
|
A
|
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
|
[
"math"
] |
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int tcs=s.nextInt();
while(tcs!=0){
int a[]=new int[3];
for(int i=0;i<3;i++) a[i]=s.nextInt();
int coins=s.nextInt();
Arrays.sort(a);
int dif=2*a[2]-a[1]-a[0];
if(coins<dif) System.out.println("NO");
else{
coins=coins-dif;
if(coins%3==0) System.out.println("YES");
else System.out.println("NO");
}
tcs--;
}
}
}
|
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"
] |
//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();
int arr[]=new int[n-1];
for(int i=0;i<n-1;i++)
{arr[i]=in.nextInt();
}
int q[]=new int[n-1];
for(int i =0;i<n-1;i++)
q[i]=arr[i];
for(int i =1;i<n-1;i++)
arr[i]=arr[i]+arr[i-1];
// for(int i :arr)
// System.out.print(i+" ");
int max=-1000000000;
int min =0;
for(int i :arr)
{
max=Math.max(i,max);
min=Math.min(i,min);
}
int x =1-min;
ArrayList<Integer>ans=new ArrayList<>();
ans.add(x);
for(int i =0;i<n-1;i++)
ans.add(x+arr[i]);
HashSet<Integer>set=new HashSet<>();
//System.out.println(ans);
for(int i :ans)
{
if(set.contains(i)||i>n||i<1)
{
out.prlong("-1");
continue fl;
}
set.add(i);
}
for(int i :ans)
out.prlong(i+" ");
out.prlong("");
}
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
|
1321
|
C
|
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a.
|
[
"brute force",
"constructive algorithms",
"greedy",
"strings"
] |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
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);
ARemoveAdjacent solver = new ARemoveAdjacent();
solver.solve(1, in, out);
out.close();
}
static class ARemoveAdjacent {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
char[] arr = in.next().toCharArray();
ArrayList<Character> list = new ArrayList<>();
for (char c : arr) list.add(c);
boolean[] vis = new boolean[n];
for (char c = 'z'; c >= 'b'; c--) {
char last = c;
int lid = -1;
for (int i = 0; i < n; i++) {
if (vis[i]) continue;
if (lid != -1 && arr[i] == arr[lid] + 1 && arr[i] == c) {
vis[i] = true;
} else {
lid = i;
}
}
lid = -1;
for (int i = n - 1; i >= 0; i--) {
if (vis[i]) continue;
if (lid != -1 && arr[i] == arr[lid] + 1 && arr[i] == c) {
vis[i] = true;
} else {
lid = i;
}
}
}
int c = 0;
for (int i = 0; i < n; i++) {
if (vis[i]) c++;
}
out.println(c);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
java
|
1293
|
A
|
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
|
[
"binary search",
"brute force",
"implementation"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
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(char[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = (char) 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;
}
static int countFreq(int[] arr, int n) {
HashMap<Integer, Integer> map = new HashMap<>();
int x = 0;
for (int i = 0; i < n; i++) {
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}
for (int i = 0; i < n; i++) {
if (map.get(arr[i]) == 1)
x++;
}
return x;
}
static boolean symm(String str) {
if (str.length() == 1 || str.length() == 0)
return true;
if (str.substring(0, (str.length() / 2)).equals(str.substring(str.length() / 2)))
return symm(str.substring(0, (str.length() / 2)));
return false;
}
static void reverse(int[] arr, int l, int r) {
int d = (r - l + 1) / 2;
for (int i = 0; i < d; i++) {
int t = arr[l + i];
arr[l + i] = arr[r - i];
arr[r - i] = t;
}
// print array here
}
static int f(int x) {
x++;
while (x % 10 == 0) {
x /= 10;
}
return x;
}
public static boolean isFair(long x) {
long n = x;
while (n != 0) {
long r = (long) n % 10;
if (r != 0 && x % r != 0)
return false;
n = n / 10;
}
return true;
}
static void sort(String []s, int n)
{
for (int i=1 ;i<n; i++)
{
String temp = s[i];
// Insert s[j] at its correct position
int j = i - 1;
while (j >= 0 && temp.length() < s[j].length())
{
s[j+1] = s[j];
j--;
}
s[j+1] = temp;
}
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
int t = sc.nextInt();
while (t-- != 0) {
int n=sc.nextInt();
int s=sc.nextInt();
int k=sc.nextInt();
int d=0;
List<Integer> a=new ArrayList<>();
while(k--!=0) {
a.add(sc.nextInt());
}
for(int i=0;i<n;i++) {
int x=s-i;
int y=s+i;
if(x>0 && !a.contains(x)) {
d=i;
break;
}
if(y<n+1 && !a.contains(y)) {
d=i;
break;
}
}
System.out.println(d);
}
}
}
|
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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
/*
*
* 820 = 729,81,9,1;
* 0 , 0 ,
*
*
* */
public class Codeforces {
public static void main(String[] args) {
FastReader fastReader = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int tt = fastReader.nextInt();
while(tt--> 0){
int n = fastReader.nextInt();
int a[] = fastReader.ria(n);
if(n == 1){
out.println("YES");
continue;
}
int index = 0;
int min = a[0];
HashSet<Integer> set1 = new HashSet<>();
for(int i = 0 ; i < n; i++){
if(a[i] <= min){
index = i;
min = a[i];
}
int min_len = index+1;
int max_len = i+1;
if(min_len -1 <= min && a[i] >= max_len-1){
set1.add(i);
}else{
break;
}
}
index = n-1;
min = a[n-1];
HashSet<Integer> set2 = new HashSet<>();
for(int i = n-1; i >=0 ; i--){
if(a[i] <= min){
index = i;
min = a[i];
}
int min_len = n - index;
int max_len = n-i;
if(min_len -1 <= min && a[i] >= max_len-1){
set2.add(i);
}else{
break;
}
}
if(set1.contains(n-1)){
out.println("YES");
}else if(set2.contains(0)){
out.println("YES");
}else{
boolean contains = false;
for(int i : set1) {
if(set2.contains(i)) {
contains = true;
break;
}
}
out.println(contains ? "YES" : "NO");
}
}
out.close();
}
static class Pair{
int x;
int y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
}
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
static Random __r = new Random();
// math util
static int minof(int a, int b, int c) {
return min(a, min(b, c));
}
static int minof(int... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return min(x[0], x[1]);
if (x.length == 3)
return min(x[0], min(x[1], x[2]));
int min = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] < min)
min = x[i];
return min;
}
static long minof(long a, long b, long c) {
return min(a, min(b, c));
}
static long minof(long... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return min(x[0], x[1]);
if (x.length == 3)
return min(x[0], min(x[1], x[2]));
long min = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] < min)
min = x[i];
return min;
}
static int maxof(int a, int b, int c) {
return max(a, max(b, c));
}
static int maxof(int... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return max(x[0], x[1]);
if (x.length == 3)
return max(x[0], max(x[1], x[2]));
int max = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] > max)
max = x[i];
return max;
}
static long maxof(long a, long b, long c) {
return max(a, max(b, c));
}
static long maxof(long... x) {
if (x.length == 1)
return x[0];
if (x.length == 2)
return max(x[0], x[1]);
if (x.length == 3)
return max(x[0], max(x[1], x[2]));
long max = x[0];
for (int i = 1; i < x.length; ++i)
if (x[i] > max)
max = x[i];
return max;
}
static int powi(int a, int b) {
if (a == 0)
return 0;
int ans = 1;
while (b > 0) {
if ((b & 1) > 0)
ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static long powl(long a, int b) {
if (a == 0)
return 0;
long ans = 1;
while (b > 0) {
if ((b & 1) > 0)
ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static int fli(double d) {
return (int) d;
}
static int cei(double d) {
return (int) ceil(d);
}
static long fll(double d) {
return (long) d;
}
static long cel(double d) {
return (long) ceil(d);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static int[] exgcd(int a, int b) {
if (b == 0)
return new int[] { 1, 0 };
int[] y = exgcd(b, a % b);
return new int[] { y[1], y[0] - y[1] * (a / b) };
}
static long[] exgcd(long a, long b) {
if (b == 0)
return new long[] { 1, 0 };
long[] y = exgcd(b, a % b);
return new long[] { y[1], y[0] - y[1] * (a / b) };
}
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static long mix(long x) {
x += 0x9e3779b97f4a7c15L;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
return x ^ (x >> 31);
}
public static boolean[] findPrimes(int limit) {
assert limit >= 2;
final boolean[] nonPrimes = new boolean[limit];
nonPrimes[0] = true;
nonPrimes[1] = true;
int sqrt = (int) Math.sqrt(limit);
for (int i = 2; i <= sqrt; i++) {
if (nonPrimes[i])
continue;
for (int j = i; j < limit; j += i) {
if (!nonPrimes[j] && i != j)
nonPrimes[j] = true;
}
}
return nonPrimes;
}
// array util
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i)
ans[i] = a[i];
return ans;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] ria(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = Integer.parseInt(next());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] rla(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = Long.parseLong(next());
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
java
|
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 Main {
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
Reader r = new Reader();
// int t = r.nextInt();
// while (t-- > 0) {
solve(r);
// }
System.out.println(sb.deleteCharAt(sb.length() - 1));
}
private static void solve(Reader sc) {
int n = sc.nextInt();
int[] nums = new int[n + 1];
int[] pre = new int[n + 1];
for (int i = 1; i <= n; i++) {
nums[i] = sc.nextInt();
pre[i] = pre[i - 1] + nums[i];
}
HashMap<Integer, ArrayList<int[]>> map = new HashMap<>();
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
int key = pre[j] - pre[i - 1];
ArrayList<int[]> list = map.getOrDefault(key, new ArrayList<>());
list.add(new int[]{i, j});
map.put(key, list);
}
}
int ans = 0;
ArrayList<int[]> maxQue = new ArrayList<>();
for (ArrayList<int[]> que : map.values()) {
ArrayList<int[]> cp = new ArrayList<>();
que.sort((o1, o2) -> o2[1] == o1[1] ? o2[0] - o1[0] : o1[1] - o2[1]);
cp.add(que.get(0));
int c = 1;
int preRight = que.get(0)[1];
for (int i = 1; i < que.size(); i++) {
if (preRight < que.get(i)[0]) {
c++;
preRight = que.get(i)[1];
cp.add(que.get(i));
}
}
if (ans < c) {
ans = c;
maxQue = cp;
}
}
println(ans);
for (int[] item :maxQue) {
printArr(item);
println();
}
}
static class BitIndexTree {
long[] trie;
int n;
public BitIndexTree(int n) {
this.n = n;
trie = new long[n + 1];
}
public static int lowBit(int x) {
return x & (-x);
}
public void add(int index, int v) {
while (index <= n) {
trie[index] += v;
index += lowBit(index);
}
}
public long query(int index) {
long ans = 0;
while (index > 0) {
ans += trie[index];
index -= lowBit(index);
}
return ans;
}
}
private static void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
public static long pow3(long a, long b) {
long ans = 1;
while (b > 0) {
if ((b & 1) == 1) {
ans *= a;
}
a *= a;
b >>= 1;
}
return ans;
}
public static long pow4(long a, long b, int p) {
long ans = 1;
a %= p;
while (b > 0) {
if ((b & 1) == 1) {
ans = ans * a % p;
}
a = a * a % p;
b >>= 1;
}
return ans;
}
public static List<Integer> euler(int n) {
boolean[] check = new boolean[n + 1];
List<Integer> ans = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (!check[i]) {
ans.add(i);
}
for (Integer item : ans) {
if (item * i > n) break;
check[(item * i)] = true;
if (i % item == 0) break;
}
}
return ans;
}
public static void euler_phi(int n) {
int ans = n;
for (int i = 2; i <= n / i; i++) {
if (n % i == 0) {
ans *= (1 - 1.0 / i);
while (n % i == 0) {
n /= i;
}
}
}
if (n > 1) ans *= (1 - 1.0 / n);
System.out.println(ans);
}
public static int[] eulers(int n) {
boolean[] check = new boolean[n + 1];
int[] phi = new int[n + 1];
phi[1] = 1;
ArrayList<Integer> primes = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (!check[i]) {
primes.add(i);
phi[i] = i - 1;
}
for (Integer item : primes) {
if (item * i > n) break;
check[item * i] = true;
if (i % item == 0) {
phi[item * i] = item * phi[i];
break;
}
phi[item * i] = (item - 1) * phi[i];
}
}
return phi;
}
static final Random random = new Random();
static void ruffleSort(int[] a) {
int n = a.length;//shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static class Reader {
BufferedReader buf;
StringTokenizer tok;
Reader() {
buf = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext() {
while (tok == null || !tok.hasMoreElements()) {
try {
tok = new StringTokenizer(buf.readLine());
} catch (Exception e) {
return false;
}
}
return true;
}
String nextLine() {
try {
return buf.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
if (hasNext()) return tok.nextToken();
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArrForSizeIndexOfOne(int size) {
int[] nums = new int[size + 1];
for (int i = 1; i <= size; i++) {
nums[i] = nextInt();
}
return nums;
}
int[] nextIntArrForSizeIndexOfZero(int size) {
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
nums[i] = nextInt();
}
return nums;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
private static void printf(Object t) {
sb.append(t).append(" ");
}
private static void println(Object t) {
sb.append(t).append("\n");
}
private static void println() {
sb.append("\n");
}
private static <T> void printArr(long[] arr) {
for (Object o : arr) {
sb.append(o).append(" ");
}
}
private static <T> void printArr(int[] arr) {
for (Object o : arr) {
sb.append(o).append(" ");
}
}
}
|
java
|
1300
|
B
|
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
|
[
"greedy",
"implementation",
"sortings"
] |
import java.util.*;
import java.io.*;
public class Problem{
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 main(String[] args){
int t;
FastReader f=new FastReader();
t=f.nextInt();
while(t-->0){
int n;
n=f.nextInt();
int[] arr=new int[2*n];
for (int i = 0; i < arr.length; i++) {
arr[i]=f.nextInt();
}
Arrays.sort(arr);
System.out.println(arr[arr.length/2]-arr[arr.length/2-1]);
}
}
}
|
java
|
1311
|
C
|
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.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.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.
|
[
"brute force"
] |
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class class15 {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;
}
}
static long gcd(long a,long b)
{
if(a==0)
{
return b;
}
return gcd(b%a,a);
}
static long findgcd(long a[])
{
long result=0;
for(long val:a)
{
result=gcd(result,val);
if(result==1)
{
return 1;
}
}
return result;
}
public static void main(String arg[])
{
Scanner input=new Scanner(System.in);
int t=input.nextInt();
while(t-->0) {
int n=input.nextInt();
int m=input.nextInt();
int b[]=new int[n];
int c[]=new int[26];
String s=input.next();
PriorityQueue<Integer>d=new PriorityQueue<>();
Arrays.fill(b,1);
for(int i=0;i<m;i++) {
int temp=input.nextInt();
d.add(temp);
}
int v=0;
while(d.size()>0) {
int temp=d.poll();
if(v==temp) {
continue;
}
else {
int temp2=d.size()+1;
for(int j=v;j<temp;j++) {
b[j]=b[j]+temp2;
}
v=temp;
}
}
for(int i=0;i<n;i++) {
int j=(int)s.charAt(i)-97;
c[j]=c[j]+b[i];
}
for(int i=0;i<26;i++) {
System.out.print(c[i]+" ");
}
System.out.println();
}
}
}
|
java
|
1288
|
B
|
B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).
|
[
"math"
] |
import java.util.*;
import java.io.*;
public class practice {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new PrintWriter(System.out)));
StringBuilder sb = new StringBuilder();
int t = Integer.parseInt(br.readLine());
while (t --> 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
long tot = 0;
for (long i = 9; i <= b; i = (i * 10) + 9) tot += a;
sb.append(tot).append("\n");
}
pw.println(sb.toString().trim());
pw.close();
br.close();
}
}
|
java
|
1307
|
D
|
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
|
[
"binary search",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"shortest paths",
"sortings"
] |
import java.io.*;
import java.util.*;
/*
*/
public class A {
static FastReader sc=null;
public static void main(String[] args) {
sc=new FastReader();
int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt();
int a[]=sc.readArray(k);
for(int i=0;i<k;i++)a[i]--;
ArrayList<Integer> adj[]=new ArrayList[n];
for(int i=0;i<n;i++)adj[i]=new ArrayList<>();
for(int i=0;i<m;i++) {
int v=sc.nextInt()-1,w=sc.nextInt()-1;
adj[v].add(w);
adj[w].add(v);
}
int dists[]=bfs(adj,0),diste[]=bfs(adj,n-1);
//maximize the minimum of (dist_s[u]+dist_e[v],dist_e[u]+dist_s[v])
//xa+yb<=xb+ya
//xa-ya<=xb-yb
//sort based on this and find the suffix maximum at each point of time
Pair ps[]=new Pair[k];
for(int i=0;i<k;i++) {
ps[i]=new Pair(a[i],dists[a[i]],diste[a[i]]);
}
Arrays.sort(ps);
//gives the maximum end until now
int suff[]=new int[k];
suff[k-1]=ps[k-1].e;
for(int i=k-2;i>=0;i--)suff[i]=Math.max(suff[i+1], ps[i].e);
int ans=0;
for(int i=0;i+1<k;i++) {
ans=Math.max(ps[i].s+suff[i+1]+1, ans);
}
ans=(Math.min(ans, dists[n-1]));
System.out.println(ans);
}
static class Pair implements Comparable<Pair>{
int id,s,e,sort;
Pair(int id,int s,int e){
this.id=id;
this.s=s;
this.e=e;
this.sort=s-e;
}
public int compareTo(Pair o) {
return this.sort-o.sort;
}
}
static int[] bfs(ArrayList<Integer> adj[],int src) {
int n=adj.length;
int dist[]=new int[n];
Arrays.fill(dist, -1);
dist[src]=0;
ArrayDeque<Integer> bfs=new ArrayDeque<>();
bfs.add(src);
while(!bfs.isEmpty()) {
int q=bfs.remove();
for(int e:adj[q]) {
if(dist[e]==-1) {
dist[e]=dist[q]+1;
bfs.add(e);
}
}
}
return dist;
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader{
StringTokenizer st=new StringTokenizer("");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String next() {
while(!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
}
catch(IOException e){
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
return a;
}
}
}
|
java
|
1288
|
F
|
F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
OutputCopy35
BUURRU
InputCopy3 1 3 4 5
RRR
B
2 1
1 1
3 1
OutputCopy-1
InputCopy3 1 3 4 5
URU
B
2 1
1 1
3 1
OutputCopy14
RBB
|
[
"constructive algorithms",
"flows"
] |
// upsolve with rainboy
import java.io.*;
import java.util.*;
public class CF1288F extends PrintWriter {
CF1288F() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1288F o = new CF1288F(); o.main(); o.flush();
}
static final int INF = 0x3f3f3f3f;
int[] oo, oh; int __ = 1;
int link(int o, int h) {
oo[__] = o; oh[__] = h;
return __++;
}
int[] ii, jj, cc, cost, cost_; int m_;
int[] ae, pi, dd, ff; int n_;
int[] pq, iq; int cnt;
void init() {
oo = new int[1 + m_ * 2]; oh = new int[1 + m_ * 2];
ii = new int[m_]; jj = new int[m_];
cc = new int[m_ * 2];
cost = new int[m_]; cost_ = new int[m_];
ae = new int[n_]; pi = new int[n_]; dd = new int[n_]; ff = new int[n_];
pq = new int[1 + n_]; iq = new int[n_];
m_ = 0;
}
void link_(int i, int j, int c, int co) {
int h = m_++;
ii[h] = i; jj[h] = j; cc[h << 1] = c; cost[h] = co;
ae[i] = link(ae[i], h << 1);
ae[j] = link(ae[j], h << 1 | 1);
}
boolean less(int u, int v) {
return pi[u] < pi[v] || pi[u] == pi[v] && dd[u] < dd[v];
}
int i2(int i) {
return (i *= 2) > cnt ? 0 : i < cnt && less(pq[i + 1], pq[i]) ? i + 1 : i;
}
void pq_up(int u) {
int i, j, v;
for (i = iq[u]; (j = i / 2) > 0 && less(u, v = pq[j]); i = j)
pq[iq[v] = i] = v;
pq[iq[u] = i] = u;
}
void pq_dn(int u) {
int i, j, v;
for (i = iq[u]; (j = i2(i)) > 0 && less(v = pq[j], u); i = j)
pq[iq[v] = i] = v;
pq[iq[u] = i] = u;
}
void pq_add_last(int u) {
pq[iq[u] = ++cnt] = u;
}
int pq_remove_first() {
int u = pq[1], v = pq[cnt--];
if (v != u) {
iq[v] = 1; pq_dn(v);
}
iq[u] = 0;
return u;
}
boolean dijkstra(int s, int t) {
Arrays.fill(pi, INF);
pi[s] = 0; pq_add_last(s);
while (cnt > 0) {
int i = pq_remove_first();
int d = dd[i] + 1;
for (int o = ae[i]; o != 0; o = oo[o]) {
int h_ = oh[o];
if (cc[h_] > 0) {
int h = h_ >> 1;
int j = i ^ ii[h] ^ jj[h];
int p = pi[i] + ((h_ & 1) == 0 ? cost_[h] : -cost_[h]);
if (pi[j] > p || (pi[j] == p && dd[j] > d)) {
if (pi[j] == INF)
pq_add_last(j);
pi[j] = p; dd[j] = d; ff[j] = h_;
pq_up(j);
}
}
}
}
return pi[t] != INF;
}
boolean trace(int s, int t) {
int sum = 0;
for (int i = t; i != s; ) {
int h_ = ff[i], h = h_ >> 1;
sum += (h_ & 1) == 0 ? cost[h] : -cost[h];
i ^= ii[h] ^ jj[h];
}
if (sum >= 0)
return false;
for (int i = t; i != s; ) {
int h_ = ff[i], h = h_ >> 1;
cc[h_]--; cc[h_ ^ 1]++;
i ^= ii[h] ^ jj[h];
}
return true;
}
int edmonds_karp(int s, int t) {
for (int h = 0; h < m_; h++)
cost_[h] = cost[h];
while (dijkstra(s, t)) {
if (!trace(s, t))
break;
for (int h = 0; h < m_; h++) {
int i = ii[h], j = jj[h];
if (pi[i] != INF && pi[j] != INF) {
// pi[j] <= pi[i] + cost_[h]
// cost_[h] + pi[i] - pi[j] >= 0
cost_[h] += pi[i] - pi[j];
}
}
}
int sum = 0;
for (int h = 0; h < m_; h++)
sum += cost[h] * cc[h << 1 | 1];
return sum;
}
void main() {
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int m = sc.nextInt();
int r = sc.nextInt();
int b = sc.nextInt();
int inf = m * (r + b) + 1;
n_ = 1 + n1 + n2 + 1;
m_ = (m + n1 + n2) * 2;
init();
byte[] c1 = sc.next().getBytes();
byte[] c2 = sc.next().getBytes();
for (int h = 0; h < m; h++) {
int i = sc.nextInt() - 1;
int j = sc.nextInt() - 1;
int i_ = 1 + i;
int j_ = 1 + n1 + j;
link_(i_, j_, 1, r);
link_(j_, i_, 1, b);
}
int s = 0, t = n_ - 1;
for (int i = 0; i < n1; i++) {
int i_ = 1 + i;
if (c1[i] == 'R') {
link_(s, i_, 1, -inf);
link_(s, i_, m, 0);
} else if (c1[i] == 'B') {
link_(i_, t, 1, -inf);
link_(i_, t, m, 0);
} else {
link_(s, i_, m, 0);
link_(i_, t, m, 0);
}
}
for (int j = 0; j < n2; j++) {
int j_ = 1 + n1 + j;
if (c2[j] == 'R') {
link_(j_, t, 1, -inf);
link_(j_, t, m, 0);
} else if (c2[j] == 'B') {
link_(s, j_, 1, -inf);
link_(s, j_, m, 0);
} else {
link_(s, j_, m, 0);
link_(j_, t, m, 0);
}
}
int ans = edmonds_karp(s, t);
for (int h = 0; h < m_; h++)
if (cost[h] == -inf) {
if (cc[h << 1 | 1] == 0) {
println(-1);
return;
}
ans += inf;
}
println(ans);
char[] colors = new char[m];
for (int h = 0; h < m; h++) {
int hr = h << 1, hb = h << 1 | 1;
if (cc[hr << 1 | 1] > 0)
colors[h] = 'R';
else if (cc[hb << 1 | 1] > 0)
colors[h] = 'B';
else
colors[h] = 'U';
}
println(colors);
}
}
|
java
|
1303
|
C
|
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
|
[
"dfs and similar",
"greedy",
"implementation"
] |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
public class PerfectKeyboard {
static BufferedReader br;
static PrintWriter pw;
static HashSet<Character>[] adj = new HashSet[26];
public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
for (int i = 0; i < t; i++) test();
}
static void test() throws Exception {
boolean[] visited = new boolean[26];
String str = br.readLine();
for (int i = 0; i < adj.length; i++) {
adj[i] = new HashSet<>();
}
for (int i = 0; i < str.length(); i++) {
int c = str.charAt(i) - 'a';
if (i > 0) adj[c].add(str.charAt(i - 1));
if (i < str.length() - 1) adj[c].add(str.charAt(i + 1));
if (adj[c].size() > 2) {
System.out.println("NO");
return;
}
}
for (int i = 0; i < 26; i++) {
char c = (char) (i + 97);
if (!visited[i]) {
boolean cycle = checkCycle(c, c, visited);
if (cycle) {
System.out.println("NO");
return;
}
}
}
System.out.println("YES");
var index = 0;
for (int i = 0; i < 26; i++) {
if (adj[i].size() == 1) {
index = i;
break;
}
}
char c = (char) (index + 97);
StringBuilder sb = getKeyboard(c, c, new StringBuilder(c + ""));
HashSet<Character> set = new HashSet<>();
for (int i = 0; i < 26; i++)
set.add((char) (i + 97));
for (int i = 0; i < sb.length(); i++)
set.remove(sb.charAt(i));
for (char s : set) sb.append(s);
System.out.println(sb);
}
static StringBuilder getKeyboard(char curr, char prev, StringBuilder sb) {
for (var a : adj[curr - 'a']) {
if (a != prev) {
sb.append(a);
getKeyboard(a, curr, sb);
}
}
return sb;
}
static boolean checkCycle(char c, char prev, boolean[] visited) {
if (visited[c - 'a']) return false;
visited[c - 'a'] = true;
for (char a : adj[c - 'a']) {
int v = a - 'a';
if (visited[v]) {
if (a != prev) return true;
} else {
if (checkCycle(a, c, visited)) return true;
}
}
return false;
}
}
|
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"
] |
// have faith in yourself!!!!!
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class CodeForces {
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void main(String[] args) throws IOException {
openIO();
int testCase = 1;
// testCase = sc. nextInt();
for (int i = 1; i <= testCase; i++) solve(i);
closeIO();
}
public static void solve(int tCase) throws IOException {
Deque<Integer> [] left = new ArrayDeque[27];
Deque<Integer> [] right = new ArrayDeque[27];
for(int i=0;i<27;i++){
left[i] = new ArrayDeque<>();
right[i] = new ArrayDeque<>();
}
int n = sc.nextInt();
char[] s = sc.next().toCharArray();
for(int i=0;i<n;i++){
if(s[i]=='?')left[26].add(i);
else left[s[i] - 'a'].add(i);
}
s = sc.next().toCharArray();
for(int i=0;i<n;i++){
if(s[i]=='?')right[26].add(i);
else right[s[i] - 'a'].add(i);
}
List<int[]> ans = new ArrayList<>();
for(int i=0;i<27;i++){
Deque<Integer> ll = left[i];
Deque<Integer> rr = right[i];
while (!ll.isEmpty() && !rr.isEmpty()){
ans.add(new int[]{ll.pop(),rr.pop()});
}
Deque<Integer> rrr = right[26];
while (!ll.isEmpty() && !rrr.isEmpty()){
ans.add(new int[]{ll.pop(),rrr.pop()});
}
Deque<Integer> lll = left[26];
while (!lll.isEmpty() && !rr.isEmpty()){
ans.add(new int[]{lll.pop(),rr.pop()});
}
}
out.println(ans.size());
for(int[] x : ans)out.println((x[0]+1)+" "+(x[1]+1));
}
public static int mod = (int) 1e9 + 7;
// public static int mod = 998244353;
public static int inf_int = (int) 2e9 ;
public static long inf_long = (long) 2e14;
public static void _sort(int[] arr,boolean isAscending){
int n = arr.length;
List<Integer> list = new ArrayList<>();
for(int ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
public static void _sort(long[] arr,boolean isAscending){
int n = arr.length;
List<Long> list = new ArrayList<>();
for(long ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
static class Pair<K,V> {
K f;
V s;
public Pair(K f) {
this.f = f;
}
public Pair(K f, V s) {
this.f = f;
this.s = s;
}
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException{
sc = new FastestReader();
out = new PrintWriter(System.out);
}
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
public static void closeIO() throws IOException{
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) { return -ret; }
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) { buffer[0] = -1; }
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) { fillBuffer(); }
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
}
|
java
|
1311
|
E
|
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example:
|
[
"brute force",
"constructive algorithms",
"trees"
] |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
// editorial: start w chain & move leaves up (-1 sum depth every move)
public class cf1311e {
public static void main(String[] args) throws IOException {
int t = ri();
next:
while (t --> 0) {
int n = rni(), d = ni(), cur = n * (n - 1) / 2, lb = 0;
for (int dep = 0, sz = 1, left = n; left > 0; ++dep, sz <<= 1) {
int delta = min(left, sz);
left -= delta;
lb += dep * delta;
}
if (d < lb || cur < d) {
prN();
continue;
}
int ans[] = new int[n - 1], dep[] = new int[n], chd_cnt[] = new int[n];
for (int i = 1; i < n; ++i) {
ans[i - 1] = dep[i] = i;
chd_cnt[i - 1] = 1;
}
boolean bad[] = new boolean[n];
while (cur > d) {
int leaf = -1, new_par = -1;
for (int i = 1; i < n; ++i) {
if (!bad[i] && chd_cnt[i] == 0 && (leaf == -1 || dep[i] < dep[leaf])) {
leaf = i;
}
}
if (leaf == -1) {
prN();
continue next;
}
for (int i = 0; i < n; ++i) {
if (chd_cnt[i] < 2 && dep[i] == dep[leaf] - 2) {
new_par = i;
break;
}
}
if (new_par == -1) {
bad[leaf] = true;
continue;
}
--chd_cnt[ans[leaf - 1] - 1];
++chd_cnt[new_par];
ans[leaf - 1] = new_par + 1;
--dep[leaf];
--cur;
}
prY();
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
|
1288
|
B
|
B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).
|
[
"math"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
public class Main {
static BiFunction<Integer, Integer, Integer> ADD = (x, y) -> (x + y);
static BiFunction<ArrayList<Integer>, ArrayList<Integer>, ArrayList<Integer>> ADD_ARRAY_LIST = (x, y) -> {
x.addAll(y);
return x;
};
static Function<Pair<Integer, Integer>, Integer> GET_FIRST = (x) -> (x.first);
static Function<Pair<Integer, Integer>, Integer> GET_SECOND = (x) -> (x.second);
static Comparator<Pair<Integer, Integer>> C = Comparator.comparing(x -> x.first + x.second);
static long MOD = 1_000_000_000 + 7;
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
int t = in.nextInt();
while (t-- > 0) {
solve();
}
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms");
exit(0);
}
static void solve() {
int a = in.nextInt();
int b = in.nextInt();
long start = 0;
long count = 0;
while (start * 10 + 9 <= b) {
start = start * 10 + 9;
count++;
}
out.println(count * a);
}
static void debug(Object... args) {
for (Object a : args) {
out.println(a);
}
}
static int dist(Pair<Integer, Integer> a, Pair<Integer, Integer> b) {
return Math.abs(a.first - b.first) + Math.abs(a.second - b.second);
}
static void y() {
out.println("YES");
}
static void n() {
out.println("NO");
}
static int[] stringToArray(String s) {
return s.chars().map(x -> Character.getNumericValue(x)).toArray();
}
static <T> T min(T a, T b, Comparator<T> C) {
if (C.compare(a, b) <= 0) {
return a;
}
return b;
}
static <T> T max(T a, T b, Comparator<T> C) {
if (C.compare(a, b) >= 0) {
return a;
}
return b;
}
static void fail() {
out.println("-1");
}
static class Pair<T, R> {
public T first;
public R second;
public Pair(T first, R second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Pair<?, ?> pair = (Pair<?, ?>) o;
return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "Pair{" + "a=" + first + ", b=" + second + '}';
}
public T getFirst() {
return first;
}
public R getSecond() {
return second;
}
}
static <T, R> Pair<T, R> make_pair(T a, R b) {
return new Pair<>(a, b);
}
static long mod_inverse(long a, long m) {
Number x = new Number(0);
Number y = new Number(0);
extended_gcd(a, m, x, y);
return (m + x.v % m) % m;
}
static long extended_gcd(long a, long b, Number x, Number y) {
long d = a;
if (b != 0) {
d = extended_gcd(b, a % b, y, x);
y.v -= (a / b) * x.v;
} else {
x.v = 1;
y.v = 0;
}
return d;
}
static class Number {
long v = 0;
public Number(long v) {
this.v = v;
}
}
static int lcm(int a, int b) {
int p = a * b;
return (int) (p / gcd(a, b));
}
static int gcd(int a, int b) {
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
static class ArrayUtils {
static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(char[] a, int i, int j) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void print(char[] a) {
for (char c : a) {
out.print(c);
}
out.println("");
}
static int[] reverse(int[] data) {
int[] p = new int[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static void prefixSum(long[] data) {
for (int i = 1; i < data.length; i++) {
data[i] += data[i - 1];
}
}
static void prefixSum(int[] data) {
for (int i = 1; i < data.length; i++) {
data[i] += data[i - 1];
}
}
static long[] reverse(long[] data) {
long[] p = new long[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static char[] reverse(char[] data) {
char[] p = new char[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static int[] MergeSort(int[] A) {
if (A.length > 1) {
int q = A.length / 2;
int[] left = new int[q];
int[] right = new int[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
int[] left_sorted = MergeSort(left);
int[] right_sorted = MergeSort(right);
return Merge(left_sorted, right_sorted);
} else {
return A;
}
}
static int[] Merge(int[] left, int[] right) {
int[] A = new int[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
static long[] MergeSort(long[] A) {
if (A.length > 1) {
int q = A.length / 2;
long[] left = new long[q];
long[] right = new long[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
long[] left_sorted = MergeSort(left);
long[] right_sorted = MergeSort(right);
return Merge(left_sorted, right_sorted);
} else {
return A;
}
}
static long[] Merge(long[] left, long[] right) {
long[] A = new long[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
static int upper_bound(int[] data, int num, int start) {
int low = start;
int high = data.length - 1;
int mid = 0;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (data[mid] < num) {
low = mid + 1;
} else if (data[mid] >= num) {
high = mid - 1;
ans = mid;
}
}
if (ans == -1) {
return 100000000;
}
return data[ans];
}
static int lower_bound(int[] data, int num, int start) {
int low = start;
int high = data.length - 1;
int mid = 0;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (data[mid] <= num) {
low = mid + 1;
ans = mid;
} else if (data[mid] > num) {
high = mid - 1;
}
}
if (ans == -1) {
return 100000000;
}
return data[ans];
}
}
static boolean[] primeSieve(int n) {
boolean[] primes = new boolean[n + 1];
Arrays.fill(primes, true);
primes[0] = false;
primes[1] = false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (primes[i]) {
for (int j = i * i; j <= n; j += i) {
primes[j] = false;
}
}
}
return primes;
}
// Iterative Version
static HashMap<Integer, Boolean> subsets_sum_iter(int[] data) {
HashMap<Integer, Boolean> temp = new HashMap<Integer, Boolean>();
temp.put(data[0], true);
for (int i = 1; i < data.length; i++) {
HashMap<Integer, Boolean> t1 = new HashMap<Integer, Boolean>(temp);
t1.put(data[i], true);
for (int j : temp.keySet()) {
t1.put(j + data[i], true);
}
temp = t1;
}
return temp;
}
static HashMap<Integer, Integer> subsets_sum_count(int[] data) {
HashMap<Integer, Integer> temp = new HashMap<>();
temp.put(data[0], 1);
for (int i = 1; i < data.length; i++) {
HashMap<Integer, Integer> t1 = new HashMap<>(temp);
t1.merge(data[i], 1, ADD);
for (int j : temp.keySet()) {
t1.merge(j + data[i], temp.get(j) + 1, ADD);
}
temp = t1;
}
return temp;
}
static class Graph {
ArrayList<Integer>[] g;
boolean[] visited;
ArrayList<Integer>[] graph(int n) {
g = new ArrayList[n];
visited = new boolean[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
return g;
}
void BFS(int s) {
Queue<Integer> Q = new ArrayDeque<>();
visited[s] = true;
Q.add(s);
while (!Q.isEmpty()) {
int v = Q.poll();
for (int a : g[v]) {
if (!visited[a]) {
visited[a] = true;
Q.add(a);
}
}
}
}
}
static class SparseTable {
int[] log;
int[][] st;
public SparseTable(int n, int k, int[] data, BiFunction<Integer, Integer, Integer> f) {
log = new int[n + 1];
st = new int[n][k + 1];
log[1] = 0;
for (int i = 2; i <= n; i++) {
log[i] = log[i / 2] + 1;
}
for (int i = 0; i < data.length; i++) {
st[i][0] = data[i];
}
for (int j = 1; j <= k; j++)
for (int i = 0; i + (1 << j) <= data.length; i++)
st[i][j] = f.apply(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
}
public int query(int L, int R, BiFunction<Integer, Integer, Integer> f) {
int j = log[R - L + 1];
return f.apply(st[L][j], st[R - (1 << j) + 1][j]);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 2048);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readAllInts(int n) {
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextInt();
}
return p;
}
public int[] readAllInts(int n, int s) {
int[] p = new int[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextInt();
}
return p;
}
public long[] readAllLongs(int n) {
long[] p = new long[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextLong();
}
return p;
}
public long[] readAllLongs(int n, int s) {
long[] p = new long[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextLong();
}
return p;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static void exit(int a) {
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
|
java
|
1323
|
A
|
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
|
[
"brute force",
"dp",
"greedy",
"implementation"
] |
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Task1323A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.nextLine());
int[] par = new int[t];
int[][] value = new int[100][100];
for (int i = 0; i < t; i++) {
par[i] = Integer.parseInt(in.nextLine());
value[i] = parser(in.nextLine());
}
task(par, value);
}
public static int[] parser(String str) {
String[] strArr = str.split(" ");
int[] numArr = new int[strArr.length];
for (int i = 0; i < strArr.length; i++) {
numArr[i] = Integer.parseInt(strArr[i]);
}
return numArr;
}
public static void task(int[] par, int[][] value) {
int dp = 0;
boolean f = true;
for (int i = 0; i < par.length; i++) {
f = true;
dp = 0;
for (int j = 0; j < par[i]; j++) {
if (value[i][j] % 2 == 0) {
System.out.println(1);
System.out.println(j + 1);
f = false;
break;
} else {
if (dp == 0) {
dp = j + 1;
} else {
System.out.println(2);
System.out.println(dp + " " + (j + 1));
f = false;
break;
}
}
}
if (f) {
System.out.println(-1);
}
}
}
}
|
java
|
1324
|
B
|
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.
|
[
"brute force",
"strings"
] |
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static final PrintWriter out =new PrintWriter(System.out);
static final FastReader sc = new FastReader();
//I invented a new word!Plagiarism!
//Did you hear about the mathematician who’s afraid of negative numbers?He’ll stop at nothing to avoid them
//What do Alexander the Great and Winnie the Pooh have in common? Same middle name.
//I finally decided to sell my vacuum cleaner. All it was doing was gathering dust!
//ArrayList<Integer> a=new ArrayList <Integer>();
//PriorityQueue<Integer> pq=new PriorityQueue<>();
//char[] a = s.toCharArray();
// char s[]=sc.next().toCharArray();
public static boolean sorted(int a[])
{
int n=a.length,i;
int b[]=new int[n];
for(i=0;i<n;i++)
b[i]=a[i];
Arrays.sort(b);
for(i=0;i<n;i++)
{
if(a[i]!=b[i])
return false;
}
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
int tes=sc.nextInt();
label:while(tes-->0)
{
int n=sc.nextInt();
int a[]=new int[n];
int i,j;
for(i=0;i<n;i++)
a[i]=sc.nextInt();
for(i=0;i<n;i++)
{
for(j=i+2;j<n;j++)
{
if(a[i]==a[j])
{
System.out.println("Yes");
continue label;
}
}
}
System.out.println("No");
}
}
public static int first(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)
return mid;
else if (x > arr.get(mid))
return first(arr, (mid + 1), high, x, n);
else
return first(arr, low, (mid - 1), x, n);
}
return -1;
}
public static int last(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)
return mid;
else if (x < arr.get(mid))
return last(arr, low, (mid - 1), x, n);
else
return last(arr, (mid + 1), high, x, n);
}
return -1;
}
public static int lis(int[] arr) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>=x) {
al.add(arr[i]);
}else {
int v = upper_bound(al, 0, al.size(), arr[i]);
al.set(v, arr[i]);
}
}
return al.size();
}
public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get((int)mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long mod=1000000007;
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
java
|
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.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.AbstractMap;
import java.util.TreeMap;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jaynil
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public static void add(TreeMap x, int p) {
x.put(p, (int) x.getOrDefault(p, 0) + 1);
}
public static void remove(TreeMap x, int p) {
int cnt = (int) x.get(p) - 1;
if (cnt == 0) {
x.remove(p);
} else x.put(p, cnt);
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
ArrayList<node> a = new ArrayList<>();
ArrayList<node> b = new ArrayList<>();
for (int i = 0; i < n; i++) {
int p = in.nextInt();
int q = in.nextInt();
int r = in.nextInt();
int s = in.nextInt();
a.add(new node(p, r, s, 1));
a.add(new node(q, r, s, 0));
b.add(new node(r, p, q, 1));
b.add(new node(s, p, q, 0));
}
Collections.sort(a, (x, y) -> Integer.compare(x.x, y.x) != 0 ? Integer.compare(x.x, y.x) : Integer.compare(y.st, x.st));
TreeMap<Integer, Integer> start = new TreeMap<Integer, Integer>();
TreeMap<Integer, Integer> end = new TreeMap<Integer, Integer>();
for (int i = 0; i < a.size(); i++) {
if (a.get(i).st == 1) {
if (!start.isEmpty()) {
int ss = Math.max(start.lastKey(), a.get(i).s);
int ee = Math.min(end.firstKey(), a.get(i).e);
if (ss > ee) {
out.println("NO");
return;
}
}
add(start, a.get(i).s);
add(end, a.get(i).e);
} else {
remove(start, a.get(i).s);
remove(end, a.get(i).e);
}
}
Collections.sort(b, (x, y) -> Integer.compare(x.x, y.x) != 0 ? Integer.compare(x.x, y.x) : Integer.compare(y.st, x.st));
for (int i = 0; i < b.size(); i++) {
if (b.get(i).st == 1) {
if (!start.isEmpty()) {
int ss = Math.max(start.lastKey(), b.get(i).s);
int ee = Math.min(end.firstKey(), b.get(i).e);
if (ss > ee) {
out.println("NO");
return;
}
}
add(start, b.get(i).s);
add(end, b.get(i).e);
} else {
remove(start, b.get(i).s);
remove(end, b.get(i).e);
}
}
out.println("YES");
}
class node {
int x;
int s;
int e;
int st;
node(int x, int s, int e, int start) {
this.x = x;
this.s = s;
this.e = e;
this.st = start;
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
java
|
1325
|
A
|
A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100) — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.
|
[
"constructive algorithms",
"greedy",
"number theory"
] |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
while(t!=0)
{
int x=sc.nextInt();
int a=1;
int b=x-1;
int lcm=0;
int gcd=1;
int p=0;
while(true)
{
for(int i=1;i<=a&&i<=b;i++)
{
if(a%i==0 && b%i==0)
{
gcd=i;
}
}
lcm=(a*b)/gcd;
if(lcm+gcd==x)
{
//p=1;
break;
}
a++;
b--;
}
System.out.println(a+" "+b);
t--;
}
}
}
|
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"
] |
// package c1294;
//
// Codeforces Round #615 (Div. 3) 2020-01-22 06:35
// A. Collecting Coins
// https://codeforces.com/contest/1294/problem/A
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently,
// Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned
// from the trip around the world and brought n coins.
//
// He wants to distribute these n 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 A coins to Alice, B coins to Barbara and C coins to Cerene
// (A+B+C=n), then a + A = b + B = c + C.
//
// 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 n coins between sisters in a way
// described above.
//
// You have to answer t independent test cases.
//
// Input
//
// The first line of the input contains one integer t (1 <= t <= 10^4) -- the number of test cases.
//
// The next t lines describe test cases. Each test case is given on a new line and consists of four
// space-separated integers a, b, c and n (1 <= a, b, c, n <= 10^8) -- 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.
//
// Output
//
// For each test case, print "YES" if Polycarp can distribute n coins between his sisters and "NO"
// otherwise.
//
// Example
/*
input:
5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
output:
YES
YES
NO
NO
YES
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1294A {
static final int MOD = 998244353;
static final Random RAND = new Random();
static boolean solve(int a, int b, int c, int n) {
int sum = a + b + c + n;
if (sum % 3 != 0) {
return false;
}
int m = sum / 3;
return a <= m && b <= m && c <= m ? true : false;
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int n = in.nextInt();
boolean ans = solve(a, b, c, n);
System.out.println(ans? "YES" : "NO");
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 4000) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
java
|
1321
|
C
|
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a.
|
[
"brute force",
"constructive algorithms",
"greedy",
"strings"
] |
import java.util.*;
import java.io.*;
import java.text.*;
public class C1321 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
char[] arr = sc.next().toCharArray();
ArrayList<Character> a = new ArrayList<Character>();
for (char c : arr)
a.add(c);
int og = a.size();
while (a.size() > 0) {
int remove = -1;
char rem = 0;
for (int i = 0; i < a.size(); i++) {
if (remove == -1) {
if (i != 0) {
if (a.get(i - 1) == a.get(i) - 1) {
remove = i;
rem = a.get(i);
}
}
if (i != a.size() - 1) {
if (a.get(i + 1) == a.get(i) - 1) {
remove = i;
rem = a.get(i);
}
}
} else if (a.get(i) > rem) {
if (i != 0) {
if (a.get(i - 1) == a.get(i) - 1) {
remove = i;
rem = a.get(i);
}
}
if (i != a.size() - 1) {
if (a.get(i + 1) == a.get(i) - 1) {
remove = i;
rem = a.get(i);
}
}
}
}
if (remove == -1)
break;
else
a.remove(remove);
}
pw.println(og - a.size());
pw.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
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 int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextInt();
return arr;
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
java
|
1304
|
E
|
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
|
[
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] |
import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
static class seg_tree {
int seg_tree[],seg_indx[];
public seg_tree(int n,int arr[]) {
seg_tree=new int[4*n];
seg_indx=new int[4*n];
create_seg_tree(arr,0,0,n-1);
}
//0 index-Left child-(2*i+1) Right Child-(2*i+2)
public void create_seg_tree(int arr[],int vertex,int l,int r) {
if(l==r) {
seg_indx[vertex]=r;
seg_tree[vertex]=arr[r];
return;
}
int mid=(l+r)/2;
//Left Child
create_seg_tree(arr,(2*vertex)+1,l,mid);
//Right Child
create_seg_tree(arr,(2*vertex)+2,mid+1,r);
//Filling this node
if(seg_tree[(2*vertex)+1]<seg_tree[(2*vertex)+2]) {
seg_tree[vertex]=seg_tree[(2*vertex)+1];
seg_indx[vertex]=seg_indx[(2*vertex)+1];
}
else {
seg_tree[vertex]=seg_tree[(2*vertex)+2];
seg_indx[vertex]=seg_indx[(2*vertex)+2];
}
}
public int[] min(int vertex,int l,int r,int ql,int qr) { //ql->query left , qr-> query right l->curr Segmrnt left r->curr segment right
if(ql>qr) {
return new int[]{Integer.MAX_VALUE,-1};
}
if(ql==l && qr==r) {
return new int[]{seg_tree[vertex],seg_indx[vertex]};
}
int mid=(l+r)/2;
//Left Child
int min1[]=min((2*vertex)+1,l,mid,ql,Math.min(qr, mid));
//Right Child
int min2[]=min((2*vertex)+2,mid+1,r,Math.max(mid+1,ql),qr);
if(min1[0]<min2[0]) {
return min1;
}
else {
return min2;
}
}
public void update(int vertex,int l,int r,int pos,int value) { //pos->Position of the update value->updates value
if(l==r) {
seg_tree[vertex]=value;
return;
}
int mid=(l+r)/2;
//Left Child
if(pos<=mid) {
update((2*vertex)+1,l,mid,pos,value);
}
//Right Child
else {
update((2*vertex)+2,mid+1,r,pos,value);
}
if(seg_tree[(2*vertex)+1]<seg_tree[(2*vertex)+2]) {
seg_tree[vertex]=seg_tree[(2*vertex)+1];
seg_indx[vertex]=seg_indx[(2*vertex)+1];
}
else {
seg_tree[vertex]=seg_tree[(2*vertex)+2];
seg_indx[vertex]=seg_indx[(2*vertex)+2];
}
}
}
static ArrayList<Integer> adj_lst[],et,etd;
static int parent[],euler_tour_depth[],euler_tour[],first[],depth[];
static seg_tree st;
public static void main(String args[]) throws IOException {
Scan input=new Scan();
int n=input.scanInt();
adj_lst=new ArrayList[n];
parent=new int[n];
et=new ArrayList<>();
etd=new ArrayList<>();
depth=new int[n];
for(int i=0;i<n;i++) {
adj_lst[i]=new ArrayList<>();
}
for(int i=0;i<n-1;i++) {
int u=input.scanInt()-1;
int v=input.scanInt()-1;
adj_lst[u].add(v);
adj_lst[v].add(u);
}
DFS(0,-1,0);
euler_tour_depth=new int[et.size()];
euler_tour=new int[etd.size()];
for(int i=0;i<et.size();i++) {
euler_tour[i]=et.get(i);
euler_tour_depth[i]=etd.get(i);
}
st=new seg_tree(euler_tour_depth.length,euler_tour_depth);
first=new int[n];
Arrays.fill(first, -1);
for(int i=0;i<euler_tour.length;i++) {
if(first[euler_tour[i]]==-1) {
first[euler_tour[i]]=i;
}
}
StringBuilder ans=new StringBuilder("");
int q=input.scanInt();
for(int qq=1;qq<=q;qq++) {
int x=input.scanInt()-1;
int y=input.scanInt()-1;
int a=input.scanInt()-1;
int b=input.scanInt()-1;
int k=input.scanInt();
if(solve(x,y,a,b,k)) {
ans.append("YES\n");
}
else {
ans.append("NO\n");
}
}
System.out.println(ans);
}
public static boolean solve(int x,int y,int a,int b,int k) {
int dist1=get_dist(a,b);
int dist2=Math.min(get_dist(x,a)+get_dist(y,b),get_dist(y,a)+get_dist(x,b))+1;
// System.out.println(dist1+" "+dist2);
if(k<Math.min(dist1,dist2)) {
return false;
}
if(k>=dist1 && k%2==dist1%2) {
return true;
}
if(k>=dist2 && k%2==dist2%2) {
return true;
}
return false;
}
public static int get_dist(int u,int v) {
int lca=get_lca(u,v);
return Math.abs(depth[lca]-depth[u])+Math.abs(depth[lca]-depth[v]);
}
public static int get_lca(int u,int v) {
int l=Math.min(first[u],first[v]);
int r=Math.max(first[u],first[v]);
int indx=st.min(0, 0, euler_tour_depth.length-1, l, r)[1];
return euler_tour[indx];
}
public static void DFS(int root,int par,int dep) {
parent[root]=par;
et.add(root);
etd.add(dep);
depth[root]=dep;
for(int i=0;i<adj_lst[root].size();i++) {
if(adj_lst[root].get(i)==par) {
continue;
}
DFS(adj_lst[root].get(i),root,dep+1);
et.add(root);
etd.add(dep);
}
}
}
|
java
|
1305
|
A
|
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
|
[
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] |
import java.util.*;
import java.io.*;
public class solution {
static FastReader in=new FastReader();
static final Random random=new Random();
static long mod=1000000007L;
static HashMap<String,Integer>map=new HashMap<>();
public static void main(String args[]) throws IOException {
int t=in.nextInt();
while(t-->0){
int n=in.nextInt();
int[] xi=new int[n];
int[] yi=new int[n];
for(int i=0;i<n;i++) xi[i]=in.nextInt();
for(int i=0;i<n;i++) yi[i]=in.nextInt();
Arrays.sort(xi);
Arrays.sort(yi);
for(int i:xi) System.out.print(i+" ");
System.out.println();
for(int i:yi) System.out.print(i+" ");
System.out.println();
}
}
static boolean containsSubsequence(String s,String a){
int i=0,j=0;
while(i<a.length() && j<s.length()){
if(s.charAt(j)==a.charAt(i)) i++;
j++;
}
return i>=a.length();
}
static boolean isPalindrome(String a){
int n=a.length();
for(int i=0;i<a.length();i++){
if(a.charAt(i)!=a.charAt(n-i-1)) return false;
}
return true;
}
static int lengthOfLIS(int[] nums)
{
int n=nums.length;
int[] lisi = new int[n];
for(int i=0;i<n;i++) lisi[i]=1;
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if(nums[j]<=nums[i]){
lisi[i]=lisi[j]+1;
}
}
}
return lisi[n-1];
}
// static int lengthOfLIS(int[] nums)
// {
// int[] tails = new int[nums.length];
// int size = 0;
// for (int x : nums) {
// int i = 0, j = size;
// while (i != j) {
// int m = (i + j) / 2;
// if (tails[m] <= x)
// i = m + 1;
// else
// j = m;
// }
// tails[i] = x;
// if (i == size) ++size;
// }
// return size;
// }
static void swap(int[] arr,int a,int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
static int max(int a, int b)
{
if(a<b)
return b;
return a;
}
static int min(int a,int b){
if(a > b)
return b;
return a;
}
static void ruffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static < E > void print(E res)
{
System.out.println(res);
}
static int gcd(int a,int b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static int abs(int a)
{
if(a<0)
return -1*a;
return a;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
int [] readintarray(int n) {
int res [] = new int [n];
for(int i = 0; i<n; i++)res[i] = nextInt();
return res;
}
long [] readlongarray(int n) {
long res [] = new long [n];
for(int i = 0; i<n; i++)res[i] = nextLong();
return res;
}
}
}
|
java
|
1324
|
B
|
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.
|
[
"brute force",
"strings"
] |
import java.io.*;import java.util.*;
public class Main {
static FastReader fr=new FastReader();
public static void main(String[] args) throws IOException {
int tt=1;
tt=fr.ni();
while(tt-->0) {
int n=fr.ni();
int a[]=iarr(n);
Map<Integer,Integer> hm=new HashMap<>();
boolean f=false;
for(int i=0;i<n;i++) {
if(hm.containsKey(a[i])) {
if(i-hm.get(a[i])>1) {
// System.out.println(i+" i here ");
f=true;
break;
}
}
else hm.put(a[i], i);
}
System.out.println(f==true?"YES":"NO");
}
}
static void opil(List<Integer> al) {StringBuilder sb= new StringBuilder();for(int x:al)sb.append(x+" ");System.out.println(sb.toString());}
static void opll(List<Long> al) {StringBuilder sb= new StringBuilder();for(long x:al)sb.append(x+" ");System.out.println(sb.toString());}
static int[] iarr(int n) {int a[]=new int[n];for(int i=0;i<n;i++)a[i]=fr.ni();return a;}
static long[] larr(int n) {long a[]=new long[n];for(int i=0;i<n;i++)a[i]=fr.nl();return a;}
static void op(int a[]) {StringBuilder sb= new StringBuilder();for(int x:a)sb.append(x+" ");System.out.println(sb.toString());}
static void op(long a[]) {StringBuilder sb= new StringBuilder();for(long x:a)sb.append(x+" ");System.out.println(sb.toString());}
static void sort(int[] a) {ArrayList<Integer>l=new ArrayList<>();for(int i:a) l.add(i);Collections.sort(l);for (int i=0; i<a.length; i++) a[i]=l.get(i);}
static void sort(long[] a) {ArrayList<Long>l=new ArrayList<>();for(long i:a) l.add(i);Collections.sort(l);for (int i=0; i<a.length; i++) a[i]=l.get(i);}
static 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 ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
java
|
1304
|
C
|
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
|
[
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] |
import java.io.*;
import java.util.*;
public class cf {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
//st = new StringTokenizer(br.readLine());
int q = Integer.parseInt(br.readLine());
while(q-->0){
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int t = 0;
int max = m;
int min = m;
int f = 0;
int[][] arr = new int[n][3];
for(int i=0; i<n; i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
max += (a-t);
min -= (a-t);
if(max<b || min>c){
f++;
}
max = Math.min(max, c);
min = Math.max(min, b);
t = a;
}
if(f==0){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
}
|
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.util.*;
import java.util.Scanner;
public class Main {
static int mod=1000000007;
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
for(int i=0;i<n;i++)
{
int num=scn.nextInt();
answer(num);
}
}
public static void answer(int n)
{
int a;
int b;
int c=0;
for(a=2;a*a*a<=n;a++)
{
if(n%a==0)
{
break;
}
}
int rem=n/a;
for( b=a+1;b*b<=rem;b++)
{
if(rem%b==0)
{
c=rem/b;
if(b>=c)
{
c=0;
}
break;
}
}
if(a*b*c==n)
{
System.out.println("YES");
System.out.println(a+" "+b+" "+c);
return;
}
System.out.println("NO");
}
}
|
java
|
1316
|
A
|
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.
|
[
"implementation"
] |
import java.lang.*;
// import java.math.*;
import java.io.*;
import java.util.*;
public class Main{
public static int mod=(int)(1e9) + 7;
public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter ot=new PrintWriter(System.out);
public static int[] take_arr(int n){
int a[]=new int[n];
try {
String s[]=br.readLine().trim().split(" ");
for(int i=0;i<n;i++)
a[i]=Integer.parseInt(s[i]);
} catch (Exception e) {
e.printStackTrace();
}
return a;
}
public static void main (String[] args) throws java.lang.Exception
{
try{
int t=Integer.parseInt(br.readLine().trim());
int cno=1;
while(t-->0){
String s[]=br.readLine().trim().split(" ");
int n=Integer.parseInt(s[0]);
int m=Integer.parseInt(s[1]);
// int k=Integer.parseInt(s[2]);
int a[]=take_arr(n);
// int b[]=take_arr(n);
// char ch[]=br.readLine().trim().toCharArray();
// long n=Long.parseLong(s[0]);
solve(a,n,m);
}
ot.close();
br.close();
}catch(Exception e){
e.printStackTrace();
return;
}
}
static void solve(int a[], int n, int m){
try{
for(int i=1;i<n;i++){
a[0]+=Math.min(a[i], m-a[0]);
}
ot.println(a[0]);
} catch(Exception e){
e.printStackTrace();
return ;
}
}
}
|
java
|
1305
|
A
|
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
|
[
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] |
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
for(int x=0;x<t;x++){
int n=Integer.parseInt(br.readLine());
StringTokenizer st=new StringTokenizer(br.readLine());
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(st.nextToken());
}
st=new StringTokenizer(br.readLine());
int b[]=new int[n];
for(int i=0;i<n;i++){
b[i]=Integer.parseInt(st.nextToken());
}
Arrays.sort(a);
Arrays.sort(b);
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
System.out.println();
for(int i=0;i<n;i++){
System.out.print(b[i]+" ");
}
System.out.println();
}
}
}
|
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 Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine());
int sum = 0;
for(int i=2;i<=n-1;i++){
int p = n;
while(p > 0){
sum += (p % i);
p /= i;
}
}
int a = sum, b = n - 2;
while(b > 0){
int pom = b;
b = a % b;
a = pom;
}
System.out.println((sum/a) + "/" + ((n - 2)/a));
}
}
|
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 {
static long mod = 1000000007;
static long max ;
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
int t = sc.nextInt();
while( t-- > 0) {
/*
* i will form a arrray or 2n integers assign all integers strating form 1 with diff 2 the value give in b
*
*/
HashSet<Integer> hs = new HashSet<>();
int n = sc.nextInt();
int b[] = new int[n];
for( int i = 0 ;i< n ;i++) {
b[i] = sc.nextInt();
}
boolean check = true;
int arr[] = new int[2*n];
int j = 0;
for( int i = 0 ;i < 2*n ;i+=2) {
arr[i] = b[j];
hs.add(b[j]);
j++;
}
for( int i = 1 ;i< 2*n ;i+=2) {
boolean find = false;
for( j = arr[i-1]+ 1 ; j<=2*n ;j++) {
if(!hs.contains(j)) {
find = true;
arr[i] = j;
hs.add(j);
break;
}
}
if( !find) {
check = false;
}
}
if( check) {
for( int x : arr) {
out.print(x+" ");
}
out.println();
}
else {
out.println(-1);
}
}
out.flush();
}
/*
* WARNING -> DONT EVER USE ARRAYS.SORT() IN ANY WAY.
* FIRST AND VERY IMP -> READ AND UNDERSTAND THE QUESTION VERY CAREFULLY.
* WARNING -> DONT CODE BULLSHIT , ALWAYS CHECK THE LOGIC ON MULTIPLE TESTCASES AND EDGECASES BEFORE.
* SECOND -> TRY TO FIND RELEVENT PATTERN SMARTLY.
* WARNING -> IF YOU THINK YOUR SOLUION IS JUST DUMB DONT SUBMIT IT BEFORE RECHECKING ON YOUR END.
*/
public static boolean ifpowof2(long n ) {
return ((n&(n-1)) == 0);
}
static boolean isprime(long x ) {
if( x== 2) {
return true;
}
if( x%2 == 0) {
return false;
}
for( long i = 3 ;i*i <= x ;i+=2) {
if( x%i == 0) {
return false;
}
}
return true;
}
static boolean[] sieveOfEratosthenes(long n) {
boolean prime[] = new boolean[(int)n + 1];
for (int i = 0; i <= n; i++) {
prime[i] = true;
}
for (long p = 2; p * p <= n; p++) {
if (prime[(int)p] == true) {
for (long i = p * p; i <= n; i += p)
prime[(int)i] = false;
}
}
return prime;
}
public static int[] nextLargerElement(int[] arr, int n) {
Stack<Integer> stack = new Stack<>();
int rtrn[] = new int[n];
rtrn[n-1] = -1;
stack.push( n-1);
for( int i = n-2 ;i >= 0 ; i--){
int temp = arr[i];
int lol = -1;
while( !stack.isEmpty() && arr[stack.peek()] <= temp){
if(arr[stack.peek()] == temp ) {
lol = stack.peek();
}
stack.pop();
}
if( stack.isEmpty()){
if( lol != -1) {
rtrn[i] = lol;
}
else {
rtrn[i] = -1;
}
}
else{
rtrn[i] = stack.peek();
}
stack.push( i);
}
return rtrn;
}
static void mysort(int[] arr) {
for(int i=0;i<arr.length;i++) {
int rand = (int) (Math.random() * arr.length);
int loc = arr[rand];
arr[rand] = arr[i];
arr[i] = loc;
}
Arrays.sort(arr);
}
static void mySort(long[] arr) {
for(int i=0;i<arr.length;i++) {
int rand = (int) (Math.random() * arr.length);
long loc = arr[rand];
arr[rand] = arr[i];
arr[i] = loc;
}
Arrays.sort(arr);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b)
{
return (a / gcd(a, b)) * b;
}
static long rightmostsetbit(long n) {
return n&-n;
}
static long leftmostsetbit(long n)
{
long k = (long)(Math.log(n) / Math.log(2));
return 1 << k;
}
static HashMap<Long,Long> primefactor( long n){
HashMap<Long ,Long> hm = new HashMap<>();
long temp = 0;
while( n%2 == 0) {
temp++;
n/=2;
}
if( temp!= 0) {
hm.put( 2L, temp);
}
long c = (long)Math.sqrt(n);
for( long i = 3 ; i <= c ; i+=2) {
temp = 0;
while( n% i == 0) {
temp++;
n/=i;
}
if( temp!= 0) {
hm.put( i, temp);
}
}
if( n!= 1) {
hm.put( n , 1L);
}
return hm;
}
static ArrayList<Integer> allfactors(int abs) {
HashMap<Integer,Integer> hm = new HashMap<>();
ArrayList<Integer> rtrn = new ArrayList<>();
for( int i = 2 ;i*i <= abs; i++) {
if( abs% i == 0) {
hm.put( i , 0);
hm.put(abs/i, 0);
}
}
for( int x : hm.keySet()) {
rtrn.add(x);
}
if( abs != 0) {
rtrn.add(abs);
}
return rtrn;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
java
|
1295
|
C
|
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
|
[
"dp",
"greedy",
"strings"
] |
import java.io.*;
import java.util.*;
public class CF1562C extends PrintWriter {
CF1562C() { super(System.out); }
public static Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1562C o = new CF1562C(); o.main(); o.flush();
}
static long calculate(long p, long q)
{
long mod = 1000000007, expo;
expo = mod - 2;
// Loop to find the value
// until the expo is not zero
while (expo != 0)
{
// Multiply p with q
// if expo is odd
if ((expo & 1) == 1)
{
p = (p * q) % mod;
}
q = (q * q) % mod;
// Reduce the value of
// expo by 2
expo >>= 1;
}
return p;
}
static String longestPalSubstr(String str)
{
// The result (length of LPS)
int maxLength = 1;
int start = 0;
int len = str.length();
int low, high;
// One by one consider every
// character as center
// point of even and length
// palindromes
for (int i = 1; i < len; ++i) {
// Find the longest even
// length palindrome with
// center points as i-1 and i.
low = i - 1;
high = i;
while (low >= 0 && high < len
&& str.charAt(low)
== str.charAt(high)) {
--low;
++high;
}
// Move back to the last possible valid palindrom substring
// as that will anyway be the longest from above loop
++low; --high;
if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {
start = low;
maxLength = high - low + 1;
}
// Find the longest odd length
// palindrome with center point as i
low = i - 1;
high = i + 1;
while (low >= 0 && high < len
&& str.charAt(low)
== str.charAt(high)) {
--low;
++high;
}
// Move back to the last possible valid palindrom substring
// as that will anyway be the longest from above loop
++low; --high;
if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {
start = low;
maxLength = high - low + 1;
}
}
return str.substring(start, start + maxLength - 1);
}
long check(long a){
long ret=0;
for(long k=2;(k*k*k)<=a;k++){
ret=ret+(a/(k*k*k));
}
return ret;
}
/*public static int getFirstSetBitPos(int n)
{
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
public static int bfsq(int n, int m, HashMap<Integer,ArrayList<Integer>>h,boolean v ){
v[n]=true;
if(n==m)
return 1;
else
{
int a=h.get(n).get(0);
int b=h.get(n).get(1);
if(b>m)
return(m-n);
else
{
int a1=bfsq(a,m,h,v);
int b1=bfsq(b,m,h,v);
return 1+Math.min(a1,b1);
}
}
}*/
static long nCr(int n, int r)
{ return fact(n) / (fact(r) *
fact(n - r));
}
// Returns factorial of n
static long fact(long n)
{
long res = 1;
for (long i = 2; i <= n; i++)
res = res * i;
return res;
}
/*void bfs(int src, HashMap<Integer,ArrayList<Integer,Integer>>h,int deg, boolean v[] ){
a[src]=deg;
Queue<Integer>= new LinkedList<Integer>();
q.add(src);
while(!q.isEmpty()){
(int a:h.get(src)){
if()
}
}
}*/
/* void dfs(int root, int par, HashMap<Integer,ArrayList<Integer>>h,int dp[], int child[]) {
dp[root]=0;
child[root]=1;
for(int x: h.get(root)){
if(x == par) continue;
dfs(x,root,h,in,dp);
child[root]+=child[x];
}
ArrayList<Integer> mine= new ArrayList<Integer>();
for(int x: h.get(root)) {
if(x == par) continue;
mine.add(x);
}
if(mine.size() >=2){
int y= Math.max(child[mine.get(0)] - 1 + dp[mine.get(1)] , child[mine.get(1)] -1 + dp[mine.get(0)]);
dp[root]=y;}
else if(mine.size() == 1)
dp[root]=child[mine.get(0)] - 1;
}
*/
class Pair implements Comparable<Pair>{
int i;
int j;
Pair (int a, int b){
i = a;
j = b;
}
public int compareTo(Pair A){
return (int)(this.i-A.i);
}}
/*static class Pair {
int i;
int j;
Pair() {
}
Pair(int i, int j) {
this.i = i;
this.j = j;
}
}*/
/*ArrayList<Integer> check(int a[], int b){
int n=a.length;
long ans=0;int k=0;
ArrayList<Integer>ab= new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(a[i]%m==0)
{k=a[i];
while(a[i]%m==0){
a[i]=a[i]/m;
}
for(int z=0;z<k/a[i];z++){
ab.add(a[i]);
}
}
else{
ab.add(a[i]);
}
}
return ab;
} */
/*int check[];
int tree[];
static void build( int []arr)
{
// insert leaf nodes in tree
for (int i = 0; i < n; i++)
tree[n + i] = arr[i];
// build the tree by calculating
// parents
for (int i = n - 1; i > 0; --i){
int ans= Math.min(tree[i << 1],
tree[i << 1 | 1]);
int ans1=Math.max((tree[i << 1],
tree[i << 1 | 1]));
if(ans==0)
}
}*/
/*static void ab(long n)
{
// Note that this loop runs till square root
for (long i=1; i<=Math.sqrt(n); i++)
{
if(i==1)
{
p.add(n/i);
continue;
}
if (n%i==0)
{
// If divisors are equal, print only one
if (n/i == i)
p.add(i);
else // Otherwise print both
{
p.add(i);
p.add(n/i);
}
}
}
}*/
void main() {
int g=sc.nextInt();
int mod=1000000007;
sc.nextLine();
for(int w1=0;w1<g;w1++){
String s=sc.nextLine();
String t=sc.nextLine();
HashMap<Character,TreeSet<Integer>>h = new HashMap<Character,TreeSet<Integer>>();
for(int i=0;i<s.length();i++){
char a=s.charAt(i);
if(h.containsKey(a)){
h.get(a).add(i);
}
else{
TreeSet<Integer>t1= new TreeSet<Integer>();
t1.add(i);
t1.add(1000000);
h.put(a,t1);
}
}
int c=1;
boolean ans=true;
int k=-1;
int j=1000000;
for(int i=0;i<t.length();i++){
if(h.containsKey(t.charAt(i))){
int w=h.get(t.charAt(i)).higher(k);
if(w==j){
c++;
k=h.get(t.charAt(i)).first();
}
else
k=w;
}
else{
ans=false;
break;
}
}
if(!ans)
println(-1);
else
println(c);
}
}
}
|
java
|
1320
|
B
|
B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3
|
[
"dfs and similar",
"graphs",
"shortest paths"
] |
import java.util.*;
import java.io.*;
public class A {
static boolean tests = false;
static class Graph{
ArrayList<Integer>[] graph;
int[] dist;
int destination, highestNode;
Graph(int highestNode){
this.highestNode = highestNode;
this.graph = new ArrayList[highestNode+5];
this.dist = new int[highestNode+5];
Arrays.fill(dist, int_max);
}
void addEdge(int u, int v){
if (graph[v] == null) graph[v] = new ArrayList<>();
graph[v].add(u);
}
void clear(){
for (int i = 0; i <= highestNode; ++i){
if (graph[i] == null) continue;
graph[i].clear();
}
}
void calcDistFrom(int destination){
this.destination = destination;
ArrayDeque<Node> pq = new ArrayDeque<>();
pq.add(new Node(destination, 0));
dist[destination] = 0;
while (!pq.isEmpty()){
Node node = pq.poll();
for (int u : graph[node.v]){
if (dist[u] > node.d+1){
dist[u] = node.d+1;
pq.addLast(new Node(u, node.d+1));
}
}
}
}
int nodeDist(int v){
return dist[v];
}
ArrayList<Integer> adj(int v){
return graph[v];
}
class Node{
int v, d;
public Node(int v, int d){
this.v = v;
this.d = d;
}
}
}
static void printPath(int v, Graph g, int av, int bv){
int node = v;
while (node != g.destination){
System.out.println(node);
for (int u : g.adj(node)){
if (g.nodeDist(node) == g.nodeDist(u)+1 && u != av && u != bv){
node = u;
break;
}
}
}
System.out.println(node);
}
static void solve(){
int n = fs.nextInt();
int m = fs.nextInt();
Graph graph = new Graph(n);
int[][] edges = new int[m][2];
for (int i = 0; i < m; ++i){
edges[i][0] = fs.nextInt();
edges[i][1] = fs.nextInt();
graph.addEdge(edges[i][0], edges[i][1]);
}
int k = fs.nextInt();
int[] path = fs.readIntArray(k);
graph.calcDistFrom(path[k-1]);
graph.clear();
for (int[] edge : edges){
graph.addEdge(edge[1], edge[0]);
}
int min = 0, max = 0;
for (int i = 0; i < k-1; ++i){
int dist = graph.nodeDist(path[i]);
int nextDist = graph.nodeDist(path[i+1]);
if (dist != nextDist+1){
++min;
}
for (int v : graph.adj(path[i])){
if (v == path[i+1]){
continue;
}
if (graph.nodeDist(v)+1 == dist){
++max;
break;
}
}
}
System.out.println(min+" "+max);
}
static FastScanner fs = new FastScanner();
static int int_max = (int)1e9+5;
public static void main(String[] args) {
int t = 1;
if (tests) t = fs.nextInt();
while (t-- > 0) solve();
}
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;
}
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());
}
double nextDouble(){
return Double.parseDouble(next());
}
}
}
|
java
|
1325
|
B
|
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].
|
[
"greedy",
"implementation"
] |
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcases = sc.nextInt();
while(testcases-->0){
int n = sc.nextInt();
int[] a = new int[n];
for(int i=0;i<n;++i){
a[i] = sc.nextInt();
}
HashSet<Integer> b = new HashSet<>();
for(int x:a){
b.add(x);
}
System.out.println(b.size());
}
}
}
|
java
|
1295
|
C
|
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
|
[
"dp",
"greedy",
"strings"
] |
import java.util.*;
import java.io.*;
public class C1295 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int T = scn.nextInt();
while (T-- > 0) {
char[] s = scn.next().toCharArray();
char[] t = scn.next().toCharArray();
HashSet<Character> set = new HashSet<>();
for (char c : s) {
set.add(c);
}
boolean flag = true;
for (char c : t) {
if (!set.contains(c)) {
flag = false;
break;
}
}
if (flag) {
TreeSet<Integer>[] index = new TreeSet[26]; // stores the index of each character
for (int i = 0; i < 26; i++) {
index[i] = new TreeSet<>();
}
for(int i=0;i<s.length;i++){
index[s[i]-'a'].add(i);
}
int ans = 1;
int pos = -1;
for(char c : t){
Integer i = index[c-'a'].ceiling(pos+1); // just higher
if(i!=null){
pos = i;
}else{
ans++;
pos = index[c-'a'].ceiling(0);
}
}
System.out.println(ans);
} else {
System.out.println("-1");
}
}
}
}
|
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.io.*;
import java.util.*;
public class Two_Arrays {
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 long[][] dp;
private static void solve() {
int n = fs.nextInt(), m = fs.nextInt();
dp = new long[(2 * m)][n + 5];
for (long[] r : dp) Arrays.fill(r, -1);
long ans = getAns(0, 1, m, n);
fw.out.println(ans);
}
private static long getAns(int i, int prev, int m, int n) {
if (i >= (2 * m)) return 1;
if (dp[i][prev] != -1) return dp[i][prev];
long ans = 0;
for (int num = prev; num <= n; num++) {
ans = (ans + getAns(i + 1, num, m, n)) % mod1;
}
return dp[i][prev] = ans;
}
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
|
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 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_New_Year_and_Permutation {
static long mod = Long.MAX_VALUE;
static OutputStream outputStream = System.out;
static PrintWriter out = new PrintWriter(outputStream);
static FastReader f = new FastReader();
public static void main(String[] args) {
int t = 1;
while(t-- > 0){
solve();
}
out.close();
}
public static void solve() {
int n = f.nextInt();
mod = f.nextLong();
long fact[] = new long[n+1];
fact[0] = 1;
for(int i = 1; i <= n; i++) {
fact[i] = (fact[i-1]*i)%mod;
}
long ans = 0;
for(int i = 1; i <= n; i++) {
long curr = fact[i];
curr = (curr * (n-i+1)) % mod;
curr = (curr * fact[n-i+1]) % mod;
ans = (ans + curr) % mod;
}
out.println(ans);
}
// Sort an array
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
// Find all divisors of n
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
// Check if n is prime or not
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
// Find gcd of a and b
public static long gcd(long a, long b) {
long dividend = a > b ? a : b;
long divisor = a < b ? a : b;
while(divisor > 0) {
long reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
// Find lcm of a and b
public static long lcm(long a, long b) {
long lcm = gcd(a, b);
long hcf = (a * b) / lcm;
return hcf;
}
// Find factorial in O(n) time
public static long fact(int n) {
long res = 1;
for(int i = 2; i <= n; i++) {
res = res * i;
}
return res;
}
// Find power in O(logb) time
public static long power(long a, long b) {
long res = 1;
while(b > 0) {
if((b&1) == 1) {
res = (res * a)%mod;
}
a = (a * a)%mod;
b >>= 1;
}
return res;
}
// Find nCr
public static long nCr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / (fact(r) * fact(n-r));
return ans;
}
// Find nPr
public static long nPr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / fact(r);
return ans;
}
// sort all characters of a string
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// User defined class for fast I/O
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
boolean hasNext() {
if (st != null && st.hasMoreTokens()) {
return true;
}
String tmp;
try {
br.mark(1000);
tmp = br.readLine();
if (tmp == null) {
return false;
}
br.reset();
} catch (IOException e) {
return false;
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
// (a/b)%mod == (a * moduloInverse(b)) % mod;
// moduloInverse(b) = power(b, mod-2);
|
java
|
1311
|
E
|
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example:
|
[
"brute force",
"constructive algorithms",
"trees"
] |
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws Exception{
MScanner sc=new MScanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int tc=sc.nextInt();
while(tc-->0) {
int n=sc.nextInt(),d=sc.nextInt();
long max=((n-1)*n)/2;
long min=0;
int nodes=n-1;
int lvl=1;long cnt=2;
while(true) {
if(cnt>nodes) {
long inc=lvl*1l*nodes;
min+=inc;
break;
}
long inc=lvl*1l*cnt;
min+=inc;
nodes-=cnt;
lvl++;
cnt*=2;
}
if(d<min || d>max) {
pw.println("NO");
}
else {
pw.println("YES");
LinkedList<Integer>[]levels=new LinkedList[n];
long[]cap=new long[n];
for(int i=0;i<n;i++) {
levels[i]=new LinkedList<Integer>();
levels[i].add(i);
cap[i]=i==0?1:(cap[i-1]*2l);
}
int cmax=n-1,cmin=1;
while(true) {
long dif=cmax-cmin;
if(max-dif<=d) {
dif=max-d;
levels[(int)(cmax-dif)].add(levels[cmax].poll());
break;
}
else {
levels[cmin].add(levels[cmax].poll());
if(levels[cmin].size()==cap[cmin]) {
cmin++;
}
}
cmax--;
max-=dif;
}
int[]par=new int[n];
int[]children=new int[n];
for(int i=n-1;i>=1;i--) {
if(levels[i].size()==0)continue;
int[]parents=new int[levels[i-1].size()];
int o=0;
for(int j:levels[i-1]) {
parents[o++]=j;
}
o=0;
for(int j:levels[i]) {
int curP=parents[o];
par[j]=curP;
children[curP]++;
if(children[curP]==2)o++;
}
}
for(int i=1;i<n;i++)pw.print((par[i]+1)+" ");
pw.println();
}
}
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
|
1288
|
F
|
F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
OutputCopy35
BUURRU
InputCopy3 1 3 4 5
RRR
B
2 1
1 1
3 1
OutputCopy-1
InputCopy3 1 3 4 5
URU
B
2 1
1 1
3 1
OutputCopy14
RBB
|
[
"constructive algorithms",
"flows"
] |
import java.io.*;
import java.util.*;
public class F
{
//@ <- not printed in hackpack
static class MinCostFlow {
static int MINCOSTFLOW = 0, MINCOSTMAXFLOW = 1;
int s, t, N, ss, tt; // use s and t as your source & sink
long oo = (long)1e12;
long[] ex; ArrayList<Edge>[] adjj; Edge[][] adj;
public MinCostFlow(int NN) { this(NN, MINCOSTMAXFLOW); }
public MinCostFlow(int NN, int flowType) {
N = (tt = (ss = (t = (s = NN) + 1) + 1) + 1) + 1;
adj = new Edge[N][0]; adjj = new ArrayList[N];
for (int i = 0; i < N; i++) adjj[i] = new ArrayList<Edge>();
ex = new long[N]; add(t, s, oo, -oo / 10 * flowType);
}
public void add(int i, int j, long cap, long cost) {
Edge fwd = new Edge(i, j, cap, 0, cost);
Edge rev = new Edge(j, i, 0, 0, -cost);
adjj[i].add(rev.rev = fwd); adjj[j].add(fwd.rev = rev);
}
public void add(int i, int j, long cap, long cost, int id, int ttype) {
Edge fwd = new Edge(i, j, cap, 0, cost, id, ttype);
Edge rev = new Edge(j, i, 0, 0, -cost, id, ttype);
adjj[i].add(rev.rev = fwd); adjj[j].add(fwd.rev = rev);
}
public long[] getFlow() {
preFlow();
for (int i = 0; i < N; i++) adj[i] = adjj[i].toArray(adj[i]);
boolean[] canU = new boolean[N], hasU = new boolean[N];
long[] dist = new long[N], width = new long[N];
Edge[] prev = new Edge[N];
while (true) {
Arrays.fill(dist, oo); dist[ss] = 0;
width[ss] = oo; boolean updated = hasU[ss] = true;
while (updated) {
updated = false;
for (int i = 0; i < N; hasU[i++] = false) canU[i] = hasU[i];
for (int i = 0; i < N; i++)
if (canU[i])
for (Edge e : adj[i])
if (e.flow != e.cap && dist[e.j] > dist[e.i] + e.cost) {
dist[e.j] = dist[e.i] + (prev[e.j] = e).cost;
width[e.j] = Math.min(width[e.i], e.cap - e.flow);
hasU[e.j] = updated = true;
}
}
if (dist[tt] >= oo) break;
for (Edge e = prev[tt]; e != null; e = prev[e.i])
e.rev.flow = -(e.flow += width[tt]);
}
long flow = 0, cost = 0;
for (Edge e : adj[s]) if (e.flow > 0) flow += e.flow;
for (int i = 0; i < N; i++)
for (Edge e : adj[i])
if (e.flow > 0 && e.i != t && e.j != s && e.i < ss && e.j < ss)
cost += e.flow * e.cost;
return new long[] {flow, cost};
}
public void preFlow() {
for (int i = 0; i < N; i++)
for (Edge e : adjj[i])
if (e.cost < 0 && e.cap - e.flow > 0) {
ex[e.i] -= e.cap - e.flow;
ex[e.j] += e.cap - e.flow;
e.rev.flow = -(e.flow = e.cap);
}
for (int i = 0; i < N; i++)
if (ex[i] > 0) add(ss, i, ex[i], -oo);
else if (ex[i] < 0) add(i, tt, -ex[i], -oo);
Arrays.fill(ex, 0);
}
}
static class Edge {
int i, j; long cap, flow, cost; Edge rev;
int id = -1, type = 0;
Edge(int ii, int jj, long cc, long ff, long C) {
i = ii; j = jj; cap = cc; flow = ff; cost = C;
}
Edge(int ii, int jj, long cc, long ff, long C, int iid, int ttype) {
i = ii; j = jj; cap = cc; flow = ff; cost = C;
id = iid;
type = ttype;
}
}
void solve(FastIO io)
{
int n1 = io.nextInt();
int n2 = io.nextInt();
int m = io.nextInt();
int r = io.nextInt();
int b = io.nextInt();
char[] s1 = io.next().toCharArray();
char[] s2 = io.next().toCharArray();
MinCostFlow mcmf = new MinCostFlow(n1 + n2, 0);
long soo = 1000000;
int cnt = n1 + n2;
for (int i = 0; i < n1; i++)
{
if (s1[i] == 'R')
{
mcmf.add(mcmf.s, i, 1, -soo);
mcmf.add(mcmf.s, i, 1000, 0);
}
else if (s1[i] == 'B')
{
mcmf.add(i, mcmf.t, 1, -soo);
mcmf.add(i, mcmf.t, 1000, 0);
}
else
{
cnt--;
mcmf.add(mcmf.s, i, 1000, 0);
mcmf.add(i, mcmf.t, 1000, 0);
}
}
for (int i = 0; i < n2; i++)
{
if (s2[i] == 'B')
{
mcmf.add(mcmf.s, i + n1, 1, -soo);
mcmf.add(mcmf.s, i + n1, 1000, 0);
}
else if (s2[i] == 'R')
{
mcmf.add(i + n1, mcmf.t, 1, -soo);
mcmf.add(i + n1, mcmf.t, 1000, 0);
}
else
{
cnt--;
mcmf.add(mcmf.s, i + n1, 1000, 0);
mcmf.add(i + n1, mcmf.t, 1000, 0);
}
}
int[] from = new int[m];
int[] to = new int[m];
for (int i = 0; i < m; i++)
{
int u = from[i] = io.nextInt() - 1;
int v = to[i] = io.nextInt() - 1;
mcmf.add(u, n1 + v, 1, r, i, 1);
mcmf.add(n1 + v, u, 1, b, i, -1);
}
long[] flow = mcmf.getFlow();
if (flow[1] + cnt * soo > soo)
{
io.println(-1);
return;
}
long ans = flow[1] + soo * cnt;
long[] col = new long[m];
long[] bal1 = new long[n1];
long[] bal2 = new long[n2];
for (ArrayList<Edge> list : mcmf.adjj)
for (Edge e : list)
if (e.id != -1 && e.flow > 0)
{
col[e.id] = e.type;
bal1[from[e.id]] += e.type;
bal2[to[e.id]] += e.type;
}
for (int i = 0; i < n1; i++)
if ((s1[i] == 'R' && bal1[i] <= 0) || (s1[i] == 'B' && bal1[i] >= 0))
{
io.println(-1);
return;
}
for (int i = 0; i < n2; i++)
if ((s2[i] == 'R' && bal2[i] <= 0) || (s2[i] == 'B' && bal2[i] >= 0))
{
io.println(-1);
return;
}
io.println(ans);
for (int i = 0; i < m; i++)
io.print(col[i] > 0 ? 'R' : (col[i] < 0 ? 'B' : 'U'));
io.println();
}
public static void main(String[] args)
{
FastIO io = new FastIO();
new F().solve(io);
io.close();
}
static class FastIO extends PrintWriter
{
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
FastIO()
{
super(System.out);
}
public String next()
{
while (!st.hasMoreTokens())
{
try {
st = new StringTokenizer(r.readLine());
} catch (Exception e) {
//TODO: handle exception
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
}
}
|
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.io.*;
import java.util.*;
public class cp {
static int mod=(int)1e9+7;
// static Reader sc=new Reader();
static FastReader sc=new FastReader(System.in);
static int[] sp;
static int size=(int)1e6;
static int[] arInt;
static long[] arLong;
public static void main(String[] args) throws IOException {
// long tc=sc.nextLong();
// Scanner sc=new Scanner(System.in);
int tc=1;
// print_int(pre);
// primeSet=new HashSet<>();
// primeCnt=new int[(int)1e9];
// sieveOfEratosthenes((int)1e9);
while(tc-->0)
{
int n=sc.nextInt();
int x[]=new int[n];
int v[]=new int[n];
HashMap<Integer, Integer> unique=new HashMap<>();
for (int i = 0; i < v.length; i++) {
x[i]=sc.nextInt();
}
for (int i = 0; i < v.length; i++) {
v[i]=sc.nextInt();
unique.put(v[i], -1);
}
Pair arr[]=new Pair[n];
for (int i = 0; i < arr.length; i++) {
arr[i]=new Pair(x[i], v[i]);
}
sort(v);
int k=0;
for (int i = 0; i < arr.length; i++) {
if (unique.get(v[i])==-1) {
unique.put(v[i], k++);
}
}
fwt forCnt=new fwt(n);
fwt forSum=new fwt(n);
long ans=0;
Arrays.sort(arr);
for(int i=0;i<n;i++)
{
int pos=unique.get(arr[i].y);
long cnt=forCnt.getSum(pos);
long sum=forSum.getSum(pos);
forCnt.updateBIT(n, pos, 1);
forSum.updateBIT(n, pos, arr[i].x);
ans+=arr[i].x*cnt-sum;
}
out.println(ans);
}
out.flush();
out.close();
System.gc();
}
/*
...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...
*/
static void mapping(int a[])
{
Pair[] temp=new Pair[a.length];
for (int i = 0; i < temp.length; i++) {
temp[i]=new Pair(a[i], i);
}
Arrays.sort(temp);
int k=0;
for (int i = 0; i < temp.length; i++) {
a[temp[i].y]=k++;
}
}
static boolean palin(String s)
{
for(int i=0;i<s.length()/2;i++)
if(s.charAt(i)!=s.charAt(s.length()-i-1))
return false;
return true;
}
static class temp implements Comparable<temp>{
int x;
int y;
int sec;
public temp(int x,int y,int l) {
// TODO Auto-generated constructor stub
this.x=x;
this.y=y;
this.sec=l;
}
@Override
public int compareTo(cp.temp o) {
// TODO Auto-generated method stub
return this.sec-o.sec;
}
}
static class Node{
int x;
int y;
ArrayList<Integer> edges;
public Node(int x,int y) {
// TODO Auto-generated constructor stub
this.x=x;
this.y=y;
this.edges=new ArrayList<>();
}
}
static int lis(int arr[],int n)
{
int ans=0;
int dp[]=new int[n+1];
Arrays.fill(dp, int_max);
dp[0]=int_min;
for(int i=0;i<n;i++)
{
int j=UpperBound(dp,arr[i]);
if(dp[j-1]<=arr[i] && arr[i]<dp[j])
dp[j]=arr[i];
}
for(int i=0;i<=n;i++)
{
if(dp[i]<int_max)
ans=i;
}
return ans;
}
static long get(long n)
{
return n*(n+1)/2L;
}
static boolean go(ArrayList<Pair> caves,int k)
{
for(Pair each:caves)
{
if(k<=each.x)
return false;
k+=each.y;
}
return true;
}
static String revString(String s)
{
char arr[]=s.toCharArray();
int n=s.length();
for(int i=0;i<n/2;i++)
{
char temp=arr[i];
arr[i]=arr[n-i-1];
arr[n-i-1]=temp;
}
return String.valueOf(arr);
}
static void dfs(Graph gp,boolean[] vis,int node,int[] dp)
{
vis[node]=true;
dp[node]=0;
for(Integer child:gp.list[node])
{
if(!vis[child])
{
dfs(gp, vis, child, dp);
}
dp[node]=Math.max(dp[node], 1+dp[child]);
}
}
// Fuction return the number of set bits in n
static int SetBits(int n)
{
int cnt=0;
while(n>0)
{
if((n&1)==1)
{
cnt++;
}
n=n>>1;
}
return cnt;
}
static boolean isPowerOfTwo(int n)
{
return (int)(Math.ceil((Math.log(n) / Math.log(2))))
== (int)(Math.floor(((Math.log(n) / Math.log(2)))));
}
static void arrInt(int n) throws IOException
{
arInt=new int[n];
for (int i = 0; i < arInt.length; i++) {
arInt[i]=sc.nextInt();
}
}
static void arrLong(int n) throws IOException
{
arLong=new long[n];
for (int i = 0; i < arLong.length; i++) {
arLong[i]=sc.nextLong();
}
}
static ArrayList<Integer> add(int id,int c)
{
ArrayList<Integer> newArr=new ArrayList<>();
for(int i=0;i<id;i++)
newArr.add(arInt[i]);
newArr.add(c);
for(int i=id;i<arInt.length;i++)
{
newArr.add(arInt[i]);
}
return newArr;
}
// function to find first index >= y
static int upper(ArrayList<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (h-l>1)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= x)
l=mid+1;
else
{
h=mid;
}
}
if(arr.get(l)>x)
{
return l;
}
if(arr.get(h)>x)
return h;
return -1;
}
static int upper(ArrayList<Long> arr, int n, long x)
{
int l = 0, h = n - 1;
while (h-l>1)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= x)
l=mid+1;
else
{
h=mid;
}
}
if(arr.get(l)>x)
{
return l;
}
if(arr.get(h)>x)
return h;
return -1;
}
static int lower(ArrayList<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (h-l>1)
{
int mid = (l + h) / 2;
if (arr.get(mid) < x)
l=mid+1;
else
{
h=mid;
}
}
if(arr.get(l)>=x)
{
return l;
}
if(arr.get(h)>=x)
return h;
return -1;
}
static int N = 501;
// 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;
}
static String tr(String s)
{
int now = 0;
while (now + 1 < s.length() && s.charAt(now)== '0')
++now;
return s.substring(now);
}
static ArrayList<Integer> ans;
static void dfs(int node,Graph gg,int cnt,int k,ArrayList<Integer> temp)
{
if(cnt==k)
return;
for(Integer each:gg.list[node])
{
if(each==0)
{
temp.add(each);
ans=new ArrayList<>(temp);
temp.remove(temp.size()-1);
continue;
}
temp.add(each);
dfs(each,gg,cnt+1,k,temp);
temp.remove(temp.size()-1);
}
return;
}
static boolean isPrime(long n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static ArrayList<Integer> commDiv(int a, int b)
{
// find gcd of a, b
int n = gcd(a, b);
// Count divisors of n.
ArrayList<Integer> Div=new ArrayList<>();
for (int i = 1; i <= Math.sqrt(n); i++) {
// if 'i' is factor of n
if (n % i == 0) {
// check if divisors are equal
if (n / i == i)
Div.add(i);
else
{
Div.add(i);
Div.add(n/i);
}
}
}
return Div;
}
static HashSet<Integer> factors(int x)
{
HashSet<Integer> a=new HashSet<Integer>();
for(int i=2;i*i<=x;i++)
{
if(x%i==0)
{
a.add(i);
a.add(x/i);
}
}
return a;
}
static void primeFactors(int n,HashSet<Integer> factors)
{
// Print the number of 2s that divide n
while (n%2==0)
{
factors.add(2);
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
factors.add(i);
n /= i;
}
}
// This condition is to handle the case when
// n is a prime number greater than 2
if (n > 2)
factors.add(n);
}
// static class Node
// {
// int vertex;
// HashSet<Node> adj;
// int deg;
// Node(int ver)
// {
// vertex=ver;
// deg=0;
// adj=new HashSet<Node>();
// }
// @Override
// public String toString()
// {
// return vertex+" ";
// }
// }
static class Tuple{
int a;
int b;
int c;
public Tuple(int a,int b,int c) {
this.a=a;
this.b=b;
this.c=c;
}
}
//function to find prime factors of n
static HashMap<Long,Long> findFactors(long n2)
{
HashMap<Long,Long> ans=new HashMap<>();
if(n2%2==0)
{
ans.put(2L, 0L);
// cnt++;
while((n2&1)==0)
{
n2=n2>>1;
ans.put(2L, ans.get(2L)+1);
//
}
}
for(long i=3;i*i<=n2;i+=2)
{
if(n2%i==0)
{
ans.put((long)i, 0L);
// cnt++;
while(n2%i==0)
{
n2=n2/i;
ans.put((long)i, ans.get((long)i)+1);
}
}
}
if(n2!=1)
{
ans.put(n2, ans.getOrDefault(n2, (long) 0)+1);
}
return ans;
}
//fenwick tree implementaion
static class fwt
{
int n;
long BITree[];
fwt(int n)
{
this.n=n;
BITree=new long[n+1];
}
fwt(int arr[], int n)
{
this.n=n;
BITree=new long[n+1];
for(int i = 0; i < n; i++)
updateBIT(n, i, arr[i]);
}
long getSum(int index)
{
long sum = 0;
index = index + 1;
while(index>0)
{
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
void updateBIT(int n, int index,int val)
{
index = index + 1;
while(index <= n)
{
BITree[index] += val;
index += index & (-index);
}
}
void print()
{
for(int i=0;i<n;i++)
out.print(getSum(i)+" ");
out.println();
}
}
static class sparseTable{
int n;
long[][]dp;
int log2[];
int P;
void buildTable(long[] 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 long[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++)
{
long left=dp[p-1][i];
long right=dp[p-1][i+(1<<(p-1))];
dp[p][i]=gcd(left, right);
}
}
}
long maxQuery(int l,int r)
{
int len=r-l+1;
int p=(int)Math.floor(log2[len]);
long left=dp[p][l];
long right=dp[p][r-(1<<p)+1];
return gcd(left, right);
}
}
//Function to find number of set bits
static int setBitNumber(long n)
{
if (n == 0)
return 0;
int msb = 0;
n = n / 2;
while (n != 0) {
n = n / 2;
msb++;
}
return msb;
}
static int getFirstSetBitPos(long n)
{
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
static ArrayList<Integer> primes;
static HashSet<Integer> primeSet;
static boolean prime[];
static int primeCnt[];
static void sieveOfEratosthenes(int n)
{
prime= new boolean[n + 1];
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
primeCnt[i]=primeCnt[i-1]+1;
}
}
static long mod(long a, long b) {
long c = a % b;
return (c < 0) ? c + b : c;
}
static void swap(long arr[],int i,int j)
{
long temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
static boolean util(int a,int b,int c)
{
if(b>a)util(b, a, c);
while(c>=a)
{
c-=a;
if(c%b==0)
return true;
}
return (c%b==0);
}
static void flag(boolean flag)
{
out.println(flag ? "YES" : "NO");
out.flush();
}
static void print(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print(long a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print_int(ArrayList<Integer> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void print_long(ArrayList<Long> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void printYesNo(boolean condition)
{
if (condition) {
out.println("YES");
}
else {
out.println("NO");
}
}
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 lowerIndex(int arr[], int n, int x)
{
int l = 0, h = n - 1;
while (l<=h)
{
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid -1 ;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
static int upperIndex(int arr[], int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
static int upperIndex(long arr[], int n, long y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
static int UpperBound(int a[], int x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static int UpperBound(long a[], long x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static class DisjointUnionSets
{
int[] rank, parent;
int n;
// Constructor
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
// Creates n sets with single item in each
void makeSet()
{
for (int i = 0; i < n; i++)
parent[i] = i;
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
// Unites the set that includes x and the set
// that includes x
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else // if ranks are the same
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
// if(xRoot!=yRoot)
// parent[y]=x;
}
int connectedComponents()
{
int cnt=0;
for(int i=0;i<n;i++)
{
if(parent[i]==i)
cnt++;
}
return cnt;
}
}
static class Graph
{
int v;
ArrayList<Integer> list[];
Graph(int v)
{
this.v=v;
list=new ArrayList[v+1];
for(int i=1;i<=v;i++)
list[i]=new ArrayList<Integer>();
}
void addEdge(int a, int b)
{
this.list[a].add(b);
}
}
// static class GraphMap{
// Map<String,ArrayList<String>> graph;
// GraphMap() {
// // TODO Auto-generated constructor stub
// graph=new HashMap<String,ArrayList<String>>();
//
// }
// void addEdge(String a,String b)
// {
// if(graph.containsKey(a))
// this.graph.get(a).add(b);
// else {
// this.graph.put(a, new ArrayList<>());
// this.graph.get(a).add(b);
// }
// }
// }
// static void dfsMap(GraphMap g,HashSet<String> vis,String src,int ok)
// {
// vis.add(src);
//
// if(g.graph.get(src)!=null)
// {
// for(String each:g.graph.get(src))
// {
// if(!vis.contains(each))
// {
// dfsMap(g, vis, each, ok+1);
// }
// }
// }
//
// cnt=Math.max(cnt, ok);
// }
static double sum[];
static long cnt;
// static void DFS(Graph g, boolean[] visited, int u)
// {
// visited[u]=true;
//
// for(int i=0;i<g.list[u].size();i++)
// {
// int v=g.list[u].get(i);
//
// if(!visited[v])
// {
// cnt1=cnt1*2;
// DFS(g, visited, v);
//
// }
//
// }
//
//
// }
static class Pair implements Comparable<Pair>
{
int x;
int y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
return this.x-o.x;
}
}
static long sum_array(int a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static long sum_array(long a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static void sort(int[] a)
{
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void reverse_array(int a[])
{
int n=a.length;
int i,t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static void reverse_array(long a[])
{
int n=a.length;
int i; long t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
// static long modInverse(long a, long m)
// {
// long g = gcd(a, m);
//
// return power(a, m - 2, m);
//
// }
static long power(long x, long y)
{
long 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;
}
static int power(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; // y = y/2
x = (x * x) % mod;
}
return res;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
//cnt+=a/b;
return gcd(b%a,a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
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;
}
}
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();
}
}
static PrintWriter out=new PrintWriter(System.out);
static int int_max=Integer.MAX_VALUE;
static int int_min=Integer.MIN_VALUE;
static long long_max=Long.MAX_VALUE;
static long long_min=Long.MIN_VALUE;
}
|
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 Solution {
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;
}
}
static void sort(int a[]){ // int -> long
ArrayList<Integer> arr=new ArrayList<>(); // Integer -> Long
for(int i=0;i<a.length;i++)
arr.add(a[i]);
Collections.sort(arr);
for(int i=0;i<a.length;i++)
a[i]=arr.get(i);
}
private static long gcd(long a, long b){
if(b==0)return a;
return gcd(b,a%b);
}
private static long pow(long x,long y){
if(y==0)return 1;
long temp = pow(x, y/2);
if(y%2==1){
return x*temp*temp;
}
else{
return temp*temp;
}
}
static int log(long n){
int res = 0;
while(n>0){
res++;
n/=2;
}
return res;
}
static int mod = (int)1e9+7;
static int INF = Integer.MAX_VALUE;
static PrintWriter out;
static FastReader sc ;
public static void main(String[] args) throws IOException {
sc = new FastReader();
out = new PrintWriter(System.out);
// primes();
// ================================ //
int n = sc.nextInt();
int[][]arr =new int[n][2];
for(int i=0;i<n;i++){
arr[i][0] = sc.nextInt();
}
for(int i=0;i<n;i++){
arr[i][1] = sc.nextInt();
}
solver(arr ,n);
// ================================ //
out.flush();
}
public static void solver(int[][]arr, int n) {
Arrays.sort(arr,(a,b)->a[0]-b[0]);
long res = 0;
PriorityQueue<Integer>pq = new PriorityQueue<>((a,b)->b-a);
int cur = 0;
long idk = 0;
for(int i=0;i<n;i++){
// System.out.println(arr[i][0]+"__"+ cur);
while(!pq.isEmpty() && cur<arr[i][0]){
idk-=pq.poll();
res+=idk;
cur++;
}
pq.offer(arr[i][1]);
idk+=arr[i][1];
cur = arr[i][0];
}
while(!pq.isEmpty() ){
idk-=pq.poll();
res+=idk;
}
out.println( res);
}
}
|
java
|
1293
|
A
|
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
|
[
"binary search",
"brute force",
"implementation"
] |
import java.util.*;
import java.io.*;
public class practice {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new PrintWriter(System.out)));
StringBuilder sb = new StringBuilder();
int t = Integer.parseInt(br.readLine());
while (t --> 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int s = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
Set<Integer> set = new HashSet<>();
for (int i = 0; i < k; i++) set.add(Integer.parseInt(st.nextToken()));
int min1 = Integer.MAX_VALUE;
for (int i = s; i > 0; i--) {
if (!set.contains(i)) {
min1 = s - i;
break;
}
}
int min2 = Integer.MAX_VALUE;
for (int i = s; i <= n; i++) {
if (!set.contains(i)) {
min2 = i - s;
break;
}
}
sb.append(Math.min(min1, min2)).append("\n");
}
pw.println(sb.toString().trim());
pw.close();
br.close();
}
}
|
java
|
1284
|
B
|
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
|
[
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] |
import java.util.*;
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();
long op=0;
ArrayList<Integer> list=new ArrayList<>();
ArrayList<int[]> list1=new ArrayList<>();
for(int i=0;i<n;i++){
int l=i();
int[]temp=new int[l];
boolean op1=false;
int max=0;
for(int j=0;j<l;j++){
int x=i();
temp[j]=x;
if((j>0)&&(temp[j-1]<x)){
op1=true;
}
max=Math.max(x,max);
}
if(op1){
op++;
}
else{
list.add(max);
}
list1.add(temp);
}
long ans=0;
Collections.sort(list);
for(int i=0;i<n;i++){
int[]temp=list1.get(i);
boolean op1=false;
boolean isSorted=true;
int min=10000000;
int l=temp.length;
for(int j=0;j<l;j++){
int x=temp[j];
if((j>0)&&(temp[j-1]<x)) {
op1=true;
}
if(j>0&&x!=temp[j-1])isSorted=false;
min=Math.min(x,min);
}
if(op1){
ans+=n;
}
else{
ans+=op;
int lo=0;
int hi=list.size()-1;
int id=-1;
while(lo<=hi){
int mid=(lo+hi)/2;
int val=list.get(mid);
if(val<=min){
lo=mid+1;
}
else{
hi=mid-1;
id=mid;
}
}
if(id!=-1){
ans+=(list.size()-id);
}
}
}
sb.append(ans+"\n");
}
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
|
1312
|
B
|
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
|
[
"constructive algorithms",
"sortings"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class test{
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
while(t-- > 0){
int n = Integer.parseInt(br.readLine());
Integer[] a = new Integer[n];
StringTokenizer tokenizer = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++){
a[i] = Integer.parseInt(tokenizer.nextToken());
}
Arrays.sort(a);
for(int i = n-1; i >= 0; i--){
if( i < n-1) pw.print(" ");
pw.print(a[i]);
}
pw.println();
}
pw.flush();
pw.close();
br.close();
}
}
|
java
|
1320
|
C
|
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
|
[
"brute force",
"data structures",
"sortings"
] |
import java.util.*;
import java.io.*;
public class Y{
final static int M=(1<<20);
static long[] t1=new long[M*2+5];
static long[] t2=new long[M*2+5];
static long[] ca=new long[M], cb=new long[M];
static long ans;
static int n,m,p,x,y,i,j;
public static void upd(int i){
t1[i]=t1[i<<1]+t1[i<<1|1];
t2[i]=Math.max(t2[i<<1],t1[i<<1]+t2[i<<1|1]);
}
public static void add(int i,int v){
for(t1[i+=M]+=v;(i>>=1)>0;upd(i));
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long Z= 1; Z<<=60;
for(i=0;i<M;++i)ca[i]=cb[i]=Z;ans=-Z;
n=in.nextInt();m=in.nextInt();p=in.nextInt();
mons[] a = new mons[p+1];a[0]=new mons(0, 0, 0);
for(i=1;i<=n;++i){x=in.nextInt();y=in.nextInt();ca[x]=Math.min(ca[x],y);}
for(i=1;i<=m;++i){x=in.nextInt();y=in.nextInt();cb[x]=Math.min(cb[x],y);}
for(i=0;i<M;++i)t2[i+M]=-cb[i];for(i=M-1;i!=0;--i)upd(i);
for(i=1;i<=p;++i){a[i]= new mons(in.nextInt(),in.nextInt(),in.nextInt());}
Arrays.sort(a);
for(i=0,j=1;i<M;++i){
for(;j<=p && a[j].x<i;++j)add(a[j].y,a[j].z);
ans=Math.max(ans,t2[1]-ca[i]);
}
System.out.println(ans);
in.close();
}
}
class mons implements Comparable<mons>{
int x,y,z;
public mons(int x,int y, int z){
this.x=x;this.y=y;this.z=z;
}
@Override
public int compareTo(mons o) {
if(x>o.x){return 1;}
if(x<o.x){return -1;}
return 0;
}
}
|
java
|
1322
|
B
|
B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2
1 2
OutputCopy3InputCopy3
1 2 3
OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102.
|
[
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] |
import java.io.*;
import java.sql.Array;
import java.util.*;
public class Contest1 {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// /////////
//////// /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// /////////
//////// /////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static long getnum(int[] a ,int val) {
long sum = 0;
for (int i = 0; i < a.length; i++) {
int low = i + 1;
int hi = a.length - 1;
int a1 = -1, a2 = -1, a3 = -1, a4 = -1;
while (low <= hi) {
int mid = low + hi >> 1;
if (a[mid] + a[i] >= 2 * val) {
hi = mid - 1;
} else if (a[mid] + a[i] >= val) {
a1 = mid;
hi = mid - 1;
} else low = mid + 1;
}
low = i + 1;
hi = a.length - 1;
while (low <= hi) {
int mid = low + hi >> 1;
if (a[mid] + a[i] >= 2 * val) {
hi = mid - 1;
} else if (a[mid] + a[i] >= val) {
a2 = mid;
low = mid + 1;
} else low = mid + 1;
}
low = i+1;
hi = a.length - 1;
while (low <= hi) {
int mid = low + hi >> 1;
if (a[mid] + a[i] >= 4 * val - 1) {
hi = mid - 1;
} else if (a[mid] + a[i] >= 3 * val) {
a3 = mid;
hi = mid - 1;
} else low = mid + 1;
}
low = i+1;
hi = a.length - 1;
while (low <= hi) {
int mid = low + hi >> 1;
if (a[mid] + a[i] >= 4 * val - 1) {
hi = mid - 1;
} else if (a[mid] + a[i] >= 3 * val) {
a4 = mid;
low = mid + 1;
} else low = mid + 1;
}
if (a1 != -1) {
sum += a2 - a1 + 1;
}
if (a3 != -1) {
sum += a4 - a3 + 1;
}
}
return sum;
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[]a = new int[n];
for (int i =0;i<n;i++)a[i]=sc.nextInt();
int val=0;
int[]ac= new int[n];
for (int j =0;j<27;j++){
int c = 1<<(j+1);
for (int i =0;i<n;i++){
ac[i]=a[i]%c;
}
suffle(ac);
Arrays.sort(ac);
long cc= getnum(ac,1<<j);
cc%=2;
if (cc==1){
val+=1<<j;
}
}
pw.println(val);
pw.flush();
}
static void suffle(int[]a){
for (int i =0;i<a.length;i++){
int t = a[i];
int idx= (int)(Math.random()*a.length);
a[i]=a[idx];
a[idx]=t;
}
}
static long gcd(long a,long b){
if (a==0)return b;
return gcd(b%a,a);
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
java
|
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"
] |
/*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef {
static int MAX = 505;
static int[][] dp = new int[MAX][MAX];
static int[][] dp2 = new int[MAX][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 = 0; 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();
}
for (int i = 0; i < MAX; i++) {
Arrays.fill(dp[i], -1);
Arrays.fill(dp2[i], -1);
}
int res = arrayShrinking(arr, 0, n - 1);
out.println(res);
}
private static int arrayShrinking(int[] arr, int i, int j) {
// dp[i][j] stores the min array length that can be formed from elements in range i to j.
// dp2[i][j] stores the value we get after merging elements in range i to j using several operations (if possible), otherwise -1;
if (dp[i][j] != -1) {
return dp[i][j];
}
// if only one element in range, it means we can't perform any operation
if (i == j) {
// no merging of elements possible, so value left will be same as arr[i].
dp2[i][j] = arr[i];
// so min array length that can be formed is 1.
return dp[i][j] = 1;
}
int minLength = Integer.MAX_VALUE;
for (int k = i; k < j; k++) {
// we try to split the range from i to k and from k + 1 to j
int left = arrayShrinking(arr, i, k);
int right = arrayShrinking(arr, k + 1, j);
minLength = Math.min(minLength, left + right);
// left and right equals to 1 means we can further merge these into one value if they have same dp2 values.
if (left == 1 && right == 1) {
if (dp2[i][k] != -1 && dp2[i][k] == dp2[k + 1][j]) {
dp2[i][j] = dp2[i][k] + 1;
return dp[i][j] = 1;
}
}
}
return dp[i][j] = minLength;
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
java
|
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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
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 {
String str = br.readLine();
if(str == null)
throw new InputMismatchException();
st = new StringTokenizer(str);
} 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();
}
if(str == null)
throw new InputMismatchException();
return str;
}
}
static boolean pal(String s)
{
// StringBuilder strBuilder = new StringBuilder(s);
// return s.equals(strBuilder.reverse().toString());
boolean p=true;
int l=0,r=s.length()-1;
while(l<r)
{
if(s.charAt(r)!=s.charAt(l))
{
p=false;
break;
}
l++;
r--;
}
return p;
}
static boolean isPrime(long arr)
{
// Corner cases
if (arr <= 1)
return false;
if (arr <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (arr % 2 == 0 || arr % 3 == 0)
return false;
for (int i = 5; i * i <= arr; i = i + 6)
if (arr % i == 0 || arr % (i + 2) == 0)
return false;
return true;
}
public static int reverseBits(int n)
{
int rev = 0;
// traversing bits of 'n'
// from the right
while (n > 0)
{
// bitwise left shift
// 'rev' by 1
rev <<= 1;
// if current bit is '1'
if ((int)(n & 1) == 1)
rev ^= 1;
// bitwise right shift
//'n' by 1
n >>= 1;
}
// required number
return rev;
}
static long gcd(long a, long element)
{
if (a == 0)
return element;
return gcd((element % a), a);
}
static long findGCD(long arr[], int n)
{
Arrays.sort(arr);
long result = arr[0];
for (long element: arr){
result = gcd(result, element);
if(result == 1)
{
return (long)1;
}
}
return result;
}
static int fact(int n)
{
int fact=1;
while(n>=1)
{
fact=fact*n;
n--;
}
return fact;
}
static long __gcd(long a, long b)
{
if (a == 0 || b == 0)
return 0;
if (a == b)
return a;
if (a > b)
return __gcd(a-b, b);
return __gcd(a, b-a);
}
static boolean coprime(long a, long b) {
if ( __gcd(a, b) == 1)
return true;
else
return false;
}
static int xor(int n,int a,int b)
{
if(n>0)
{
xor(n-1,b,a^b);
return a^b;
}
else
{
return a^b;
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
StringBuilder sb=new StringBuilder();
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
ArrayList<Long> key=new ArrayList<Long>();
HashMap<Long,ArrayList<Long>> x=new HashMap<Long,ArrayList<Long>>();
for(int i=0;i<n;i++)
{
long x1=sc.nextLong();
long y1=sc.nextLong();
if(x.containsKey(x1))
{
x.get(x1).add(y1);
}
else
{
ArrayList<Long> x2=new ArrayList<Long>();
x2.add(y1);
key.add(x1);
x.put(x1, x2);
}
}
Collections.sort(key);
boolean p1=true;
long p=0,q=0;
String s="";
for(int i=0;i<key.size();i++)
{
long x3=key.get(i)-p;
while(x3-->0)
{
s=s+"R";
}
Collections.sort(x.get(key.get(i)));
long x4=x.get(key.get(i)).get(x.get(key.get(i)).size()-1)-q;
if(x.get(key.get(i)).get(0)-q<0)
{
p1=false;
break;
}
while(x4-->0)
{
s=s+"U";
}
p=key.get(i);
q=x.get(key.get(i)).get(x.get(key.get(i)).size()-1);
}
if(p1)
{
out.println("YES");
out.println(s);
}
else
{
out.println("NO");
}
}
out.close();
}
}
|
java
|
1294
|
A
|
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
|
[
"math"
] |
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int tcs=s.nextInt();
for(int j=0;j<tcs;j++){
int a[]=new int[3];
for(int i=0;i<3;i++) a[i]=s.nextInt();
int coins=s.nextInt();
Arrays.sort(a);
int sum=a[2]-a[1]+a[2]-a[0];
if(coins<sum) System.out.println("NO");
else{
coins=coins-sum;
if(coins%3==0) System.out.println("YES");
else System.out.println("NO");
}
}
}
}
|
java
|
1293
|
A
|
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
|
[
"binary search",
"brute force",
"implementation"
] |
import java.io.*;
import java.util.StringTokenizer;
public class Problem1293A {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int tc = scanner.nextInt();
out: while (tc-->0){
int n = scanner.nextInt();
int s = scanner.nextInt();
int k = scanner.nextInt();
int [] array = new int[k];
for (int i =0;i<k;i++){
array[i]= scanner.nextInt();
}
for (int i =0;i<=k;i++){
if (s -i>=1 && !exists(array,s-i)){
System.out.println(i);
continue out;
}
if (s+i<=n && !exists(array,s+i)){
System.out.println(i);
continue out;
}
}
}
}
static boolean exists(int [] array , int x ){
boolean yes = false;
for (int i =0;i<array.length;i++){
if (array[i]==x){
yes = true;
break;
}
}
return yes;
}
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
|
1141
|
B
|
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
|
[
"implementation"
] |
import java.util.Scanner;
public class MaximalContinuousRest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
int count = 1;
int max = 1;
int count1 = 0;
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
if (arr[i] == 1) {
count1++;
}
}
if (count1 == 0) {
System.out.println(0);
} else {
for (int i = 1; i < n; i++) {
if (arr[i - 1] == 1 && arr[i] == 1) {
count++;
} else {
max = Math.max(max, count);
count = 1;
}
}
if (arr[n - 1] == 1) {
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
count++;
} else {
break;
}
}
System.out.println(Math.max(count, max));
} else {
System.out.println(max);
}
}
}
}
|
java
|
1312
|
B
|
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
|
[
"constructive algorithms",
"sortings"
] |
import java.util.*;
import java.io.*;
public class BogoSort{
public static void main(String [] args) throws Exception{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(input.readLine());
while(a-->0){
int b = Integer.parseInt(input.readLine());
int [] c = Arrays.stream(input.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Arrays.sort(c);
String ans="";
for(int i=b-1;i>=0;i--) ans+=c[i]+" ";
System.out.println(ans);
}
}
}
|
java
|
1324
|
C
|
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.
|
[
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] |
import java.io.*;
import java.sql.Array;
import java.util.*;
public class Main {
public static void main(String[] args) {
var fastScanner = new FastScanner();
int n = fastScanner.nextInt();
for (int i=0; i<n; i++) {
var s = fastScanner.nextLine();
s = "R"+s+"R";
int index = 0;
int mx = 0;
for (int j=0;j<s.length(); j++) {
if(s.charAt(j)=='R') {
mx = Math.max(mx, j-index);
index = j;
}
}
System.out.println(mx);
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
java
|
1312
|
A
|
A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO".
|
[
"geometry",
"greedy",
"math",
"number theory"
] |
import java.util.*;
import java.io.*;
public class AAA {
static void solve() throws IOException{
int n = readInt(), m = readInt();
System.out.println(n % m ==0 ? "yes": "no");
}
public static void main(String[] args) throws IOException {
int t = readInt();
for (int i = 0; i < t; i++) {
solve();
}
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static StringTokenizer st;
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readLine() throws IOException {
return br.readLine().trim();
}
}
|
java
|
1307
|
D
|
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
|
[
"binary search",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"shortest paths",
"sortings"
] |
import java.io.*;
import java.util.*;
public class CowAndFields {
static final int INF = 1000000000;
public static int[] bfs(int N, List<List<Integer>> graph, int src) {
int[] dist = new int[N];
Arrays.fill(dist, INF);
dist[src] = 0;
Queue<Integer> queue = new LinkedList<>();
queue.add(src);
while (!queue.isEmpty()) {
int cur = queue.remove();
for (int nxt : graph.get(cur)) {
if (dist[nxt] > dist[cur] + 1) {
dist[nxt] = dist[cur] + 1;
queue.add(nxt);
}
}
}
return dist;
}
public static void main(String[] args) {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out, false);
int N = reader.nextInt();
int M = reader.nextInt();
int K = reader.nextInt();
int[] A = new int[K];
for (int i = 0; i < K; i++) {
A[i] = reader.nextInt() - 1;
}
List<List<Integer>> graph = new ArrayList<>(N);
for (int i = 0; i < N; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < M; i++) {
int x = reader.nextInt() - 1;
int y = reader.nextInt() - 1;
graph.get(x).add(y);
graph.get(y).add(x);
}
int[][] dist = new int[2][N];
dist[0] = bfs(N, graph, 0);
dist[1] = bfs(N, graph, N - 1);
Arrays.sort(A);
int[][] data = new int[K][2];
for (int i = 0; i < K; i++) {
data[i] = new int[]{dist[0][A[i]] - dist[1][A[i]], A[i]};
}
Arrays.sort(data, (a, b) -> a[0] - b[0]);
int best = 0, max = -INF;
for (int[] d : data) {
best = Math.max(best, max + dist[1][d[1]]);
max = Math.max(max, dist[0][d[1]]);
}
writer.println(Math.min(dist[0][N - 1], best + 1));
writer.close();
System.exit(0);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
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.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.StringTokenizer;
public class Ex3 {
static FastScanner in = new FastScanner();
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out);
int q = 1;
for (int e = 0; e < q; e++) {
int x = in.nextInt();
String str = in.nextToken();
int r = 0;
int l = 0;
for(int i = 0; i < x; i++){
if(str.charAt(i) == 'L') {
l++;
}else{
r++;
}
}
out.println(Math.abs(l)+Math.abs(r)+1);
// int x = in.nextInt();
// String str = in.nextToken();
// char chStr[] = str.toCharArray();
// int ans = 0;
// for (int i = 0; i < x; i++) {
// int freg[] = new int[10];
// int id = i;
// int dis = 0;
// int max = 0;
// while (id < Math.min(i + 228, x)) {
// if (freg[chStr[id] - '0'] == 0) dis++;
// freg[chStr[id] - '0']++;
// max = Math.max(freg[chStr[id] - '0'], max);
// if (max <= dis) ans++;
// id++;
// }
// }
// out.println(ans);
}
out.flush();
}
static int[] arr(int n) {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
return arr;
}
static private long factorial(long n) {
long result = 1;
if (n == 1 || n == 0) {
return result;
}
result = n * factorial(n - 1);
return result;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
init();
}
public FastScanner(String name) {
init(name);
}
public FastScanner(boolean isOnlineJudge) {
if (!isOnlineJudge || System.getProperty("ONLINE_JUDGE") != null) {
init();
} else {
init("input.txt");
}
}
private void init() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private void init(String name) {
try {
br = new BufferedReader(new FileReader(name));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
public static void mergeSort(int[] arr) {
int n = arr.length;
if (n == 1) return;
int mid = n / 2;
int left[] = new int[mid];
int right[] = new int[n - mid];
for (int i = 0; i < mid; i++) {
left[i] = arr[i];
}
for (int i = mid; i < n; i++) {
right[i - mid] = arr[i];
}
mergeSort(left);
mergeSort(right);
merge(arr, left, right);
}
public static void merge(int arr[], int left[], int right[]) {
int lenLeft = left.length;
int lenRight = right.length;
int i = 0;
int j = 0;
int idx = 0;
while (i < lenLeft && j < lenRight) {
if (left[i] < right[j]) {
arr[idx] = left[i];
i++;
idx++;
} else {
arr[idx] = right[j];
j++;
idx++;
}
}
for (int ll = i; ll < lenLeft; ll++) {
arr[idx++] = left[ll];
}
for (int rr = j; rr < lenRight; rr++) {
arr[idx++] = right[rr];
}
}
}
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.