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 |
---|---|---|---|---|---|
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"
] |
//By the name of Almighty Allah, the most Beneficent
import java.util.*;
import java.lang.*;
import java.io.*;
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.time.*;
import java.sql.*;
import java.math.*;
import java.text.*;
import javax.xml.*;
import javax.swing.*;
public class code{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Scanner sn=new Scanner(System.in);
int t;
t=sc.nextInt();
for(int i=0;i<t;i++)
{
int n;
n=sc.nextInt();
int ar[]=new int[2*n];
for(int j=0;j<2*n;j++)
ar[j]=sc.nextInt();
Arrays.sort(ar);
System.out.println(ar[n]-ar[n-1]);
}
}
}
|
java
|
1316
|
C
|
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.
|
[
"constructive algorithms",
"math",
"ternary search"
] |
/*
/$$$$$ /$$$$$$ /$$ /$$ /$$$$$$
|__ $$ /$$__ $$ |$$ |$$ /$$__ $$
| $$| $$ \ $$| $$|$$| $$ \ $$
| $$| $$$$$$$$| $$ / $$/| $$$$$$$$
/ $$ | $$| $$__ $$ \ $$ $$/ | $$__ $$
| $$ | $$| $$ | $$ \ $$$/ | $$ | $$
| $$$$$$/| $$ | $$ \ $/ | $$ | $$
\______/ |__/ |__/ \_/ |__/ |__/
/$$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$ /$$ /$$ /$$ /$$$$$$$$ /$$$$$$$
| $$__ $$| $$__ $$ /$$__ $$ /$$__ $$| $$__ $$ /$$__ $$| $$$ /$$$| $$$ /$$$| $$_____/| $$__ $$
| $$ \ $$| $$ \ $$| $$ \ $$| $$ \__/| $$ \ $$| $$ \ $$| $$$$ /$$$$| $$$$ /$$$$| $$ | $$ \ $$
| $$$$$$$/| $$$$$$$/| $$ | $$| $$ /$$$$| $$$$$$$/| $$$$$$$$| $$ $$/$$ $$| $$ $$/$$ $$| $$$$$ | $$$$$$$/
| $$____/ | $$__ $$| $$ | $$| $$|_ $$| $$__ $$| $$__ $$| $$ $$$| $$| $$ $$$| $$| $$__/ | $$__ $$
| $$ | $$ \ $$| $$ | $$| $$ \ $$| $$ \ $$| $$ | $$| $$\ $ | $$| $$\ $ | $$| $$ | $$ \ $$
| $$ | $$ | $$| $$$$$$/| $$$$$$/| $$ | $$| $$ | $$| $$ \/ | $$| $$ \/ | $$| $$$$$$$$| $$ | $$
|__/ |__/ |__/ \______/ \______/ |__/ |__/|__/ |__/|__/ |__/|__/ |__/|________/|__/ |__/
*/
import java.io.BufferedReader;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class abc {
static PrintWriter pw;
/*
* static long inv[]=new long[1000001]; static long dp[]=new long[1000001];
*/
/// MAIN FUNCTION///
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
pw = new PrintWriter(System.out);
// use arraylist as it use the concept of dynamic table(amortized analysis)
// Arrays.stream(array).forEach(a -> Arrays.fill(a, 0));
/* List<Integer> l1 = new ArrayList<Integer>(); */
int tst =1;
while (tst-- > 0) {
int n =sc.nextInt();
int m =sc.nextInt();
int p =sc.nextInt();
int a[]=sc.readArray(n);
int b[]=sc.readArray(m);
for(int i=0;i<n;i++)
{
if(a[i]%p!=0)
{
n=i;
break;
}
}
for(int i=0;i<m;i++)
{
if(b[i]%p!=0)
{
m=i;
break;
}
}
pw.println(n+m);
}
pw.flush();
}
static void recursion(int n)
{
if(n==1)
{
pw.print(n+" ");
return;
}
//pw.print(n+" "); gives us n to 1
recursion(n-1);
//pw.print(n+" "); gives us 1 to n
}
//ch.charAt(i)+"" converts into a char sequence
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;
}
/* CREATED BY ME */
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
}
public static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public static boolean isPrime(long n) {
if (n == 2)
return true;
long i = 2;
while (i * i <= n) {
if (n % i == 0)
return false;
i++;
}
return true;
}
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static int max(int x, int y) {
return Math.max(x, y);
}
static int min(int x, int y) {
return Math.min(x, y);
}
static int abs(int x) {
return Math.abs(x);
}
static long abs(long x) {
return Math.abs(x);
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
static long max(long x, long y) {
return Math.max(x, y);
}
static long min(long x, long y) {
return Math.min(x, y);
}
public static class pair {
int x;
int y;
public pair(int a, int b) {
x = a;
y = b;
}
}
public static class Comp implements Comparator<pair> {
public int compare(pair a, pair b) {
if (a.x != b.x) {
return a.x - b.x;
} else {
return a.y - b.y;
}
}
}
//modular exponentiation
public static long fastExpo(long a,int n,int mod){
if (n == 0)
return 1;
else{
if ((n&1) == 1){
long x = fastExpo(a,n/2,mod);
return (((a*x)%mod)*x)%mod;
}
else{
long x = fastExpo(a,n/2,mod);
return (((x%mod)*(x%mod))%mod)%mod;
}
}
}
public static long modInverse(long n,int p){
return fastExpo(n,p-2,p);
}
/*
* public static void extract(ArrayList<Integer> ar, int k, int d) { int c = 0;
* for (int i = 1; i < k; i++) { int x = 0; boolean dm = false; while (x > 0) {
* long dig = x % 10; x = x / 10; if (dig == d) { dm = true; break; } } if (dm)
* ar.add(i); } }
*/
public static int[] prefixfuntion(String s)
{
int n=s.length();
int z[]=new int[n];
for(int i=1;i<n;i++)
{
int j=z[i-1];
while(j>0 && s.charAt(i)!=s.charAt(j))
j=z[j-1];
if(s.charAt(i)==s.charAt(j))
j++;
z[i]=j;
}
return z;
}
public static void dfs(int index, boolean vis[], int a[], int b[], int n) {
vis[index] = true;
for (int i = 0; i < n; i++) {
if (!vis[i] && (a[i] == a[index] || b[i] == b[index]))
dfs(i, vis, a, b, n);
}
}
// counts the set(1) bit of a number
public static long countSetBitsUtil(long x) {
if (x <= 0)
return 0;
return (x % 2 == 0 ? 0 : 1) + countSetBitsUtil(x / 2);
}
//tells whether a particular index has which bit of a number
public static int getIthBitsUtil(int x, int y) {
return (x & (1 << y)) != 0 ? 1 : 0;
}
public static void swap(long x, long y) {
x = x ^ y;
y = y ^ x;
x = x ^ y;
}
/*
* static long mod_inverse(long a, long b) { long mod=(long) (1000000007); long
* ans=1; while(b>0) { if((b%2)==0) ans=(ans*a) %mod; b/=2; a=(a*a) % mod;
*
* } return ans; }
*/
public static double decimalPlaces(double sum) {
DecimalFormat df = new DecimalFormat("#.00");
String angleFormated = df.format(sum);
double fin = Double.parseDouble(angleFormated);
return fin;
}
//use collections.swap for swapping
static boolean isSubSequence(String str1, String str2, int m, int n) {
int j = 0;
for (int i = 0; i < n && j < m; i++)
if (str1.charAt(j) == str2.charAt(i))
j++;
return (j == m);
}
static long sum(long n) {
long sum = n%10;
long s2=0,c=1;
while (n > 0) {
s2 += (n % 10);
n = n / 10;
}
return s2;
}
static long pow(long base, long power) {
if (power == 0) {
return 1;
}
long result = pow(base, power / 2);
if (power % 2 == 1) {
return result * result * base;
}
return result * result;
}
// return the hash value of a string
static long compute_hash(String s) {
long val = 0;
long p = 31;
long mod = (long) (1000000007);
long pow = 1;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
val = (val + (int) (ch - 'a' + 1) * pow) % mod;
pow = (pow * p) % mod;
}
return val;
}
// return a prefix sum array of hash values
/*
* static void prefix_array_value(String s) { long p=31; long mod=(long)
* (1000000007); long pow=1; inv[0]=1; dp[0]=(long)(s.charAt(0)-'a'+1);
*
* for(int i=1;i<s.length();i++) { char ch=s.charAt(i); pow= ( pow*p ) % mod;
* inv[i]=mod_inverse(pow, mod-2); dp[i]=(dp[i-1]+ (long)(ch- 'a' +1)*pow)%mod;
* } }
*/
/*
* static long substringHash(int L , int R ) { long result = dp[R]; long
* mod=(long) (1000000007); if(L > 0) result = (result - dp[L-1] + mod) % mod;
* result= (result * inv[L]) % mod; return result; }
*/
}
|
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.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
static Reader input = new Reader();
public static void main(String[] args) throws IOException {
int n = input.nextInt();
char[] s = input.next().toCharArray();
int[] color = new int[n];
int[] answer = new int[n];
for(int i = 1; i < n; ++i) {
if(s[i] < s[i-1]) {
color[i] = (color[i-1]+1)%2;
answer[i] = (color[i-1]+1)%2;
}
int pointer = i-1;
while(pointer > -1) {
if(s[pointer] <= s[pointer+1]) break;
if(color[pointer] != color[pointer+1]) {
int temp = color[pointer];
color[pointer] = color[pointer+1];
color[pointer+1] = temp;
char t = s[pointer];
s[pointer] = s[pointer+1];
s[pointer+1] = t;
} else {
System.out.println("NO");
return;
}
--pointer;
}
}
System.out.println("YES");
for(int i = 0; i < n; ++i) {
System.out.print(answer[i]);
}
}
static class Reader {
BufferedReader reader;
StringTokenizer string;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException {
while(string == null || ! string.hasMoreElements()) {
string = new StringTokenizer(reader.readLine());
}
return string.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
|
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"
] |
/*package whatever //do not write package name here */
import java.util.Scanner;
import java.util.Arrays;
public class code{
public static void print(int[] arr){
for(int j = 0;j<arr.length;j++){
System.out.print(arr[j]+" ");
}
}
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while(t-->0){
int n = s.nextInt();
int[] arr = new int[n];
for(int i = 0;i<n;i++){
arr[i] = s.nextInt();
}
Arrays.sort(arr);
int[] arr2 = new int[n];
for(int k = 0;k<n;k++){
arr2[k] = arr[n-1-k];
}
print(arr2);
System.out.println();
System.out.println();
}
}
}
|
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"
] |
/*
Rating: 1378
Date: 10-09-2022
Time: 23-13-31
Author: Kartik Papney
Linkedin: https://www.linkedin.com/in/kartik-papney-4951161a6/
Leetcode: https://leetcode.com/kartikpapney/
Codechef: https://www.codechef.com/users/kartikpapney
----------------------------Jai Shree Ram----------------------------
*/
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class A_Journey_Planning {
public static void s() {
int n = sc.nextInt();
long[] arr = sc.readLongArray(n);
HashMap<Long, Long> map = new HashMap<>();
for(int i=0; i<arr.length; i++) {
long key = arr[i]-i;
map.put(key, map.getOrDefault(key, 0l)+arr[i]);
}
long ans = 0;
for(long v : map.values()) {
ans = Math.max(ans, v);
}
p.writeln(ans);
}
public static void main(String[] args) {
int t = 1;
// t = sc.nextInt();
while (t-- != 0) {
s();
}
p.print();
}
public static boolean isBipartite(ArrayList<ArrayList<Integer>> graph) {
int n = graph.size();
Integer[] visited = new Integer[graph.size()];
Queue<int[]> q = new ArrayDeque<>();
for(int i=1; i<=n; i++) {
if(visited[i] != null) continue;
q.add(new int[]{i, 1});
while(!q.isEmpty()) {
int[] poll = q.remove();
int node = poll[0];
int color = poll[1];
if(visited[node] != null) {
if(visited[node] == color) continue;
return false;
}
visited[node] = color;
for(int nbr : graph.get(node)) {
if(visited[nbr] == null) q.add(new int[]{nbr, (color+1)%2});
}
}
}
return true;
}
public static boolean debug = false;
static void debug(String st) {
if(debug) p.writeln(st);
}
static final Integer MOD = (int) 1e9 + 7;
static final FastReader sc = new FastReader();
static final Print p = new Print();
static class Functions {
static void sort(int... a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static void sort(long... a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static int max(int... a) {
int max = Integer.MIN_VALUE;
for (int val : a) max = Math.max(val, max);
return max;
}
static int min(int... a) {
int min = Integer.MAX_VALUE;
for (int val : a) min = Math.min(val, min);
return min;
}
static long min(long... a) {
long min = Long.MAX_VALUE;
for (long val : a) min = Math.min(val, min);
return min;
}
static long max(long... a) {
long max = Long.MIN_VALUE;
for (long val : a) max = Math.max(val, max);
return max;
}
static long sum(long... a) {
long sum = 0;
for (long val : a) sum += val;
return sum;
}
static int sum(int... a) {
int sum = 0;
for (int val : a) sum += val;
return sum;
}
public static long mod_add(long a, long b) {
return (a % MOD + b % MOD + MOD) % MOD;
}
public static long pow(long a, long b) {
long res = 1;
while (b > 0) {
if ((b & 1) != 0)
res = mod_mul(res, a);
a = mod_mul(a, a);
b >>= 1;
}
return res;
}
public static long mod_mul(long a, long b) {
long res = 0;
a %= MOD;
while (b > 0) {
if ((b & 1) > 0) {
res = mod_add(res, a);
}
a = (2 * a) % MOD;
b >>= 1;
}
return res;
}
public static long gcd(long a, long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
public static long factorial(long n) {
long res = 1;
for (int i = 1; i <= n; i++) {
res = (i % MOD * res % MOD) % MOD;
}
return res;
}
public static int count(int[] arr, int x) {
int count = 0;
for (int val : arr) if (val == x) count++;
return count;
}
public static ArrayList<Integer> generatePrimes(int n) {
boolean[] primes = new boolean[n];
for (int i = 2; i < primes.length; i++) primes[i] = true;
for (int i = 2; i < primes.length; i++) {
if (primes[i]) {
for (int j = i * i; j < primes.length; j += i) {
primes[j] = false;
}
}
}
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < primes.length; i++) {
if (primes[i]) arr.add(i);
}
return arr;
}
}
static class Print {
StringBuffer strb = new StringBuffer();
public void write(Object str) {
strb.append(str);
}
public void writes(Object str) {
char c = ' ';
strb.append(str).append(c);
}
public void writeln(Object str) {
char c = '\n';
strb.append(str).append(c);
}
public void yes() {
char c = '\n';
writeln("YES");
}
public void no() {
writeln("NO");
}
public void writeln() {
char c = '\n';
strb.append(c);
}
public void writes(int... arr) {
for (int val : arr) {
write(val);
write(' ');
}
}
public void writes(long... arr) {
for (long val : arr) {
write(val);
write(' ');
}
}
public void writeln(int... arr) {
for (int val : arr) {
writeln(val);
}
}
public void print() {
System.out.print(strb);
}
public void println() {
System.out.println(strb);
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
String[] readStringArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = nextLine();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
double[] readArrayDouble(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
String nextLine() {
String str = new String();
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
java
|
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.util.*;
public class C {
static long dfs(int source, int parent, long x, ArrayList<ArrayList<Integer>> adj, long[] arr) {
long s = arr[source];
for (Integer i : adj.get(source)) {
if (i != parent) {
s += dfs(i, source, x, adj, arr);
}
}
return Math.max(s, -x);
}
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 n, long m) {
if (m == 0)
return n;
return gcd(m, n % m);
}
static long lcm(long n, long m) {
return (n * m) / gcd(n, m);
}
static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
FastReader sc = new FastReader();
StringBuilder str = new StringBuilder();
int t = sc.nextInt();
for (int xx = 0; xx < t; xx++) {
int n = sc.nextInt();
Pair[] arr = new Pair[n];
for (int i = 0; i < n; i++) {
arr[i] = new Pair(sc.nextInt(), sc.nextInt());
}
Arrays.sort(arr, (p1, p2) -> {
if (p1.x == p2.x)
return Integer.compare(p1.y, p2.y);
return Integer.compare(p1.x, p2.x);
});
StringBuilder st = new StringBuilder();
int currx = 0;
int curry = 0;
boolean ok = true;
for (int i = 0; i < n; i++) {
if (arr[i].x < currx || arr[i].y < curry) {
ok = false;
break;
}
for (int j = currx; j < arr[i].x; j++)
st.append("R");
for (int j = curry; j < arr[i].y; j++)
st.append("U");
currx = arr[i].x;
curry = arr[i].y;
}
if (ok) {
str.append("YES" + "\n");
str.append(st + "\n");
} else
str.append("NO" + "\n");
}
System.out.println(str);
}
}
|
java
|
1305
|
D
|
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
|
[
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.Collection;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Queue;
import java.util.ArrayDeque;
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);
DKuroniAndTheCelebration solver = new DKuroniAndTheCelebration();
solver.solve(1, in, out);
out.close();
}
static class DKuroniAndTheCelebration {
int N = 1010;
int M = N * 2;
int[] h = new int[N];
int[] e = new int[M];
int[] ne = new int[M];
int idx;
int n;
int[] deg = new int[N];
public void solve(int testNumber, InputReader in, OutputWriter out) {
Arrays.fill(h, -1);
idx = 0;
n = in.nextInt();
for (int i = 0; i < n - 1; i++) {
int a = in.nextInt();
int b = in.nextInt();
add(a, b);
add(b, a);
deg[a]++;
deg[b]++;
}
Queue<Integer> queue = new ArrayDeque<>();
for (int i = 1; i <= n; i++) {
if (deg[i] == 1) {
queue.add(i);
}
}
while (queue.size() >= 2) {
int a = queue.poll();
int b = queue.poll();
out.println("?", a, b);
out.flush();
int x = in.nextInt();
if (x == a || x == b) {
out.println("!", x);
out.flush();
return;
}
for (int i = h[a]; i != -1; i = ne[i]) {
int j = e[i];
if (deg[j] > 1) {
deg[j]--;
if (deg[j] == 1) {
queue.add(j);
}
}
}
for (int i = h[b]; i != -1; i = ne[i]) {
int j = e[i];
if (deg[j] > 1) {
deg[j]--;
if (deg[j] == 1) {
queue.add(j);
}
}
}
}
out.println("!", queue.poll());
out.flush();
}
void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
java
|
1304
|
B
|
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0
InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
|
[
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"strings"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.rmi.Remote;
// import java.util.Scanner;
import java.util.*;
import javax.management.Query;
public class second {
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) {
FastReader s = new FastReader();
// int test_cases=s.nextInt();
// outer:while(test_cases-->0){
// }
int numString=s.nextInt();
int size=s.nextInt();
String [] strings=new String[numString];
String [] reverseStrings=new String[numString];
for(int i=0;i<numString ;i++){
strings[i]=s.next();
StringBuffer sb=new StringBuffer("");
sb.append(strings[i]);
reverseStrings[i]=sb.reverse().toString();
}
String first="",last="",temp="";
for (int i = 0; i < numString; i++) {
for (int j = i; j <numString; j++) {
if(strings[j].equals(reverseStrings[i])){
if(i==j){
temp=strings[i];
}
else{
first+=strings[i];
last=reverseStrings[i]+last;
}
}
}
}
first=first+temp+last;
System.out.println(first.length());
System.out.println(first);
}
}
|
java
|
1303
|
A
|
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
|
[
"implementation",
"strings"
] |
import java.util.Scanner;
public class Codeforces_1303A_Erasing_Zeroes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
String s = sc.next();
int left = -1, right = -1, sum = 0;
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == '1') {
if (left == -1) {
left = j;
}
right = j;
sum++;
}
}
System.out.println(right > left ? (right - left + 1 - sum) : 0);
}
}
}
|
java
|
1299
|
B
|
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
|
[
"geometry"
] |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedOutputStream;
import java.util.HashSet;
import java.io.UncheckedIOException;
import java.util.Objects;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author mikit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
LightScanner in = new LightScanner(inputStream);
LightWriter out = new LightWriter(outputStream);
BAerodinamicheskii solver = new BAerodinamicheskii();
solver.solve(1, in, out);
out.close();
}
static class BAerodinamicheskii {
public void solve(int testNumber, LightScanner in, LightWriter out) {
int n = in.ints();
HashSet<Vec2l> ps = new HashSet<>();
long gx = 0, gy = 0;
long[] x = new long[n], y = new long[n];
for (int i = 0; i < n; i++) {
x[i] = in.longs();
y[i] = in.longs();
gx += x[i];
gy += y[i];
x[i] *= n;
y[i] *= n;
ps.add(new Vec2l(x[i], y[i]));
}
gx *= 2;
gy *= 2;
for (int i = 0; i < n; i++) {
if (!ps.contains(new Vec2l(gx - x[i], gy - y[i]))) {
out.noln();
return;
}
}
out.yesln();
}
}
static class LightScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public LightScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public String string() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return tokenizer.nextToken();
}
public int ints() {
return Integer.parseInt(string());
}
public long longs() {
return Long.parseLong(string());
}
}
static class LightWriter implements AutoCloseable {
private final Writer out;
private boolean autoflush = false;
private boolean breaked = true;
private LightWriter.BoolLabel boolLabel = LightWriter.BoolLabel.YES_NO_FIRST_UP;
public LightWriter(Writer out) {
this.out = out;
}
public LightWriter(OutputStream out) {
this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));
}
public LightWriter print(char c) {
try {
out.write(c);
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter print(String s) {
try {
out.write(s, 0, s.length());
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter ans(String s) {
if (!breaked) {
print(' ');
}
return print(s);
}
public LightWriter ans(boolean b) {
return ans(boolLabel.transfer(b));
}
public LightWriter yesln() {
return ans(true).ln();
}
public LightWriter noln() {
return ans(false).ln();
}
public LightWriter ln() {
print(System.lineSeparator());
breaked = true;
if (autoflush) {
try {
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
return this;
}
public void close() {
try {
out.close();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
public enum BoolLabel {
YES_NO_FIRST_UP("Yes", "No"),
YES_NO_ALL_UP("YES", "NO"),
YES_NO_ALL_DOWN("yes", "no"),
Y_N_ALL_UP("Y", "N"),
POSSIBLE_IMPOSSIBLE_FIRST_UP("Possible", "Impossible"),
POSSIBLE_IMPOSSIBLE_ALL_UP("POSSIBLE", "IMPOSSIBLE"),
POSSIBLE_IMPOSSIBLE_ALL_DOWN("possible", "impossible"),
FIRST_SECOND_FIRST_UP("First", "Second"),
FIRST_SECOND_ALL_UP("FIRST", "SECOND"),
FIRST_SECOND_ALL_DOWN("first", "second"),
ALICE_BOB_FIRST_UP("Alice", "Bob"),
ALICE_BOB_ALL_UP("ALICE", "BOB"),
ALICE_BOB_ALL_DOWN("alice", "bob"),
;
private final String positive;
private final String negative;
BoolLabel(String positive, String negative) {
this.positive = positive;
this.negative = negative;
}
private String transfer(boolean f) {
return f ? positive : negative;
}
}
}
static class Vec2l implements Comparable<Vec2l> {
public long x;
public long y;
public Vec2l(long x, long y) {
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vec2l vec2i = (Vec2l) o;
return x == vec2i.x &&
y == vec2i.y;
}
public int hashCode() {
return Objects.hash(x, y);
}
public String toString() {
return "(" + x + ", " + y + ")";
}
public int compareTo(Vec2l o) {
if (x == o.x) {
return Long.compare(y, o.y);
}
return Long.compare(x, o.x);
}
public Vec2l clone() throws CloneNotSupportedException {
return (Vec2l) super.clone();
}
}
}
|
java
|
1303
|
B
|
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.
|
[
"math"
] |
import java.io.*;
import java.util.*;
public class NationalProject {
public static void main(String args[]) throws IOException {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int tc, i, j;
String s;
char p;
tc = sc.nextInt();
while (tc-- > 0) {
long n = sc.nextInt();
long good=sc.nextInt();
long bad=sc.nextInt();
long half=(long)Math.ceil(n/2.0);
long ans=(long)(Math.floor(half/(double)good))*(good+bad);
ans+=(half%good==0)?-bad:half%good;
out.println(Math.max(n,ans));
}
out.close();
}
/*--------------------------------------------------------
----------------------------------------------------------*/
//Pair Class
public static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return this.x - o.x;
}
}
/*
FASTREADER
*/
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;
}
/*DEFINED BY ME*/
//READING ARRAY
int[] readArray(int n) {
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
//COLLECTIONS SORT
void sort(int arr[]) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : arr)
l.add(i);
Collections.sort(l);
for (int i = 0; i < arr.length; i++)
arr[i] = l.get(i);
}
//EUCLID'S GCD
int gcd(int a, int b) {
if (b != 0)
return gcd(b, a % b);
else
return a;
}
void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
|
java
|
1284
|
B
|
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
|
[
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] |
import java.util.*;
public class C {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = n;
long res =0;
ArrayList<Integer> max = new ArrayList<>();
ArrayList<Integer> min = new ArrayList<>();
for (int i = 0; i < n; i++) {
int l =s.nextInt();
boolean t = false;
int el[] = new int[l] ;
el[0]=s.nextInt();
for (int j = 1; j < l; j++) {
el[j] = s.nextInt();
if(el[j]>el[j-1])t = true;
}
if(t){
res+=2*k -1;
k--;
}
else{
max.add(el[0]);
min.add(el[l-1]);
}
}
Collections.sort(min);
Collections.sort(max);
int i=0,j=0;
int tot=0;
while(j<max.size() && i < min.size()){
if(min.get(i)<max.get(j)){
i++;
tot++;
}
else {
res+=tot;
j++;
}
}
if(j< max.size())res+=(long)tot*(max.size()-j);
System.out.println(res);
}
}
|
java
|
1315
|
B
|
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
|
[
"binary search",
"dp",
"greedy",
"strings"
] |
import java.util.*;
import java.lang.*;
import java.math.BigInteger;
import java.io.*;
public class Main implements Runnable {
public static void main(String[] args) {
new Thread(null, new Main(), "whatever", 1 << 26).start();
}
private FastScanner sc;
private PrintWriter pw;
public void run() {
try {
boolean isSumitting = true;
// isSumitting = false;
if (isSumitting) {
pw = new PrintWriter(System.out);
sc = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
} else {
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
sc = new FastScanner(new BufferedReader(new FileReader("input.txt")));
}
} catch (Exception e) {
throw new RuntimeException();
}
int t = sc.nextInt();
// int t = 1;
while (t-- > 0) {
// sc.nextLine();
// System.out.println("for t=" + t);
solve();
}
pw.close();
}
public long mod = 1_000_000_007;
private long[][] dp;
public void solve() {
int a = sc.nextInt();
int b = sc.nextInt();
int p = sc.nextInt();
char[] arr = sc.next().toCharArray();
int i = arr.length - 2;
if (arr.length >= 2) {
if (arr[arr.length - 2] == 'A') {
if (p < a) {
pw.println(arr.length);
return;
}
p -= a;
} else {
if (p < b) {
pw.println(arr.length);
return;
}
p -= b;
}
}
i--;
for (; i >= 0; i--) {
if (arr[i] != arr[i + 1]) {
if (arr[i] == 'A') {
if (p < a) {
pw.println((i + 2));
return;
}
p -= a;
} else {
if (p < b) {
pw.println((i + 2));
return;
}
p -= b;
}
}
}
pw.println(1);
}
class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(BufferedReader bf) {
reader = bf;
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String[] nextStringArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = next();
}
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
}
private static class Sorter {
public static <T extends Comparable<? super T>> void sort(T[] arr) {
Arrays.sort(arr);
}
public static <T> void sort(T[] arr, Comparator<T> c) {
Arrays.sort(arr, c);
}
public static <T> void sort(T[][] arr, Comparator<T[]> c) {
Arrays.sort(arr, c);
}
public static <T extends Comparable<? super T>> void sort(ArrayList<T> arr) {
Collections.sort(arr);
}
public static <T> void sort(ArrayList<T> arr, Comparator<T> c) {
Collections.sort(arr, c);
}
public static void normalSort(int[] arr) {
Arrays.sort(arr);
}
public static void normalSort(long[] arr) {
Arrays.sort(arr);
}
public static void sort(int[] arr) {
timSort(arr);
}
public static void sort(int[] arr, Comparator<Integer> c) {
timSort(arr, c);
}
public static void sort(int[][] arr, Comparator<Integer[]> c) {
timSort(arr, c);
}
public static void sort(long[] arr) {
timSort(arr);
}
public static void sort(long[] arr, Comparator<Long> c) {
timSort(arr, c);
}
public static void sort(long[][] arr, Comparator<Long[]> c) {
timSort(arr, c);
}
private static void timSort(int[] arr) {
Integer[] temp = new Integer[arr.length];
for (int i = 0; i < arr.length; i++) temp[i] = arr[i];
Arrays.sort(temp);
for (int i = 0; i < arr.length; i++) arr[i] = temp[i];
}
private static void timSort(int[] arr, Comparator<Integer> c) {
Integer[] temp = new Integer[arr.length];
for (int i = 0; i < arr.length; i++) temp[i] = arr[i];
Arrays.sort(temp, c);
for (int i = 0; i < arr.length; i++) arr[i] = temp[i];
}
private static void timSort(int[][] arr, Comparator<Integer[]> c) {
Integer[][] temp = new Integer[arr.length][arr[0].length];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[0].length; j++)
temp[i][j] = arr[i][j];
Arrays.sort(temp, c);
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[0].length; j++)
temp[i][j] = arr[i][j];
}
private static void timSort(long[] arr) {
Long[] temp = new Long[arr.length];
for (int i = 0; i < arr.length; i++) temp[i] = arr[i];
Arrays.sort(temp);
for (int i = 0; i < arr.length; i++) arr[i] = temp[i];
}
private static void timSort(long[] arr, Comparator<Long> c) {
Long[] temp = new Long[arr.length];
for (int i = 0; i < arr.length; i++) temp[i] = arr[i];
Arrays.sort(temp, c);
for (int i = 0; i < arr.length; i++) arr[i] = temp[i];
}
private static void timSort(long[][] arr, Comparator<Long[]> c) {
Long[][] temp = new Long[arr.length][arr[0].length];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[0].length; j++)
temp[i][j] = arr[i][j];
Arrays.sort(temp, c);
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[0].length; j++)
temp[i][j] = arr[i][j];
}
}
public long fastPow(long x, long y, long mod) {
if (y == 0) return 1;
if (y == 1) return x % mod;
long temp = fastPow(x, y / 2, mod);
long ans = (temp * temp) % mod;
return (y % 2 == 1) ? (ans * (x % mod)) % mod : ans;
}
public long fastPow(long x, long y) {
if (y == 0) return 1;
if (y == 1) return x;
long temp = fastPow(x, y / 2);
long ans = (temp * temp);
return (y % 2 == 1) ? (ans * x) : ans;
}
}
|
java
|
1294
|
E
|
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
|
[
"greedy",
"implementation",
"math"
] |
// package codeforce.Training1900;
import java.io.PrintWriter;
import java.util.*;
public class ObtainaPermutation {
// MUST SEE BEFORE SUBMISSION
// check whether int part would overflow or not, especially when it is a * b!!!!
// check if top down dp would cause overflow or not !!!!!!!!!!!!!!!!!!!!!!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
// int t = sc.nextInt();
int t = 1;
for (int i = 0; i < t; i++) {
solve(sc, pw);
}
pw.close();
}
static void solve(Scanner in, PrintWriter out){
int n = in.nextInt(), m = in.nextInt();
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = in.nextInt();
}
}
int ans = 0;
for(int i = 1; i <= m; i++){
Map<Integer, Integer> mp = new HashMap<>();
for(int j = 0; j < n; j++){
int v = i + j * m;
mp.put(v, j);
}
// System.out.println(mp);
int[] cnt = new int[n];
for (int j = 0; j < n; j++) {
if (!mp.containsKey(arr[j][i - 1])) continue;
int pos = mp.get(arr[j][i - 1]);
if (pos <= j){
cnt[j - pos]++;
}else{
cnt[n - Math.abs(pos - j)]++;
}
}
// System.out.println(Arrays.toString(cnt));
int min = Integer.MAX_VALUE;
for (int j = 0; j < n; j++) {
min = Math.min(min, n - cnt[j] + j);
}
// System.out.println(min);
ans += min;
}
out.println(ans);
}
// credits to SecondThread
// Use this instead of Arrays.sort() on an array of ints. Arrays.sort() is n^2
// worst case since it uses a version of quicksort. Although this would never
// actually show up in the real world, in codeforces, people can hack, so
// this is needed.
static void ruffleSort(int[] a) {
//ruffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n), temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
}
|
java
|
1299
|
A
|
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
|
[
"brute force",
"greedy",
"math"
] |
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Main {
static class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
}
static long mod = (long) 1e9 + 7;
public static final double PI = 3.141592653589793d;
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC
{
public static void solve(int testNumber, InputReader in, OutputWriter out)
{
int n = in.readInt();
long arr[] = in.nextLongArray(n);
long prf[]=new long[n];
long suf[]=new long[n];
prf[0]=arr[0];
for(int i=1;i<n;i++)
{
prf[i]=prf[i-1]|arr[i];
}
suf[n-1]=arr[n-1];
for(int i=n-2;i>=0;--i)
{
suf[i]=suf[i+1]|arr[i];
}
long max=-1,best=-1;
for(int i=0;i<n;i++)
{
long val=(i>0?prf[i-1]:0)|(i+1<n?suf[i+1]:0);
if((arr[i]&(~val))>max)
{
max=(arr[i]&(~val));
best=i;
}
}
out.print(arr[(int)best]+" ");
for(int i=0;i<n;i++)
{
if(i!=best)
{
out.print(arr[i]+" ");
}
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int arraySize) {
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = readInt();
}
return array;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isNewLine(int c) {
return c == '\n';
}
public String nextLine() {
int c = read();
StringBuilder result = new StringBuilder();
do {
result.appendCodePoint(c);
c = read();
} while (!isNewLine(c));
return result.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
long result = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
result *= 10;
result += c & 15;
c = read();
} while (!isSpaceChar(c));
return result * sign;
}
public long[] nextLongArray(int arraySize) {
long array[] = new long[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextLong();
}
return array;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = (byte) read();
while (c <= ' ') {
c = (byte) read();
}
boolean neg = (c == '-');
if (neg) {
c = (byte) read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = (byte) read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = (byte) read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class CP {
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n == 2 || n == 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; (long) i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
public static boolean isComposite(long n) {
if (n < 2)
return true;
if (n == 2 || n == 3)
return false;
if (n % 2 == 0 || n % 3 == 0)
return true;
for (long i = 6L; i * i <= n; i += 6)
if (n % (i - 1) == 0 || n % (i + 1) == 0)
return true;
return false;
}
static int ifnotPrime(int[] prime, int x) {
return (prime[x / 64] & (1 << ((x >> 1) & 31)));
}
static int log2(long n) {
return (int) (Math.log10(n) / Math.log10(2));
}
static void makeComposite(int[] prime, int x) {
prime[x / 64] |= (1 << ((x >> 1) & 31));
}
public static int[] sieveEratosthenes(int n) {
if (n <= 32) {
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int i = 0; i < primes.length; i++) {
if (n < primes[i]) {
return Arrays.copyOf(primes, i);
}
}
return primes;
}
int u = n + 32;
double lu = Math.log(u);
int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];
ret[0] = 2;
int pos = 1;
int[] isnp = new int[(n + 1) / 32 / 2 + 1];
int sup = (n + 1) / 32 / 2 + 1;
int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int tp : tprimes) {
ret[pos++] = tp;
int[] ptn = new int[tp];
for (int i = (tp - 3) / 2; i < tp << 5; i += tp)
ptn[i >> 5] |= 1 << (i & 31);
for (int j = 0; j < sup; j += tp) {
for (int i = 0; i < tp && i + j < sup; i++) {
isnp[j + i] |= ptn[i];
}
}
}
// 3,5,7
// 2x+3=n
int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4,
13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14};
int h = n / 2;
for (int i = 0; i < sup; i++) {
for (int j = ~isnp[i]; j != 0; j &= j - 1) {
int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];
int p = 2 * pp + 3;
if (p > n)
break;
ret[pos++] = p;
if ((long) p * p > n)
continue;
for (int q = (p * p - 3) / 2; q <= h; q += p)
isnp[q >> 5] |= 1 << q;
}
}
return Arrays.copyOf(ret, pos);
}
static ArrayList<Integer> bitWiseSieve(int n) {
ArrayList<Integer> al = new ArrayList<>();
int prime[] = new int[n / 64 + 1];
for (int i = 3; i * i <= n; i += 2) {
if (ifnotPrime(prime, i) == 0)
for (int j = i * i, k = i << 1;
j < n; j += k)
makeComposite(prime, j);
}
al.add(2);
for (int i = 3; i <= n; i += 2)
if (ifnotPrime(prime, i) == 0)
al.add(i);
return al;
}
public static long[] sort(long arr[]) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list);
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static long[] revsort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static int[] revsort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
static ArrayList<Integer> sieve(long size) {
ArrayList<Integer> pr = new ArrayList<Integer>();
boolean prime[] = new boolean[(int) size];
for (int i = 2; i < prime.length; i++) prime[i] = true;
for (int i = 2; i * i < prime.length; i++) {
if (prime[i]) {
for (int j = i * i; j < prime.length; j += i) {
prime[j] = false;
}
}
}
for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i);
return pr;
}
static ArrayList<Integer> segmented_sieve(int l, int r, ArrayList<Integer> primes) {
ArrayList<Integer> al = new ArrayList<>();
if (l == 1) ++l;
int max = r - l + 1;
int arr[] = new int[max];
for (int p : primes) {
if (p * p <= r) {
int i = (l / p) * p;
if (i < l) i += p;
for (; i <= r; i += p) {
if (i != p) {
arr[i - l] = 1;
}
}
}
}
for (int i = 0; i < max; ++i) {
if (arr[i] == 0) {
al.add(l + i);
}
}
return al;
}
static boolean isfPrime(long n, int iteration) {
if (n == 0 || n == 1)
return false;
if (n == 2)
return true;
if (n % 2 == 0)
return false;
Random rand = new Random();
for (int i = 0; i < iteration; i++) {
long r = Math.abs(rand.nextLong());
long a = r % (n - 1) + 1;
if (modPow(a, n - 1, n) != 1)
return false;
}
return true;
}
static long modPow(long a, long b, long c) {
long res = 1;
for (int i = 0; i < b; i++) {
res *= a;
res %= c;
}
return res % c;
}
// static public int lengthOfLIS(ArrayList<Integer> al) {
//
// ArrayList<Integer> dp=new ArrayList<Integer>();
// int n=al.size();
// dp.add(al.get(0));
// int idx=0;
// for(int i=1;i<n;i++)
// {
// if(al.get(i)>dp.get(dp.size()-1))
// {
// dp.add(al.get(i));
// }
// else
// {
// idx=ub(dp,al.get(i));
// dp.set(idx,al.get(i));
// }
// }
// return dp.size();
// }
private static long binPower(long a, long l, long mod) {
long res = 0;
while (l > 0) {
if ((l & 1) == 1) {
res = mulmod(res, a, mod);
;
l >>= 1;
}
a = mulmod(a, a, mod);
}
return res;
}
private static long mulmod(long a, long b, long c) {
long x = 0, y = a % c;
while (b > 0) {
if (b % 2 == 1) {
x = (x + y) % c;
}
y = (y * 2L) % c;
b /= 2;
}
return x % c;
}
static long binary_Expo(long a, long b) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res *= a;
--b;
}
a *= a;
b /= 2;
}
return res;
}
static long Modular_Expo(long a, long b) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res = (res * a) % mod;
--b;
}
a = (a * a) % mod;
b /= 2;
}
return res % mod;
}
static int i_gcd(int a, int b) {
while (true) {
if (b == 0)
return a;
int c = a;
a = b;
b = c % b;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long ceil_div(long a, long b) {
return (a + b - 1) / b;
}
static int getIthBitFromInt(int bits, int i) {
return (bits >> (i - 1)) & 1;
}
private static TreeMap<Long, Long> primeFactorize(long n) {
TreeMap<Long, Long> pf = new TreeMap<>(Collections.reverseOrder());
long cnt = 0;
long total = 1;
for (long i = 2; (long) i * i <= n; ++i) {
if (n % i == 0) {
cnt = 0;
while (n % i == 0) {
++cnt;
n /= i;
}
pf.put(cnt, i);
//total*=(cnt+1);
}
}
if (n > 1) {
pf.put(1L, n);
//total*=2;
}
return pf;
}
static long upper_Bound(long a[], long x) {
long l = 0, h = 0, mid = 0, ans = -1;
while (l <= h) {
mid = (l + h) >> 1;
if (a[(int) mid] > x) {
ans = mid;
h = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
static int lower_Bound(ArrayList<Long> a, long x) {
int l = 0, r = a.size() - 1, ans = -1, mid = 0;
while (l <= r) {
mid = (l + r) >> 1;
if (a.get(mid) <= x) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return ans;
}
static long lower_Bound(long a[], long x) {
long l = 0, h = 0, mid = 0, ans = -1;
while (l <= h) {
mid = (l + h) >> 1;
if (a[(int) mid] >= x) {
ans = mid;
h = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
static int upperBound(int a[], int x) {// x is the key or target value
long l = 0, h = 0, mid = 0, ans = -1;
while (l <= h) {
mid = (l + h) >> 1;
if (a[(int) mid] > x) {
ans = mid;
h = mid - 1;
} else {
l = mid + 1;
}
}
return (int) ans;
}
static int bs(long a[], long t) {
int ans = -1;
int i = 0, j = a.length - 1;
while (i <= j) {
int mid = i + (j - i) / 2;
if (a[mid] > 0) {
ans = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ans;
}
static public int ub(ArrayList<Long> dp, long num) {
int l = 0, r = dp.size() - 1, ans = -1, mid = 0;
while (l <= r) {
mid = l + ((r - l) >> 1);
if (dp.get(mid) >= num) {
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
static boolean isSquarefactor(int x, int factor, int target) {
int s = (int) Math.round(Math.sqrt(x));
return factor * s * s == target;
}
static boolean isSquare(int x) {
int s = (int) Math.round(Math.sqrt(x));
return x * x == s;
}
static int bs(ArrayList<Integer> al, int val) {
int l = 0, h = al.size() - 1, mid = 0, ans = -1;
while (l <= h) {
mid = (l + h) >> 1;
if (al.get(mid) == val) {
return mid;
} else if (al.get(mid) > val) {
h = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
static void sort(int a[]) // heap sort
{
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 0; i < a.length; i++)
q.add(a[i]);
for (int i = 0; i < a.length; i++)
a[i] = q.poll();
}
static void shuffle(int[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * in.length);
fast_swap(in, idx, i);
}
}
static boolean isPalindrome(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
if (s.equals(sb.toString())) {
return true;
}
return false;
}
public static int[] radixSort2(int[] a) {
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for (int v : a) {
c0[(v & 0xff) + 1]++;
c1[(v >>> 8 & 0xff) + 1]++;
c2[(v >>> 16 & 0xff) + 1]++;
c3[(v >>> 24 ^ 0x80) + 1]++;
}
for (int i = 0; i < 0xff; i++) {
c0[i + 1] += c0[i];
c1[i + 1] += c1[i];
c2[i + 1] += c2[i];
c3[i + 1] += c3[i];
}
int[] t = new int[n];
for (int v : a) t[c0[v & 0xff]++] = v;
for (int v : t) a[c1[v >>> 8 & 0xff]++] = v;
for (int v : a) t[c2[v >>> 16 & 0xff]++] = v;
for (int v : t) a[c3[v >>> 24 ^ 0x80]++] = v;
return a;
}
static int[] computeLps(String pat) {
int len = 0, i = 1, m = pat.length();
int lps[] = new int[m];
lps[0] = 0;
while (i < m) {
if (pat.charAt(i) == pat.charAt(len)) {
++len;
lps[i] = len;
++i;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = len;
++i;
}
}
}
return lps;
}
static ArrayList<Integer> kmp(String s, String pat) {
ArrayList<Integer> al = new ArrayList<>();
int n = s.length(), m = pat.length();
int lps[] = computeLps(pat);
int i = 0, j = 0;
while (i < n) {
if (s.charAt(i) == pat.charAt(j)) {
i++;
j++;
if (j == m) {
al.add(i - j);
j = lps[j - 1];
}
} else {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return al;
}
static void reverse_ruffle_sort(int a[]) {
shuffle(a);
Arrays.sort(a);
for (int l = 0, r = a.length - 1; l < r; ++l, --r)
fast_swap(a, l, r);
}
static void ruffle_sort(int a[]) {
shuffle(a);
Arrays.sort(a);
}
static int getMax(int arr[], int n) {
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
static ArrayList<Long> primeFactors(long n) {
ArrayList<Long> al = new ArrayList<>();
al.add(1L);
while (n % 2 == 0) {
if (!al.contains(2L)) {
al.add(2L);
}
n /= 2L;
}
for (long i = 3; (long) i * i <= n; i += 2) {
while ((n % i == 0)) {
if (!al.contains((long) i)) {
al.add((long) i);
}
n /= i;
}
}
if (n > 2) {
if (!al.contains(n)) {
al.add(n);
}
}
return al;
}
public static long totFactors(int n) {
long cnt = 0, tot = 1;
while (n % 2 == 0) {
n /= 2;
++cnt;
}
tot *= (cnt + 1);
for (int i = 3; i <= Math.sqrt(n); i += 2) {
cnt = 0;
while (n % i == 0) {
n /= i;
++cnt;
}
tot *= (cnt + 1);
}
if (n > 2) {
tot *= 2;
}
return tot;
}
static int[] z_function(String s) {
int n = s.length(), z[] = new int[n];
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = Math.min(z[i - l], r - i + 1);
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))
++z[i];
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
static void fast_swap(int[] a, int idx1, int idx2) {
if (a[idx1] == a[idx2])
return;
a[idx1] ^= a[idx2];
a[idx2] ^= a[idx1];
a[idx1] ^= a[idx2];
}
static void fast_swap(long[] a, int idx1, int idx2) {
if (a[idx1] == a[idx2])
return;
a[idx1] ^= a[idx2];
a[idx2] ^= a[idx1];
a[idx1] ^= a[idx2];
}
public static void fast_sort(long[] array) {
ArrayList<Long> copy = new ArrayList<>();
for (long i : array)
copy.add(i);
Collections.sort(copy);
for (int i = 0; i < array.length; i++)
array[i] = copy.get(i);
}
static int factorsCount(int n) {
boolean hash[] = new boolean[n + 1];
Arrays.fill(hash, true);
for (int p = 2; p * p < n; p++)
if (hash[p] == true)
for (int i = p * 2; i < n; i += p)
hash[i] = false;
int total = 1;
for (int p = 2; p <= n; p++) {
if (hash[p]) {
int count = 0;
if (n % p == 0) {
while (n % p == 0) {
n = n / p;
count++;
}
total = total * (count + 1);
}
}
}
return total;
}
static long binomialCoeff(long n, long k) {
long res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res = (res * (n - i));
res /= (i + 1);
}
return res;
}
static long c(long fact[], long n, long k) {
if (k > n) return 0;
long res = fact[(int) n];
res = (int) ((res * Modular_Expo(fact[(int) k], mod - 2)) % mod);
res = (int) ((res * Modular_Expo(fact[(int) n - (int) k], mod - 2)) % mod);
return res % mod;
}
public static ArrayList<Long> getFact(long x) {
ArrayList<Long> facts = new ArrayList<>();
for (long i = 2; i * i <= x; ++i) {
if (x % i == 0) {
facts.add(i);
if (i != x / i) {
facts.add(x / i);
}
}
}
return facts;
}
static void matrix_ex(long n, long[][] A, long[][] I) {
while (n > 0) {
if (n % 2 == 0) {
Multiply(A, A);
n /= 2;
} else {
Multiply(I, A);
n--;
}
}
}
static void Multiply(long[][] A, long[][] B) {
int n = A.length, m = A[0].length, p = B[0].length;
long[][] C = new long[n][p];
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < m; k++) {
C[i][j] += ((A[i][k] % mod) * (B[k][j] % mod)) % mod;
C[i][j] = C[i][j] % mod;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
A[i][j] = C[i][j];
}
}
}
public static HashMap<Character, Integer> sortMapDesc(HashMap<Character, Integer> map) {
List<Map.Entry<Character, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
HashMap<Character, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Character, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Integer, Integer> sortMapAsc(HashMap<Integer, Integer> map) {
List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue());
HashMap<Integer, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Integer, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static long lcm(long l, long l2) {
long val = CP.gcd(l, l2);
return (l * l2) / val;
}
public static int isSubsequence(String s, String t) {
int n = s.length();
int m = t.length();
if (m > n) {
return Integer.MAX_VALUE;
}
int i = 0, j = 0, skip = 0;
while (i < n && j < m) {
if (s.charAt(i) == t.charAt(j)) {
--skip;
++j;
}
++skip;
++i;
}
while (i < n) {
++i;
++skip;
}
if (j != m) {
skip = Integer.MAX_VALUE;
}
return skip;
}
public static int lcs(String s, String t) {
int n = s.length(), m = t.length();
int dp[][] = new int[n + 1][m + 1];
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= m; ++j) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[n][m];
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
public void printLine(int i) {
writer.println(i);
}
public void printLine(char c) {
writer.println(c);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
}
}
|
java
|
1301
|
E
|
E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105) — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
OutputCopy16
4
4
4
0
InputCopy6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
OutputCopy36
4
16
16
16
InputCopy8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
OutputCopy64
0
16
4
16
4
36
0
NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.
|
[
"binary search",
"data structures",
"dp",
"implementation"
] |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class E {
private static final boolean DEBUG = false;
public static void main(String[] args) {
var scanner = new BufferedScanner();
var writer = new PrintWriter(new BufferedOutputStream(System.out));
var n = scanner.nextInt();
var m = scanner.nextInt();
var q = scanner.nextInt();
// var n = 500;
// var m = 500;
// var q = 1;
var s = new int[n][m];
for (int i = 0; i < n; i++) {
var ss = scanner.next().toCharArray();
for (int j = 0; j < m; j++) {
s[i][j] = C2I.get(ss[j]);
// s[i][j] = (int) (Math.random() * 4) + 1;
}
}
var logo = new int[n][m];
var t = System.nanoTime();
prepare(n, m, s, logo);
log("prepare: %.2f", (System.nanoTime() - t) / 1e9);
for (int i = 0; i < q; i++) {
var r1 = scanner.nextInt() - 1;
var c1 = scanner.nextInt() - 1;
var r2 = scanner.nextInt() - 1;
var c2 = scanner.nextInt() - 1;
writer.println(query(n, m, s, r1, c1, r2, c2, logo));
}
scanner.close();
writer.flush();
writer.close();
}
/**
* @param logo logo[r][c], logo size with left upper corner at (r,c)
*/
private static void prepare(int n, int m, int[][] s, int[][] logo) {
var t = System.nanoTime();
colorCount = preAreaAcc(1, 4, 1, n, m, s);
log("color count: %.2f", (System.nanoTime() - t) / 1e9);
t = System.nanoTime();
// for every (r,c) at most one size of logo exists
for (int r = 0; r < n; r++) {
for (int c = 0; c < m; c++) {
if (s[r][c] == 1) {
var redSize = maxRedSize(r, c, n, m, s);
// log("redSize(%d,%d)=%d", r, c, redSize);
if (redSize == 0) {
continue;
}
if (isSquare(2, r, c + redSize, redSize, s)
&& isSquare(3, r + redSize, c, redSize, s)
&& isSquare(4, r + redSize, c + redSize, redSize, s)) {
logo[r][c] = redSize * 2;
}
}
}
}
log("logo: %.2f", (System.nanoTime() - t) / 1e9);
t = System.nanoTime();
// prepare logo count
logoCount = preAreaAcc(2, Math.min(n, m), 2, n, m, logo);
log("logo count: %.2f", (System.nanoTime() - t) / 1e9);
}
private static int maxRedSize(int r, int c, int n, int m, int[][] s) {
if (s[r][c] != 1) {
return 0;
}
var low = 1;
var high = Math.min(n - r, m - c);
var ans = 0;
while (low <= high) {
var mid = (low + high) / 2;
if (isSquare(1, r, c, mid, s)) {
ans = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return ans;
}
private static int[][][] preAreaAcc(int typeLow, int typeHigh, int typeInc, int n, int m, int[][] s) {
// var ans = new int[typeHigh + 1][n + 1][m + 1];
var ans = new int[typeHigh + 1][][];
for (var type = typeLow; type <= typeHigh; type += typeInc) {
ans[type] = new int[n + 1][m + 1];
}
for (var r = n - 1; r >= 0; r--) {
for (var type = typeLow; type <= typeHigh; type += typeInc) {
ans[type][r][m] = ans[type][r + 1][m];
}
for (var c = m - 1; c >= 0; c--) {
for (var type = typeLow; type <= typeHigh; type += typeInc) {
ans[type][r][c] = ans[type][r + 1][c]
+ ans[type][r][c + 1]
- ans[type][r + 1][c + 1];
if (type == s[r][c]) {
ans[type][r][c]++;
}
}
}
}
return ans;
}
private static void log(String fmt, Object... a) {
if (DEBUG) {
System.out.println(String.format(fmt, a));
}
}
private static int query(int n, int m, int[][] s, int r1, int c1, int r2, int c2, int[][] logo) {
// 索引区域内的logo左上角?
// 如何快速去掉不在区域内的?
// 当找到某一种尺寸的logo之后,接下来就要找更长的
// 【重要】logo往内缩一圈还是logo。
// 所以,如果一个矩形包含的最大logo边长是L,那么这个矩形也包含1..L的logo。
// 所以,可以用二分查找。
return cleverQuery(r1, c1, r2, c2);
// return bfQuery(n, m, s, r1, c1, r2, c2, logo);
}
private static int cleverQuery(int r1, int c1, int r2, int c2) {
// 这里要对半径进行二分查找,因为半径才是连续的,直径差是2。
var low = 1;
var high = Math.min(r2 - r1 + 1, c2 - c1 + 1) / 2;
var ans = 0;
while (low <= high) {
var mid = (low + high) / 2;
if (exists(mid * 2, r1, c1, r2 - mid * 2 + 1, c2 - mid * 2 + 1)) {
ans = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return ans * ans * 4;
}
static int[][][] logoCount;
private static boolean exists(int size, int r1, int c1, int r2, int c2) {
var a = logoCount[size];
var area = a[r1][c1] - a[r2 + 1][c1] - a[r1][c2 + 1] + a[r2 + 1][c2 + 1];
return area > 0;
}
private static int bfQuery(int n, int m, int[][] s, int r1, int c1, int r2, int c2, int[][] logo) {
var ans = 0;
for (var r = r1; r <= r2; r++) {
for (var c = c1; c <= c2; c++) {
if (logo[r][c] > 0 && r + logo[r][c] - 1 <= r2 && c + logo[r][c] - 1 <= c2) {
ans = Math.max(ans, logo[r][c]);
}
}
}
return ans * ans;
}
private static boolean isSquare(int color, int r, int c, int size, int[][] s) {
if (r + size - 1 >= s.length || c + size - 1 >= s[0].length) {
return false;
}
return area(color, r, c, size) == size * size;
}
static int[][][] colorCount; // areaAcc[color][r][c], [(r,c)..(n-1,m-1)]中color的个数
private static int area(int color, int r, int c, int size) {
var a = colorCount[color];
return a[r][c] - a[r + size][c] - a[r][c + size] + a[r + size][c + size];
}
static final Map<Character, Integer> C2I = Map.of('R', 1, 'G', 2, 'Y', 3, 'B', 4);
public static class BufferedScanner {
BufferedReader br;
StringTokenizer st;
public BufferedScanner(Reader reader) {
br = new BufferedReader(reader);
}
public BufferedScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b > 0) {
long tmp = b;
b = a % b;
a = tmp;
}
return a;
}
static long inverse(long a, long m) {
long[] ans = extgcd(a, m);
return ans[0] == 1 ? (ans[1] + m) % m : -1;
}
private static long[] extgcd(long a, long m) {
if (m == 0) {
return new long[]{a, 1, 0};
} else {
long[] ans = extgcd(m, a % m);
long tmp = ans[1];
ans[1] = ans[2];
ans[2] = tmp;
ans[2] -= ans[1] * (a / m);
return ans;
}
}
private static List<Integer> primes(double upperBound) {
var limit = (int) Math.sqrt(upperBound);
var isComposite = new boolean[limit + 1];
var primes = new ArrayList<Integer>();
for (int i = 2; i <= limit; i++) {
if (isComposite[i]) {
continue;
}
primes.add(i);
int j = i + i;
while (j <= limit) {
isComposite[j] = true;
j += i;
}
}
return primes;
}
}
|
java
|
1312
|
C
|
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.
|
[
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] |
////package com.company;
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=in.nextInt();
// 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);
fl:
while (testCases-- > 0) {
int n =in.nextInt();
long k =in.nextLong();
long arr[]=new long[n];
for(int i =0;i<n;i++)
arr[i]=in.nextLong();
int c[]=new int[60];
int ans[][]=new int[n][60];
for(int i =0;i<n;i++)
{
int j=0;
if(arr[i]==0)
continue ;
while(arr[i]!=0) {
c[j]+=arr[i]%k;
// System.out.println(arr[i]);
if(arr[i]%k>1)
{
System.out.println("NO");
continue fl;
}
++j;
if(arr[i]%k==1&&arr[i]!=1)
{
ans[i][j]++;
}
arr[i]/=k;
}
ans[i][j]++;
}
for(int j =0;j<60;j++)
{int sum =0;
for(int i =0;i<n;i++)
{
sum+=(ans[i][j]);
}
if(sum>1)
{
System.out.println("NO");
continue fl;
}
}
// for(int i :c)
// {
// if(i>1)
// {
// System.out.println("NO");
// continue fl;
// }
// }
System.out.println("YES");
}
out.close();
} catch (Exception e) {
return;
}
}
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
|
1296
|
B
|
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111
|
[
"math"
] |
import java.util.*;
/**
* B_Food_Buying
*/
public class B_Food_Buying {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
long n = sc.nextLong();
long ans=0 ;
while(n!=0){
if(n<10){
ans+=n;
n=0;
}else{
long a =n/10;
ans += a*10;
n %= 10;
n+=a;
}
}
System.out.println(ans);
}
}
}
|
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"
] |
// package TreeQueries;
import java.util.*;
import java.io.*;
public class addEdge {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws java.lang.Exception {
FastReader sc = new FastReader();
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
int t = 1;
// t = sc.nextInt();
while (t-- != 0) {
int n = sc.nextInt();
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i <= n; i++)
adj.add(new ArrayList<Integer>());
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
adj.get(u).add(v);
adj.get(v).add(u);
}
int level[] = new int[n + 1];
int limit = (int) (Math.log(n) / Math.log(2));
int parent[][] = new int[n + 1][limit + 1];
dfs(1, 0, 0, adj, level, parent);
for (int i = 1; i <= limit; i++) {
for (int j = 1; j <= n; j++) {
int x = parent[j][i - 1];
parent[j][i] = parent[x][i - 1];
}
}
int q = sc.nextInt();
for (int i = 0; i < q; i++) {
int k = 5;
int qur[] = new int[k];
for (int j = 0; j < k; j++) {
qur[j] = sc.nextInt();
}
int withoutedge = getDist(qur[2], qur[3], parent, level);
int d2 = getDist(qur[2], qur[0], parent, level) + 1 + getDist(qur[1], qur[3], parent, level);
int d3 = getDist(qur[3], qur[0], parent, level) + 1 + getDist(qur[1], qur[2], parent, level);
// System.out.println`(withoutedge + " " + d2 + " " + d3);
int withedge = Math.min(d2, d3);
int ans = Integer.MAX_VALUE;
if (withedge % 2 == qur[4] % 2) {
ans = withedge;
}
if (withoutedge % 2 == qur[4] % 2) {
ans = Math.min(ans, withoutedge);
}
if (ans <= qur[4]) {
w.write("YES\n");
} else {
w.write("NO\n");
}
// int a=sc.nextInt();
// int b=sc.nextInt();
// System.out.println(getDist(a, b, parent, level));
// w.write(ans+"\n");
}
w.flush();
}
w.close();
}
private static int getDist(int a, int b, int[][] parent, int[] level) {
if (level[a] > level[b]) {
int temp = a;
a = b;
b = temp;
}
int diff = level[b] - level[a];
int ans = 0;
while (diff > 0) {
int log = (int) (Math.log(diff) / Math.log(2));
b = parent[b][log];
diff -= (1 << log);
ans += (1 << log);
}
if(a==b)return ans;
for(int i=parent[0].length-1;i>=0;i--){
if(parent[b][i] != parent[a][i]){
a = parent[a][i];
b = parent[b][i];
ans += (1 << (i + 1));
}
}
return ans+2;
}
private static void dfs(int i, int p, int l, ArrayList<ArrayList<Integer>> adj, int[] level, int[][] parent) {
parent[i][0] = p;
level[i] = l;
for (int nbr : adj.get(i)) {
if (nbr == p)
continue;
dfs(nbr, i, l + 1, adj, level, parent);
}
}
}
|
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"
] |
//package javaapplication3;
import java.util.Scanner;
public class JavaApplication3 {
static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
int t = scan.nextInt();
for(int i=0;i<t;i++){
long a = scan.nextLong();
long b = scan.nextLong();
System.out.println(a * numOf9(b));
}
}
static int numOf9(long i){
int num = String.valueOf(i).length();
if(i < Math.pow(10,num)-1){
num--;
}
return num;
}
}
|
java
|
1292
|
B
|
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
|
[
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] |
import java.util.*;
import 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();
static PrintWriter out=new PrintWriter(System.out);
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{
long x; long y;
int count;
Pair(long x , long y , int count){
this.x = x;
this.y = y;
this.count = count;
}
public String toString() {
return "{"+x+","+y+"}";
}
}
static void TEST_CASE() throws IOException {
long x0 = sc.nextLong() , y0 = sc.nextLong();
long ax = sc.nextLong() , ay = sc.nextLong();
long bx = sc.nextLong() , by = sc.nextLong();
long xs = sc.nextLong() , ys = sc.nextLong() , t = sc.nextLong();
ArrayList<Pair> al = new ArrayList<>();
al.add(new Pair(x0, y0, 1));
int c = 2;
while(x0<3e16 && y0<3e16) {
long nx = ax*x0 + bx;
long ny = ay*y0 + by;
al.add(new Pair(nx, ny, c));
c++;
x0 = nx; y0 = ny;
}
long ans = 0;
// System.out.println(al);
for(int i = 0 ; i<al.size(); i++) {
long mx = xs , my = ys , time = t;
long count = 0 ;
for(int j = i ; j<al.size() ; j++) {
Pair pp = al.get(j);
long tc = Math.abs(pp.x - mx) + Math.abs(pp.y - my);
// System.out.println(Math.abs(pp.x - mx) +" "+pp.x +" "+pp.y);
if(tc>time) break;
time -= tc;
count ++;
mx = pp.x;
my = pp.y;
}
// System.out.println(i +" "+count);
ans = max(ans , count);
mx = xs ; my = ys ; time = t;
count = 0 ;
for(int j = i ; j>=0 ; j--) {
Pair pp = al.get(j);
long tc = Math.abs(pp.x - mx) + Math.abs(pp.y - my);
if(tc>time) break;
time -= tc;
count ++;
mx = pp.x;
my = pp.y;
}
// System.out.println(i+" "+count);
ans = max(ans , count);
}
System.out.println(ans);
}
}
/*******************************************************************************************************************************************************/
/**
*/
|
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;
import java.io.*;
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 {
int n = sc.nextInt();
int[] q = new int[n - 1];
int upper = 0, qSum = 0;
for (int i = 0; i < n - 1; i++) {
q[i] = sc.nextInt();
qSum += q[i];
if (qSum > 0)
upper++;
}
int[] p = new int[n];
int[] sorted = new int[n];
p[0] = n - upper;
try {
sorted[p[0] - 1] = p[0];
for (int i = 1; i < n; i++) {
p[i] = p[i - 1] + q[i - 1];
if (sorted[p[i] - 1] != 0) {
throw new Exception();
}
sorted[p[i] - 1] = p[i];
}
} catch (Exception e) {
System.out.println(-1);
return;
}
for (int i = 0; i < n; i++) {
System.out.print(p[i] + " ");
}
}
public static int mod = (int) 1e9 + 7;
// private static int mod = 998244353;
public static int inf_int = (int) 2e9 ;
public static long inf_long = (long) 2e15;
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);
}
/*-------------------------------------------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
|
1141
|
F1
|
F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
|
[
"greedy"
] |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Main {
private static int getTotal(int sum , int n) {
int ans = 0 , s = 0;
Set<Integer> set = new HashSet<>();
set.add(0);
for (int i = 1;i <= n;i ++) {
s += a[i];
int need = s - sum;
if (set.contains(need)) {
set.clear();
set.add(s);
ans ++;
} else {
set.add(s);
}
}
return ans;
}
private static void solve(int sum , int n) {
Map<Integer , Integer> map = new HashMap<>();
int i , s = 0;
List<int[]> list = new ArrayList<>();
map.put(0 , 0);
for (i = 1;i <= n;i ++) {
s += a[i];
int need = s - sum;
if (map.containsKey(need)) {
list.add(new int[] {map.get(need) + 1 , i});
map.clear();
map.put(s , i);
} else {
map.put(s , i);
}
}
System.out.println(list.size());
for (int[] result : list) {
System.out.println(result[0] + " " + result[1]);
}
}
private static int[] a = new int[2000];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i , j , n = scan.nextInt() , max = 0 , s = 0;
Set<Integer> set = new HashSet<>();
for (i = 1;i <= n;i ++) {
a[i] = scan.nextInt();
}
for (i = 1;i <= n;i ++) {
int sum = 0;
for (j = i;j <= n;j ++) {
sum += a[j];
set.add(sum);
}
}
for (int sum : set) {
int total = getTotal(sum , n);
if (total > max) {
max = total;
s = sum;
}
}
solve(s , n);
}
}
|
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"
] |
/*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = sc.nextInt();
for (int t = 0; t < test; t++) {
solve();
}
out.close();
}
private static void solve() {
int busTicket = sc.nextInt();
int tramTicket = sc.nextInt();
int roublesLeft = sc.nextInt();
char[] crossroad = sc.next().toCharArray();
int n = crossroad.length;
// min walk index, after which we can reach home using public transports and paying roubles we have
int minWalkIndex = getMinWalk(crossroad, n, busTicket, tramTicket, roublesLeft);
out.println(minWalkIndex + 1);
}
private static int getMinWalk(char[] crossroad, int n, int busTicket, int tramTicket, int roublesLeft) {
int lo = 0, hi = n - 1;
while (lo < hi) {
int mid = (lo + hi) >> 1;
if (canReachHome(crossroad, n, busTicket, tramTicket, roublesLeft, mid)) {
hi = mid;
}else {
lo = mid + 1;
}
}
return lo;
}
private static boolean canReachHome(char[] crossroad, int n, int busTicket, int tramTicket, int roublesLeft, int index) {
long costToReachHome = 0;
boolean atBusStation = (crossroad[index] == 'A');
index++;
while (index < n) {
if (crossroad[index] == 'A') { // at bus station
if (!atBusStation) {
// from tram to bus station
costToReachHome += tramTicket;
atBusStation = true;
}
}else {
// at tram station
if (atBusStation) {
// from bus to tram station
costToReachHome += busTicket;
atBusStation = false;
}
}
index++;
}
index--;
costToReachHome += (crossroad[index] == crossroad[index - 1]) ? (crossroad[index] == 'A' ? busTicket : tramTicket) : 0;
return costToReachHome <= roublesLeft;
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException end)
{
end.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException end)
{
end.printStackTrace();
}
return str;
}
}
}
|
java
|
1311
|
E
|
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example:
|
[
"brute force",
"constructive algorithms",
"trees"
] |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jaynil
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
EConstructTheBinaryTree solver = new EConstructTheBinaryTree();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class EConstructTheBinaryTree {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int d = in.nextInt();
int tot = (n * (n - 1)) / 2;
PriorityQueue<int[]> highest = new PriorityQueue<>((x, y) -> x[1] - y[1]);
PriorityQueue<int[]> lowest = new PriorityQueue<>((x, y) -> y[1] - x[1]);
if (d > tot) {
out.println("NO");
return;
}
//p d c
int a[][] = new int[n][4];
for (int i = 0; i < n; i++) {
a[i][0] = i - 1;
a[i][1] = i;
a[i][2] = 1;
a[i][3] = i;
highest.add(a[i]);
lowest.add(a[i]);
}
a[n - 1][2] = 0;
while (highest.size() > 0 && lowest.size() > 0 && tot - d > 0) {
int[] h = highest.poll();
if (h[2] == 2) continue;
int[] l = lowest.poll();
if (l[2] > 0) {
highest.add(h);
continue;
}
if (tot - l[1] + 1 + h[1] >= d) {
tot = tot - l[1] + 1 + h[1];
h[2]++;
a[l[0]][2]--;
l[1] = h[1] + 1;
l[0] = h[3];
highest.add(l);
highest.add(h);
} else {
lowest.add(l);
}
}
if (tot == d) {
out.println("YES");
for (int i = 1; i < n; i++) {
out.print((a[i][0] + 1) + " ");
}
out.println();
} else {
out.println("NO");
// out.println(tot);
// out.println(highest.size());
// out.println(lowest.size());
// for(int i=1;i<n;i++){
// out.print((a[i][0]+1) + " ");
// }
out.println();
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
java
|
1300
|
A
|
A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4.
|
[
"implementation",
"math"
] |
import java.util.*;
public class MyClass {
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int t = kb.nextInt();
while(t-- > 0)
{
int n = kb.nextInt();
int sum=0;
int zero=0;
for(int i=0;i<n;i++)
{
int a = kb.nextInt();
sum+=a;
if(a == 0)
{
zero++;
}
}
sum+=zero;
if(sum == 0)
{
zero++;
}
System.out.println(zero);
}
}
}
|
java
|
1286
|
A
|
A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.
|
[
"dp",
"greedy",
"sortings"
] |
// Problem: A. Garland
// Contest: Codeforces - Codeforces Round #612 (Div. 1)
// URL: https://codeforces.com/problemset/problem/1286/A
// Memory Limit: 256 MB
// Time Limit: 1000 ms
import java.util.*;
import java.io.*;
public class Main {
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
static int dx[]={0,0,-1,1},dy[]={-1,1,0,0};
static final double pi=3.1415926536;
static long mod=1000000007;
// static long mod=998244353;
static int MAX=Integer.MAX_VALUE;
static int MIN=Integer.MIN_VALUE;
static long MAXL=Long.MAX_VALUE;
static long MINL=Long.MIN_VALUE;
static ArrayList<Integer> graph[];
static long fact[];
static long seg[];
// static int dp[][];
static long dp[][];
public static void main (String[] args) throws java.lang.Exception {
// code goes here
var n = I();
var inf = 0x3f3f3f3f;
int[][] dp = new int[n / 2 + 1][2];
for(int j = 1; j <= n / 2; j++){
dp[j][0] = inf;
dp[j][1] = inf;
}
var v = 0;
for(int i = 1; i <= n; i++){
v = I();
for(int j = n / 2; j >= 0; j--){
if(v == 0 || v % 2 == 1){
dp[j][1] = Math.min(dp[j][0] + 1, dp[j][1]);
}else{
dp[j][1] = inf;
}
if(j > 0 && v % 2 == 0){
dp[j][0] = Math.min(dp[j - 1][0], dp[j - 1][1] + 1);
}else{
dp[j][0] = inf;
}
}
}
out.println(Math.min(dp[n / 2][0], dp[n / 2][1]));
out.close();
}
static class Pair implements Comparable<Pair> {
int x, y, idx;
public Pair(int x, int y, int idx) {
this.x = x;
this.y = y;
this.idx = idx;
}
@Override
public boolean equals(Object o) {
Pair pair = (Pair) o;
return x == pair.x && y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public int compareTo(Pair o) {
return x == o.x ? y - o.y : (x - o.x);
}
}
public static int[] I(int n, int s){int a[]=new int[n + s];for(int i=s;i<n + s;i++){a[i]=I();}return a;}
public static long[] IL(int n, int s){long a[]=new long[n + s];for(int i=s;i<n + s;i++){a[i]=L();}return a;}
public static int I(){return sc.I();}
public static long L(){return sc.L();}
public static String S(){return sc.S();}
public static double D(){return sc.D();}
}
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 I(){ return Integer.parseInt(next());}
long L(){ return Long.parseLong(next());}
double D(){return Double.parseDouble(next());}
String S(){
String str = "";
try {
str = br.readLine();
}
catch (IOException e){
e.printStackTrace();
}
return str;
}
}
|
java
|
1316
|
D
|
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters — UU, DD, LL, RR or XX — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103) — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :
|
[
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] |
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static class tuple{
int a, b;
long c;
public tuple(int a, int b, long c) {this.a = a;this.b = b;this.c = c;}
}
static class Pair implements Comparable<Pair>{
int a;
int b;
// int ind;
// public Pair(int x, long y) {a = x;b=y;}
public Pair(int x, int y) {a = x;b=y;}
// public Pair(int x,int y, int z){a=x;b=y;ind = z;}
public int compareTo(Pair p){
return p.a - a;
}
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + a;
// result = prime * result + b;
//
// return result;
// }
// @Override
// public boolean equals(Object obj) {
// Pair cur = (Pair)obj;
// if((a==cur.a && b==cur.b))return true;
// return false;
// }
}
static class cell{
int a, b;
public cell(int x, int y) {
a = x;
b = y;
}
}
static class TrieNode{
TrieNode left, right;
int cnt;
public TrieNode() {
cnt = 0;
}
}
public static int gcd(int a,int b)
{
if(a<b)
return gcd(b,a);
if(b==0)
return a;
return gcd(b,a%b);
}
static int lcm(int a,int b) {
return a*b / (int)gcd(a,b);
}
public static void main(String[] args) throws Exception {
new Thread(null, null, "Anshum Gupta", 99999999) {
public void run() {
try {
solve();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static long pow(long x,long y){
if(y == 0)return 1;
if(y==1)return x;
long a = pow(x,y/2);
a = (a*a)%mod;
if(y%2==0){
return a;
}
return (a*x)%mod;
}
static final long mxx = (long)(1e18+5);
static final int mxN = (int)(1e5 + 5);
static final int mxV = (int)(2e5);
static final long mod = (long)(1e9+7); //998244353;//
static long[]fact,inv_fact;
static long my_inv(long a) {
return pow(a,mod-2);
}
static long bin(int a,int b) {
if(a < b || a<0 || b<0)return 0;
return ((fact[a]*inv_fact[a-b])%mod * inv_fact[b])%mod;
}
static void make_facts() {
fact=new long[mxN];
inv_fact = new long[mxN];
fact[0]=inv_fact[0]=1L;
for(int i=1;i<mxN;i++) {
fact[i] = (i*fact[i-1])%mod;
inv_fact[i] = my_inv(fact[i]);
}
}
static void lazy(int st, int e, int tn) {
if(lazy[tn] != INF) {
tree[tn] = Math.min(tree[tn], lazy[tn]);
if(st != e) {
lazy[2*tn] = Math.min(lazy[2*tn], lazy[tn]);
lazy[2*tn+1] = Math.min(lazy[2*tn+1], lazy[tn]);
}
lazy[tn] = INF;
}
}
static void update(int ind, int val, int st, int e, int tn) {
if(st == e) {
tree[tn] = val;
return;
}
int mid = (st + e) >> 1;
if(ind <= mid)
update(ind, val, st, mid, 2*tn);
else
update(ind, val, mid+1, e, 2*tn+1);
tree[tn] = Math.min(tree[2*tn], tree[2*tn+1]);
}
static int query(int l, int r, int st, int e, int tn) {
if(st > r || e < l)return INF;
if(st >= l && e <= r) {
return tree[tn];
}
int mid = (st + e) >> 1;
int x = query(l, r, st, mid, 2 * tn);
int y = query(l, r, mid+1, e, 2 * tn + 1);
return Math.min(x, y);
}
static int[]tree, lazy;
static final int INF = (int)1e9+5;
static ArrayList<ArrayList<Pair>> adj;
static boolean[]vis;
static int n;
static char[][]res;
static Pair[][]arr;
static final int[]dx = {-1, 1, 0, 0}, dy = {0, 0, -1, 1};
static final char[]d = {'U', 'D', 'L', 'R'};
static void dfs(int x, int y) {
for(int i=0; i<4; i++) {
int x1 = x + dx[i];
int y1 = y + dy[i];
if(x1 < 0 || y1 < 0 || x1 >= n || y1 >= n)continue;
if(arr[x1][y1].a != arr[x][y].a || arr[x1][y1].b != arr[x][y].b)continue;
if(res[x1][y1] != '\0')continue;
res[x1][y1] = d[i ^ 1];
dfs(x1, y1);
}
}
public static void solve() throws Exception {
// solve the problem here
MyScanner s = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), true);
int tc = 1;//s.nextInt();
// make_facts();
while(tc-->0){
n = s.nextInt();
res = new char[n][n];
arr = new Pair[n][n];
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
int x = s.nextInt();
int y = s.nextInt();
x--;y--;
arr[i][j] = new Pair(x, y);
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(arr[i][j].a == i && arr[i][j].b == j) {
// out.println("i = " + i + " j = " + j);
res[i][j] = 'X';
dfs(i, j);
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(arr[i][j].a != -2)continue;
for(int k=0; k<4; k++) {
int x1 = i + dx[k];
int y1 = j + dy[k];
if(x1 < 0 || y1 < 0 || x1 >= n || y1 >= n)continue;
if(arr[x1][y1].a == -2 && arr[x1][y1].b == -2) {
res[i][j] = d[k];
}
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(res[i][j] == '\0') {
out.println("INVALID");
return;
}
}
}
out.println("VALID");
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
out.print(res[i][j]);
}out.println();
}
}
out.flush();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
|
java
|
1305
|
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.*;
public class D {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws IOException {
readInput();
//out.close();
}
static int n;
static List<Integer>[] adj;
static boolean[] bad;
static int dist;
static int maxNode;
static void dfs(int i, int p, int d) {
if (bad[i]) return;
if (d > dist) {
dist = d;
maxNode = i;
}
for (int x: adj[i]) {
if (x == p) continue;
dfs(x,i,d+1);
}
}
static void mark(int i, int p, int t) {
if (bad[i]) return;
if (i == t) return;
//System.out.println("Marking " + i + " Target " + t);
bad[i] = true;
for (int x: adj[i]) {
if (p ==x) continue;
mark(x,i,t);
}
}
public static void readInput() throws IOException {
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
// Idea: Get diameter of tree, query LCA. If LCA is either one of the nodes, immidiately exit.
// Else, mark every node on the path to LCA as bad or someth. Continue;
n = Integer.parseInt(br.readLine());
adj = new List[n+1];
bad = new boolean[n+1];
for (int i= 0 ; i <= n; i++) adj[i] = new ArrayList<Integer>();
for (int i = 0; i < n-1; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
adj[x].add(y);
adj[y].add(x);
}
int prev = 1;
while (true) {
dist = 0;
maxNode = prev;
dfs(prev,prev,0);
int u = maxNode;
dist = 0;
maxNode = u;
dfs(u,u,0);
int v = maxNode;
if (u == v) {
System.out.println("! " + v);
System.out.flush();
break;
}
System.out.println("? " + u + " " + v);
System.out.flush();
int lca = Integer.parseInt(br.readLine());
if (lca == -1) System.exit(0);
else if (lca == u || lca == v) {
System.out.println("! " + lca);
System.out.flush();
break;
}
mark(u,u,lca);
mark(v,v,lca);
prev = lca;
}
}
}
|
java
|
1141
|
A
|
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.
|
[
"implementation",
"math"
] |
import java.util.*;
import java.io.*;
import java.rmi.ConnectIOException;
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 n,m;
FastReader f=new FastReader();
n=f.nextInt();
m=f.nextInt();
int cnt=0;
if(m%n!=0){
System.out.println(-1);
return;
}
int d=m/n;
while(d%2==0){
d/=2;
cnt++;
}
while(d%3==0){
d/=3;
cnt++;
}
if(d==1)
System.out.println(cnt);
else
System.out.println(-1);
}
}
|
java
|
1305
|
C
|
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
|
[
"brute force",
"combinatorics",
"math",
"number theory"
] |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
public static void main(String[] args) {
new Main().solve(new InputReader(System.in), new PrintWriter(System.out));
}
private void solve(InputReader in, PrintWriter pw) {
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
if (n > m) {
// (a*b*c)%m=a%m*b%m*c%m
// (a-b)%m=a%m-b%m
pw.println(0);
} else {
long ans = 1;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
ans = (ans * abs(a[i] - a[j])) % m;
}
}
pw.println(ans);
}
pw.close();
}
}
class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String str;
try {
str = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return str;
}
public boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String nextLine = null;
try {
nextLine = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (nextLine == null)
return false;
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
|
java
|
1325
|
C
|
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample:
|
[
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] |
import java.io.*;
import java.util.*;
public class Ehab_and_Path_etic_MEXs {
static FastScanner fs;
static FastWriter fw;
static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null;
private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}};
private static final int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
private static final int iMax = (int) (1e9 + 100), iMin = (int) (-1e9 - 100);
private static final long lMax = (long) (1e18 + 100), lMin = (long) (-1e18 - 100);
private static final int mod1 = (int) (1e9 + 7);
private static final int mod2 = 998244353;
public static void main(String[] args) throws IOException {
fs = new FastScanner();
fw = new FastWriter();
int t = 1;
//t = fs.nextInt();
while (t-- > 0) {
solve();
}
fw.out.close();
}
private static void solve() {
int n = fs.nextInt();
int[][] edges = new int[n - 1][2];
int[] inorder = new int[n + 5];
for (int i = 0; i < n - 1; i++) {
int a = fs.nextInt(), b = fs.nextInt();
inorder[a]++; inorder[b]++;
edges[i] = new int[]{a, b};
}
int curr = 0;
int[] ans = new int[n - 1];
Arrays.fill(ans, -1);
for (int i = 0; i < n - 1; i++) {
int a = edges[i][0], b = edges[i][1];
if (inorder[a] == 1 || inorder[b] == 1) {
ans[i] = curr++;
}
}
for (int i = 0; i < n - 1; i++) {
if (ans[i] == -1) ans[i] = curr++;
}
for (int i = 0; i < n - 1; i++) fw.out.println(ans[i]);
}
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 long gcd(long a, long b) {
return (b == 0 ? a : gcd(b, a % b));
}
private static long lcm(long a, long b) {
return ((a * b) / gcd(a, b));
}
private static long pow(long a, long b, int mod) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long ceilDiv(long a, long b) {
return ((a + b - 1) / b);
}
private static long getMin(long... args) {
long min = lMax;
for (long arg : args)
min = Math.min(min, arg);
return min;
}
private static long getMax(long... args) {
long max = lMin;
for (long arg : args)
max = Math.max(max, arg);
return max;
}
private static boolean isPalindrome(String s, int l, int r) {
int i = l, j = r;
while (j - i >= 1) {
if (s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
private static List<Integer> primes(int n) {
boolean[] primeArr = new boolean[n + 5];
Arrays.fill(primeArr, true);
for (int i = 2; (i * i) <= n; i++) {
if (primeArr[i]) {
for (int j = i * i; j <= n; j += i) {
primeArr[j] = false;
}
}
}
List<Integer> primeList = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (primeArr[i])
primeList.add(i);
}
return primeList;
}
private static int noOfSetBits(long x) {
int cnt = 0;
while (x != 0) {
x = x & (x - 1);
cnt++;
}
return cnt;
}
private static 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
|
1304
|
C
|
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
|
[
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.StringTokenizer;
public class AirConditioner {
static BufferedReader br;
static PrintWriter pw;
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();
pw.close();
}
static void test() throws Exception {
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int temp = Integer.parseInt(st.nextToken());
ArrayList<Customer> c = new ArrayList<>();
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
int t = Integer.parseInt(st.nextToken());
int l = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
c.add(new Customer(t, l, r));
}
c.sort(Comparator.comparingInt(o -> o.t));
long t = 0, l = temp, r = temp;
for (int i = 0; i < n; i++) {
long time = c.get(i).t - t;
Customer curr = c.get(i);
if (r + time >= curr.l && l - time <= curr.r) {
r = Math.min(r + time, curr.r);
l = Math.max(l - time, curr.l);
} else {
System.out.println("NO");
return;
}
t = curr.t;
}
System.out.println("YES");
}
static class Customer {
public int t, l, r;
public Customer(int t, int l, int r) {
this.t = t;
this.l = l;
this.r = r;
}
}
}
|
java
|
1284
|
C
|
C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.
|
[
"combinatorics",
"math"
] |
import java.io.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);
CNewYearAndPermutation solver = new CNewYearAndPermutation();
solver.solve(1, in, out);
out.close();
}
static class CNewYearAndPermutation {
int mod = 1000000007;
long[] fact = new long[2_000_001];
long[] invfact = new long[2_000_001];
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt();
mod = m;
precompFacts();
long ans = 0;
for (int i = 1; i <= n; i++) {
long c = n - i + 1;
long f = fact[i];
long rem = fact[n - i + 1];
ans = add(ans, mul(c, mul(f, rem)));
}
out.println(ans);
}
long add(long a, long b) {
return (a + b) % mod;
}
long mul(long a, long b) {
return (a * b) % mod;
}
long exp(long base, long exp) {
if (exp == 0) return 1;
long half = exp(base, exp / 2);
if (exp % 2 == 0) return mul(half, half);
return mul(half, mul(half, base));
}
void precompFacts() {
fact[0] = invfact[0] = 1;
for (int i = 1; i < fact.length; i++) fact[i] = mul(fact[i - 1], i);
invfact[fact.length - 1] = exp(fact[fact.length - 1], mod - 2);
for (int i = invfact.length - 2; i >= 0; i--)
invfact[i] = mul(invfact[i + 1], i + 1);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long 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
|
1310
|
A
|
A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.
|
[
"data structures",
"greedy",
"sortings"
] |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.AbstractCollection;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Comparator;
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);
ARecommendations solver = new ARecommendations();
solver.solve(1, in, out);
out.close();
}
static class ARecommendations {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
P[] a = new P[n];
for (int i = 0; i < n; i++) {
a[i] = new P(in.nextInt(), -1);
}
for (int i = 0; i < n; i++) {
a[i].t = in.nextInt();
}
Arrays.sort(a, Comparator.comparingInt(x -> x.v));
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((x, y) -> y - x);
long sum = 0;
long res = 0;
int cur = -1;
for (int i = 0; i < n || !priorityQueue.isEmpty(); ) {
if (priorityQueue.isEmpty()) {
cur = a[i].v;
}
while (i < n && a[i].v == cur) {
priorityQueue.add(a[i].t);
sum += a[i].t;
i++;
}
sum -= priorityQueue.poll();
res += sum;
cur++;
}
out.println(res);
}
class P {
int v;
int t;
public P(int v, int t) {
this.v = v;
this.t = t;
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
java
|
1294
|
F
|
F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.Vector;
public class Main {
static int mod = (int) (1e9) + 7;
/* ======================DSU===================== */
static class dsu {
static int parent[], n;// min[],value[];
static long size[];
dsu(int n) {
parent = new int[n + 1];
size = new long[n + 1];
// min=new int[n+1];
// value=new int[n+1];
Main.dsu.n = n;
makeSet();
}
static void makeSet() {
for (int i = 1; i <= n; i++) {
parent[i] = i;
size[i] = 1;
// min[i]=i;
}
}
static int find(int a) {
if (parent[a] == a)
return a;
else {
return parent[a] = find(parent[a]);// Path Compression
}
}
static void union(int a, int b) {
int setA = find(a);
int setB = find(b);
if (setA == setB)
return;
if (size[setA] >= size[setB]) {
parent[setB] = setA;
size[setA] += size[setB];
} else {
parent[setA] = setB;
size[setB] += size[setA];
}
}
}
/* ======================================================== */
static class Pair<X extends Number, Y extends Number> implements Comparator<Pair> {
X x;
Y y;
// Constructor
public Pair(X x, Y y) {
this.x = x;
this.y = y;
}
public Pair() {
}
@Override
public int compare(Main.Pair o1, Main.Pair o2) {
return ((int) (o1.y.intValue() - o2.y.intValue()));// Ascending Order based on 'y'
}
}
/* ===============================Tries================================= */
static class TrieNode {
private HashMap<Character, TrieNode> children = new HashMap<>();
public int size;
boolean endOfWord;
public void putChildIfAbsent(char ch) {
children.putIfAbsent(ch, new TrieNode());
}
public TrieNode getChild(char ch) {
return children.get(ch);
}
}
static private TrieNode root;
public static void insert(String str) {
TrieNode curr = root;
for (char ch : str.toCharArray()) {
curr.putChildIfAbsent(ch);
curr = curr.getChild(ch);
curr.size++;
}
// mark the current nodes endOfWord as true
curr.endOfWord = true;
}
public static int search(String word) {
TrieNode curr = root;
for (char ch : word.toCharArray()) {
curr = curr.getChild(ch);
if (curr == null) {
return 0;
}
}
// size contains words starting with prefix- word
return curr.size;
}
public boolean delete(TrieNode current, String word, int index) {
if (index == word.length()) {
// when end of word is reached only delete if currrent.endOfWord is true.
if (!current.endOfWord) {
return false;
}
current.endOfWord = false;
// if current has no other mapping then return true
return current.children.size() == 0;
}
char ch = word.charAt(index);
TrieNode node = current.children.get(ch);
if (node == null) {
return false;
}
boolean shouldDeleteCurrentNode = delete(node, word, index + 1);
// if true is returned then delete the mapping of character and trienode
// reference from map.
if (shouldDeleteCurrentNode) {
current.children.remove(ch);
// return true if no mappings are left in the map.
return current.children.size() == 0;
}
return false;
}
/* ================================================================= */
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (long i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static Pair<Integer, Integer> lowerBound(long[] a, long x) { // x is the target, returns lowerBound. If not found
// return -1
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] == x) {
return new Pair<>(m, 1);
}
if (a[m] >= x)
r = m;
else
l = m;
}
return new Pair<>(r, 0);
}
static Pair<Integer, Integer> upperBound(long[] a, long x) {// x is the target, returns upperBound. If not found
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] == x) {
return new Pair<>(m, 1);
}
if (a[m] <= x)
l = m;
else
r = m;
}
return new Pair<>(l + 1, 0);
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long power(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y >>= 1;
x = (x * x);
}
return res;
}
public double binPow(double x, int n) {// binary exponentiation with negative power as well
if (n == 0)
return 1.0;
double binPow = binPow(x, n / 2);
if (n % 2 == 0) {
return binPow * binPow;
} else {
return n > 0 ? (binPow * binPow * x) : (binPow * binPow / x);
}
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
/*
* ===========Modular Operations==================
*/
static long modPower(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long modInverse(long n, long p) {
return modPower(n, p - 2, p);
}
static long modAdd(long a, long b) {
return ((a + b + mod) % mod);
}
static long modMul(long a, long b) {
return ((a % mod) * (b % mod)) % mod;
}
static long[] fac = new long[200000 + 5];
static long[] invFac = new long[200000 + 5];
static long nCrModPFermat(int n, int r) {
if (r == 0)
return 1;
// return (fac[n] * modInverse(fac[r], mod) % mod * modInverse(fac[n - r], mod)
// % mod) % mod;
return (fac[n] * invFac[r] % mod * invFac[n - r] % mod) % mod;
}
/*
* ===============================================
*/
static void ruffleSort(long[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
long temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
int temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
static boolean isVowel(char ch) {
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}
static String binString32(int n) {
StringBuilder str = new StringBuilder("");
String bin = Integer.toBinaryString(n);
if (bin.length() != 32) {
for (int k = 0; k < 32 - bin.length(); k++) {
str.append("0");
}
str.append(bin);
}
return str.toString();
}
static class sparseTable {
public static int st[][];
public static int log = 4;
static int func(int a, int b) {// make func as per question(here min range query)
return (int) gcd(a, b);
}
void makeTable(int n, int a[]) {
st = new int[n][log];
for (int i = 0; i < n; i++) {
st[i][0] = a[i];
}
for (int j = 1; j < log; j++) {
for (int i = 0; i + (1 << j) <= n; i++) {
st[i][j] = func(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
}
}
}
static int query(int l, int r) {
int length = r - l + 1;
int k = 0;
while ((1 << (k + 1)) <= length) {
k++;
}
return func(st[l][k], st[r - (1 << k) + 1][k]);
}
static void printTable(int n) {
for (int j = 0; j < log; j++) {
for (int i = 0; i < n; i++) {
System.out.print(st[i][j] + " ");
}
System.out.println();
}
}
}
/*
* ====================================Main=================================
*/
// static int st[], a[];
// static void buildTree(int treeIndex, int lo, int hi) {
// if (hi == lo) {
// st[treeIndex] = a[lo];
// return;
// }
// int mid = (lo + hi) / 2;
// buildTree(treeIndex * 2 + 1, lo, mid);
// buildTree(treeIndex * 2 + 2, mid + 1, hi);
// st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);
// }
// static void update(int treeIndex, int lo, int hi, int arrIndex, int val) {
// if (hi == lo) {
// st[treeIndex] = val;
// a[arrIndex] = val;
// return;
// }
// int mid = (hi + lo) / 2;
// if (mid < arrIndex) {
// update(treeIndex * 2 + 2, mid + 1, hi, arrIndex, val);
// } else {
// update(treeIndex * 2 + 1, lo, mid, arrIndex, val);
// }
// st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);
// }
// static int query(int treeIndex, int lo, int hi, int l, int r) {
// if (l <= lo && r >= hi) {
// return st[treeIndex];
// }
// if (l > hi || r < lo) {
// return 0;
// }
// int mid = (hi + lo) / 2;
// return query(treeIndex * 2 + 1, lo, mid, l, Math.min(mid, r));
// }
// static int merge(int a, int b) {
// return a + b;
// }
public static long findKthPositive(long[] A, long k) {
int l = 0, r = A.length, m;
while (l < r) {
m = (l + r) / 2;
if (A[m] - 1 - m < k)
l = m + 1;
else
r = m;
}
return l + k;
}
static int[] z_function(char ar[]) {
int[] z = new int[ar.length];
z[0] = ar.length;
int l = 0;
int r = 0;
for (int i = 1; i < ar.length; i++) {
if (r < i) {
l = i;
r = i;
while (r < ar.length && ar[r - l] == ar[r])
r++;
z[i] = r - l;
r--;
} else {
int k = i - l;
if (z[k] < r - i + 1) {
z[i] = z[k];
} else {
l = i;
while (r < ar.length && ar[r - l] == ar[r])
r++;
z[i] = r - l;
r--;
}
}
}
return z;
}
static void mergeSort(int a[]) {
int n = a.length;
if (n >= 2) {
int mid = n / 2;
int left[] = new int[mid];
int right[] = new int[n - mid];
for (int i = 0; i < mid; i++) {
left[i] = a[i];
}
for (int i = mid; i < n; i++) {
right[i - mid] = a[i];
}
mergeSort(left);
mergeSort(right);
mergeSortedArray(left, right, a);
}
}
static void mergeSortedArray(int left[], int right[], int a[]) {
int i = 0, j = 0, k = 0, n = left.length, m = right.length;
while (i != n && j != m) {
if (left[i] < right[j]) {
a[k++] = left[i++];
} else {
a[k++] = right[j++];
}
}
while (i != n) {
a[k++] = left[i++];
}
while (j != m) {
a[k++] = right[j++];
}
}
// BINARY SEARCH
// count of set bits in a particular position
// suffix max array/ suffix sum array/ prefix
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[] intArr(int n) {
int res[] = new int[n];
for (int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
long[] longArr(int n) {
long res[] = new long[n];
for (int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
}
static FastReader f = new FastReader();
static BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
static ArrayList<ArrayList<Integer>> g = new ArrayList<>();
static HashSet<Integer> set = new HashSet<>();
static int maxLevel = 0, farthestNode = -1;
public static void main(String args[]) throws Exception {
int t = 1;
// t = f.nextInt();
int tc = 1;
// fac[0] = 1;
// for (int i = 1; i <= 200000; i++) {
// fac[i] = fac[i - 1] * i % mod;
// invFac[i] = modInverse(fac[i], mod);
// }
while (t-- != 0) {
int n = f.nextInt();
for (int i = 0; i <= n; i++) {
g.add(new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
int u = f.nextInt();
int v = f.nextInt();
g.get(u).add(v);
g.get(v).add(u);
}
dfs(1, -1, 0);
int endPt1 = farthestNode;
dfs(farthestNode, -1, 0);
int endPt2 = farthestNode;
Vector<Integer> stack = new Vector<Integer>();
nodesInTheDia(endPt1, endPt2, n, stack);
int max = 0, maxNodeOutsideDiameter = -1;
for (int node : set) {
Pair<Integer,Integer> p=maxDepthNode(node,0,0);
if(p.y>=max) {
max = p.y;
maxNodeOutsideDiameter = p.x;
}
}
if(maxNodeOutsideDiameter==-1 || maxNodeOutsideDiameter==endPt1 || maxNodeOutsideDiameter==endPt2) {
for(int i:set){
if(i!=endPt1 && i!=endPt2){
maxNodeOutsideDiameter=i;
break;
}
}
}
w.write((set.size() - 1 + max) + "\n");
w.write(endPt1 + " " + endPt2 + " " + maxNodeOutsideDiameter + "\n");
}
w.flush();
}
static Pair<Integer,Integer> maxDepthNode(int node,int parent,int depth){
Pair<Integer,Integer> max=new Pair<>(node,depth);
for(int child:g.get(node)){
if(child!=parent && !set.contains(child)){
Pair<Integer,Integer> p=maxDepthNode(child,node,depth+1);
if(p.y>max.y){
max=p;
}
}
}
return max;
}
static void dfs(int node, int parent, int level) {
if (level >= maxLevel) {
maxLevel = level;
farthestNode = node;
}
for (int i : g.get(node)) {
if (i != parent) {
dfs(i, node, level + 1);
}
}
}
static void printPath(Vector<Integer> stack) {
for (int i = 0; i < stack.size(); i++) {
set.add(stack.get(i));
}
}
static void DFS(boolean vis[], int x, int y, Vector<Integer> stack) {
stack.add(x);
if (x == y) {
printPath(stack);
return;
}
vis[x] = true;
if (g.get(x).size() > 0) {
for (int j = 0; j < g.get(x).size(); j++) {
if (vis[g.get(x).get(j)] == false) {
DFS(vis, g.get(x).get(j), y, stack);
}
}
}
stack.remove(stack.size() - 1);
}
static void nodesInTheDia(int x, int y, int n, Vector<Integer> stack) {
boolean vis[] = new boolean[n + 1];
DFS(vis, x, y, stack);
}
}
/*
*/
|
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 Main {
public static void main(String[] args) throws IOException {
BufferedReader r =
new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(r.readLine());
int N = Integer.parseInt(st.nextToken());
int P = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
//Read the audience.
st = new StringTokenizer(r.readLine());
pair[] A = new pair[N];
for (int i = 0; i < N; i++) {
A[i] = new pair(i, Integer.parseInt(st.nextToken()));
}
Arrays.sort(A);
//Read the player skill matrix.
int[][] skill = new int[N][P];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(r.readLine());
for (int j = 0; j < P; j++) {
skill[i][j] = Integer.parseInt(st.nextToken());
}
}
//Initialize dp matrix.
long[][] dp = new long[N + 1][(1 << P)];
for (int i = 0; i <= N; i++) {
Arrays.fill(dp[i], -1);
}
dp[0][0] = 0;
for (int i = 1; i <= N; i++) {
int ind = A[i - 1].idx;
for (int m = 0; m < (1 << P); m++) {
//Count the number of bits in the mask.
int bits = 0;
for (int j = 0; j < P; j++) {
if ((m & (1 << j)) > 0) {
bits++;
}
}
int numAud = i - 1 - bits;
//If the player is added to the audience.
if (numAud < K) {
if (dp[i - 1][m] != -1) {
dp[i][m] = dp[i - 1][m] + A[i - 1].val;
}
} else {
if (dp[i - 1][m] != -1) {
dp[i][m] = dp[i - 1][m];
}
}
//Add the player to the team.
for (int j = 0; j < P; j++) {
if ((m & (1 << j)) > 0 ) {
if ((dp[i - 1][m ^ (1 << j)]) != -1) {
dp[i][m] = Math.max(dp[i][m],
dp[i - 1][m ^ (1 << j)] + skill[ind][j]);
}
}
}
}
}
//Print the answer.
System.out.println(dp[N][(1<< P)- 1]);
}
static class pair implements Comparable<pair> {
int idx, val;
public pair(int idx, int val) {
this.idx = idx;
this.val = val;
}
public int compareTo(pair other) {
return other.val - val;
}
}
}
|
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.*;
public class Solver {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double res = 0;
for (int i=1; i<=n; i++) res += 1.0 / i;
System.out.printf("%.12f\n", res);
}
}
|
java
|
1303
|
A
|
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
|
[
"implementation",
"strings"
] |
import java.io.*;
import java.util.*;
public class Problems {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
String[] array = new String[t];
for (int i = 0; i < array.length; i++) {
array[i] = in.next();
}
for (int i = 0; i < array.length; i++) {
int counter = 0;
String str = array[i];
if (firstOne(str) == -1) {
System.out.println(0);
continue;
} else {
for (int j = firstOne(str) + 1; j < lastOne(str); j++) {
if (str.charAt(j) == '0') {
counter++;
}
}
System.out.println(counter);
}
}
}
public static int firstOne(String str) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '1') {
return i;
}
}
return -1;
}
public static int lastOne(String str) {
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) == '1') {
return i;
}
}
return -1;
}
}
|
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 javaapplication3;
import java.util.Scanner;
public class JavaApplication3 {
static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
int n = scan.nextInt();
int[] q = new int[n - 1];
int upper = 0, qSum = 0;
for (int i = 0; i < n - 1; i++) {
q[i] = scan.nextInt();
qSum += q[i];
if (qSum > 0)
upper++;
}
int[] p = new int[n];
int[] sorted = new int[n];
p[0] = n - upper;
try {
sorted[p[0] - 1] = p[0];
for (int i = 1; i < n; i++) {
p[i] = p[i - 1] + q[i - 1];
if (sorted[p[i] - 1] != 0) {
throw new Exception();
}
sorted[p[i] - 1] = p[i];
}
} catch (Exception e) {
System.out.println(-1);
return;
}
for (int i = 0; i < n; i++) {
System.out.print(p[i] + " ");
}
}
}
|
java
|
1292
|
A
|
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.
|
[
"data structures",
"dsu",
"implementation"
] |
//package com.rajan.codeforces.level_1400;
import java.io.*;
import java.util.*;
public class NekosMazeGame {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] temp = reader.readLine().split("\\s+");
int n = Integer.parseInt(temp[0]), q = Integer.parseInt(temp[1]);
boolean[][] grid = new boolean[2][n];
for (int i = 0; i < 2; i++)
Arrays.fill(grid[i], true);
Map<List<Integer>, Set<List<Integer>>> blockMap = new HashMap<>();
for (int i = 0; i < q; i++) {
temp = reader.readLine().split("\\s+");
int r = Integer.parseInt(temp[0]) - 1, c = Integer.parseInt(temp[1]) - 1;
grid[r][c] = !grid[r][c];
List<Integer> idx = List.of(r, c);
if (grid[r][c]) {
if (blockMap.containsKey(idx)) {
Set<List<Integer>> blockers = blockMap.get(idx);
for (List<Integer> item : blockers) {
if (blockMap.getOrDefault(item, new HashSet<>()).size() <= 1) {
blockMap.remove(item);
} else {
blockMap.get(item).remove(idx);
}
}
}
blockMap.remove(idx);
if (blockMap.isEmpty())
writer.write("YES\n");
else
writer.write("NO\n");
} else {
if (!grid[1 - r][c]) {
List<Integer> item = List.of(1 - r, c);
blockMap.putIfAbsent(item, new HashSet<>());
blockMap.get(item).add(idx);
blockMap.putIfAbsent(idx, new HashSet<>());
blockMap.get(idx).add(item);
}
if (c > 0 && !grid[1 - r][c - 1]) {
List<Integer> item = List.of(1 - r, c - 1);
blockMap.putIfAbsent(item, new HashSet<>());
blockMap.get(item).add(idx);
blockMap.putIfAbsent(idx, new HashSet<>());
blockMap.get(idx).add(item);
}
if (c < n - 1 && !grid[1 - r][1 + c]) {
List<Integer> item = List.of(1 - r, c + 1);
blockMap.putIfAbsent(item, new HashSet<>());
blockMap.get(item).add(idx);
blockMap.putIfAbsent(idx, new HashSet<>());
blockMap.get(idx).add(item);
}
if (blockMap.isEmpty())
writer.write("YES\n");
else
writer.write("NO\n");
// System.out.println(blockMap);
}
// for (int j = 0; j < 2 && i == 58; j++) {
// System.out.println(Arrays.toString(grid[j]));
// System.out.println(blockMap);
// }
}
writer.flush();
}
}
|
java
|
1288
|
D
|
D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
|
[
"binary search",
"bitmasks",
"dp"
] |
import java.io.*;
import java.util.*;
public class gotoJapan {
public static void main(String[] args) throws java.lang.Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solution solver = new Solution();
boolean isTest = false;
int tC = isTest ? Integer.parseInt(in.next()) : 1;
for (int i = 1; i <= tC; i++)
solver.solve(in, out, i);
out.close();
}
/* ............................................................. */
static class Solution {
InputReader in;
PrintWriter out;
public void solve(InputReader in, PrintWriter out, int test) {
this.in = in;
this.out = out;
int n=ni();
int m=ni();
int a[][]=new int[n][m];
int b[]=new int[(1<<m)+5];
//Arrays.fill(b, -1);
int ind[]=new int[(1<<m)+5];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++)a[i][j]=ni();
for(int j=1;j<(1<<m);j++) {
int min=(int)1e9;
for(int k=0;k<m;k++) {
if(((1<<k)&j)!=0)min=Math.min(a[i][k], min);
}
if(min>=b[j]) {
ind[j]=i+1;
b[j]=min;
}
}
}
b[0]=(int)1e9;
int ans1=ind[(1<<m)-1],ans2=ind[(1<<m)-1],ans=b[(1<<m)-1];
for(int i=1;i<(1<<m);i++) {
for(int j=1;j<(1<<m);j++) {
if((i^j)==((1<<m)-1)) {
int x=Math.min(b[j], b[i]);
if(x>=ans) {
ans=x;
ans1=ind[i];
ans2=ind[j];
}
}
}
}
out.println(ans1+" "+ans2);
}
class Pair {
int x;
int y;
long w;
Pair(int x, int y, long w) {
this.x = x;
this.y = y;
this.w = w;
}
}
char[] n() {
return in.next().toCharArray();
}
int ni() {
return in.nextInt();
}
long nl() {
return in.nextLong();
}
long[] nal(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
void pn(long zx) {
out.println(zx);
}
void pn(String sz) {
out.println(sz);
}
void pn(double dx) {
out.println(dx);
}
void pn(long ar[]) {
for (int i = 0; i < ar.length; i++)
out.print(ar[i] + " ");
out.println();
}
void pn(String ar[]) {
for (int i = 0; i < ar.length; i++)
out.println(ar[i]);
}
}
/* ......................Just Input............................. */
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());
}
}
/* ......................Just Input............................. */
}
|
java
|
1316
|
C
|
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.
|
[
"constructive algorithms",
"math",
"ternary search"
] |
import java.io.*;
import java.util.*;
public class E {
public static void main(String[] args) throws IOException{
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(" ");
int n = Integer.parseInt(str[0]), m = Integer.parseInt(str[1]), p = Integer.parseInt(str[2]);
StringTokenizer st1 = new StringTokenizer(br.readLine());
StringTokenizer st2 = new StringTokenizer(br.readLine());
int ans = 0;
for(int i = 0; i<n; i++){
int x = Integer.parseInt(st1.nextToken());
if(x%p != 0){
ans = i;
break;
}
}
for(int i = 0; i<m; i++){
int x = Integer.parseInt(st2.nextToken());
if(x%p != 0){
ans += i;
break;
}
}
System.out.println(ans);
}
//System.out.println(sb);
}
}
|
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 EhAb_AnD_gCd {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
int[] number = new int[t];
for (int i=0; i<t; i++) {
number[i] = scanner.nextInt();
}
for (int x : number) {
System.out.println(x-1 +" " +1);
}
}
}
|
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"
] |
//package contest;
import java.io.*;
import java.util.*;
public class A {
static class Pair{
int x;
int y;
public Pair(int x, int y) {
this.x=x;
this.y=y;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
Pair arr[] = new Pair[n];
for(int i=0;i<n;i++) {
int x = sc.nextInt();
int y = sc.nextInt();
arr[i] = new Pair(x,y);
}
Arrays.sort(arr, (p1, p2) -> {
if(p1.x==p2.x) {
return p1.y-p2.y;
}else{
return p1.x-p2.x;
}});
int sx=0,sy=0,ok=1;
String ans = "";
for(int i=0;i<n;i++) {
if(arr[i].x<sx || arr[i].y<sy) {
ok=0;
break;
}
while(sx<arr[i].x) {
ans+="R";sx++;
}
while(sy<arr[i].y) {
ans+="U";sy++;
}
}
if(ok==1) {
System.out.println("YES");
System.out.println(ans);
}else {
System.out.println("NO");
}
}
}
}
|
java
|
1311
|
A
|
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.
|
[
"greedy",
"implementation",
"math"
] |
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
//Scanner sc = new Scanner(new File(".in"));
int n = sc.nextInt();
for (int i = 0; i < n; i++){
int a = sc.nextInt();
int b = sc.nextInt();
int ans = 0;
if (a == b) {
ans = 0;
}else if (a - b < 0){
if ((b - a) % 2 == 1){
ans++;
}else{
ans = ans + 2;
}
}else {
if ((a - b) % 2 == 0){
ans++;
}else {
ans = ans + 2;
}
}
System.out.println(ans);
PrintWriter out = new PrintWriter(".out");
out.println();
out.close();
}
}}
|
java
|
1315
|
B
|
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
|
[
"binary search",
"dp",
"greedy",
"strings"
] |
import java.io.*;
import java.util.*;
public class Run {
public static int mod = 1000000007;
public static PrintWriter out = new PrintWriter(System.out);
public static boolean testing = false;
public static FastIO io;
public static String input_file = "./input.txt";
static {
try {
io = new FastIO();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static int[] sort(int[] arr) {
List<Integer> nums = new ArrayList<>();
for (int el : arr) nums.add(el);
Collections.sort(nums);
int[] res = new int[arr.length];
for (int i = 0; i < arr.length; i++) res[i] = nums.get(i);
return res;
}
public static long[] sort(long[] arr) {
List<Long> nums = new ArrayList<>();
for (long el : arr) nums.add(el);
Collections.sort(nums);
long[] res = new long[arr.length];
for (int i = 0; i < arr.length; i++) res[i] = nums.get(i);
return res;
}
public static void reverse(int[] arr, int i, int j) {
while (i < j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
++i;
--j;
}
}
public static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static int lowerBound(long[] arr, long x) {
int l = -1;
int r = arr.length;
while (r > l + 1) {
int m = l + (r - l) / 2;
if (arr[m] <= x) l = m;
else r = m;
}
return Math.max(0, l);
}
public static int upperBound(long[] arr, long x) {
int l = -1;
int r = arr.length;
while (r > l + 1) {
int m = l + (r - l) / 2;
if (arr[m] >= x) r = m;
else l = m;
}
return Math.min(arr.length - 1, r);
}
public static int log2(int a) {
return (int) (Math.log(a) / Math.log(2));
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int t = io.nextInt();
while (t-- > 0) {
int a = io.nextInt();
int b = io.nextInt();
int p = io.nextInt();
String s = '#' + io.next();
int last = s.length() - 1;
int ans = 1;
for (int i = s.length() - 2; i > 0; i--) {
char curr = s.charAt(i);
char prev = s.charAt(i - 1);
if (prev == curr) continue;
int cost = curr == 'A' ? a : b;
p -= cost;
if (p < 0) {
ans = last;
break;
}
last = i;
}
out.write(ans + "\n");
}
out.close();
}
static class CC implements Comparator<Pair> {
public int compare(Pair o1, Pair o2) {
if (o1.first == o2.first) return o1.second - o2.second;
return o1.first - o2.first;
}
}
static class Pair {
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public String toString() {
return "Pair{" +
"first=" + first +
", second=" + second +
'}';
}
}
static class FastIO {
InputStreamReader s = new InputStreamReader(testing ? new FileInputStream(input_file) : System.in);
BufferedReader br = new BufferedReader(s);
StringTokenizer st = new StringTokenizer("");
FastIO() throws FileNotFoundException {
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
java
|
1285
|
A
|
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
|
[
"math"
] |
import java.util.Scanner;
public class testing11 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
char[] ch = in.nextLine().toCharArray();
int l = 0, r = 0;
for(char c : ch) {
if(c=='L') l++;
else r++;
}
System.out.println(1 + r + l);
}
}
|
java
|
1305
|
C
|
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
|
[
"brute force",
"combinatorics",
"math",
"number theory"
] |
import java.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) {
arr.add(i);
if(i != n / i) arr.add(n / 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;
}
static long binarySearchModified(long start1, long n, ArrayList<Integer> arr, int val) {
long start = start1, end = n, ans = -1;
while(start <= end) {
long mid = (start + end) / 2;
if(arr.get((int)mid) >= val) {
if(arr.get((int)mid) == val && mid + 1 < arr.size() && arr.get((int)mid + 1) == val) {
start = mid + 1;
}else if(arr.get((int)mid) == val) {
return mid;
}else end = mid - 1;
}else {
start = mid + 1;
}
}
//System.out.println();
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 a, TreeNode b) {
// TODO Auto-generated method stub
return 0;
}
}
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();
}
static void solve() throws IOException {
/*
while(true) {
long [] n = inputLongArr();
if(n[0] == 0 && n[1] == 0 && n[2] == 0 && n[3] == 0) break;
long d = (n[3] + n[2] - n[0]);
System.out.println(d);
long [] ans = new long [2];
long gcd;
if(d < 0) {
n[1] = -1 * n[1];
}else n[2] = -1 * n[2];
gcd = extendedEuclid(Math.abs(n[1]), Math.abs(n[2]), ans);
if(d % gcd == 0) {
System.out.println(ans[0] + " " + ans[1]);
ans[0] *= Math.abs(d) / gcd;
ans[1] *= Math.abs(d) / gcd;
//System.out.println(ans[0] + " " + ans[1]);
if(n[1] < 0) {
ans[0] *= -1;
}
if(n[2] < 0) {
ans[1] *= -1;
}
if(ans[1] < 0) {
long k = -1 * (long)Math.ceil(ans[1] / (double)n[1]);
System.out.println(k);
ans[0] = ans[0] - n[2] * k;
ans[1] = ans[1] + n[1] * k;
}
if(ans[0] < 0) {
long k = (long)Math.ceil(ans[0] / (double)n[2]);
ans[0] = ans[0] - n[2] * k;
ans[1] = ans[1] + n[1] * k;
System.out.println(ans[0] + " " + ans[1] + " 1");
}
output.write(n[0] + ans[0] * n[1] + "\n");
System.out.println(ans[0] + " " + ans[1]);
}else {
output.write("Impossible\n");
}
}
*/
int [] n = inputIntArr();
long [] arr = inputLongArr();
if(n[1] < n[0]) {
output.write(0 + "\n");
return;
}
long pro = 1;
for(int i = 0; i < arr.length; i++) {
for(int j = i + 1; j < arr.length; j++) {
pro = ((pro % n[1]) * (Math.abs(arr[i] - arr[j]) % n[1])) % n[1];
if(pro == 0) {
output.write(0 + "\n");
return;
}
}
}
output.write(pro + "\n");
}
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 TreeNode {
int val; int index;
public TreeNode(int val, int index) {
this.val = val;
this.index = index;
}
public String toString() {
return val + " " + index;
}
}
/*
1
10
6 10 7 9 11 99 45 20 88 31
*/
|
java
|
1295
|
E
|
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2
|
[
"data structures",
"divide and conquer"
] |
import java.io.*;
import java.util.*;
public class Main {
static long inf=(long)1e16;
static public class SegmentTree { // 1-based DS, OOP
int N; //the number of elements in the array as a power of 2 (i.e. after padding)
long[] array, sTree, lazy;
SegmentTree(long[] in)
{
array = in; N = in.length - 1;
sTree = new long[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero
lazy = new long[N<<1];
Arrays.fill(sTree, inf);
build(1,1,N);
}
void build(int node, int b, int e) // O(n)
{
if(b == e)
sTree[node] = array[b];
else
{
int mid = b + e >> 1;
build(node<<1,b,mid);
build(node<<1|1,mid+1,e);
sTree[node] = Math.min(sTree[node<<1],sTree[node<<1|1]);
}
}
void update_range(int i, int j, int val) // O(log n)
{
update_range(1,1,N,i,j,val);
}
void update_range(int node, int b, int e, int i, int j, int val)
{
if(i > e || j < b)
return;
if(b >= i && e <= j)
{
sTree[node] += val;
lazy[node] += val;
}
else
{
int mid = b + e >> 1;
propagate(node, b, mid, e);
update_range(node<<1,b,mid,i,j,val);
update_range(node<<1|1,mid+1,e,i,j,val);
sTree[node] = Math.min(sTree[node<<1],sTree[node<<1|1]);
}
}
void propagate(int node, int b, int mid, int e)
{
lazy[node<<1] += lazy[node];
lazy[node<<1|1] += lazy[node];
sTree[node<<1] += lazy[node];
sTree[node<<1|1] += lazy[node];
lazy[node] = 0;
}
long query(int i, int j)
{
return query(1,1,N,i,j);
}
long query(int node, int b, int e, int i, int j) // O(log n)
{
if(i>e || j <b)
return inf;
if(b>= i && e <= j)
return sTree[node];
int mid = b + e >> 1;
propagate(node, b, mid, e);
long q1 = query(node<<1,b,mid,i,j);
long q2 = query(node<<1|1,mid+1,e,i,j);
return Math.min(q1, q2);
}
}
public static void main(String[] args) throws Exception {
MScanner sc=new MScanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
int[]idx=new int[n];
for(int i=0;i<n;i++) {
idx[sc.nextInt()-1]=i;
}
int[]costs=sc.takearr(n);
int N = 1; while(N < n) N <<= 1; //padding
long[]splits=new long[N+1];
long ans=inf;
for(int i=1;i<n;i++) {
splits[i]=costs[i-1]+splits[i-1];
ans=Math.min(ans, splits[i]);
}
SegmentTree split=new SegmentTree(splits);
for(int i=0;i<n;i++) {
int index=idx[i]+1;
split.update_range(index, n-1, -costs[idx[i]]);
if(index>1)
split.update_range(1, index-1, costs[idx[i]]);
ans=Math.min(ans, split.query(1, n-1));
}
pw.println(ans);
pw.flush();
}
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] takearr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] takearrl(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public Integer[] takearrobj(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] takearrlobj(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
|
java
|
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"
] |
//package round621;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class E3 {
InputStream is;
PrintWriter out;
// 12221
String INPUT = "";
public static long invl(long a, long mod) {
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
return p < 0 ? p + mod : p;
}
void solve()
{
// no two cowsとあるので、同じsweetnessのはたかだか100通り
// 左右の取り分上限を決めてしまえばsweetnessで分割できる
// 上限が決まっているときの分割しかた
// ああ1個しか入れられないやんけ
int n = ni(), m = ni();
int[] s = na(n);
int[][] cum = new int[n+1][n+1];
for(int i = 0;i < m;i++){
int a = ni(), b = ni();
cum[a][b]++;
}
for(int i = 1;i <= n;i++){
for(int j = 1;j <= n;j++){
cum[i][j] += cum[i][j-1];
}
}
int[] f = new int[n+1];
int[] rf = new int[n+1];
for(int v : s)rf[v]++;
int mod = 1000000007;
long ans = 0;
int maxnum = 0;
long vt = 1;
int[] pf = new int[n+1];
int[] prf = new int[n+1];
int[] vals = new int[n+1];
int[] nums = new int[n+1];
Arrays.fill(vals, 1);
int numt = 0;
for(int i = 0;i <= n;i++){
// <= i, <=n-i
if(i > 0)rf[s[i-1]]--;
if(i > 0){
for(int j = 1;j <= n;j++){
if(pf[j] != f[j] || prf[j] != rf[j]){
vt = vt * invl(vals[j], mod) % mod;
numt -= nums[j];
int L = cum[j][f[j]];
int R = cum[j][rf[j]];
if(L > R){
int D = L; L = R; R = D;
}
if(L >= 1 && R >= 2){
numt += 2;
nums[j] = 2;
vals[j] = L*(R-1);
vt = vt * vals[j] % mod;
}else if(R >= 1){
numt++;
nums[j] = 1;
vals[j] = L+R;
vt = vt * vals[j] % mod;
}else{
nums[j] = 0;
}
pf[j] = f[j];
prf[j] = rf[j];
}
}
}
long myvt = vt;
int mynum = i > 0 ? numt : -1;
if(i > 0)f[s[i-1]]++;
for(int j = 1;j <= n;j++){
if(pf[j] != f[j] || prf[j] != rf[j]){
vt = vt * invl(vals[j], mod) % mod;
numt -= nums[j];
int L = cum[j][f[j]];
int R = cum[j][rf[j]];
if(L > R){
int D = L; L = R; R = D;
}
if(L >= 1 && R >= 2){
numt += 2;
nums[j] = 2;
vals[j] = L*(R-1);
vt = vt * vals[j] % mod;
}else if(R >= 1){
numt++;
nums[j] = 1;
vals[j] = L+R;
vt = vt * vals[j] % mod;
}else{
nums[j] = 0;
}
pf[j] = f[j];
prf[j] = rf[j];
}
}
if(numt > maxnum){
maxnum = numt;
ans = vt;
}else if(numt == maxnum){
ans += vt;
}
if(mynum == maxnum){
ans -= myvt;
}
}
ans %= mod;
if(ans < 0)ans += mod;
out.println(maxnum + " " + ans);
}
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
{
// int n = 5000, m = 5000;
// Random gen = new Random();
// StringBuilder sb = new StringBuilder();
// sb.append(n + " ");
// sb.append(m + " ");
// for (int i = 0; i < n; i++) {
// sb.append(gen.nextInt(3)+1 + " ");
// }
// boolean[][] done = new boolean[n+1][n+1];
// for(int i = 0;i < m;i++){
// while(true){
// int x = gen.nextInt(3)+1;
// int y = gen.nextInt(n)+1;
// if(!done[x][y]){
// done[x][y] = true;
// sb.append(x + " " + y + "\n");
// break;
// }
// }
// }
// INPUT = sb.toString();
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new E3().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
|
A
|
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.
|
[
"implementation",
"math"
] |
import java.util.*;
public class Sol {
public static void main(String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
if (n == m)
System.out.println(0);
else if (m % n != 0)
System.out.println(-1);
else {
int ans = 0;
int x = m / n;
while (x % 2 == 0) {
ans++;
x /= 2;
}
while (x % 3 == 0) {
ans++;
x /= 3;
}
if (x != 1)
System.out.println(-1);
else
System.out.println(ans);
}
in.close();
}
}
|
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.io.*;
import java.util.*;
public class Mainn {
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 swap(long[] a, long i, long j) {
long temp = a[(int) i];
a[(int) i] = a[(int) j];
a[(int) j] = (int) temp;
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static int lcm(int a, int b) {
return (int) (a * b / gcd(a, b));
}
public static String sortString(String inputString) {
char[] tempArray = inputString.toCharArray();
Arrays.sort(tempArray);
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 long computeXOR(long n) {
if (n % 4 == 0)
return n;
if (n % 4 == 1)
return 1;
if (n % 4 == 2)
return n + 1;
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 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;
}
}
static void sort(String[] s, int n) {
for (int i = 1; i < n; i++) {
String temp = s[i];
int j = i - 1;
while (j >= 0 && temp.length() < s[j].length()) {
s[j + 1] = s[j];
j--;
}
s[j + 1] = temp;
}
}
static int sqr(int n) {
double x = Math.sqrt(n);
if ((int) x == x)
return (int) x;
else
return (int) (x + 1);
}
static int set_bits_count(int num) {
int count = 0;
while (num > 0) {
num &= (num - 1);
count++;
}
return count;
}
static double factorial(double n) {
double f = 1;
for (int i = 1; i <= n; i++) {
f = f * i;
}
return f;
}
static boolean palindrome(int arr[], int n) {
boolean flag = true;
for (int i = 0; i <= n / 2 && n != 0; i++) {
if (arr[i] != arr[n - i - 1]) {
flag = false;
break;
}
}
return flag;
}
public static boolean isSorted(int[] a) {
if (a == null || a.length <= 1) {
return true;
}
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
public static boolean Consecutive(List<Integer> a, int[] b, int n, int m) {
int i = 0, j = 0;
while (i < n && j < m) {
if (Objects.equals(a.get(i), b[j])) {
i++;
j++;
if (j == m)
return true;
} else {
i = i - j + 1;
j = 0;
}
}
return false;
}
static class Pair {
int l;
int r;
public Pair(int l, int r) {
this.l = l;
this.r = r;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
FastReader sc = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
int q = 1;
while (t-- != 0) {
long n = sc.nextLong();
long m = sc.nextLong();
String str = sc.next();
int[] ans = new int[26];
int[] aa = new int[(int) n];
int[] aas = new int[(int)n];
Arrays.fill(ans,0);
String res ="";
int[] arr = new int[(int) m];
aa[(int) (n-1)] = 1;
for(int i = 0; i < m ; i++){
arr[i] = sc.nextInt();
aas[arr[i]-1]++;
}
for(int i = (int) (n-2); i >=0 ; i--){
aa[i] = aas[i] + aa[i+1];
}
for(int i = 0; i < str.length() ; i++){
ans[(str.charAt(i))-'a'] += aa[i];
}
for(int i = 0; i < 26 ; i++){
System.out.print(ans[i] + " ");
}
System.out.println();
}
}
static void solve() throws IOException {
}
}
|
java
|
1294
|
E
|
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
|
[
"greedy",
"implementation",
"math"
] |
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
//BufferedReader f = new BufferedReader(new FileReader("uva.in"));
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
//PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("cowjump.out")));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[][] a = new int[n][m];
int[] row = new int[n*m+1];
for(int i = 0; i < n; i++) {
st = new StringTokenizer(f.readLine());
for(int j = 0; j < m; j++) {
a[i][j] = Integer.parseInt(st.nextToken());
row[i*m+j+1] = i;
}
}
int ans = 0;
for(int i = 0; i < m; i++) {
int[] diff = new int[n+1];
for(int j = 0; j < n; j++) {
if(a[j][i] < 1 || a[j][i] > n*m || a[j][i]%m != (i+1)%m) {
diff[n]++;
} else {
diff[(j-row[a[j][i]]+n)%n]++;
}
}
int min = n;
for(int j = 0; j < n; j++) {
min = Math.min(min, n-diff[j]+j);
}
ans += min;
}
out.println(ans);
f.close();
out.close();
}
}
|
java
|
1316
|
C
|
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.
|
[
"constructive algorithms",
"math",
"ternary search"
] |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
import java.io.*;
public class Main {
// Graph
// prefix sums
//inputs
public static void main(String args[])throws Exception{
Input sc=new Input();
precalculates p=new precalculates();
StringBuilder sb=new StringBuilder();
int d[]=sc.readArray();
int n=d[0],m=d[1],pp=d[2];
int a[]=sc.readArray();
int b[]=sc.readArray();
int x=0;
int y=0;
for(int i=0;i<n;i++){
if(p.gcd(a[i],pp)==1){
x=i;
break;
}
}
for(int i=0;i<m;i++){
if(p.gcd(b[i],pp)==1){
y=i;
break;
}
}
sb.append(x+y+"\n");
System.out.print(sb);
}
}
/*
1
qwerty
2
qwerty -> wqerty -> weqrty -> werqty -> wertqy -> wertyq
3
qwerty -> ewqrty -> erqwty -> ertwqy -> ertyqw
4
qwerty -> rewqty -> rtqwey -> rtyewq
5
qwerty -> trewqy -> tyqwer
*/
class Input{
BufferedReader br;
StringTokenizer st;
Input(){
br=new BufferedReader(new InputStreamReader(System.in));
st=new StringTokenizer("");
}
public int[] readArray() throws Exception{
st=new StringTokenizer(br.readLine());
int a[]=new int[st.countTokens()];
for(int i=0;i<a.length;i++){
a[i]=Integer.parseInt(st.nextToken());
}
return a;
}
public long[] readArrayLong() throws Exception{
st=new StringTokenizer(br.readLine());
long a[]=new long[st.countTokens()];
for(int i=0;i<a.length;i++){
a[i]=Long.parseLong(st.nextToken());
}
return a;
}
public int readInt() throws Exception{
st=new StringTokenizer(br.readLine());
return Integer.parseInt(st.nextToken());
}
public long readLong() throws Exception{
st=new StringTokenizer(br.readLine());
return Long.parseLong(st.nextToken());
}
public String readString() throws Exception{
return br.readLine();
}
public int[][] read2dArray(int n,int m)throws Exception{
int a[][]=new int[n][m];
for(int i=0;i<n;i++){
st=new StringTokenizer(br.readLine());
for(int j=0;j<m;j++){
a[i][j]=Integer.parseInt(st.nextToken());
}
}
return a;
}
}
class precalculates{
public long gcd(long p, long q) {
if (q == 0) return p;
else return gcd(q, p % q);
}
public int[] prefixSumOneDimentional(int a[]){
int n=a.length;
int dp[]=new int[n];
for(int i=0;i<n;i++){
if(i==0)
dp[i]=a[i];
else
dp[i]=dp[i-1]+a[i];
}
return dp;
}
public int[] postSumOneDimentional(int a[]) {
int n = a.length;
int dp[] = new int[n];
for (int i = n - 1; i >= 0; i--) {
if (i == n - 1)
dp[i] = a[i];
else
dp[i] = dp[i + 1] + a[i];
}
return dp;
}
public int[][] prefixSum2d(int a[][]){
int n=a.length;int m=a[0].length;
int dp[][]=new int[n+1][m+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
dp[i][j]=a[i-1][j-1]+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1];
}
}
return dp;
}
public long pow(long a,long b){
long mod=1000000007;
long ans=1;
if(b<=0)
return 1;
if(b%2==0){
ans=pow(a,b/2)%mod;
return ((ans%mod)*(ans%mod))%mod;
}else{
ans=pow(a,b-1)%mod;
return ((a%mod)*(ans%mod))%mod;
}
}
}
class GraphInteger{
HashMap<Integer,vertex> vtces;
class vertex{
HashMap<Integer,Integer> children;
public vertex(){
children=new HashMap<>();
}
}
public GraphInteger(){
vtces=new HashMap<>();
}
public void addVertex(int a){
vtces.put(a,new vertex());
}
public void addEdge(int a,int b,int cost){
if(!vtces.containsKey(a)){
vtces.put(a,new vertex());
}
if(!vtces.containsKey(b)){
vtces.put(b,new vertex());
}
vtces.get(a).children.put(b,cost);
// vtces.get(b).children.put(a,cost);
}
public boolean isCyclicDirected(){
boolean isdone[]=new boolean[vtces.size()+1];
boolean check[]=new boolean[vtces.size()+1];
for(int i=1;i<=vtces.size();i++) {
if (!isdone[i] && isCyclicDirected(i,isdone, check)) {
return true;
}
}
return false;
}
private boolean isCyclicDirected(int i,boolean isdone[],boolean check[]){
if(check[i])
return true;
if(isdone[i])
return false;
check[i]=true;
isdone[i]=true;
Set<Integer> set=vtces.get(i).children.keySet();
for(Integer ii:set){
if(isCyclicDirected(ii,isdone,check))
return true;
}
check[i]=false;
return false;
}
}
class union_find {
int n;
int[] sz;
int[] par;
union_find(int nval) {
n = nval;
sz = new int[n + 1];
par = new int[n + 1];
for (int i = 0; i <= n; i++) {
par[i] = i;
sz[i] = 1;
}
}
int root(int x) {
if (par[x] == x)
return x;
return par[x] = root(par[x]);
}
boolean find(int a, int b) {
return root(a) == root(b);
}
int union(int a, int b) {
int ra = root(a);
int rb = root(b);
if (ra == rb)
return 0;
if(a==b)
return 0;
if (sz[a] > sz[b]) {
int temp = ra;
ra = rb;
rb = temp;
}
par[ra] = rb;
sz[rb] += sz[ra];
return 1;
}
}
|
java
|
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"
] |
/*
7
4 1 2 2 1 5 3
*/
import java.util.*;
import java.io.*;
public class Main{
public static int n;
public static int[] vals;
public static HashMap<Integer, ArrayList<Block>> sortedBlocks = new HashMap<Integer, ArrayList<Block>>(); //all blocks of a certain value, sorted from earliest to latest endpoint and then earliest to latest starting point
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
vals = new int[n];
StringTokenizer vs = new StringTokenizer(br.readLine());
for(int a = 0; a < n; a++) vals[a] = Integer.parseInt(vs.nextToken());
int[] pre = new int[n];
pre[0] = vals[0];
for(int b = 1; b < n; b++){
pre[b] = vals[b] + pre[b - 1];
}
for(int fi = 0; fi < n; fi++){
for(int si = fi; si < n; si++){
int v = pre[si];
if(fi > 0) v -= pre[fi-1];
if(!sortedBlocks.containsKey(v)) sortedBlocks.put(v, new ArrayList<Block>());
sortedBlocks.get(v).add(new Block(fi, si, v));
}
}
//System.out.println(sortedBlocks);
int lg = 0; //most blocks of a certain value
String best = "";
for(int value : sortedBlocks.keySet()){
Collections.sort(sortedBlocks.get(value));
int t = -1;
int sm = 0;
StringBuilder cr = new StringBuilder();
for(Block b : sortedBlocks.get(value)){ //given a set of ranges, what is the most ranges that you can use?
if(b.a > t){
t = b.b;
sm++;
cr.append((b.a + 1) + " " + (b.b + 1) + "\n");
}
}
if(sm > lg){
lg = sm;
best = cr.toString();
}
}
System.out.println(lg + "\n" + best.toString());
br.close();
}
}
class Block implements Comparable<Block>{
int a;
int b; //starting and ending indices
int val;
public Block(int ac, int bc, int v){
a = ac;
b = bc;
val = v;
}
public int compareTo(Block c){
if(c.b != b) return b - c.b;
if(c.a != a) return a - c.a;
return val - c.val;
}
public String toString(){
return a + " " + b;
}
}
|
java
|
1304
|
A
|
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
|
[
"math"
] |
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt(), x, y, a, b;
double c;
while(t -- > 0){
x = sc.nextInt();
y = sc.nextInt();
a = sc.nextInt();
b = sc.nextInt();
c = 1.0 * (y - x) / (a + b);
System.out.println(c == (int)c ? (int)c : -1);
}
sc.close();
}
}
|
java
|
1305
|
C
|
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
|
[
"brute force",
"combinatorics",
"math",
"number theory"
] |
import java.io.*;
import java.util.*;
public class JavAki {
public static Scanner sc = new Scanner(System.in);
public static int n, m;
public static int[] a;
public static void Input() {
n = sc.nextInt(); m = sc.nextInt();
a = new int[n];
for (int i=0; i<n; i++) a[i] = sc.nextInt();
}
public static void Solve() {
if (n > m) {System.out.println(0); return;}
int ans = 1;
for (int i=0; i<n; i++) {
for (int j=i+1; j<n; j++) {
ans = (int)(((long)ans * Math.abs(a[i] - a[j])) % m);
}
}
System.out.println(ans);
}
public static void main(String[] args) {
Input(); Solve();
}
}
|
java
|
1294
|
C
|
C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
|
[
"greedy",
"math",
"number theory"
] |
import java.util.ArrayList;
import java.util.Scanner;
public class Lesson7ProductOf3Numbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tcc = sc.nextInt();
while (tcc-- > 0) {
int n = sc.nextInt();
int a = 0;
int b = 0;
for (int i = 2; i * i < n; i++) {
if (n % i == 0) {
a = i;
n /= i;
break;
}
}
for (int i = 2; i * i < n; i++) {
if (n % i == 0 && i != a) {
b = i;
n /= i;
break;
}
}
if (a != 0 && b != 0 && n != 1) {
System.out.println("yes");
System.out.println(a + " " + b + " " + n);
} else {
System.out.println("no");
}
}
}
}
|
java
|
1313
|
C2
|
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
|
[
"data structures",
"dp",
"greedy"
] |
import java.io.*;
import java.util.*;
public class CodeForces{
/*****************************************WRITING CODE STARTS HERE******************************************/
public static void solve(int tCase)throws IOException {
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++ )arr[i] = sc.nextInt();
int[] smallerOnLeft = new int[n];
Deque<Integer> st = new ArrayDeque<>();
for(int i=0;i<n;i++){
while (!st.isEmpty() && arr[st.peek()] >= arr[i])st.pop();
smallerOnLeft[i] = st.isEmpty()?-1:st.peek();
st.push(i);
}
st.clear();
int[] smallerOnRight = new int[n];
for(int i=n-1;i>=0;i--){
while(!st.isEmpty() && arr[st.peek()] >= arr[i])st.pop();
smallerOnRight[i] = st.isEmpty()?-1:st.peek();
st.push(i);
}
long[] leftDp = new long[n];
long[] rightDp = new long[n];
Arrays.fill(leftDp,-1);
Arrays.fill(rightDp,-1);
long ans = 0;
int ind = -1;
for(int i=0;i<n;i++){
long curr = leftSum(i,arr,smallerOnLeft,leftDp) + rightSum(i,arr,smallerOnRight,rightDp) - arr[i];
if(curr>ans){
ind = i;
ans = curr;
}
// out.println(curr);
}
int[] res = new int[n];
res[ind] = arr[ind];
int leftVal = arr[ind];
for(int i=ind-1;i>=0;i--){
leftVal = Math.min(leftVal,arr[i]);
res[i] = leftVal;
}
int rightVal = arr[ind];
for(int i=ind+1;i<n;i++){
rightVal = Math.min(rightVal,arr[i]);
res[i] = rightVal;
}
for(int ele : res)out.print(ele+" ");
}
private static long leftSum(int i,int[] arr,int[] smallerOnLeft,long[] leftDp){
long ans = 0;
if(leftDp[i]!=-1)return leftDp[i];
if(smallerOnLeft[i]==-1)ans = (long) arr[i] *(i+1);
else{
ans = leftSum(smallerOnLeft[i],arr,smallerOnLeft,leftDp) +
(long) (i - smallerOnLeft[i]) * arr[i];
}
return leftDp[i] = ans;
}
private static long rightSum(int i,int[] arr,int[] smallerOnRight,long[] rightDp){
long ans = 0;
if(rightDp[i]!=-1)return rightDp[i];
if(smallerOnRight[i]==-1)ans = (long) arr[i] *(arr.length-i);
else{
ans = rightSum(smallerOnRight[i],arr,smallerOnRight,rightDp) +
(long) (smallerOnRight[i] - i) * arr[i];
}
return rightDp[i] = ans;
}
/*****************************************WRITING CODE ENDS 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();
}
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException{
sc = new FastestReader();
out = new PrintWriter(System.out);
}
/**************************************HELPER FUNCTION STARTS HERE ************************************/
public static int mod = (int) 1e9 +7;
public static int inf_int = (int) 1e9;
public static long inf_long = (long) 1e15;
public static final String YES = "YES";
public static final String NO = "NO";
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
long x = Math.min(a, b);
long y = Math.max(a, b);
if (y % x == 0) return x;
return _gcd(y % x, x);
}
public static long _lcm(long a, long b) {
// lcm(a,b) * gcd(a,b) = a * b
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _power(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
//sieve/first divisor time : O(mx * log ( log (mx) ) )
public static int[] seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
firstDivisor[j] = i;
return firstDivisor;
}
/**************************************HELPER FUNCTION ENDS HERE ************************************/
/*****************************************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
|
1299
|
A
|
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
|
[
"brute force",
"greedy",
"math"
] |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
static final int MAX_N = 1000010;
static final int INF = 0x3f3f3f3f;
static final int mod = 1000000007;
public static void main(String[] args) throws IOException {
initReader(System.in);
// int T = nextInt();
// for (int i = 1; i <= T; i++)
solve();
pw.flush();
}
/*******************************************************************************************************************************/
public static void solve() throws IOException {
int n = nextInt();
int[] a = new int[n + 2];
int[] pre = new int[n + 2];
int[] suf = new int[n + 2];
for (int i = 1; i <= n; i++) {
a[i] = nextInt();
}
// pre and suf
for (int i = 1, j = n; i <= n; i++, j--) {
pre[i] = pre[i - 1] | a[i];
suf[j] = suf[j + 1] | a[j];
}
int Max = -INF, inx = 0;
for (int i = 1; i <= n; i++) {
int temp = a[i] & ~(pre[i - 1] | suf[i + 1]);
if (temp > Max) {
Max = temp;
inx = i;
}
}
int temp = a[1];
a[1] = a[inx];
a[inx] = temp;
for (int i = 1; i <= n; i++) {
pw.print(a[i] + " ");
}
pw.println();
}
/*******************************************************************************************************************************/
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter pw;
public static void initReader(InputStream input) throws IOException {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
// reader = new BufferedReader(new FileReader("ate.in"));
// tokenizer = new StringTokenizer("");
// printWriter = new PrintWriter(new BufferedWriter(new FileWriter("ate.out")));
}
public static boolean hasNext() {
try {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
public static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static char nextChar() throws IOException {
return next().charAt(0);
}
}
|
java
|
1141
|
A
|
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.
|
[
"implementation",
"math"
] |
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long m = sc.nextLong();
int res = solve(n, m);
if(res >= 10000000) System.out.println(-1);
else System.out.println(res);
}
private static int solve(long current, long target)
{
if(current == target) return 0;
if(current > target || current < 0) return 10000000;
int mulTwo = 1 + solve(current * 2, target);
int mulThree = 1 + solve(current * 3, target);
return Math.min(mulTwo, mulThree);
}
}
|
java
|
1141
|
C
|
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1
|
[
"math"
] |
import java.util.*;
import java.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=1;
lable: while(tes-->0)
{
int n=sc.nextInt();
HashSet<Integer> set=new HashSet<>();
int a[]=new int[n];
int b[]=new int[n-1];
int i,min=0,sum=0;
for(i=0;i<n-1;i++)
{
b[i]=sc.nextInt();
sum+=b[i];
min=Math.min(min,sum);
}
a[0]=1-min;
set.add(a[0]);
if(a[0]<1 || a[0]>n)
{
System.out.println(-1);
continue lable;
}
for(i=1;i<n;i++)
{
a[i]=a[i-1]+b[i-1];
set.add(a[i]);
if(a[i]<1 || a[i]>n)
{
System.out.println(-1);
continue lable;
}
}
if(set.size()!=n)
{
System.out.println(-1);
continue;
}
for(int it:a)
System.out.print(it+" ");
}
}
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
|
1312
|
D
|
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
|
[
"combinatorics",
"math"
] |
import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static int mod = 998244353;
static void solve(long n,long m) {
if(n<=2){
System.out.println(0);
return;
}
long v1 = ncr((int)m,(int)(n-1));
long v2 = n-2;
long v3 = p(2,n-3);
long ans = 1;
ans = (v1*v2)%mod;
ans = (ans*v3)%mod;
System.out.println(ans);
}
public static void main(String[] args) {
sb = new StringBuilder();
int test = 1;
while (test-- > 0) {
long n=l();
long m=l();
factorial(m);
solve(n,m);
}
System.out.println(sb);
}
public static void factorial(long m){
fact=new long[(int)m+1];
fact[0] = 1;
fact[1] = 1;
for(int i = 2; i<=m;i++)
fact[i] = ((long
)fact[i-1]*i)%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
|
1141
|
D
|
D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
|
[
"greedy",
"implementation"
] |
/*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import javax.management.InstanceNotFoundException;
import javax.swing.*;
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
static class Boot {
int left;
int right;
Boot(int left, int right) {
this.left = left;
this.right = right;
}
}
static Map<Integer, List<Integer>> leftBootIndexMap;
static Map<Integer, List<Integer>> rightBootIndexMap;
static List<Boot> boots = new ArrayList<>();
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 1; t <= test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
char[] leftBootsColor = sc.next().toCharArray();
char[] rightBootsColor = sc.next().toCharArray();
int[] freqLeftBoots = getFreqOfBoots(leftBootsColor, n);
int[] freqRightBoots = getFreqOfBoots(rightBootsColor, n);
leftBootIndexMap = getIndexMappingOfBoots(leftBootsColor, n);
rightBootIndexMap = getIndexMappingOfBoots(rightBootsColor, n);
int totalPairsOfBoots = findMaxPairOfBoots(freqLeftBoots, freqRightBoots);
out.println(totalPairsOfBoots);
for (Boot boot : boots) {
out.println(boot.left + " " + boot.right);
}
}
private static Map<Integer, List<Integer>> getIndexMappingOfBoots(char[] bootsColor, int n) {
Map<Integer, List<Integer>> indexMappingOfBoots = new HashMap<>();
for (int i = 0; i < 27; i++) {
indexMappingOfBoots.put(i, new ArrayList<>());
}
for (int i = 0; i < n; i++) {
int colorIndex = bootsColor[i] == '?' ? 26 : bootsColor[i] - 'a';
indexMappingOfBoots.get(colorIndex).add(i + 1);
}
return indexMappingOfBoots;
}
private static int findMaxPairOfBoots(int[] freqLeftBoots, int[] freqRightBoots) {
int totalPairsOfBoots = 0, remainingLeftBoots = 0, remainingRightBoots = 0;
for (int i = 0; i < 26; i++) {
int matchingPairs = Math.min(freqLeftBoots[i], freqRightBoots[i]);
totalPairsOfBoots += matchingPairs;
freqLeftBoots[i] -= matchingPairs;
freqRightBoots[i] -= matchingPairs;
addPairsOfBoots(i, i, matchingPairs);
remainingLeftBoots += freqLeftBoots[i];
remainingRightBoots += freqRightBoots[i];
}
int indefiniteLeftMatches = Math.min(remainingLeftBoots, freqRightBoots[26]);
int indefiniteRightMatches = Math.min(remainingRightBoots, freqLeftBoots[26]);
freqLeftBoots[26] -= indefiniteRightMatches;
freqRightBoots[26] -= indefiniteLeftMatches;
List<Integer> leftBootsRemaining = getRemainingBoots(leftBootIndexMap);
for (int i = 0; i < indefiniteLeftMatches; i++) {
int size = leftBootsRemaining.size();
int leftBootIndex = leftBootsRemaining.get(size - 1);
leftBootsRemaining.remove(size - 1);
size = rightBootIndexMap.get(26).size();
int rightBootIndex = rightBootIndexMap.get(26).get(size - 1);
rightBootIndexMap.get(26).remove(size - 1);
boots.add(new Boot(leftBootIndex, rightBootIndex));
}
List<Integer> rightBootsRemaining = getRemainingBoots(rightBootIndexMap);
for (int i = 0; i < indefiniteRightMatches; i++) {
int size = leftBootIndexMap.get(26).size();
int leftBootIndex = leftBootIndexMap.get(26).get(size - 1);
leftBootIndexMap.get(26).remove(size - 1);
size = rightBootsRemaining.size();
int rightBootIndex = rightBootsRemaining.get(size - 1);
rightBootsRemaining.remove(size - 1);
boots.add(new Boot(leftBootIndex, rightBootIndex));
}
totalPairsOfBoots += indefiniteLeftMatches + indefiniteRightMatches;
int bothIndefinite = Math.min(freqLeftBoots[26], freqRightBoots[26]);
addPairsOfBoots(26, 26, bothIndefinite);
totalPairsOfBoots += bothIndefinite;
return totalPairsOfBoots;
}
private static List<Integer> getRemainingBoots(Map<Integer, List<Integer>> bootIndexMap) {
List<Integer> remaining = new ArrayList<>();
for (int color : bootIndexMap.keySet()) {
if (color == 26) {
continue;
}
remaining.addAll(bootIndexMap.get(color));
}
return remaining;
}
private static void addPairsOfBoots(int leftColor, int rightColor, int matchingPairs) {
for (int i = 0; i < matchingPairs; i++) {
int size = leftBootIndexMap.get(leftColor).size();
int leftBootIndex = leftBootIndexMap.get(leftColor).get(size - 1);
leftBootIndexMap.get(leftColor).remove(size - 1);
size = rightBootIndexMap.get(rightColor).size();
int rightBootIndex = rightBootIndexMap.get(rightColor).get(size - 1);
rightBootIndexMap.get(rightColor).remove(size - 1);
boots.add(new Boot(leftBootIndex, rightBootIndex));
}
}
private static int[] getFreqOfBoots(char[] bootsColor, int n) {
int[] freq = new int[27];
for (int i = 0; i < n; i++) {
if (bootsColor[i] == '?') {
freq[26]++;
}else {
freq[bootsColor[i] - 'a']++;
}
}
return freq;
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
}
|
java
|
1291
|
A
|
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
|
[
"greedy",
"math",
"strings"
] |
import java.util.Scanner;
public class Ebne {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int cases = input.nextInt();
while(cases-- > 0)
{
int sze = input.nextInt();
String str = input.next();
if(sze < 2)
{
System.out.println(-1);
}
else
{
char[] temp = str.toCharArray();
String answer = "";
boolean two = false;
int counter = 0;
for (int i = 0; i < temp.length; i++) {
char c = temp[i];
int cin = Character.getNumericValue(c);
if(cin % 2 == 1)
{
answer += cin;
counter++;
if(counter >= 2)
{
two = true;
break;
}
}
}
if(two)
{
System.out.println(answer);
}
else
System.out.println(-1);
}
}
input.close();
}
}
|
java
|
1299
|
C
|
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.
|
[
"data structures",
"geometry",
"greedy"
] |
import java.util.*;
import java.io.*;
public class water_balance {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer line = new StringTokenizer(in.readLine());
int n = Integer.parseInt(line.nextToken());
int[] a = new int[n];
line = new StringTokenizer(in.readLine());
for (int i = 0; i < n; i++)
a[i] = Integer.parseInt(line.nextToken());
Stack<double[]> stack = new Stack();
for (int i = n - 1; i >= 0; i--) {
double sum = a[i];
int len = 1;
while (!stack.isEmpty()) {
double[] top = stack.peek();
if (sum / len > top[0]) {
sum += top[0] * top[1];
len += top[1];
stack.pop();
} else
break;
}
double curr = sum / len;
stack.push(new double[] { curr, len });
}
while (!stack.isEmpty()) {
double[] curr = stack.pop();
while (curr[1]-- > 0)
out.printf("%.10f\n", curr[0]);
}
out.close();
}
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
|
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 Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt(), n, m;
while(t -- > 0){
n = sc.nextInt();
m = sc.nextInt();
System.out.println(n % m == 0 || m % n == 0 ? "YES" : "NO");
}
sc.close();
}
}
|
java
|
1296
|
F
|
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1
|
[
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] |
import java.io.*;
import java.util.*;
public class Task {
public static void main(String[] args) throws Exception {
new Task().go();
}
PrintWriter out;
Reader in;
BufferedReader br;
Task() throws IOException {
try {
//br = new BufferedReader( new FileReader("input.txt") );
//in = new Reader("input.txt");
in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
}
catch (Exception e) {
//br = new BufferedReader( new InputStreamReader( System.in ) );
in = new Reader();
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
}
}
void go() throws Exception {
//int t = in.nextInt();
int t = 1;
while (t > 0) {
solve();
t--;
}
out.flush();
out.close();
}
int inf = 2000000000;
int mod = 1000000007;
double eps = 0.000000001;
int n;
int m;
ArrayList<Integer>[] g;
int[][] buity = new int[5000][5000];
void solve() throws IOException {
int n = in.nextInt();
g = new ArrayList[n];
Pair[] edges = new Pair[n - 1];
for (int i = 0; i < n; i++)
g[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
g[x].add(y);
g[y].add(x);
buity[x][y] = 1;
buity[y][x] = 1;
edges[i] = new Pair(x, y);
}
boolean ok = true;
int m = in.nextInt();
int[][] paths = new int[m][n + 1];
int[] gs = new int[m];
int[] sz = new int[m];
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
int z = in.nextInt();
gs[i] = z;
ArrayDeque<Integer> q = new ArrayDeque<>();
q.add(a);
int[] p = new int[n];
Arrays.fill(p, -1);
p[a] = a;
while (!q.isEmpty()) {
int v = q.poll();
for (int u : g[v]) {
if (p[u] == -1) {
p[u] = v;
q.add(u);
}
}
}
int pos = 1;
while (b != a) {
paths[i][pos] = b;
pos++;
int prev = b;
b = p[b];
if (buity[prev][b] < z) {
buity[prev][b] = z;
buity[b][prev] = z;
}
}
paths[i][pos] = a;
pos++;
paths[i][0] = pos;
}
for (int i = 0; i < m; i++) {
int min = 1000000;
int len = paths[i][0];
for (int j = 2; j < len; j++) {
int x = paths[i][j - 1];
int y = paths[i][j];
min = Math.min(min, buity[x][y]);
}
ok &= min == gs[i];
}
if (ok) {
for (int i = 0; i < n - 1; i++)
out.print(buity[edges[i].a][edges[i].b] + " ");
} else {
out.println(-1);
}
}
class Pair implements Comparable<Pair> {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (a != p.a)
return Integer.compare(a, p.a);
else
return Integer.compare(-b, -p.b);
}
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
static class InputReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public InputReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public InputReader(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();
}
}
}
|
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.*;
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 T = Integer.parseInt(br.readLine());
while(T-->0){
String str = br.readLine();
char[] c = str.toCharArray();
boolean[] vis = new boolean[26];
ArrayList<Character> al = new ArrayList<Character>();
boolean pos = true;
int ix = -1;
for(char ch: c){
if (vis[ch-'a']==true){
if (ix-1>=0 && al.get(ix-1)==ch){
ix--;
}else if (ix+1<al.size() && al.get(ix+1)==ch){
ix++;
}else{
pos = false;
break;
}
}
else{
if (ix+1==al.size()){
al.add(ch);
ix++;
}else if (ix==0){
al.add(0 , ch);
ix=0;
}else{
pos = false;
break;
}
vis[ch-'a'] = true;
}
if (pos==false){
break;
}
}
if(pos){
System.out.println("YES");
StringBuilder ans = new StringBuilder();
for (char ch:al){
ans.append(ch);
}
for (int i=0;i<26;i++){
if(!vis[i]){
ans.append((char)(i+'a'));
}
}
System.out.println(ans);
}else{
System.out.println("NO");
}
}
}
}
|
java
|
1307
|
A
|
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Next 2t2t lines contain a description of test cases — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100) — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.
|
[
"greedy",
"implementation"
] |
import java.util.*;
public class practice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while (t --> 0) {
int n = scan.nextInt();
int d = scan.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) arr[i] = scan.nextInt();
int i = 1;
while (d >= i && i < n) {
while (arr[i] > 0) {
arr[0]++;
arr[i]--;
d -= i;
break;
}
if (arr[i] == 0) i++;
}
System.out.println(arr[0]);
}
scan.close();
}
}
|
java
|
1299
|
A
|
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
|
[
"brute force",
"greedy",
"math"
] |
import java.util.*;
public class AnuHasAFunction {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int l = s.nextInt();
int[] arr = new int[l];
int[] cnt = new int[32];
int[] idx = new int[32];
for (int i = 0; i < l; i++) {
arr[i] = s.nextInt();
for (int j = 0; j < 32; j++) {
if ((arr[i] & (1 << j)) > 0 ) {
cnt[j]++;
idx[j] = i;
}
}
}
for (int i = 31; i >= 0; i--) {
if (cnt[i] == 1) {
int swap = arr[0];
arr[0] = arr[idx[i]];
arr[idx[i]] = swap;
break;
}
}
StringBuilder sb = new StringBuilder();
for (int i: arr)
sb.append(Integer.toString(i) + " ");
System.out.println(sb.toString());
}
}
|
java
|
1312
|
D
|
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
|
[
"combinatorics",
"math"
] |
import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static long mod = (long)998244353;
static BufferedReader br;
static HashMap<Long, Long> map;
static long d;
static long k;
static long a;
static long b;
static long t;
static long ans = Long.MAX_VALUE;
static void solve() {
long n = l();
long m = l();
if(n<=2) sb.append(0).append("\n");
else{
long v1 = ncr((int)m, (int)n-1);
long v2 = n-2;
long v3 = p(2, n-3);
long v = ((v1*v2)+mod)%mod;
v = ((v*v3)+mod)%mod;
sb.append(v).append("\n");
}
}
public static void main(String[] args) throws Exception{
sb = new StringBuilder();
br = new BufferedReader(new InputStreamReader(System.in));
int t = 1;
fact=new long[(int)1e6+10]; fact[0]=fact[1]=1;
for(int i=2;i<fact.length;i++){
fact[i]=((long)(i%mod)*(long)(fact[i-1]%mod))%mod;
}
while (t-- > 0) {
solve();
}
out.printLine(sb);
out.close();
}
//**************NCR%P******************
static long ncr(int n, int r) {
if (r > n)
return (long) 0;
long res = fact[n] % mod;
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;
return res;
}
static long p(long x, long y)// POWER FXN MODULO //
{
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;
}
// *************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);
}
}
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;
}
//*************NORMAL POWER******************************
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)));
}
// ****BINARY SEARCH****//
private static long bins(long arr[], long tar) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] > tar) high = mid - 1;
else if (arr[mid] < tar) low = mid + 1;
else return mid;;
}
return -1;
}
// ********COUNTER******//
private static void count(long arr[]) {
map = new HashMap();
for (long val : arr) map.put(val, map.getOrDefault(val, 0l) + 1l);
}
//INPUT PATTERN********************************************************
public static int i() {
return in.Int();
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static String s() {
return in.String();
}
public static int[] readArrayi(int n) {
int A[] = new int[n];
for (int i = 0; i < n; i++) {
A[i] = i();
}
return A;
}
public static long[] readArray(long n) {
long A[] = new long[(int) n];
for (int i = 0; i < n; i++) {
A[i] = l();
}
return A;
}
}
|
java
|
1324
|
F
|
F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.
|
[
"dfs and similar",
"dp",
"graphs",
"trees"
] |
import java.io.*;
import java.util.*;
public class MaximumWhiteSubtree {
static int[] result;
static int[] dp;
static List<List<Integer>> G;
static int[] A;
public static void dfs1(int cur, int par) {
dp[cur] = A[cur];
for (int nxt : G.get(cur)) {
if (nxt != par) {
dfs1(nxt, cur);
dp[cur] += Math.max(0, dp[nxt]);
}
}
}
public static void dfs2(int cur, int par) {
result[cur] = dp[cur];
for (int nxt : G.get(cur)) {
if (nxt != par) {
dp[cur] -= Math.max(0, dp[nxt]);
dp[nxt] += Math.max(0, dp[cur]);
dfs2(nxt, cur);
dp[nxt] -= Math.max(0, dp[cur]);
dp[cur] += Math.max(0, dp[nxt]);
}
}
}
public static void main(String[] args) {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out, false);
int N = reader.nextInt();
A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = reader.nextInt();
if (A[i] == 0) A[i] = -1;
}
G = new ArrayList<>(N);
for (int i = 0; i < N; i++) {
G.add(new ArrayList<>());
}
for (int i = 0; i < N - 1; i++) {
int u = reader.nextInt() - 1;
int v = reader.nextInt() - 1;
G.get(u).add(v);
G.get(v).add(u);
}
dp = new int[N];
result = new int[N];
dfs1(0, -1);
dfs2(0, -1);
for (int i = 0; i < N; i++) {
writer.print(result[i] + " ");
}
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
|
1312
|
C
|
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.
|
[
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] |
import java.io.*;
import java.lang.*;
import java.util.*;
public class ComdeFormces {
static int x[]= {0,-1,1,1,1,1,-1,-1};
static int y[]= {-1,0,0,0,1,-1,1,-1};
// static int dp[][][];
static int seg[];
static int E;
static class Trie{
Trie a[];
int ind;
public Trie() {
this.a=new Trie[3];
this.ind=-1;
}
}
static long ncr[][];
static int cst;
static HashMap<Integer,Integer> hm;
static int dp[][];
static ArrayList<Integer> tp;
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
FastReader sc=new FastReader();
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
// OutputStream out = new BufferedOutputStream ( System.out );
int t=sc.nextInt();
int tc=1;
// InverseofNumber(m);
// InverseofFactorial(m);
// factorial(m);
//
while(t--!=0) {
int n=sc.nextInt();
int k=sc.nextInt();
long a[]=new long[n];
for(int i=0;i<n;i++)a[i]=sc.nextLong();
int pw[]=new int[70];
boolean ans=true;
for(int i=0;i<n;i++) {
if(a[i]>0) {
long p=1;
int ptr=0;
while(p*k<=a[i]) {
p*=k;
ptr++;
}
long num=a[i];
while(num!=0) {
long dv=num/p;
if(dv>1) {
ans=false;
break;
}
else if(dv==1) {
if(pw[ptr]>0) {
ans=false;
break;
}
pw[ptr]++;
num-=dv*p;
}
p/=k;
ptr--;
}
}
}
log.write((ans?"YES":"NO")+"\n");
log.flush();
}
}
static int N = 1000001;
// Array to store inverse of 1 to N
static long[] factorialNumInverse = new long[N + 1];
// Array to precompute inverse of 1! to N!
static long[] naturalNumInverse = new long[N + 1];
// Array to store factorial of first N numbers
static long[] fact = new long[N + 1];
// Function to precompute inverse of numbers
public static void InverseofNumber(int p)
{
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i <= N; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] *
(long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
public static void InverseofFactorial(int p)
{
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// Precompute inverse of natural numbers
for(int i = 2; i <= N; i++)
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p;
}
// Function to calculate factorial of 1 to N
public static void factorial(int p)
{
fact[0] = 1;
// Precompute factorials
for(int i = 1; i <= N; i++)
{
fact[i] = (fact[i - 1] * (long)i) % p;
}
}
// Function to return nCr % p in O(1) time
public static long Binomial(int N, int R, int p)
{
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) %
p * factorialNumInverse[N - R]) % p;
return ans;
}
public static int m=(int)(998244353);
public static int mul(int a, int b) {
return ((a%m)*(b%m))%m;
}
public static long mul(long a, long b) {
return ((a%m)*(b%m))%m;
}
public static int add(int a, int b) {
return ((a%m)+(b%m))%m;
}
public static long add(long a, long b) {
return ((a%m)+(b%m))%m;
}
public static long sub(long a,long b) {
return ((a%m)-(b%m)+m)%m;
}
static long gcd(long a,long b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static int gcd(int a,int b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static long ncr(int n, int r){
if(r>n-r)r=n-r;
long ans=1;
long m=(int)(1e9+7);
for(int i=0;i<r;i++){
ans=ans*(n-i);
ans/=i+1;
}
return ans;
}
public static class num{
long v;
}
static long gcd(long a,long b,num x,num y) {
if(b==0) {
x.v=1;
y.v=0;
return a;
}
num x1=new num();
num y1=new num();
long ans=gcd(b,a%b,x1,y1);
x.v=y1.v;
y.v=x1.v-(a/b)*y1.v;
return ans;
}
static long inverse(long b,long m) {
num x=new num();
num y=new num();
long gc=gcd(b,m,x,y);
if(gc!=1) {
return -1;
}
return (x.v%m+m)%m;
}
static long div(long a,long b,long m) {
a%=m;
if(inverse(b,m)==-1)return a/b;
return (inverse(b,m)*a)%m;
}
public static class trip{
int a;
int b;
long c;
int d;
public trip(int a,int b,long c,int d) {
this.a=a;
this.b=b;
this.c=c;
this.d=d;
}
}
static void mergesort(int[] a,int start,int end) {
if(start>=end)return ;
int mid=start+(end-start)/2;
mergesort(a,start,mid);
mergesort(a,mid+1,end);
merge(a,start,mid,end);
}
static void merge(int[] a, int start,int mid,int end) {
int ptr1=start;
int ptr2=mid+1;
int b[]=new int[end-start+1];
int i=0;
while(ptr1<=mid && ptr2<=end) {
if(a[ptr1]<=a[ptr2]) {
b[i]=a[ptr1];
ptr1++;
i++;
}
else {
b[i]=a[ptr2];
ptr2++;
i++;
}
}
while(ptr1<=mid) {
b[i]=a[ptr1];
ptr1++;
i++;
}
while(ptr2<=end) {
b[i]=a[ptr2];
ptr2++;
i++;
}
for(int j=start;j<=end;j++) {
a[j]=b[j-start];
}
}
public static class FastReader {
BufferedReader b;
StringTokenizer s;
public FastReader() {
b=new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(s==null ||!s.hasMoreElements()) {
try {
s=new StringTokenizer(b.readLine());
}
catch(IOException e) {
e.printStackTrace();
}
}
return s.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str="";
try {
str=b.readLine();
}
catch(IOException e) {
e.printStackTrace();
}
return str;
}
boolean hasNext() {
if (s != null && s.hasMoreTokens()) {
return true;
}
String tmp;
try {
b.mark(1000);
tmp = b.readLine();
if (tmp == null) {
return false;
}
b.reset();
} catch (IOException e) {
return false;
}
return true;
}
}
public static class pair{
int a;
int b;
public pair(int a,int b) {
this.a=a;
this.b=b;
}
@Override
public String toString() {
return "{"+this.a+" "+this.b+"}";
}
}
static long pow(long a, long pw) {
long temp;
if(pw==0)return 1;
temp=pow(a,pw/2);
if(pw%2==0)return mul(temp,temp);
return mul(a,mul(temp,temp));
}
public static int md=998244353;
static int pow(int a, int pw) {
int temp;
if(pw==0)return 1;
temp=pow(a,pw/2);
if(pw%2==0)return temp*temp;
return a*temp*temp;
}
}
|
java
|
1141
|
G
|
G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1
|
[
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] |
import java.util.*;
import java.lang.*;
import java.io.*;
import java.awt.*;
// U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................
//JUst keep faith in ur strengths ..................................................
// ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219
// odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4
// FOR ANY ODD NO N : N,N-1,N-2
//ALL ARE PAIRWISE COPRIME
//THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS
// two consecutive odds are always coprime to each other
// two consecutive even have always gcd = 2 ;
// Rectangle r = new Rectangle(int x , int y,int widht,int height)
//Creates a rect. with bottom left cordinates as (x, y) and top right as ((x+width),(y+height))
//BY DEFAULT Priority Queue is MIN in nature in java
//to use as max , just push with negative sign and change sign after removal
// We can make a sieve of max size 1e7 .(no time or space issue)
// In 1e7 starting nos we have about 66*1e4 prime nos
public class Main
{
// static int[] arr = new int[100002] ;
// static int[] dp = new int[100002] ;
static PrintWriter out;
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}
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 int countDigit(long n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
/////////////////////////////////////////////////////////////////////////////////////////
public static int sumOfDigits(long n)
{
if( n< 0)return -1 ;
int sum = 0;
while( n > 0)
{
sum = sum + (int)( n %10) ;
n /= 10 ;
}
return sum ;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long arraySum(int[] arr , int start , int end)
{
long ans = 0 ;
for(int i = start ; i <= end ; i++)ans += arr[i] ;
return ans ;
}
/////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public static void swapArray(int[] arr , int start , int end)
{
while(start < end)
{
int temp = arr[start] ;
arr[start] = arr[end];
arr[end] = temp;
start++ ;end-- ;
}
}
//////////////////////////////////////////////////////////////////////////////////
static long factorial(long a)
{
if(a== 0L || a==1L)return 1L ;
return a*factorial(a-1L) ;
}
///////////////////////////////////////////////////////////////////////////////
public static int[][] rotate(int[][] input){
int n =input.length;
int m = input[0].length ;
int[][] output = new int [m][n];
for (int i=0; i<n; i++)
for (int j=0;j<m; j++)
output [j][n-1-i] = input[i][j];
return output;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// ////////////////////////////////////////////////
public static boolean isPowerOfTwo(long n)
{
if(n==0)
return false;
if(((n ) & (n-1)) == 0 ) return true ;
else return false ;
}
/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
public static String reverse(String input)
{
StringBuilder str = new StringBuilder("") ;
for(int i =input.length()-1 ; i >= 0 ; i-- )
{
str.append(input.charAt(i));
}
return str.toString() ;
}
///////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
public static boolean isPossibleTriangle(int a ,int b , int c)
{
if( a + b > c && c+b > a && a +c > b)return true ;
else return false ;
}
////////////////////////////////////////////////////////////////////////////////////////////
static long xnor(long num1, long num2) {
if (num1 < num2) {
long temp = num1;
num1 = num2;
num2 = temp;
}
num1 = togglebit(num1);
return num1 ^ num2;
}
static long togglebit(long n) {
if (n == 0)
return 1;
long i = n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return i ^ n;
}
///////////////////////////////////////////////////////////////////////////////////////////////
public static int xorOfFirstN(int n)
{
if( n % 4 ==0)return n ;
else if( n % 4 == 1)return 1 ;
else if( n % 4 == 2)return n+1 ;
else return 0 ;
}
//////////////////////////////////////////////////////////////////////////////////////////////
public static int gcd(int a, int b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
public static long gcd(long a, long b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c , int d )
{
int temp = lcm(a,b , c) ;
int ans = lcm(temp ,d ) ;
return ans ;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a, int b ,int c )
{
int temp = lcm(a,b) ;
int ans = lcm(temp ,c) ;
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////
public static int lcm(int a , int b )
{
int gc = gcd(a,b);
return (a/gc)*b ;
}
public static long lcm(long a , long b )
{
long gc = gcd(a,b);
return (a/gc)*b;
}
///////////////////////////////////////////////////////////////////////////////////////////
static boolean isPrime(long n)
{
if(n==1)
{
return false ;
}
boolean ans = true ;
for(long i = 2L; i*i <= n ;i++)
{
if(n% i ==0)
{
ans = false ;break ;
}
}
return ans ;
}
static boolean isPrime(int n)
{
if(n==1)
{
return false ;
}
boolean ans = true ;
for(int i = 2; i*i <= n ;i++)
{
if(n% i ==0)
{
ans = false ;break ;
}
}
return ans ;
}
///////////////////////////////////////////////////////////////////////////
static int sieve = 1000000 ;
static boolean[] prime = new boolean[sieve + 1] ;
public static void sieveOfEratosthenes()
{
// FALSE == prime
// TRUE == COMPOSITE
// FALSE== 1
// time complexity = 0(NlogLogN)== o(N)
// gives prime nos bw 1 to N
for(int i = 4; i<= sieve ; i++)
{
prime[i] = true ;
i++ ;
}
for(int p = 3; p*p <= sieve; p++)
{
if(prime[p] == false)
{
for(int i = p*p; i <= sieve; i += p)
prime[i] = true;
}
p++ ;
}
}
///////////////////////////////////////////////////////////////////////////////////
public static void sortD(int[] arr , int s , int e)
{
sort(arr ,s , e) ;
int i =s ; int j = e ;
while( i < j)
{
int temp = arr[i] ;
arr[i] =arr[j] ;
arr[j] = temp ;
i++ ; j-- ;
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long countSubarraysSumToK(long[] arr ,long sum )
{
HashMap<Long,Long> map = new HashMap<>() ;
int n = arr.length ;
long prefixsum = 0 ;
long count = 0L ;
for(int i = 0; i < n ; i++)
{
prefixsum = prefixsum + arr[i] ;
if(sum == prefixsum)count = count+1 ;
if(map.containsKey(prefixsum -sum))
{
count = count + map.get(prefixsum -sum) ;
}
if(map.containsKey(prefixsum ))
{
map.put(prefixsum , map.get(prefixsum) +1 );
}
else{
map.put(prefixsum , 1L );
}
}
return count ;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// KMP ALGORITHM : TIME COMPL:O(N+M)
// FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING
//RETURN THE ARRAYLIST OF INDEXES
// IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING
public static ArrayList<Integer> kmpAlgorithm(String str , String pat)
{
ArrayList<Integer> list =new ArrayList<>();
int n = str.length() ;
int m = pat.length() ;
String q = pat + "#" + str ;
int[] lps =new int[n+m+1] ;
longestPefixSuffix(lps, q,(n+m+1)) ;
for(int i =m+1 ; i < (n+m+1) ; i++ )
{
if(lps[i] == m)
{
list.add(i-2*m) ;
}
}
return list ;
}
public static void longestPefixSuffix(int[] lps ,String str , int n)
{
lps[0] = 0 ;
for(int i = 1 ; i<= n-1; i++)
{
int l = lps[i-1] ;
while( l > 0 && str.charAt(i) != str.charAt(l))
{
l = lps[l-1] ;
}
if(str.charAt(i) == str.charAt(l))
{
l++ ;
}
lps[i] = l ;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n
// TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1
// or n and the no will be coprime in nature
//time : O(n*(log(logn)))
public static void eulerTotientFunction(int[] arr ,int n )
{
for(int i = 1; i <= n ;i++)arr[i] =i ;
for(int i= 2 ; i<= n ;i++)
{
if(arr[i] == i)
{
arr[i] =i-1 ;
for(int j =2*i ; j<= n ; j+= i )
{
arr[j] = (arr[j]*(i-1))/i ;
}
}
}
return ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long nCr(int n,int k)
{
long ans=1L;
k=k>n-k?n-k:k;
int j=1;
for(;j<=k;j++,n--)
{
if(n%j==0)
{
ans*=n/j;
}else
if(ans%j==0)
{
ans=ans/j*n;
}else
{
ans=(ans*n)/j;
}
}
return ans;
}
///////////////////////////////////////////////////////////////////////////////////////////
public static ArrayList<Integer> allFactors(int n)
{
ArrayList<Integer> list = new ArrayList<>() ;
for(int i = 1; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
public static ArrayList<Long> allFactors(long n)
{
ArrayList<Long> list = new ArrayList<>() ;
for(long i = 1L; i*i <= n ;i++)
{
if( n % i == 0)
{
if(i*i == n)
{
list.add(i) ;
}
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static final int MAXN = 1000001;
static int spf[] = new int[MAXN];
static void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
spf[i] = i;
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
if (spf[i] == i)
{
for (int j=i*i; j<MAXN; j+=i)
if (spf[j]==j)
spf[j] = i;
}
}
}
static ArrayList<Integer> getPrimeFactorization(int x)
{
ArrayList<Integer> ret = new ArrayList<Integer>();
while (x != 1)
{
ret.add(spf[x]);
x = x / spf[x];
}
return ret;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
public static void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void sort(long arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
public static void merge(long arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
//Copy data to temp arrays
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
public static long knapsack(int[] weight,long value[],int maxWeight){
int n= value.length ;
//dp[i] stores the profit with KnapSack capacity "i"
long []dp = new long[maxWeight+1];
//initially profit with 0 to W KnapSack capacity is 0
Arrays.fill(dp, 0);
// iterate through all items
for(int i=0; i < n; i++)
//traverse dp array from right to left
for(int j = maxWeight; j >= weight[i]; j--)
dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]);
/*above line finds out maximum of dp[j](excluding ith element value)
and val[i] + dp[j-wt[i]] (including ith element value and the
profit with "KnapSack capacity - ith element weight") */
return dp[maxWeight];
}
///////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
// to return max sum of any subarray in given array
public static long kadanesAlgorithm(long[] arr)
{
if(arr.length == 0)return 0 ;
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
/////////////////////////////////////////////////////////////////////////////////////////////
public static long kadanesAlgorithm(int[] arr)
{
if(arr.length == 0)return 0 ;
long[] dp = new long[arr.length] ;
dp[0] = arr[0] ;
long max = dp[0] ;
for(int i = 1; i < arr.length ; i++)
{
if(dp[i-1] > 0)
{
dp[i] = dp[i-1] + arr[i] ;
}
else{
dp[i] = arr[i] ;
}
if(dp[i] > max)max = dp[i] ;
}
return max ;
}
///////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
//TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING
// JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive
//Function for swapping the characters at position I with character at position j
public static String swapString(String a, int i, int j) {
char[] b =a.toCharArray();
char ch;
ch = b[i];
b[i] = b[j];
b[j] = ch;
return String.valueOf(b);
}
//Function for generating different permutations of the string
public static void generatePermutation(String str, int start, int end)
{
//Prints the permutations
if (start == end-1)
System.out.println(str);
else
{
for (int i = start; i < end; i++)
{
//Swapping the string by fixing a character
str = swapString(str,start,i);
//Recursively calling function generatePermutation() for rest of the characters
generatePermutation(str,start+1,end);
//Backtracking and swapping the characters again.
str = swapString(str,start,i);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
public static long factMod(long n, long mod) {
if (n <= 1) return 1;
long ans = 1;
for (int i = 1; i <= n; i++) {
ans = (ans * i) % mod;
}
return ans;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
public static long power(int a ,int b)
{
//time comp : o(logn)
long x = (long)(a) ;
long n = (long)(b) ;
if(n==0)return 1 ;
if(n==1)return x;
long ans =1L ;
while(n>0)
{
if(n % 2 ==1)
{
ans = ans *x ;
}
n = n/2L ;
x = x*x ;
}
return ans ;
}
public static long power(long a ,long b)
{
//time comp : o(logn)
long x = (a) ;
long n = (b) ;
if(n==0)return 1L ;
if(n==1)return x;
long ans =1L ;
while(n>0)
{
if(n % 2 ==1)
{
ans = ans *x ;
}
n = n/2L ;
x = x*x ;
}
return ans ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public static long powerMod(long x, long n, long mod) {
//time comp : o(logn)
if(n==0)return 1L ;
if(n==1)return x;
long ans = 1;
while (n > 0) {
if (n % 2 == 1) ans = (ans * x) % mod;
x = (x * x) % mod;
n /= 2;
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/*
lowerBound - finds largest element equal or less than value paased
upperBound - finds smallest element equal or more than value passed
if not present return -1;
*/
public static long lowerBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static int lowerBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]<=k)
{
ans=arr[mid];
start=mid+1;
}
else
{
end=mid-1;
}
}
return ans;
}
public static long upperBound(long[] arr,long k)
{
long ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
public static int upperBound(int[] arr,int k)
{
int ans=-1;
int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]>=k)
{
ans=arr[mid];
end=mid-1;
}
else
{
start=mid+1;
}
}
return ans;
}
//////////////////////////////////////////////////////////////////////////////////////////
public static void printArray(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printArrayln(int[] arr , int si ,int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printLArray(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
}
public static void printLArrayln(long[] arr , int si , int ei)
{
for(int i = si ; i <= ei ; i++)
{
out.print(arr[i] +" ") ;
}
out.println() ;
}
public static void printtwodArray(int[][] ans)
{
for(int i = 0; i< ans.length ; i++)
{
for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" ");
out.println() ;
}
out.println() ;
}
static long modPow(long a, long x, long p) {
//calculates a^x mod p in logarithmic time.
a = a % p ;
if(a == 0)return 0L ;
long res = 1L;
while(x > 0) {
if( x % 2 != 0) {
res = (res * a) % p;
}
a = (a * a) % p;
x =x/2;
}
return res;
}
static long modInverse(long a, long p) {
//calculates the modular multiplicative of a mod p.
//(assuming p is prime).
return modPow(a, p-2, p);
}
static long[] factorial = new long[1000001] ;
static void modfac(long mod)
{
factorial[0]=1L ; factorial[1]=1L ;
for(int i = 2; i<= 1000000 ;i++)
{
factorial[i] = factorial[i-1] *(long)(i) ;
factorial[i] = factorial[i] % mod ;
}
}
static long modBinomial(long n, long r, long p) {
// calculates C(n,r) mod p (assuming p is prime).
if(n < r) return 0L ;
long num = factorial[(int)(n)] ;
long den = (factorial[(int)(r)]*factorial[(int)(n-r)]) % p ;
long ans = num*(modInverse(den,p)) ;
ans = ans % p ;
return ans ;
}
static void update(int val , long[] bit ,int n)
{
for( ; val <= n ; val += (val &(-val)) )
{
bit[val]++ ;
}
}
static long query(int val , long[] bit , int n)
{
long ans = 0L;
for( ; val >=1 ; val-=(val&(-val)) )ans += bit[val];
return ans ;
}
static int countSetBits(long n)
{
int count = 0;
while (n > 0) {
n = (n) & (n - 1L);
count++;
}
return count;
}
static int abs(int x)
{
if(x < 0)x = -1*x ;
return x ;
}
static long abs(long x)
{
if(x < 0)x = -1L*x ;
return x ;
}
////////////////////////////////////////////////////////////////////////////////////////////////
static void p(int val)
{
out.print(val) ;
}
static void p()
{
out.print(" ") ;
}
static void pln(int val)
{
out.println(val) ;
}
static void pln()
{
out.println() ;
}
static void p(long val)
{
out.print(val) ;
}
static void pln(long val)
{
out.println(val) ;
}
static void yes()
{
out.println("YES") ;
}
static void no()
{
out.println("NO") ;
}
////////////////////////////////////////////////////////////////////////////////////////////
// calculate total no of nos greater than or equal to key in sorted array arr
static int bs(int[] arr, int s ,int e ,int key)
{
if( s> e)return 0 ;
int mid = (s+e)/2 ;
if(arr[mid] <key)
{
return bs(arr ,mid+1,e , key) ;
}
else{
return bs(arr ,s ,mid-1, key) + e-mid+1;
}
}
// static ArrayList<Integer>[] adj ;
// static int mod= 1000000007 ;
static ArrayList<Pair> adj[] ;
static int[] col ;
static void dfs(int curr , int max , int p , int colp)
{
int color = 1 ;
for(Pair a : adj[curr])
{
int v = a.first ; int index = a.second ;
if(v== p)continue ;
if(color == colp)
{
color++ ;
}
if(color > max)color = 1 ;
col[index] = color ;
dfs(v,max,curr,color) ;
color++ ;
if(color > max)color = 1;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
public static void solve()
{
FastReader scn = new FastReader() ;
//Scanner scn = new Scanner(System.in);
//int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ;
// product of first 11 prime nos is greater than 10 ^ 12;
//sieve() ;
//ArrayList<Integer> arr[] = new ArrayList[n] ;
ArrayList<Integer> list = new ArrayList<>() ;
ArrayList<Long> lista = new ArrayList<>() ;
ArrayList<Long> listb = new ArrayList<>() ;
// ArrayList<Integer> lista = new ArrayList<>() ;
// ArrayList<Integer> listb = new ArrayList<>() ;
//ArrayList<String> lists = new ArrayList<>() ;
HashMap<Integer,Integer> map = new HashMap<>() ;
//HashMap<Long,Long> map = new HashMap<>() ;
HashMap<Integer,Integer> mapx = new HashMap<>() ;
HashMap<Integer,Integer> mapy = new HashMap<>() ;
//HashMap<String,Integer> maps = new HashMap<>() ;
//HashMap<Integer,Boolean> mapb = new HashMap<>() ;
//HashMap<Point,Integer> point = new HashMap<>() ;
Set<Integer> set = new HashSet<>() ;
Set<Integer> setx = new HashSet<>() ;
Set<Integer> sety = new HashSet<>() ;
StringBuilder sb =new StringBuilder("") ;
//Collections.sort(list);
//if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ;
//else map.put(arr[i],1) ;
// if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ;
// else map.put(temp,1) ;
//int bit =Integer.bitCount(n);
// gives total no of set bits in n;
// Arrays.sort(arr, new Comparator<Pair>() {
// @Override
// public int compare(Pair a, Pair b) {
// if (a.first != b.first) {
// return a.first - b.first; // for increasing order of first
// }
// return a.second - b.second ; //if first is same then sort on second basis
// }
// });
int testcase = 1;
//testcase = scn.nextInt() ;
for(int testcases =1 ; testcases <= testcase ;testcases++)
{
//if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ;
//if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ;
//adj = new ArrayList[n] ;
// for(int i = 0; i< n; i++)
// {
// adj[i] = new ArrayList<Integer>();
// }
// long n = scn.nextLong() ;
//String s = scn.next() ;
int n= scn.nextInt() ;int k = scn.nextInt() ;
int[] deg= new int[n] ;
int[] temp = new int[n] ;col = new int[n] ;
adj = new ArrayList[n] ;
for(int i = 0 ; i< n ;i++)
{
adj[i] = new ArrayList<Pair>() ;
}
for(int i=0; i <= n-2;i++)
{
int u = scn.nextInt()-1 ; int v = scn.nextInt()-1 ;
temp[u]++ ;temp[v]++ ;
adj[u].add(new Pair(v,i)) ;
adj[v].add(new Pair(u,i)) ;
}
sort(temp,0,n-1) ;
pln(temp[n-k-1]) ;
dfs(0,temp[n-k-1],-1,-1) ;
for(int i = 0; i <= n-2 ;i++)
{
out.print(col[i]+" ");
}
out.println() ;
//out.println(ans) ;
//out.println(ans+" "+in) ;
//out.println("Case #" + testcases + ": " + ans ) ;
//out.println("@") ;
set.clear() ;
sb.delete(0 , sb.length()) ;
list.clear() ;lista.clear() ;listb.clear() ;
map.clear() ;
mapx.clear() ;
mapy.clear() ;
setx.clear() ;sety.clear() ;
} // test case end loop
out.flush() ;
} // solve fn ends
public static void main (String[] args) throws java.lang.Exception
{
solve() ;
}
}
class Pair
{
int first ;
int second ;
public Pair(int f ,int s)
{
this.first = f ;
this.second = s ;
}
@Override
public String toString() {
String ans = "" ;
ans += this.first ;
ans += " ";
ans += this.second ;
return ans ;
}
}
|
java
|
1303
|
A
|
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
|
[
"implementation",
"strings"
] |
import java.util.*;
import java.io.*;
// import static java.lang.Math.max;
//import static java.lang.Math.min;
// import static java.lang.Math.abs;
public class A_Erasing_Zeroes {
static PrintWriter out;
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
out = new PrintWriter(System.out);
int tcas = in.nextInt();
while (tcas-- > 0) {
String s = in.next();
int res =0;
int c0=0;
int c1=0;
int clz =0;
int k =0;
if(s.charAt(0)=='0')
while(s.charAt(k++)!='1'&& k<s.length()){
clz++;
}
dbg(clz);
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)=='0'){
c0++;
}
else if(s.charAt(i)=='1' && c0>0){
res+=c0;
c0=0;
}
}
if(res>0)
out.println(res-clz);
else{
out.println(0);
}
}
in.close();
out.close();
}
static long[] readLongArray(int n){
long b[] = new long[n];
for (int i = 0; i < n; i++) {
b[i]= in.nextLong();
}
return b;
}
static int[] readIntArray(int n){
int b[] = new int[n];
for (int i = 0; i < n; i++) {
b[i]= in.nextInt();
}
return b;
}
}
|
java
|
1286
|
C1
|
C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4
a
aa
a
cb
b
c
cOutputCopy? 1 2
? 3 4
? 4 4
! aabc
|
[
"brute force",
"constructive algorithms",
"interactive",
"math"
] |
//package com.company;
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
public static class Task {
String sor(String s) {
char[] cc = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
cc[i] = s.charAt(i);
}
Arrays.sort(cc);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cc.length; i++) {
sb.append(cc[i]);
}
return sb.toString();
}
public void solve(Scanner sc) throws IOException {
int n = sc.nextInt();
System.out.println("? 1 " + n);
System.out.flush();
Map<String, Integer> mp = new HashMap<>();
for (int i = 0; i < n * (n + 1) / 2; i++) {
String s = sc.next();
s = sor(s);
mp.put(s, mp.getOrDefault(s, 0) + 1);
}
if (n == 1) {
for (String s: mp.keySet()) {
System.out.println("! " + s);
return;
}
}
System.out.println("? 2 " + n);
System.out.flush();
for (int i = 0; i < n * (n - 1) / 2; i++) {
String s = sc.next();
s = sor(s);
mp.put(s, mp.get(s) - 1);
}
List<String> ss = new ArrayList<>();
for (Map.Entry<String, Integer> en: mp.entrySet()) {
if (en.getValue() == 1) {
ss.add(en.getKey());
}
}
StringBuilder sol = new StringBuilder();
int[] con = new int[255];
Collections.sort(ss, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
for (int i = 0; i < ss.size(); i++) {
for (int j = 0; j < ss.get(i).length(); j++) {
con[ss.get(i).charAt(j)]--;
}
for (int j = 0; j < 255; j++) {
if (con[j] < 0) sol.append((char) j);
}
Arrays.fill(con, 0);
for (int j = 0; j < ss.get(i).length(); j++) {
con[ss.get(i).charAt(j)]++;
}
}
System.out.println("! " + sol.toString());
}
}
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("nondec.in"));
// PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
// PrintWriter pw = new PrintWriter(new FileOutputStream("nondec.out"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
// pw.close();
System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);
System.err.println("Time used: " + (TIME_END - TIME_START) + ".");
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
|
java
|
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.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DEhabTheXorcist solver = new DEhabTheXorcist();
solver.solve(1, in, out);
out.close();
}
static class DEhabTheXorcist {
public void solve(int testNumber, InputReader in, OutputWriter out) {
long u = in.nextLong();
long v = in.nextLong();
if (u > v || u % 2 != v % 2) {
out.println(-1);
return;
}
if (u == v && u == 0) {
out.println(0);
return;
}
if (u == v) {
out.println(1);
out.println(u);
return;
}
long t = (v - u) / 2;
if ((u & t) == 0) {
out.println(2);
out.print(u + t);
} else {
out.println(3);
out.print(u);
out.print(" " + t);
}
out.println(" " + t);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public 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 println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void print(long i) {
writer.print(i);
}
public void println(long i) {
writer.println(i);
}
public void println(int i) {
writer.println(i);
}
}
}
|
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.util.stream.Collectors;
public class ObtainTheString {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
outer:
while(t-->0) {
String s=sc.next();
Set<Character> foo= s.chars().mapToObj(e->(char)e).collect(Collectors.toSet());
String ss=sc.next();
if(s.equals(ss)) {
System.out.println(1);
continue outer;
}
for(int i=0;i<ss.length();i++) {
if(!foo.contains(ss.charAt(i))) {
System.out.println(-1);
continue outer;
}
}
int n=s.length();
int arr[][]=new int[n][26];
for(int i=n-1;i>0;i--) {
arr[i-1][s.charAt(i)-'a']=i;
for(int j=0;j<26;j++) {
if(arr[i-1][j]==0) {
arr[i-1][j]=arr[i][j];
}
}
}
if(n>1) {
for(int j=1;j<26;j++) {
if(arr[0][j]==0) {
arr[0][j]=arr[1][j];
}
}
}
else {
System.out.println(ss.length());
continue outer;
}
int k=0,count=0,i=0;
if(s.charAt(0)==ss.charAt(0)) {
i++;
}
for(;i<ss.length();i++) {
if(arr[k][ss.charAt(i)-'a']!=0) {
k=arr[k][ss.charAt(i)-'a'];
}
else if(s.charAt(0)==ss.charAt(i)) {
k=0;
count++;
}
else {
// System.out.println(ss.charAt(i));
k=0;
count++;
i--;
}
}
// System.out.println(Arrays.deepToString(arr));
System.out.println(count+1);
}
}
}
|
java
|
1304
|
A
|
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
|
[
"math"
] |
import java.util.*;
public class hopping{
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t-- > 0){
long x = scan.nextLong();
long y = scan.nextLong();
long a = scan.nextLong();
long b = scan.nextLong();
long i = y-x;
long j = a+b;
System.out.println(i%j > 0 ? -1 : i/j);
}
}
}
|
java
|
1284
|
A
|
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
|
[
"implementation",
"strings"
] |
import java.util.*;
import java.io.*;
// @author : sam45jh
public class Main{
/* declare some global variables */
static FastReader scn;
static FastWriter out;
static int imax = Integer.MAX_VALUE;
static int imin = Integer.MIN_VALUE;
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 {
BufferedWriter bw;
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
FastWriter() {
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
<T> void print(T obj) throws IOException {
bw.write(obj.toString());
bw.flush();
}
void println() throws IOException {
print("\n");
}
<T> void println(T obj) throws IOException {
print(obj.toString() + "\n");
}
void print(int[] arr) throws IOException {
for (int x : arr) {
print(x + " ");
}
println();
}
void print(long[] arr) throws IOException {
for (long x : arr) {
print(x + " ");
}
println();
}
void print(boolean[] arr) throws IOException{
for(boolean x:arr)
print(x+" ");
}
void print(double[] arr) throws IOException {
for (double x : arr) {
print(x + " ");
}
println();
}
void print(float[] nums) throws IOException{
for(float x: nums){
print(x+" ");
}
println();
}
void printCharN(char c, int n) throws IOException {
for (int i = 0; i < n; i++) {
print(c);
}
}
}
/* print functions for primitives */
private static void print(int s) throws IOException {
out.println(s);
}
private static void print(long s) throws IOException {
out.println(s);
}
private static void print(boolean s) throws IOException{
out.println(s);
}
private static void print(double s) throws IOException {
out.println(s);
}
private static void print(String s) throws IOException{
out.println(s);
}
private static void print(float s) throws IOException{
out.println(s);
}
/* Disclaimer */
// note that if you want to use a function than uase IOException;
// public static void call() throws IOException{
// print(10+"Abhishek Jha");
// }
/* Main function */
public static void main(String[] hi) throws IOException{
scn = new FastReader();
out = new FastWriter();
// String[] s = scn.nextLine().trim().split(" ");
int n = scn.nextInt();
int m = scn.nextInt();
String[] s = scn.nextLine().trim().split(" ");
String[] t = scn.nextLine().trim().split(" ");
int tws = scn.nextInt();
while(tws--!=0){
int yr = scn.nextInt();
int x = yr%(s.length);
int y = yr%(t.length);
if(x == 0)
x=s.length;
if(y==0)
y=t.length;
print(s[x-1].concat(t[y-1]));
}
}
/* sorting an array in nlogn time */
public static void sort(int[] nums){
ArrayList<Integer> vals = new ArrayList<>();
for(int i=0;i<nums.length;i++){
vals.add(nums[i]);
}
Collections.sort(vals);
for(int i=0;i<vals.size();i++){
nums[i]=vals.get(i);
}
}
// the reason I didnt use arrays.sort(nums) is that it uses quick sort and
// that has a TC of n2 in worst case. However, Collections sort uses merge sort
// which is always nlogn even in worst case.
}
|
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 Solution {
public static long gcd(long a,long b) {
if(a==0) return b;
return gcd(b%a,a);
}
public static long lcm(long a,long b) {
return (a*b)/gcd(a,b);
}
public static long [] input(BufferedReader br,int n) throws java.lang.Exception{
long ans[]=new long[n];
String input[]=br.readLine().split(" ");
for(int i=0;i<n;i++) {
ans[i]=Long.parseLong(input[i]);
}
return ans;
}
static class FenWick{
long tree[];
int n;
public FenWick(int n) {
tree=new long[n];
this.n=n;
}
public void add(int idx,long x) {
while(idx<n) {
tree[idx]+=x;
idx+=(idx&-idx);
}
}
public long sum(int idx) {
long sum=0;
while(idx>0) {
sum=sum+tree[idx];
idx-=(idx&(-idx));
}
return sum;
}
}
public static long[] compress(long s[]) {
List<Long>list=new ArrayList<>();
for(long a:s) list.add(a);
Collections.sort(list);
HashMap<Long,Long>map=new HashMap<>();
Long b=1l;
for(int i=0;i<list.size();i++) {
if(!map.containsKey(list.get(i))) {
map.put(list.get(i), b++);
}
}
long out[]=new long[s.length];
for(int i=0;i<s.length;i++) {
out[i]=map.get(s[i]);
}
return out;
}
public static void main(String[] args) throws java.lang.Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
// int testCases=Integer.parseInt(br.readLine());
int testCases=1;
while(testCases-->0) {
int n=(int)input(br,1)[0];
long x[]=input(br,n);
long s[]=input(br,n);
s=compress(s);
List<int[]>list=new ArrayList<>();
for(int i=0;i<n;i++) {
list.add(new int[] {(int)x[i],(int)s[i]});
}
Collections.sort(list,(a,b)->(int)(a[0]-b[0]));
FenWick obj1=new FenWick(n+1);
FenWick obj2=new FenWick(n+1);
long ans=0;
for(int i=0;i<list.size();i++) {
int a[]=list.get(i);
int v=a[1];
long ct=obj1.sum(v);
long st=obj2.sum(v);
ans+=a[0]*ct-st;
obj1.add(v, 1);
obj2.add(v, a[0]);
}
out.println(ans);
}
out.close();
}
}
|
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 CF1311E extends PrintWriter {
CF1311E() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1311E o = new CF1311E(); o.main(); o.flush();
}
void main() {
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int s = sc.nextInt();
int[] kk = new int[n];
if (s > n * (n - 1) / 2) {
println("NO");
continue;
}
for (int d = 0, k = n; d < n && k > 0; d++)
while (k > 0 && kk[d] < 1 << d) {
k--; kk[d]++;
s -= d;
}
if (s < 0) {
println("NO");
continue;
}
println("YES");
while (s > 0)
for (int d = 1; d + 1 < n && s > 0; d++)
while (s > 0 && kk[d + 1] + 1 <= (kk[d] - 1) * 2) {
s--; kk[d + 1]++; kk[d]--;
}
for (int d = 1, i = 1, j = 2; d < n; d++) {
int i_ = j;
while (kk[d]-- > 0) {
print(i + " "); j++;
if (kk[d]-- > 0) {
print(i + " "); j++;
}
i++;
}
i = i_;
}
println();
}
}
}
|
java
|
1312
|
F
|
F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
OutputCopy2
3
0
InputCopy10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
OutputCopy0
2
1
2
5
12
5
0
0
2
|
[
"games",
"two pointers"
] |
//package educational.round83;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class F2 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
for(int T = ni();T > 0;T--){
go();
}
}
void go()
{
int n = ni();
int[] x = na(3);
long[] a = new long[n];
for(int i = 0;i < n;i++){
a[i] = nl();
}
int D = 5000;
int[][][] nim = new int[2][2][D];
for(int i = 1;i < D;i++){
for(int s = 0;s < 2;s++){
for(int t = 0;t < 2;t++){
long u = 0;
for(int j = 0;j < 3;j++){
if(j == 1 && s == 1)continue;
if(j == 2 && t == 1)continue;
int ns = j == 1 ? 1 : 0;
int nt = j == 2 ? 1 : 0;
u |= 1L<<nim[ns][nt][Math.max(i-x[j], 0)];
}
nim[s][t][i] = Long.numberOfTrailingZeros(~u);
}
}
// tr(i, nim[0][0][i], nim[0][1][i], nim[1][0][i], nim[1][1][i]);
}
// for(int u = 0;u < 2;u++){
// for(int v = 0;v < 2;v++){
// for(int k = D-1;k >= D/2;k--){
// assert nim[u][v][k] == nim[u][v][k-PE];
// }
// }
// }
int PE = 2520;
int base = 0;
for(long v : a){
base ^= get(nim[0][0], v, D, PE);
}
long nwin = 0;
for(long v : a){
base ^= get(nim[0][0], v, D, PE);
if((base ^ get(nim[0][0], v-x[0], D, PE)) == 0)nwin++;
if((base ^ get(nim[1][0], v-x[1], D, PE)) == 0)nwin++;
if((base ^ get(nim[0][1], v-x[2], D, PE)) == 0)nwin++;
base ^= get(nim[0][0], v, D, PE);
}
out.println(nwin);
}
int get(int[] a, long v, int D, int pe)
{
if(v < 0)return a[0];
if(v < D){
return a[(int)v];
}else{
return a[(int)((v-D)%pe-pe+D)];
}
}
public static boolean inc(int[] a, int base) {
int n = a.length;
int i;
for (i = n - 1; i >= 0 && a[i] == base - 1; i--)
;
if (i == -1)
return false;
a[i]++;
Arrays.fill(a, i + 1, n, 0);
return true;
}
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 F2().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
|
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.*;
public class C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
char[] s = sc.next().toCharArray();
Map<String, Integer> vis = new HashMap<String, Integer>();
int x = 0, y = 0, step = 0;
vis.put(x+" "+y, step);
step++;
int min = Integer.MAX_VALUE, p = -1;
for(int i=0;i<n;i++) {
if(s[i]=='U')
y++;
else if(s[i]=='D')
y--;
else if(s[i]=='L')
x--;
else
x++;
if(vis.containsKey(x+" "+y) && step-vis.get(x+" "+y)+1<min) {
p = vis.get(x+" "+y);
min = step-p+1;
}
vis.put(x+" "+y, step);
step++;
}
System.out.println(p==-1 ? p : (p+1)+" "+(p+min-1));
}
}
}
|
java
|
1303
|
D
|
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
|
[
"bitmasks",
"greedy"
] |
import java.util.*;
import javax.swing.text.Segment;
import java.io.*;
import java.math.*;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
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 void rvrs(int[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static void rvrs(long[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long mod_mul( long mod , 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 mod , 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 boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2, m);
}
static long 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, long m){
if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z;
private long[] z1;
private long[] z2;
public Combinations(long N , long mod) {
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return invrsFac((int)n);
}
long ncr(long N, long R, long mod)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int 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.max(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.max(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
/**
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = Math.min(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(1e17);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return Math.min(left, right);
}
public void update(int index , int val) {
arr[index] = val;
for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
*/
/* ***************************************************************************************************************************************************/
// static MyScanner sc = new MyScanner(); // only in case of less memory
static Reader sc = new Reader();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
tc = sc.nextInt();
for(int i = 1 ; i<=tc ; i++) {
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.println(sb);
}
static void TEST_CASE() {
long n = sc.nextLong();
int m = sc.nextInt();
long[] arr = new long[m];
for(int i = 0 ;i<m ; i++)
arr[i] = sc.nextLong();
sort(arr);
Map<Long , Integer> map = new HashMap<>();
long num = 1;
for(int i =0 ; num<=1e18 ; i++) {
map.put( num, i );
num *= 2l;
}
if(!bool(n, arr)) {
sb.append("-1\n");
return;
}
// System.out.println(map);
long[] c = new long[42];
for(long e : arr ) {
c[map.get(e)]++;
}
boolean[] visit = new boolean[42];
for(int i = 0 ; i<42 ; i++) {
if((n&(1l<<i)) != 0) visit[i] = true;
}
// for(long e:c) System.out.print(e+" ");
// System.out.println();
// for(boolean e:visit) System.out.print(e+" ");
// System.out.println();
for(int i = 0 ;i<42 ; i++) {
if(visit[i] && c[i] > 0) {
visit[i] = false;
c[i]--;
}
}
long ans = 0;
for(int i = 0 ; i<42 ; i++) {
if(!visit[i]) continue;
if(visit[i] && c[i] > 0) {
visit[i] = false;
c[i]--;
continue;
}
for(int j = 0 ; j<i ; j++) {
long add = c[j]/2;
c[j] %=2;
c[j+1] += add;
}
if(c[i] > 0) {
visit[i] = false;
c[i]--;
continue;
}
int ind = -1;
for(int j = i+1 ; j<42 ; j++) {
if(c[j] > 0) {
ind = j;
break;
}
}
if(ind == -1) {
sb.append("-1\n");
return;
}
c[ind]--;
long add = 0;
for(int j = ind-1 ; j>=i ; j--) {
c[j]++;
add++;
}
ans += max(add , 1);
// System.out.println(i +" "+ans);
}
sb.append(ans+"\n");
}
static boolean bool(long n , long[] arr) {
long sum = 0 ;
for(long e:arr) {
sum += e;
if(sum >= n) return true;
}
return false;
}
}
/*******************************************************************************************************************************************************/
/**
*/
|
java
|
1312
|
D
|
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
|
[
"combinatorics",
"math"
] |
import java.util.*;
import java.io.*;
public class CounttheArrays {
// https://codeforces.com/problemset/problem/1312/D
// I HAVE RIGHT CLOSED FORM, CAN'T DO THE FACTORIALs
static long[] fact, inv_fact;
static long mod = 998244353;
public static void main(String[] args) throws IOException, FileNotFoundException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader in = new BufferedReader(new FileReader("CounttheArrays.in"));
// INPUT //
StringTokenizer st = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
long result = 1;
fact = new long[Math.max(m+1, n+1)];
inv_fact = new long[Math.max(m+1, n+1)];
fact[0] = inv_fact[0] = 1;
for (int i=1; i<fact.length; i++) {
fact[i] = fact[i-1] * i;
fact[i] %= mod;
inv_fact[i] = pow(fact[i], mod-2, mod);
}
result *= choose(m, n-1);
result %= 998244353;
result *= (n-2);
result %= 998244353 ;
result *= pow(2, n-3, 998244353);
result %= 998244353;
// OUTPUT //
System.out.println(result);
}
static long pow(long a, long b, long m) {
long ans=1;
while (b >0) {
if (b%2 == 1) {
ans *= a;
ans %= m;
}
a *= a;
a %= m;
b >>= 1;
}
return ans;
}
// top! / bottom! (top - bottom)!
public static long choose(int top, int bottom) {
return fact[top] * inv_fact[bottom] % mod * inv_fact[top - bottom] % mod;
}
}
/*
CLosed form is easy to find
{m choose n-1} * (n-2) * 2^{n-3}
// too large
if (n-1 > m-n+1) {
for (int i = m; i >= n; i--) {
result *= i;
}
for (int i = m-n+1; i >= 2; i--) {
result /= i;
}
}
else {
for (int i = m; i >= m-n+2; i--) {
result *= i;
}
for (int i = n-1; i >= 2; i--) {
result /= i;
}
}
ArrayList<Long> factorial = new ArrayList<>();
factorial.add((long) 1);
for (int i = 1; i <= m; i++) {
factorial.add(factorial.get(i-1) * i % 998244353);
System.out.print(i + " " + factorial.get(i));
System.out.println();
}
result *= factorial.get((int) m);
result /= factorial.get((int) (n-1));
result /= factorial.get((int) (m-n+1));
*/
|
java
|
1301
|
C
|
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
|
[
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] |
import java.io.*;
import java.util.*;
public class c1156withfastIO implements Runnable {
public void solve() {
/*int l = ri();
int d = ri();
int a[] = new int[l];
for (int i = 0; i < l; i++) {
a[i] = ri();
}
Arrays.sort(a);
int c = 0;
int indexF = 0;
for (int indexL = (l + 1) / 2; indexL < l; indexL++){
if (a[indexL] - a[indexF] >= d) {
c++;
indexF++;
}
}
System.out.println(c);
*/
int t = ri();
for (int i = 0; i < t; i++) {
long n = ri();
long o = ri();
long segments = o + 1;
long sL = (n - o) / segments;
long longer = (n - o) % segments;
System.out.println(n * (n + 1) / 2 - (segments - longer) * sL * (sL + 1) / 2 - longer * (sL + 1) * (sL + 2) / 2);
}
}
/************************************************************************************************************************************************/
public static void main(String[] args) throws IOException {
new Thread(null, new c1156withfastIO(), "1", 1 << 26).start();
}
static PrintWriter out = new PrintWriter(System.out);
static Reader read = new Reader();
static StringBuilder sbr = new StringBuilder();
static int mod = (int) 1e9 + 7;
static int dmax = Integer.MAX_VALUE;
static long lmax = Long.MAX_VALUE;
static int dmin = Integer.MIN_VALUE;
static long lmin = Long.MIN_VALUE;
static int[] dprimes = new int[] { 1, 11, 101, 1087, 99991, 100001, 1000003, 15485863, 999999937 };
@Override
public void run() {
solve();
out.close();
}
static class Reader {
private byte[] buf = new byte[1024];
private int index;
private InputStream in;
private int total;
public Reader() {
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 intNext() 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 doubleNext() 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 read() 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 void print(Object object) {
out.print(object);
}
static void println(Object object) {
out.println(object);
}
static int[] iArr(int len) {
return new int[len];
}
static long[] lArr(int len) {
return new long[len];
}
static long min(long a, long b) {
return Math.min(a, b);
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long max(Long a, Long b) {
return Math.max(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int ri() {
try {
return read.intNext();
} catch (IOException e) {
e.printStackTrace();
}
System.exit(2);
return -1;
}
static long rl() {
try {
return Long.parseLong(read.read());
} catch (IOException e) {
e.printStackTrace();
}
System.exit(2);
return -1;
}
static String rs() {
try {
return read.read();
} catch (IOException e) {
e.printStackTrace();
}
System.exit(2);
return "";
}
static char rc() {
return rs().charAt(0);
}
static double rd() {
try {
return read.doubleNext();
} catch (IOException e) {
e.printStackTrace();
}
System.exit(2);
return -1;
}
}
|
java
|
1294
|
F
|
F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
import java.util.ArrayList;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 23:56:43 02/05/2021
Custom Competitive programming helper.
*/
public class Main {
static int n;
static ArrayList<Integer>[] adj;
static int maxCount,maxIdx;
public static int[] diameter() {
maxCount = 0;
maxIdx = 0;
dfs(0,-1, 0);
int A = maxIdx;
maxCount = 0;
maxIdx = 0;
dfs(A, -1, 0);
return new int[] {A,maxIdx,maxCount};
}
public static void dfs(int i, int prev,int count) {
if(adj[i].size()==1 && count>maxCount) {
maxIdx = i;
maxCount = count;
}
from[i] = prev;
for(Integer next : adj[i]) if(next!=prev) dfs(next, i, count+1);
}
static int[] from;
static int mxDfs;
static int mxDfsIdx;
public static void dfs3(int i, int cnt) {
if(from[i]==1) return;
from[i] = 1;
if(cnt>mxDfs) {
mxDfs = cnt;
mxDfsIdx = i;
}
for(Integer next : adj[i]) dfs3(next, cnt+1);
}
public static void solve() {
n = in.nextInt();
adj = new ArrayList[n];
for(int i = 0; i<n; i++) adj[i] = new ArrayList<>();
for(int i = 0; i<n-1; i++) {
int u = in.nextInt()-1, v = in.nextInt()-1;
adj[u].add(v);
adj[v].add(u);
}
from = new int[n];
int[] d = diameter();
int A = d[0], B = d[1];
ArrayList<Integer> a = new ArrayList<>();
int v = B;
while(v!=-1) {
a.add(v);
v = from[v];
}
Arrays.fill(from, 0);
for(int i : a) from[i] = 1;
mxDfs = 0;
mxDfsIdx = a.get(1);
for(int i : a) for(int k : adj[i]) dfs3(k,1);
out.println(mxDfs+d[2]);
out.println((A+1)+" "+(B+1)+" "+(mxDfsIdx+1));
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = 1;
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util{
private static Random random = new Random();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i*i <= n; i++) if (isPrime[i])
for (int j = i; i*j <= n; j++) isPrime[i*j] = false;
return isPrime;
}
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(char[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
char tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
|
java
|
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 java.io.*;
import java.nio.file.FileStore;
import java.util.*;
public class zia
{
static void BFS(ArrayList<ArrayList<Integer>> adj,int s, boolean[] visited)
{
Queue<Integer> q=new LinkedList<>();
visited[s] = true;
q.add(s);
while(q.isEmpty()==false)
{
int u = q.poll();
for(int v:adj.get(u)){
if(visited[v]==false){
visited[v]=true;
q.add(v);
}
}
}
}
// static int BFS(ArrayList<ArrayList<Integer>> adj,pair s, boolean[] visited,int ar[],int m)
// {
// Queue<pair> q=new LinkedList<>();
// visited[s.a] = true;
// q.add(s);
// int count=0;
// while(q.isEmpty()==false)
// {
// pair u = q.poll();
// // if(adj.get(u.a).size()==0)
// // count++;
// boolean end=true;
// for(int v:adj.get(u.a)){
// if(visited[v]==false){
// visited[v]=true;
// end=false;
// int cat=ar[v]==0?0:ar[v]+u.b;
// if(cat>m)
// continue;
// q.add(new pair(v, cat));
// // System.out.print("--"+v+" "+cat+"--");
// }
// }
// if(end)
// count++;
// // System.out.println(u.a+" "+adj.get(u.a).size()+" count "+count);
// }
// return count;
// }
static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v)
{
adj.get(u).add(v);
adj.get(v).add(u);
}
static void ruffleSort(long[] a) {
int n=a.length;
Random random = new Random();
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a) {
int n=a.length;
Random random = new Random();
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
public static int Lcm(int a,int b)
{ int max=Math.max(a,b);
for(int i=1;;i++)
{
if((max*i)%a==0&&(max*i)%b==0)
return (max*i);
}
}
static void sieve(int n,boolean prime[])
{
// boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i =i+ p)
prime[i] = false;
}
}
}
// public static String run(int ar[],int n)
// {
// }
public static int upperbound(int s,int e, long ar[],long x)
{
int res=-1;
while(s<=e)
{ int mid=((s-e)/2)+e;
if(ar[mid]>x)
{e=mid-1;res=mid;}
else if(ar[mid]<x)
{s=mid+1;}
else
{e=mid-1;res=mid;
if(mid>0&&ar[mid]==ar[mid-1])
e=mid-1;
else
break;
}
}
return res;
}
public static long lowerbound(int s,int e, long ar[],long x)
{
long res=-1;
while(s<=e)
{ int mid=((s-e)/2)+e;
if(ar[mid]>x)
{e=mid-1;}
else if(ar[mid]<x)
{s=mid+1;res=mid;}
else
{res=mid;
if(mid+1<ar.length&&ar[mid]==ar[mid+1])
s=mid+1;
else
break;}
}
return res;
}
static long modulo=1000000007;
public static long power(long a, long b)
{
if(b==0) return 1;
long temp=power(a,b/2)%modulo;
if((b&1)==0)
return (temp*temp)%modulo;
else
return (((temp*temp)%modulo)*a)%modulo;
}
public static long powerwithoutmod(long a, long b)
{
if(b==0) return 1;
long temp=power(a,b/2);
if((b&1)==0)
return (temp*temp);
else
return ((temp*temp)*a);
}
public static double log2(long a)
{ double d=Math.log(a)/Math.log(2);
return d;
}
public static int log10(long a)
{ double d=Math.log(a)/Math.log(10);
return (int)d;
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public static void tree(int s,int e,int ar[],int c)
{
if(s<=e)
{
int max=s;
for(int i=s;i<=e;i++)
if(ar[i]>ar[max])
max=i;
ar[max]=c++;
tree(s,max-1,ar,c);
tree(max+1,e,ar,c);
}
}
static int resturant=0;
static void DFS(ArrayList<ArrayList<Integer>> al,boolean visited[],int s,int max,int curr,int ar[])
{
visited[s]=true;
if(al.get(s).size()==1&&visited[al.get(s).get(0)]==true)
{resturant++;return;}
// System.out.println(s+" "+curr);
for(int x:al.get(s))
{
if(visited[x]==false)
{
if(ar[x]==0)
DFS(al, visited, x, max, 0, ar);
else if(curr+ar[x]<=max)
DFS(al, visited, x, max, curr+ar[x], ar);
}
}
}
public static void main(String[] args) throws Exception
{
FastIO sc = new FastIO();
//sc.println();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
int test=sc.nextInt();
// // double c=Math.log(10);
// boolean prime[]=new boolean[233334];
// sieve(233334, prime);
// HashMap<Character,Integer> hm=new HashMap<>(9);
// char c='1';
// for(int i=1;i<=9;i++)
// hm.put(c++,i);
while(test-->0)
{
int n=sc.nextInt();
int ar[]=new int[n];
for (int i = 0; i < n; i++) {
ar[i]=sc.nextInt();
}
int d=0;
int max=Integer.MIN_VALUE,min=Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if(ar[i]==-1)
{
if(i-1>=0&&ar[i-1]!=-1)
{
min=Math.min(min,ar[i-1]);
max=Math.max(max,ar[i-1]);
}
if(i+1<n&&ar[i+1]!=-1)
{
min=Math.min(min,ar[i+1]);
max=Math.max(max,ar[i+1]);
}
}
else
{
if(i-1>=0&&ar[i-1]!=-1)
d=Math.max(d,Math.abs(ar[i-1]-ar[i]));
if(i+1<n&&ar[i+1]!=-1)
d=Math.max(d,Math.abs(ar[i+1]-ar[i]));
}
}
if(min==Integer.MAX_VALUE&&max==Integer.MIN_VALUE)
{
sc.println("0 0");
}
else if(min==max)
{
sc.println(d+" "+min);
}
else
{
int mean=(min+max)/2;
d=Math.max(d,mean-min);
d=Math.max(d,max-mean);
sc.println(d+" "+mean);
}
}
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sc.close();
}
}
class pair implements Comparable<pair>{
int a;
int b;
pair(int a,int b)
{this.a=a;
this.b=b;
}
public int compareTo(pair p)
{
if(this.a-p.a==0)
return this.b-p.b;
return (this.a-p.a);
}
}
class triplet implements Comparable<triplet>{
long first,second,third;
triplet(long first,long second,long third)
{this.first=first;
this.second=second;
this.third=third;
}
public int compareTo(triplet p)
{
return (int)(this.first-p.first);
}
}
// class triplet
// {
// int x1,x2,i;
// triplet(int a,int b,int c)
// {x1=a;x2=b;i=c;}
// }
class FastIO extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1<<16];
private int curChar, numChars;
// standard input
public FastIO() { this(System.in,System.out); }
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
public String nextLine() {
int c; do { c = nextByte(); } while (c <= '\n');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n');
return res.toString();
}
public String next() {
int c; do { c = nextByte(); } while (c <= ' ');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');
return res.toString();
}
public int nextInt() {
int c; do { c = nextByte(); } while (c <= ' ');
int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() {
int c; do { c = nextByte(); } while (c <= ' ');
long sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() { return Double.parseDouble(next()); }
}
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.