contest_id
stringclasses 33
values | problem_id
stringclasses 14
values | statement
stringclasses 181
values | tags
sequencelengths 1
8
| code
stringlengths 21
64.5k
| language
stringclasses 3
values |
---|---|---|---|---|---|
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] |
import java.io.*;
import java.util.StringTokenizer;
public class Problem1288B {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int tc = scanner.nextInt();
while (tc-->0){
int a = scanner.nextInt();
int b = scanner.nextInt();
long cnt = 0;
for (long i =9;i<=b;i=i*10+9){
cnt+=a;
}
System.out.println(cnt);
}
}
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 |
1296 | E2 | E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1
| [
"data structures",
"dp"
] | import java.io.*;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.function.Predicate;
public class E1296E2 {
public static void main(String[] args) {
FastIO io = new FastIO();
int n = io.nextInt();
ArrayList<Integer> l = new ArrayList<>();
char[] s = io.next().toCharArray();
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
int val = s[i];
int up = firstTrue(0, l.size() - 1, (x) -> val >= l.get(x));
if (up == l.size()) l.add(val);
l.set(up, val);
ans[i] = up + 1;
}
io.println(l.size());
for (int v : ans) io.print(v + " ");
io.close();
}
public static int firstTrue(int lo, int hi, Predicate<Integer> test) {
hi++;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (test.test(mid)) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
private static class FastIO extends PrintWriter {
private final InputStream stream;
private final byte[] buf = new byte[1 << 16];
private int curChar, numChars;
// standard input
public FastIO() {
this(System.in, System.out);
}
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c;
do {
c = nextByte();
} while (c <= ' ');
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nextByte();
} while (c > ' ');
return res.toString();
}
public int nextInt() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| java |
1293 | A | A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor. | [
"binary search",
"brute force",
"implementation"
] | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static final PrintWriter out =new PrintWriter(System.out);
static final FastReader sc = new FastReader();
public static boolean sorted(int a[])
{
int n=a.length,i;
int b[]=new int[n];
for(i=0;i<n;i++)
b[i]=a[i];
Arrays.sort(b);
for(i=0;i<n;i++)
{
if(a[i]!=b[i])
return false;
}
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
int tes=sc.nextInt();
label:while(tes-->0)
{
int n=sc.nextInt();
int s=sc.nextInt();
int k=sc.nextInt();
ArrayList<Integer> arr=new ArrayList<>();
int i;
for(i=0;i<k;i++)
arr.add(sc.nextInt());
if(!arr.contains(s))
{
System.out.println(0);
continue;
}
for(i=1;i<=k;i++)
{
if(s+i<=n && !arr.contains(s+i))
{
System.out.println(i);
continue label;
}
if(s-i>=1 && !arr.contains(s-i))
{
System.out.println(i);
continue label;
}
}
}
}
public static int first(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)
return mid;
else if (x > arr.get(mid))
return first(arr, (mid + 1), high, x, n);
else
return first(arr, low, (mid - 1), x, n);
}
return -1;
}
public static int last(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)
return mid;
else if (x < arr.get(mid))
return last(arr, low, (mid - 1), x, n);
else
return last(arr, (mid + 1), high, x, n);
}
return -1;
}
public static int lis(int[] arr) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>=x) {
al.add(arr[i]);
}else {
int v = upper_bound(al, 0, al.size(), arr[i]);
al.set(v, arr[i]);
}
}
return al.size();
}
public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get((int)mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long mod=1000000007;
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | java |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012) — the elements of the array.OutputPrint a single integer — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | [
"math",
"number theory",
"probabilities"
] | import java.io.*;
import java.util.StringTokenizer;
public class MinimumPunishment {
// A composite number not greater than 10**12 must have a prime factor
// less than PRIME_LIMIT.
final static int PRIME_LIMIT = 1000000;
// s[i] tells whether i is composite for i >= 2
final static boolean[] isPrime = new boolean[PRIME_LIMIT];
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static {
isPrime[2] = true;
for (int i = 3; i < PRIME_LIMIT; i += 2) {
isPrime[i] = true;
}
final int SQUARE_ROOT = (int) Math.sqrt(PRIME_LIMIT);
for (int i = 3; i <= SQUARE_ROOT; i++) {
if (isPrime[i]) {
for (int j = i * i; j < PRIME_LIMIT; j += i * 2) {
isPrime[j] = false;
}
}
}
}
static long readLong() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return Long.parseLong(st.nextToken());
}
public static void main(String[] args) throws IOException {
int n = (int) readLong();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = readLong();
}
// Each integer can be changed to an even number by at most one operation.
long min = n;
for (int i = 2; i < PRIME_LIMIT; i++) {
if (isPrime[i]) {
int ops = 0;
for (long aa : a) {
if (aa <= i) {
ops += i - aa;
} else {
long remainder = aa % i;
ops += Math.min(remainder, i - remainder);
}
if (min <= ops) break;
}
if (min > ops) {
min = ops;
}
}
}
final long left = Math.max(a[0] - (min - 1), 3);
final long right = a[0] + (min - 1);
final int size = (int) (right - left + 1);
if (size > 0) {
long[] b = new long[size];
for (int i = 0; i < size; i++) {
b[i] = left + i;
}
for (int i = 2; i < PRIME_LIMIT; i++) {
if (isPrime[i]) {
// remove the highest power of i from b[j]
long f = i;
while (true) {
// the smallest multiple of f that is no less than left
long start = (left + f - 1) / f * f;
if (start > right) break;
for (long j = start - left; j < size; j += f) {
b[(int) j] /= i;
}
f *= i;
}
}
}
for (long i : b) {
if (i != 1) {
// Since i is a factor of b[i] that has no prime factor smaller than
// PRIME_LIMIT, i must be a prime greater than PRIME_LIMIT
int ops = 0;
for (long aa : a) {
if (aa <= i) {
ops += i - aa;
} else {
long remainder = aa % i;
ops += Math.min(remainder, i - remainder);
}
if (min <= ops) break;
}
if (min > ops) {
min = ops;
}
}
}
}
System.out.println(min);
}
}
| java |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
| [
"math"
] | import java.util.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
int testcases = in.nextInt();
while (testcases-- > 0) {
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int n = in.nextInt();
int x = Math.max(a, Math.max(b, c));
x = (x - a) + (x - b) + (x - c);
if (x > n) {
System.out.println("NO");
continue;
} else {
n -= x;
if (n % 3 == 0)
System.out.println("YES");
else
System.out.println("NO");
}
}
in.close();
}
} | java |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
int t = kb.nextInt();
while(t-- > 0)
{
int n = kb.nextInt();
int x = 0;
int[] arr1 = new int[n];
boolean even = false;
int index=-1;
for(int i=0;i<n;i++)
{
arr1[i] = kb.nextInt();
if(arr1[i]%2==0)
{
even = true;
index=i+1;
}
}
if(even)
{
System.out.println(1);
System.out.println(index);
}
else if(n==1)
{
System.out.println(-1);
}
else
{
System.out.println(2);
System.out.println(1+" "+2);
}
}
}
} | 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.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.HashMap;
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);
EObtainAPermutation solver = new EObtainAPermutation();
solver.solve(1, in, out);
out.close();
}
static class EObtainAPermutation {
int n;
int m;
int[][] arr;
int[][] f;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
m = in.nextInt();
arr = in.nextIntMatrix(n, m);
f = new int[n][m];
int k = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
f[i][j] = k++;
}
}
int ans = 0;
for (int i = 0; i < m; i++) {
// out.println(i,val(i));
ans += val(i);
}
out.println(ans);
}
int val(int c) {
int[] dis = new int[n];
HashMap<Integer, Integer> index = new HashMap<>();
for (int i = 0; i < n; i++) {
index.put(f[i][c], i);
}
for (int i = 0; i < n; i++) {
int x = arr[i][c];
if (!index.containsKey(x)) continue;
int id = index.get(x);
if (id <= i) {
dis[i - id]++;
} else {
dis[n - (id - i)]++;
}
}
int ans = n;
for (int i = n - 1; i >= 0; i--) {
if (dis[i] == 0) continue;
ans = Math.min(ans, i + n - dis[i]);
}
return ans;
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[][] nextIntMatrix(int rows, int cols) {
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextInt();
return matrix;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
| java |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
public final class CFPS {
static FastReader fr = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static final int gigamod = 1000000007;
static final int mod = 998244353;
static int t = 1;
static boolean[] isPrime;
static int[] smallestFactorOf;
static final int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3;
static int cmp;
@SuppressWarnings({"unused"})
public static void main(String[] args) throws Exception {
t = fr.nextInt();
OUTER:
for (int tc = 0; tc < t; tc++) {
int n = fr.nextInt();
char[] chars = fr.next().toCharArray();
int[] digs = new int[n];
for (int i = 0; i < n; i++)
digs[i] = chars[i] - '0';
// last digit is odd
// sum is even
// --
// therefore, two odd digits in total
int oddCnt = 0;
ArrayList<Integer> odds = new ArrayList<>();
for (int i = 0; i < n && oddCnt < 2; i++)
if (digs[i] % 2 == 1) {
oddCnt++;
odds.add(digs[i]);
}
if (oddCnt < 2) {
out.println("-1");
continue OUTER;
}
for (int i : odds)
out.print(i);
out.println();
}
out.close();
}
static boolean isPalindrome(char[] s) {
char[] rev = s.clone();
reverse(rev);
return Arrays.compare(s, rev) == 0;
}
static class Segment implements Comparable<Segment> {
int size;
long val;
int stIdx;
Segment left, right;
Segment(int ss, long vv, int ssii) {
size = ss;
val = vv;
stIdx = ssii;
}
@Override
public int compareTo(Segment that) {
cmp = size - that.size;
if (cmp == 0)
cmp = stIdx - that.stIdx;
if (cmp == 0)
cmp = Long.compare(val, that.val);
return cmp;
}
}
static class Pair implements Comparable<Pair> {
int first, second;
int idx;
Pair() { first = second = 0; }
Pair (int ff, int ss) {first = ff; second = ss;}
Pair (int ff, int ss, int ii) { first = ff; second = ss; idx = ii; }
public int compareTo(Pair that) {
cmp = first - that.first;
if (cmp == 0)
cmp = second - that.second;
return (int) cmp;
}
}
// (range add - segment min) segTree
static int nn;
static int[] arr;
static int[] tree;
static int[] lazy;
static void build(int node, int leftt, int rightt) {
if (leftt == rightt) {
tree[node] = arr[leftt];
return;
}
int mid = (leftt + rightt) >> 1;
build(node << 1, leftt, mid);
build(node << 1 | 1, mid + 1, rightt);
tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]);
}
static void segAdd(int node, int leftt, int rightt, int segL, int segR, int val) {
if (lazy[node] != 0) {
tree[node] += lazy[node];
if (leftt != rightt) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
}
lazy[node] = 0;
}
if (segL > rightt || segR < leftt) return;
if (segL <= leftt && rightt <= segR) {
tree[node] += val;
if (leftt != rightt) {
lazy[node << 1] += val;
lazy[node << 1 | 1] += val;
}
lazy[node] = 0;
return;
}
int mid = (leftt + rightt) >> 1;
segAdd(node << 1, leftt, mid, segL, segR, val);
segAdd(node << 1 | 1, mid + 1, rightt, segL, segR, val);
tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]);
}
static int minQuery(int node, int leftt, int rightt, int segL, int segR) {
if (lazy[node] != 0) {
tree[node] += lazy[node];
if (leftt != rightt) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
}
lazy[node] = 0;
}
if (segL > rightt || segR < leftt) return Integer.MAX_VALUE / 10;
if (segL <= leftt && rightt <= segR)
return tree[node];
int mid = (leftt + rightt) >> 1;
return Math.min(minQuery(node << 1, leftt, mid, segL, segR),
minQuery(node << 1 | 1, mid + 1, rightt, segL, segR));
}
static void compute_automaton(String s, int[][] aut) {
s += '#';
int n = s.length();
int[] pi = prefix_function(s.toCharArray());
for (int i = 0; i < n; i++) {
for (int c = 0; c < 26; c++) {
int j = i;
while (j > 0 && 'A' + c != s.charAt(j))
j = pi[j-1];
if ('A' + c == s.charAt(j))
j++;
aut[i][c] = j;
}
}
}
static void timeDFS(int current, int from, UGraph ug,
int[] time, int[] tIn, int[] tOut) {
tIn[current] = ++time[0];
for (int adj : ug.adj(current))
if (adj != from)
timeDFS(adj, current, ug, time, tIn, tOut);
tOut[current] = ++time[0];
}
static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) {
// we will check if c3 lies on line through (c1, c2)
long a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return a == 0;
}
static int[] treeDiameter(UGraph ug) {
int n = ug.V();
int farthest = -1;
int[] distTo = new int[n];
diamDFS(0, -1, 0, ug, distTo);
int maxDist = -1;
for (int i = 0; i < n; i++)
if (maxDist < distTo[i]) {
maxDist = distTo[i];
farthest = i;
}
distTo = new int[n + 1];
diamDFS(farthest, -1, 0, ug, distTo);
distTo[n] = farthest;
return distTo;
}
static void diamDFS(int current, int from, int dist, UGraph ug, int[] distTo) {
distTo[current] = dist;
for (int adj : ug.adj(current))
if (adj != from)
diamDFS(adj, current, dist + 1, ug, distTo);
}
static class TreeDistFinder {
UGraph ug;
int n;
int[] depthOf;
LCA lca;
TreeDistFinder(UGraph ug) {
this.ug = ug;
n = ug.V();
depthOf = new int[n];
depthCalc(0, -1, ug, 0, depthOf);
lca = new LCA(ug, 0);
}
TreeDistFinder(UGraph ug, int a) {
this.ug = ug;
n = ug.V();
depthOf = new int[n];
depthCalc(a, -1, ug, 0, depthOf);
lca = new LCA(ug, a);
}
private void depthCalc(int current, int from, UGraph ug, int depth, int[] depthOf) {
depthOf[current] = depth;
for (int adj : ug.adj(current))
if (adj != from)
depthCalc(adj, current, ug, depth + 1, depthOf);
}
public int dist(int a, int b) {
int lc = lca.lca(a, b);
return (depthOf[a] - depthOf[lc] + depthOf[b] - depthOf[lc]);
}
}
public static long[][] GCDSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
} else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = gcd(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeGCDQ(long[][] table, int l, int r)
{
// [a,b)
if(l > r)return 1;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return gcd(table[t][l], table[t][r-(1<<t)]);
}
static class Trie {
TrieNode root;
Trie(char[][] strings) {
root = new TrieNode('A', false);
construct(root, strings);
}
public Stack<String> set(TrieNode root) {
Stack<String> set = new Stack<>();
StringBuilder sb = new StringBuilder();
for (TrieNode next : root.next)
collect(sb, next, set);
return set;
}
private void collect(StringBuilder sb, TrieNode node, Stack<String> set) {
if (node == null) return;
sb.append(node.character);
if (node.isTerminal)
set.add(sb.toString());
for (TrieNode next : node.next)
collect(sb, next, set);
if (sb.length() > 0)
sb.setLength(sb.length() - 1);
}
private void construct(TrieNode root, char[][] strings) {
// we have to construct the Trie
for (char[] string : strings) {
if (string.length == 0) continue;
root.next[string[0] - 'a'] = put(root.next[string[0] - 'a'], string, 0);
if (root.next[string[0] - 'a'] != null)
root.isLeaf = false;
}
}
private TrieNode put(TrieNode node, char[] string, int idx) {
boolean isTerminal = (idx == string.length - 1);
if (node == null) node = new TrieNode(string[idx], isTerminal);
node.character = string[idx];
node.isTerminal |= isTerminal;
if (!isTerminal) {
node.isLeaf = false;
node.next[string[idx + 1] - 'a'] = put(node.next[string[idx + 1] - 'a'], string, idx + 1);
}
return node;
}
class TrieNode {
char character;
TrieNode[] next;
boolean isTerminal, isLeaf;
boolean canWin, canLose;
TrieNode(char c, boolean isTerminallll) {
character = c;
isTerminal = isTerminallll;
next = new TrieNode[26];
isLeaf = true;
}
}
}
static class Edge implements Comparable<Edge> {
int from, to;
long weight, ans;
int id;
// int hash;
Edge(int fro, int t, long wt, int i) {
from = fro;
to = t;
id = i;
weight = wt;
// hash = Objects.hash(from, to, weight);
}
/*public int hashCode() {
return hash;
}*/
public int compareTo(Edge that) {
return Long.compare(this.id, that.id);
}
}
public static long[][] minSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeMinQ(long[][] table, int l, int r)
{
// [a,b)
if(l >= r)return Integer.MAX_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.min(table[t][l], table[t][r-(1<<t)]);
}
public static long[][] maxSparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.max(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRangeMaxQ(long[][] table, int l, int r)
{
// [a,b)
if(l >= r)return Integer.MIN_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.max(table[t][l], table[t][r-(1<<t)]);
}
static class LCA {
int[] height, first, segtree;
ArrayList<Integer> euler;
boolean[] visited;
int n;
LCA(UGraph ug, int root) {
n = ug.V();
height = new int[n];
first = new int[n];
euler = new ArrayList<>();
visited = new boolean[n];
dfs(ug, root, 0);
int m = euler.size();
segtree = new int[m * 4];
build(1, 0, m - 1);
}
void dfs(UGraph ug, int node, int h) {
visited[node] = true;
height[node] = h;
first[node] = euler.size();
euler.add(node);
for (int adj : ug.adj(node)) {
if (!visited[adj]) {
dfs(ug, adj, h + 1);
euler.add(node);
}
}
}
void build(int node, int b, int e) {
if (b == e) {
segtree[node] = euler.get(b);
} else {
int mid = (b + e) / 2;
build(node << 1, b, mid);
build(node << 1 | 1, mid + 1, e);
int l = segtree[node << 1], r = segtree[node << 1 | 1];
segtree[node] = (height[l] < height[r]) ? l : r;
}
}
int query(int node, int b, int e, int L, int R) {
if (b > R || e < L)
return -1;
if (b >= L && e <= R)
return segtree[node];
int mid = (b + e) >> 1;
int left = query(node << 1, b, mid, L, R);
int right = query(node << 1 | 1, mid + 1, e, L, R);
if (left == -1) return right;
if (right == -1) return left;
return height[left] < height[right] ? left : right;
}
int lca(int u, int v) {
int left = first[u], right = first[v];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
return query(1, 0, euler.size() - 1, left, right);
}
}
static class FenwickTree {
long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates
public FenwickTree(int size) {
array = new long[size + 1];
}
public long rsq(int ind) {
assert ind > 0;
long sum = 0;
while (ind > 0) {
sum += array[ind];
//Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number
ind -= ind & (-ind);
}
return sum;
}
public long rsq(int a, int b) {
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, long value) {
assert ind > 0;
while (ind < array.length) {
array[ind] += value;
//Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number
ind += ind & (-ind);
}
}
public int size() {
return array.length - 1;
}
}
static class Point implements Comparable<Point> {
long x;
long y;
long z;
long id;
// private int hashCode;
Point() {
x = z = y = 0;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(Point p) {
this.x = p.x;
this.y = p.y;
this.z = p.z;
this.id = p.id;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(long x, long y, long z, long id) {
this.x = x;
this.y = y;
this.z = z;
this.id = id;
// this.hashCode = Objects.hash(x, y, id);
}
Point(long a, long b) {
this.x = a;
this.y = b;
this.z = 0;
// this.hashCode = Objects.hash(a, b);
}
Point(long x, long y, long id) {
this.x = x;
this.y = y;
this.id = id;
}
@Override
public int compareTo(Point o) {
if (this.x < o.x)
return -1;
if (this.x > o.x)
return 1;
if (this.y < o.y)
return -1;
if (this.y > o.y)
return 1;
if (this.z < o.z)
return -1;
if (this.z > o.z)
return 1;
return 0;
}
@Override
public boolean equals(Object that) {
return this.compareTo((Point) that) == 0;
}
}
static class BinaryLift {
// FUNCTIONS: k-th ancestor and LCA in log(n)
int[] parentOf;
int maxJmpPow;
int[][] binAncestorOf;
int n;
int[] lvlOf;
// How this works?
// a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}.
// b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we
// lift level in the tree.
public BinaryLift(UGraph tree) {
n = tree.V();
maxJmpPow = logk(n, 2) + 1;
parentOf = new int[n];
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
parentConstruct(0, -1, tree, 0);
binConstruct();
}
// TODO: Implement lvlOf[] initialization
public BinaryLift(int[] parentOf) {
this.parentOf = parentOf;
n = parentOf.length;
maxJmpPow = logk(n, 2) + 1;
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
UGraph tree = new UGraph(n);
for (int i = 1; i < n; i++)
tree.addEdge(i, parentOf[i]);
binConstruct();
parentConstruct(0, -1, tree, 0);
}
private void parentConstruct(int current, int from, UGraph tree, int depth) {
parentOf[current] = from;
lvlOf[current] = depth;
for (int adj : tree.adj(current))
if (adj != from)
parentConstruct(adj, current, tree, depth + 1);
}
private void binConstruct() {
for (int node = 0; node < n; node++)
for (int lvl = 0; lvl < maxJmpPow; lvl++)
binConstruct(node, lvl);
}
private int binConstruct(int node, int lvl) {
if (node < 0)
return -1;
if (lvl == 0)
return binAncestorOf[node][lvl] = parentOf[node];
if (node == 0)
return binAncestorOf[node][lvl] = -1;
if (binAncestorOf[node][lvl] != -1)
return binAncestorOf[node][lvl];
return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1);
}
// return ancestor which is 'k' levels above this one
public int ancestor(int node, int k) {
if (node < 0)
return -1;
if (node == 0)
if (k == 0) return node;
else return -1;
if (k > (1 << maxJmpPow) - 1)
return -1;
if (k == 0)
return node;
int ancestor = node;
int highestBit = Integer.highestOneBit(k);
while (k > 0 && ancestor != -1) {
ancestor = binAncestorOf[ancestor][logk(highestBit, 2)];
k -= highestBit;
highestBit = Integer.highestOneBit(k);
}
return ancestor;
}
public int lca(int u, int v) {
if (u == v)
return u;
// The invariant will be that 'u' is below 'v' initially.
if (lvlOf[u] < lvlOf[v]) {
int temp = u;
u = v;
v = temp;
}
// Equalizing the levels.
u = ancestor(u, lvlOf[u] - lvlOf[v]);
if (u == v)
return u;
// We will now raise level by largest fitting power of two until possible.
for (int power = maxJmpPow - 1; power > -1; power--)
if (binAncestorOf[u][power] != binAncestorOf[v][power]) {
u = binAncestorOf[u][power];
v = binAncestorOf[v][power];
}
return ancestor(u, 1);
}
}
static class DFSTree {
// NOTE: The thing is made keeping in mind that the whole
// input graph is connected.
UGraph tree;
UGraph backUG;
int hasBridge;
int n;
Edge backEdge;
DFSTree(UGraph ug) {
this.n = ug.V();
tree = new UGraph(n);
hasBridge = -1;
backUG = new UGraph(n);
treeCalc(0, -1, new boolean[n], ug);
}
private void treeCalc(int current, int from, boolean[] marked, UGraph ug) {
if (marked[current]) {
// This is a backEdge.
backUG.addEdge(from, current);
backEdge = new Edge(from, current, 1, 0);
return;
}
if (from != -1)
tree.addEdge(from, current);
marked[current] = true;
for (int adj : ug.adj(current))
if (adj != from)
treeCalc(adj, current, marked, ug);
}
public boolean hasBridge() {
if (hasBridge != -1)
return (hasBridge == 1);
// We have to determine the bridge.
bridgeFinder();
return (hasBridge == 1);
}
int[] levelOf;
int[] dp;
private void bridgeFinder() {
// Finding the level of each node.
levelOf = new int[n];
levelDFS(0, -1, 0);
// Applying DP solution.
// dp[i] -> Highest level reachable from subtree of 'i' using
// some backEdge.
dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE / 100);
dpDFS(0, -1);
// Now, we will check each edge and determine whether its a
// bridge.
for (int i = 0; i < n; i++)
for (int adj : tree.adj(i)) {
// (i -> adj) is the edge.
if (dp[adj] > levelOf[i])
hasBridge = 1;
}
if (hasBridge != 1)
hasBridge = 0;
}
private void levelDFS(int current, int from, int lvl) {
levelOf[current] = lvl;
for (int adj : tree.adj(current))
if (adj != from)
levelDFS(adj, current, lvl + 1);
}
private int dpDFS(int current, int from) {
dp[current] = levelOf[current];
for (int back : backUG.adj(current))
dp[current] = Math.min(dp[current], levelOf[back]);
for (int adj : tree.adj(current))
if (adj != from)
dp[current] = Math.min(dp[current], dpDFS(adj, current));
return dp[current];
}
}
static class UnionFind {
// Uses weighted quick-union with path compression.
private int[] parent; // parent[i] = parent of i
private int[] size; // size[i] = number of sites in tree rooted at i
// Note: not necessarily correct if i is not a root node
private int count; // number of components
public UnionFind(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
// Number of connected components.
public int count() {
return count;
}
// Find the root of p.
public int find(int p) {
while (p != parent[p])
p = parent[p];
return p;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public int numConnectedTo(int node) {
return size[find(node)];
}
// Weighted union.
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
public static int[] connectedComponents(UnionFind uf) {
// We can do this in nlogn.
int n = uf.size.length;
int[] compoColors = new int[n];
for (int i = 0; i < n; i++)
compoColors[i] = uf.find(i);
HashMap<Integer, Integer> oldToNew = new HashMap<>();
int newCtr = 0;
for (int i = 0; i < n; i++) {
int thisOldColor = compoColors[i];
Integer thisNewColor = oldToNew.get(thisOldColor);
if (thisNewColor == null)
thisNewColor = newCtr++;
oldToNew.put(thisOldColor, thisNewColor);
compoColors[i] = thisNewColor;
}
return compoColors;
}
}
static class UGraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public UGraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
adj[to].add(from);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int degree(int v) {
return adj[v].size();
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static void dfsMark(int current, boolean[] marked, UGraph g) {
if (marked[current]) return;
marked[current] = true;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, marked, g);
}
public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) {
if (marked[current]) return;
marked[current] = true;
if (from != -1)
distTo[current] = distTo[from] + 1;
HashSet<Integer> adj = g.adj(current);
int alreadyMarkedCtr = 0;
for (int adjc : adj) {
if (marked[adjc]) alreadyMarkedCtr++;
dfsMark(adjc, current, distTo, marked, g, endPoints);
}
if (alreadyMarkedCtr == adj.size())
endPoints.add(current);
}
public static void bfsOrder(int current, UGraph g) {
}
public static void dfsMark(int current, int[] colorIds, int color, UGraph g) {
if (colorIds[current] != -1) return;
colorIds[current] = color;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, colorIds, color, g);
}
public static int[] connectedComponents(UGraph g) {
int n = g.V();
int[] componentId = new int[n];
Arrays.fill(componentId, -1);
int colorCtr = 0;
for (int i = 0; i < n; i++) {
if (componentId[i] != -1) continue;
dfsMark(i, componentId, colorCtr, g);
colorCtr++;
}
return componentId;
}
public static boolean hasCycle(UGraph ug) {
int n = ug.V();
boolean[] marked = new boolean[n];
boolean[] hasCycleFirst = new boolean[1];
for (int i = 0; i < n; i++) {
if (marked[i]) continue;
hcDfsMark(i, ug, marked, hasCycleFirst, -1);
}
return hasCycleFirst[0];
}
// Helper for hasCycle.
private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) {
if (marked[current]) return;
if (hasCycleFirst[0]) return;
marked[current] = true;
HashSet<Integer> adjc = ug.adj(current);
for (int adj : adjc) {
if (marked[adj] && adj != parent && parent != -1) {
hasCycleFirst[0] = true;
return;
}
hcDfsMark(adj, ug, marked, hasCycleFirst, current);
}
}
}
static class Digraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public Digraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public Digraph reversed() {
Digraph dg = new Digraph(V());
for (int i = 0; i < V(); i++)
for (int adjVert : adj(i)) dg.addEdge(adjVert, i);
return dg;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static int[] KosarajuSharirSCC(Digraph dg) {
int[] id = new int[dg.V()];
Digraph reversed = dg.reversed();
// Gotta perform topological sort on this one to get the stack.
Stack<Integer> revStack = Digraph.topologicalSort(reversed);
// Initializing id and idCtr.
id = new int[dg.V()];
int idCtr = -1;
// Creating a 'marked' array.
boolean[] marked = new boolean[dg.V()];
while (!revStack.isEmpty()) {
int vertex = revStack.pop();
if (!marked[vertex])
sccDFS(dg, vertex, marked, ++idCtr, id);
}
return id;
}
private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) {
marked[source] = true;
id[source] = idCtr;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id);
}
public static Stack<Integer> topologicalSort(Digraph dg) {
// dg has to be a directed acyclic graph.
// We'll have to run dfs on the digraph and push the deepest nodes on stack first.
// We'll need a Stack<Integer> and a int[] marked.
Stack<Integer> topologicalStack = new Stack<Integer>();
boolean[] marked = new boolean[dg.V()];
// Calling dfs
for (int i = 0; i < dg.V(); i++)
if (!marked[i])
runDfs(dg, topologicalStack, marked, i);
return topologicalStack;
}
static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) {
marked[source] = true;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex])
runDfs(dg, topologicalStack, marked, adjVertex);
topologicalStack.add(source);
}
}
static class FastReader {
private BufferedReader bfr;
private StringTokenizer st;
public FastReader() {
bfr = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bfr.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return next().toCharArray()[0];
}
String nextString() {
return next();
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
double[] nextDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextDouble();
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
int[][] nextIntGrid(int n, int m) {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
grid[i][j] = fr.nextInt();
}
return grid;
}
}
@SuppressWarnings("serial")
static class CountMap<T> extends TreeMap<T, Integer>{
CountMap() {
}
CountMap(Comparator<T> cmp) {
}
CountMap(T[] arr) {
this.putCM(arr);
}
public Integer putCM(T key) {
return super.put(key, super.getOrDefault(key, 0) + 1);
}
public Integer removeCM(T key) {
int count = super.getOrDefault(key, -1);
if (count == -1) return -1;
if (count == 1)
return super.remove(key);
else
return super.put(key, count - 1);
}
public Integer getCM(T key) {
return super.getOrDefault(key, 0);
}
public void putCM(T[] arr) {
for (T l : arr)
this.putCM(l);
}
}
static long dioGCD(long a, long b, long[] x0, long[] y0) {
if (b == 0) {
x0[0] = 1;
y0[0] = 0;
return a;
}
long[] x1 = new long[1], y1 = new long[1];
long d = dioGCD(b, a % b, x1, y1);
x0[0] = y1[0];
y0[0] = x1[0] - y1[0] * (a / b);
return d;
}
static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) {
g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0);
if (c % g[0] > 0) {
return false;
}
x0[0] *= c / g[0];
y0[0] *= c / g[0];
if (a < 0) x0[0] = -x0[0];
if (b < 0) y0[0] = -y0[0];
return true;
}
static long[][] prod(long[][] mat1, long[][] mat2) {
int n = mat1.length;
long[][] prod = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
// determining prod[i][j]
// it will be the dot product of mat1[i][] and mat2[][i]
for (int k = 0; k < n; k++)
prod[i][j] += mat1[i][k] * mat2[k][j];
return prod;
}
static long[][] matExpo(long[][] mat, long power) {
int n = mat.length;
long[][] ans = new long[n][n];
if (power == 0)
return null;
if (power == 1)
return mat;
long[][] half = matExpo(mat, power / 2);
ans = prod(half, half);
if (power % 2 == 1) {
ans = prod(ans, mat);
}
return ans;
}
static int KMPNumOcc(char[] text, char[] pat) {
int n = text.length;
int m = pat.length;
char[] patPlusText = new char[n + m + 1];
for (int i = 0; i < m; i++)
patPlusText[i] = pat[i];
patPlusText[m] = '^'; // Seperator
for (int i = 0; i < n; i++)
patPlusText[m + i] = text[i];
int[] fullPi = piCalcKMP(patPlusText);
int answer = 0;
for (int i = 0; i < n + m + 1; i++)
if (fullPi[i] == m)
answer++;
return answer;
}
static int[] piCalcKMP(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static boolean[] prefMatchesSuff(char[] s) {
int n = s.length;
boolean[] res = new boolean[n + 1];
int[] pi = prefix_function(s);
res[0] = true;
for (int p = n; p != 0; p = pi[p])
res[p] = true;
return res;
}
static int[] prefix_function(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static long hash(long key) {
long h = Long.hashCode(key);
h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4);
return h & (gigamod-1);
}
static void Yes() {out.println("Yes");}static void YES() {out.println("YES");}static void yes() {out.println("Yes");}static void No() {out.println("No");}static void NO() {out.println("NO");}static void no() {out.println("no");}
static int mapTo1D(int row, int col, int n, int m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static int[] mapTo2D(int idx, int n, int m) {
// Inverse of what the one above does.
int[] rnc = new int[2];
rnc[0] = idx / m;
rnc[1] = idx % m;
return rnc;
}
static long mapTo1D(long row, long col, long n, long m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static boolean[] primeGenerator(int upto) {
// Sieve of Eratosthenes:
isPrime = new boolean[upto + 1];
smallestFactorOf = new int[upto + 1];
Arrays.fill(smallestFactorOf, 1);
Arrays.fill(isPrime, true);
isPrime[1] = isPrime[0] = false;
for (long i = 2; i < upto + 1; i++)
if (isPrime[(int) i]) {
smallestFactorOf[(int) i] = (int) i;
// Mark all the multiples greater than or equal
// to the square of i to be false.
for (long j = i; j * i < upto + 1; j++) {
if (isPrime[(int) j * (int) i]) {
isPrime[(int) j * (int) i] = false;
smallestFactorOf[(int) j * (int) i] = (int) i;
}
}
}
return isPrime;
}
static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) {
if (smallestFactorOf == null)
primeGenerator(num + 1);
HashMap<Integer, Integer> fnps = new HashMap<>();
while (num != 1) {
fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1);
num /= smallestFactorOf[num];
}
return fnps;
}
static HashMap<Long, Integer> primeFactorization(long num) {
// Returns map of factor and its power in the number.
HashMap<Long, Integer> map = new HashMap<>();
while (num % 2 == 0) {
num /= 2;
Integer pwrCnt = map.get(2L);
map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1);
}
for (long i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
num /= i;
Integer pwrCnt = map.get(i);
map.put(i, pwrCnt != null ? pwrCnt + 1 : 1);
}
}
// If the number is prime, we have to add it to the
// map.
if (num != 1)
map.put(num, 1);
return map;
}
static HashSet<Long> divisors(long num) {
HashSet<Long> divisors = new HashSet<Long>();
divisors.add(1L);
divisors.add(num);
for (long i = 2; i * i <= num; i++) {
if (num % i == 0) {
divisors.add(num/i);
divisors.add(i);
}
}
return divisors;
}
static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) {
if (m > limit) return;
if (m <= limit && n <= limit)
coprimes.add(new Point(m, n));
if (coprimes.size() > numCoprimes) return;
coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes);
coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes);
coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes);
}
static long nCr(long n, long r, long[] fac) { long p = gigamod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; }
static long modInverse(long n, long p) { return power(n, p - 2, p); }
static long modDiv(long a, long b){return mod(a * power(b, mod - 2, mod), mod);}
static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; }
static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); }
static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; }
static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); }
static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static boolean isPrime(long n) {if (n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();}
static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();}
static long mod(long a, long m){return(a%m+1000000L*m)%m;}
}
/*
*
* int[] arr = new int[] {1810, 1700, 1710, 2320, 2000, 1785, 1780
, 2130, 2185, 1430, 1460, 1740, 1860, 1100, 1905, 1650};
int n = arr.length;
sort(arr);
int bel1700 = 0, bet1700n1900 = 0, abv1900 = 0;
for (int i = 0; i < n; i++)
if (arr[i] < 1700)
bel1700++;
else if (1700 <= arr[i] && arr[i] < 1900)
bet1700n1900++;
else if (arr[i] >= 1900)
abv1900++;
out.println("COUNT: " + n);
out.println("PERFS: " + toString(arr));
out.println("MEDIAN: " + arr[n / 2]);
out.println("AVERAGE: " + Arrays.stream(arr).average().getAsDouble());
out.println("[0, 1700): " + bel1700 + "/" + n);
out.println("[1700, 1900): " + bet1700n1900 + "/" + n);
out.println("[1900, 2400): " + abv1900 + "/" + n);
*
* */
// NOTES:
// ASCII VALUE OF 'A': 65
// ASCII VALUE OF 'a': 97
// Range of long: 9 * 10^18
// ASCII VALUE OF '0': 48
// Primes upto 'n' can be given by (n / (logn)). | java |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int t=1;
t=sc.nextInt();
while(--t>=0){
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
int min=a+b+c;
int X=-1,Y=-1,Z=-1;
for(int i=1;i<=Math.max(a,Math.max(b,c))*2;i++){
int x;
int X1,Y1,Z1;
if(c<=i){
x=Math.abs(i-c)+Math.abs(i-b);
Z1=i;
}
else{
int l=(c/i)*i;
int u=((c+i-1)/i)*i;
if(Math.abs(c-l)<Math.abs(c-u)){
Z1=l;
}
else{
Z1=u;
}
x=Math.min(Math.abs(c-l),Math.abs(c-u))+Math.abs(b-i);
}
for(int j=1;j*j<=i;j++){
if(i%j==0){
if(min>(x+Math.abs(a-j))){
min=x+Math.abs(a-j);
X=j;Y=i;Z=Z1;
}
if(min>(x+Math.abs(a-i/j))){
min=x+Math.abs(a-i/j);
X=i/j;Y=i;Z=Z1;
}
// min=Math.min(min,x+Math.abs(a-j));
// min=Math.min(min,x+Math.abs(a-i/j));
}
}
}
out.println(min);
out.println(X+" "+Y+" "+Z);
}
out.close();
}
}
| java |
1321 | A | A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal. | [
"greedy"
] |
import java.util.*;
public class Solution {
public static void main(String... args) throws Exception {
Scanner scan = new Scanner(System.in);
// int t = scan.nextInt();
int t=1;
while (t-- > 0) {
solve(scan);
}
scan.close();
}
public static void solve(Scanner scan) {
int n=scan.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for(int i=0;i<n;i++)
a[i]=scan.nextInt();
for(int i=0;i<n;i++)
b[i]=scan.nextInt();
int x=0,y=0;
for(int i=0;i<n;i++){
if(a[i]==1 && b[i]==0)
x++;
else if(b[i]==1 && a[i]==0)
y++;
}
if(x==0){
System.out.println("-1");
}
else{
int ans=(y)/x+1;
System.out.println(ans);
}
}
}
| java |
1285 | D | D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5. | [
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DDrEvilUnderscores solver = new DDrEvilUnderscores();
solver.solve(1, in, out);
out.close();
}
static class DDrEvilUnderscores {
int n;
int[] arr;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
arr = in.nextIntArray(n);
ArrayList<Integer> list = new ArrayList<>();
for (int a : arr) list.add(a);
out.println(rec(29, list));
}
int rec(int bit, ArrayList<Integer> list) {
if (bit < 0) return 0;
ArrayList<Integer> zero = new ArrayList<>();
ArrayList<Integer> one = new ArrayList<>();
for (int a : list) {
if (((1 << bit) & a) != 0) one.add(a);
else zero.add(a);
}
if (one.size() == 0) return rec(bit - 1, zero);
if (zero.size() == 0) return rec(bit - 1, one);
return (1 << bit) + Math.min(rec(bit - 1, zero), rec(bit - 1, one));
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| java |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00. | [
"math",
"number theory"
] |
import java.io.*;
import java.math.*;
import java.util.*;
// @author : Dinosparton
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long function(long n)
{
long ans=n;
for(long i=2;i*i<=n;i++)
{
if(n%i==0)
{
while(n%i==0)n/=i;
ans=ans-ans/i;
}
}
if(n>1)
ans=ans-ans/n;
return ans;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuilder res = new StringBuilder();
int tc = sc.nextInt();
while(tc-->0) {
long a = sc.nextLong();
long m = sc.nextLong();
res.append(function(m/gcd(a,m))+"\n");
}
System.out.println(res);
}
}
| java |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | import java.io.*;
import java.util.*;
public class A {
public static void main (String[] args) throws IOException {
Kattio io = new Kattio();
int t = io.nextInt();
for (int ii=0; ii<t; ii++) {
int n = io.nextInt();
int m = io.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i=0; i<n; i++) {
arr[i] = io.nextInt();
sum += arr[i];
}
System.out.println(Math.min(sum, m));
}
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() { this(System.in, System.out); }
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(new FileWriter(problemName + ".out"));
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.readLine());
return st.nextToken();
} catch (Exception e) { }
return null;
}
public int nextInt() { return Integer.parseInt(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public long nextLong() { return Long.parseLong(next()); }
}
} | java |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1
| [
"brute force",
"math",
"number theory"
] |
import java.io.*;
import java.util.*;
public class Codeforces{
static long mod = 1000000007L;
// map.put(a[i],map.getOrDefault(a[i],0)+1);
// map.putIfAbsent;
static MyScanner sc = new MyScanner();
//<----------------------------------------------WRITE HERE------------------------------------------->
static void solve(){
long n = sc.nextLong();
long a = 1;
long b = n;
for(long i=2;i*i<=n;i++) {
if(n%i == 0 && i != n/i) {
if(gcd(i,n/i) == 1) {
a = i;
b = n/i;
}
}
}
out.print(a+" "+b);
}
private static void sieve(boolean[] a, int n) {
a[1] = true;
for(int i=2;i*i<=n;i++) {
if(!a[i]) {
for(int j=i*i;j<=n;j+=i)
a[j] = true;
}
}
}
static boolean isPrime(long n) {
for(int i=2;i*i<=n;i++) {
if(n%i == 0) {
return false;
}
}
return true;
}
static long modInv(long x,long mod) {
return expo(x,mod-2,mod)%mod;
}
static long expo(long x,long k,long mod) {
long res = 1;
while(k>0) {
if(k%2 != 0) {
res = (res*x)%mod;
k--;
}
x = (x*x)%mod;
k /= 2;
}
return res%mod;
}
//<----------------------------------------------WRITE HERE------------------------------------------->
static void swap(int[] a,int i,int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void priArr(int[] a) {
for(int i=0;i<a.length;i++) {
out.print(a[i] + " ");
}
out.println();
}
static long gcd(long a,long b){
if(b==0) return a;
return gcd(b,a%b);
}
static class Pair implements Comparable<Pair>{
Integer val;
Integer ind;
Pair(int v,int f){
val = v;
ind = f;
}
public int compareTo(Pair p){
int s1 = this.ind-this.val;
int s2 = p.ind-p.val;
if(s1 != s2) return s1-s2;
return this.val - p.val;
}
}
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
// int t = sc.nextInt();
int t= 1;
while(t-- >0){
solve();
}
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int[] readIntArray(int n){
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = Integer.parseInt(next());
}
return arr;
}
int[] reverse(int arr[]){
int n= arr.length;
int i = 0;
int j = n-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;i++;
}
return arr;
}
long[] readLongArray(int n){
long arr[] = new long[n];
for(int i = 0;i<n;i++){
arr[i] = Long.parseLong(next());
}
return arr;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
} | java |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1
| [
"brute force",
"math",
"number theory"
] | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static int mod = (int) Math.pow(10, 9) + 7;
public static void main(String[] args) {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter o = new PrintWriter(System.out);
long n = inplongarray(f,1)[0];
var factors = new ArrayList<Long>();
for(long i=1;i*i<=n;i+=(long) 1){
if(n%i==0){
factors.add(i);factors.add(n/i);
}
}
Collections.sort(factors);
int num = factors.size();
int l = num/2-1,r=num/2;
while(lcm(factors.get(l),factors.get(r))!=n){
--l;++r;
}
out(o,factors.get(l)+" "+factors.get(r),false);
o.close();
}
public static int logg2(int n) {
return (int) (Math.log((double) n) / Math.log((double) 2));
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static String LCS(String str1, String str2, int p, int q) {
// create a matrix which act as a table for LCS
int[][] tableForLCS = new int[p + 1][q + 1];
// fill the table in the bottom up way
for (int i = 0; i <= p; i++) {
for (int j = 0; j <= q; j++) {
if (i == 0 || j == 0)
tableForLCS[i][j] = 0; // Fill each cell corresponding to first row and first column with 0
else if (str1.charAt(i - 1) == str2.charAt(j - 1))
tableForLCS[i][j] = tableForLCS[i - 1][j - 1] + 1; // add 1 in the cell of the previous row and column and fill the current cell with it
else
tableForLCS[i][j] = Math.max(tableForLCS[i - 1][j], tableForLCS[i][j - 1]); //find the maximum value from the cell of the previous row and current column and the cell of the current row and previous column
}
}
int index = tableForLCS[p][q];
int temp = index;
char[] longestCommonSubsequence = new char[index + 1];
longestCommonSubsequence[index] = '\0';
int i = p, j = q;
String lcs ="";
while (i > 0 && j > 0) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
longestCommonSubsequence[index - 1] = str1.charAt(i - 1);
i--;
j--;
index--;
}
else if (tableForLCS[i - 1][j] > tableForLCS[i][j - 1])
i--;
else
j--;
}
for (int k = 0; k <= temp; k++)
lcs = lcs + longestCommonSubsequence[k];
return lcs;
}
public static long lcm(long a, long b) {
long gcd = gcd(a, b);
return (a * b) / gcd;
}
public static int[] inp(BufferedReader f, int n) {
try {
StringTokenizer st = new StringTokenizer(f.readLine());
int[] out = new int[n];
for (int i = 0; i < n; ++i)
out[i] = Integer.parseInt(st.nextToken());
return out;
} catch (Exception e) {
return new int[] { 0, 0 };
}
}
public static long[] inplongarray(BufferedReader f, int n) {
try {
StringTokenizer st = new StringTokenizer(f.readLine());
long[] out = new long[n];
for (int i = 0; i < n; ++i)
out[i] = Long.parseLong(st.nextToken());
return out;
} catch (Exception e) {
return new long[] { 0, 0 };
}
}
public static String inp(BufferedReader f, boolean b) {
try {
return f.readLine();
} catch (Exception e) {
return "";
}
}
public static void out(PrintWriter out, String s, boolean chk) {
if (!chk)
out.println(s);
else
out.print(s);
}
public static void nl() {
System.out.print("\n");
}
public static void out(PrintWriter out, int[] a) {
for (int i = 0; i < a.length; ++i)
out.print(a[i] + " ");
out.print("\n");
}
public static void out(PrintWriter out, long[] a) {
for (int i = 0; i < a.length; ++i)
out.print(a[i] + " ");
out.print("\n");
}
public static void out(PrintWriter out, int n) {
out.println(n);
}
public static void out(PrintWriter out, long n) {
out.println(n);
}
public static void sort(int[] a) {
int n = a.length;
ArrayList<Integer> b = new ArrayList<Integer>();
for (int i : a)
b.add(i);
Collections.sort(b);
for (int i = 0; i < n; ++i) {
a[i] = b.get(i);
}
}
public static int lower_bound(int[] a, int n, int tar) {
int k = -1;
for (int b = n / 2; b >= 1; b /= 2)
while (k + b < n && a[k + b] < tar)
k += b;
return k + 1;
}
public static int upper_bound(ArrayList<Integer> a, int n, int tar) {
int k = 0;
for (int b = n / 2; b >= 1; b /= 2)
while (k + b < n && a.get(k + b) <= tar)
k += b;
return k;
}
public static void pow(int a, int b, int mod) {
BigInteger big1, big2, exp, result;
// initialize all BigInteger objects
big1 = new BigInteger(Integer.toString(a));
big2 = new BigInteger(Integer.toString(mod));
exp = new BigInteger(Integer.toString(b));
// perform modPow operation on big1 using big2 and exp
result = big1.modPow(exp, big2);
String str = "" + result;
System.out.println(str);
}
static class Pair {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int a() {
return b;
}
public int b() {
return a;
}
public void b(int nv) {
b = nv;
}
public void a(int nk) {
a = nk;
}
}
}
// Arrays.sort(a, new Comparator<int[]>() {
// public int compare(int[] frst, int[] scnd) {
// if (frst[2] > scnd[2]) {
// return -1;
// } else
// return 1;
// }
// }); | 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"
] | /**
* Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
*/
import java.io.*;
import java.util.Arrays;
public class Main {
private static long[] st, lazy;
private static int n, h;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
n = Integer.parseInt(br.readLine());
int[] p = new int[n], a = new int[n];
String[] line = br.readLine().split(" ");
for (int i = 0; i < n; ++i) {
p[i] = Integer.parseInt(line[i]);
}
line = br.readLine().split(" ");
for (int i = 0; i < n; ++i) {
a[i] = Integer.parseInt(line[i]);
}
h = -1;
for (int i = 1; i <= n; i <<= 1) {
++h;
}
st = new long[n << 1];
lazy = new long[n];
int[] indices = new int[n];
for (int i = 0; i < n; ++i) {
indices[p[i] - 1] = i;
st[n + i] = st[n + i - 1] + a[i];
}
for (int i = n - 1; i > 0; --i) {
st[i] = Math.min(st[i << 1], st[i << 1 | 1]);
}
int res = (int)query(0, n - 1);
for (int i = 0; i < n; ++i) {
int ind = indices[i];
update(ind, n, -a[ind]);
update(0, ind, a[ind]);
res = (int)Math.min(query(0, n - 1), res);
}
bw.write(Integer.toString(res));
bw.newLine();
br.close();
bw.close();
}
private static void apply(int pos, long val) {
st[pos] += val;
if (pos < n) {
lazy[pos] += val;
}
}
private static void build(int pos) {
while (pos > 1) {
pos >>= 1;
st[pos] = Math.min(st[pos << 1], st[pos << 1 | 1]) + lazy[pos];
}
}
private static void push(int pos) {
for (int s = h; s > 0; --s) {
int i = pos >> s;
if (lazy[i] != 0) {
apply(i << 1, lazy[i]);
apply(i << 1 | 1, lazy[i]);
lazy[i] = 0;
}
}
}
private static void update(int l, int r, long val) {
l += n; r += n;
for (int l2 = l, r2 = r; l2 < r2; l2 >>= 1, r2 >>= 1) {
if ((l2 & 1) != 0) {
apply(l2++, val);
}
if ((r2 & 1) != 0) {
apply(--r2, val);
}
}
build(l);
build(r - 1);
}
private static long query(int l, int r) {
l += n;
r += n;
push(l);
push(r - 1);
long res = Integer.MAX_VALUE;
while (l < r) {
if ((l & 1) != 0) {
res = Math.min(res, st[l++]);
}
if ((r & 1) != 0) {
res = Math.min(res, st[--r]);
}
l >>= 1;
r >>= 1;
}
return res;
}
} | java |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] | import java.util.*;
public class deadline {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
for (int i=0; i<count; i++) {
int n = sc.nextInt(); // required num days
int d = sc.nextInt(); // current num days
boolean yes = false;
for (int j=0; j<n; j++) {
double x = (double)d / (double)(j + 1);
int optimized = j + (int)Math.ceil(x);
if (optimized<=n) {
yes = true;
break;
}
}
if (yes) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| 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.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
public class Main {
static final long MOD=1000000007;
static final long MOD1=998244353;
static long ans=0;
//static ArrayList<Integer> ans=new ArrayList<>();
public static void main(String[] args){
PrintWriter out = new PrintWriter(System.out);
InputReader sc=new InputReader(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
int[][] A = new int[N][M];
for (int i = 0; i < A.length; i++) {
A[i] = sc.nextIntArray(M);
}
int from= 0;
int to= 1000000009;
while ((to-from)>=1) {
int mid=(to-from)/2+from;
if (f(mid, N, M, A)) {
to=mid;
}
else {
from=mid+1;
}
}
int ans = to-1;
int[] anss = f1(ans, N, M, A);
System.out.println(anss[0]+" "+anss[1]);
}
static boolean f(int mid,int N,int M,int[][] A) {
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i < N; i++) {
int fl = 0;
for (int j = 0; j < M; j++) {
if (mid<=A[i][j]) fl |= 1<<j;
}
set.add(fl);
}
int[] a = new int[set.size()];
int c = 0;
for (int i : set) {
a[c++] = i;
}
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++) {
int v = a[i]|a[j];
if (Integer.bitCount(v)==M) return false;
}
}
return true;
}
static int[] f1(int mid,int N,int M,int[][] A) {
HashSet<Integer> set = new HashSet<Integer>();
int[] s = new int[N];
for (int i = 0; i < N; i++) {
int fl = 0;
for (int j = 0; j < M; j++) {
if (mid<=A[i][j]) fl |= 1<<j;
}
s[i] = fl;
set.add(fl);
}
int[] a = new int[set.size()];
int c = 0;
for (int i : set) {
a[c++] = i;
}
int[] ans = new int[2];
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++) {
int v = a[i]|a[j];
if (Integer.bitCount(v)==M) {
for (int k = 0; k < N; k++) {
if (s[k]==a[i]) {
ans[0] = k + 1;
break;
}
}
for (int k = 0; k < N; k++) {
if (s[k]==a[j]) {
ans[1] = k + 1;
break;
}
}
return ans;
}
}
}
return null;
}
static class InputReader {
private InputStream in;
private byte[] buffer = new byte[1024];
private int curbuf;
private int lenbuf;
public InputReader(InputStream in) {
this.in = in;
this.curbuf = this.lenbuf = 0;
}
public boolean hasNextByte() {
if (curbuf >= lenbuf) {
curbuf = 0;
try {
lenbuf = in.read(buffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return false;
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[curbuf++];
else
return -1;
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private void skip() {
while (hasNextByte() && isSpaceChar(buffer[curbuf]))
curbuf++;
}
public boolean hasNext() {
skip();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (!isSpaceChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = nextDouble();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public char[][] nextCharMap(int n, int m) {
char[][] map = new char[n][m];
for (int i = 0; i < n; i++)
map[i] = next().toCharArray();
return map;
}
}
}
| java |
1288 | C | C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1]. | [
"combinatorics",
"dp"
] |
import java.util.Scanner;
public class Main{
static long mod=(long)(Math.pow(10,9)+7);
public static void main(String[] args){
Scanner in= new Scanner(System.in);
while(in.hasNext()){
int n=in.nextInt();
int m=in.nextInt();
long[][] a=new long[2*m+1][n+1];
for(int i=1;i<=n;i++) a[1][i] = 1;
for(int i=2;i<=2*m;i++){
for(int j=1;j<=n;j++){
long s = 0;
for(int k=1;k<=j;k++){
s=(s+a[i-1][k])%mod;
}
a[i][j] = s;
}
}
long ans = 0;
for(int i=1;i<=n;i++){
ans = (ans+a[2*m][i])%mod;
}
System.out.println(ans);
}
}
}
| java |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class cf {
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
public static int cnt;
//-----------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;
}
public void close() {
// TODO Auto-generated method stub
}
}
static boolean pal(String s)
{
StringBuilder sb=new StringBuilder();
sb.append(s);
sb.reverse();
String s1=sb.toString();
if(s1.contentEquals(s))
{
return true;
}
else
{
return false;
}
}
static boolean isPrime(int n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static int reverseBits(int n)
{
int rev = 0;
// traversing bits of 'n'
// from the right
while (n > 0)
{
// bitwise left shift
// 'rev' by 1
rev <<= 1;
// if current bit is '1'
if ((int)(n & 1) == 1)
rev ^= 1;
// bitwise right shift
//'n' by 1
n >>= 1;
}
// required number
return rev;
}
public static ArrayList<String> getSequence(String str)
{
// If 1
// string is empty
if (str.length() == 0) {
// Return an empty arraylist
ArrayList<String> empty = new ArrayList<>();
empty.add("");
return empty;
}
// Take first character of str
char ch = str.charAt(0);
// Take sub-string starting from the
// second character
String subStr = str.substring(1);
// Recursive call for all the sub-sequences
// starting from the second character
ArrayList<String> subSequences =
getSequence(subStr);
// Add first character from str in the beginning
// of every character from the sub-sequences
// and then store it into the resultant arraylist
ArrayList<String> res = new ArrayList<>();
for (String val : subSequences) {
res.add(val);
res.add(ch + val);
}
return res;
}
static int fact(int n)
{
int fact=1;
while(n>=1)
{
fact=fact*n;
n--;
}
return fact;
}
static long __gcd(long a, long b)
{
if (a == 0 || b == 0)
return 0;
if (a == b)
return a;
if (a > b)
return __gcd(a-b, b);
return __gcd(a, b-a);
}
static boolean coprime(long a, long b) {
if ( __gcd(a, b) == 1)
return true;
else
return false;
}
static int xor(int n,int a,int b)
{
if(n>0)
{
xor(n-1,b,a^b);
return a^b;
}
else
{
return a^b;
}
}
static ArrayList<ArrayList<Integer>> printSubArrays(int[] arr, int start, int end,ArrayList<ArrayList<Integer>> x)
{
if (end == arr.length)
{
return x;
}
else if (start > end)
{
printSubArrays(arr, 0, end + 1,x);
}
else
{
ArrayList<Integer> x1=new ArrayList<Integer>();
for (int i = start; i < end; i++)
{
x1.add(arr[i]);
}
x1.add(arr[end]);
x.add(x1);
printSubArrays(arr, start + 1, end,x);
}
return x;
}
public static ArrayList<ArrayList<Integer>> printSubsequences(int[] arr, int index,
ArrayList<Integer> path)
{
// Print the subsequence when reach
// the leaf of recursion tree
ArrayList<ArrayList<Integer>> x=new ArrayList<ArrayList<Integer>>();
if (index == arr.length)
{
// Condition to avoid printing
// empty subsequence
if (path.size() > 0)
x.add(path);
return x;
}
else
{
// Subsequence without including
// the element at current index
printSubsequences(arr, index + 1, path);
path.add(arr[index]);
x.add(path);
// Subsequence including the element
// at current index
printSubsequences(arr, index + 1, path);
x.add(path);
// Backtrack to remove the recently
// inserted element
path.remove(path.size() - 1);
x.add(path);
}
return x;
}
public static void main(String[] args)
{
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int d=sc.nextInt();
int x=1;
boolean p=false;
if(d>n)
{
while(x<=n)
{
long p1=d/(x+1);
if(d%(x+1)!=0)
{
p1++;
}
if(x+p1<=n)
{
p=true;
break;
}
x++;
}
}
else
{
p=true;
}
if(p==true)
{
out.println("YES");
}
else
{
out.println("NO");
}
}
out.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 ProblemD {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
StringBuilder sb = new StringBuilder();
int test = in.readInt();
while(test-->0){
int n = in.readInt();
int p = in.readInt();
String s = in.readLine();
int pos[] = new int[p];
for(int i = 0;i<p;i++)pos[i] = in.readInt()-1;
int count[][] = new int[n][26];
for(int i = 0;i<n;i++){
count[i][s.charAt(i)-'a']++;
if(i-1>=0){
for(int j =0;j<26;j++){
count[i][j]+=count[i-1][j];
}
}
}
int res[] = new int[26];
for(int i =0;i<p;i++){
for(int j = 0;j<26;j++){
res[j]+=count[pos[i]][j];
}
}
for(int j = 0;j<26;j++){
res[j]+=count[n-1][j];
}
for(int it:res)sb.append(it+" ");
sb.append("\n");
}
System.out.println(sb);
}
public static long nearest(TreeSet<Long> list,long target){
long nearest = -1,sofar = Integer.MAX_VALUE;
for(long it:list){
if(Math.abs(it - target)<sofar){
sofar = Math.abs(it - target);
nearest = it;
}
}
return nearest;
}
public static TreeSet<Long> factors(long n){
TreeSet<Long>set = new TreeSet<>();
for(long i = 1;i*i<=n;i++){
if(n%i == 0){
set.add(i);
if(n/i != i)set.add(n/i);
}
}
return set;
}
public static void swap(int a[],int i, int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static boolean sorted(int a[]){
for(int i =0;i<a.length;i++){
if(i+1<a.length && a[i]>a[i+1])return false;
}
return true;
}
public static int first(ArrayList<Long>list,long target){
int index = -1;
int l = 0,r = list.size()-1;
while(l<=r){
int mid = (l+r)/2;
if(list.get(mid) == target){
index = mid;
r = mid-1;
}else if(list.get(mid)>target){
r = mid-1;
}else l = mid+1;
}
return index;
}
public static int last(ArrayList<Long>list,long target){
int index = -1;
int l = 0,r = list.size()-1;
while(l<=r){
int mid = (l+r)/2;
if(list.get(mid) == target){
index= mid;
l = mid+1;
}else if(list.get(mid)<target){
l = mid+1;
}else r = mid-1;
}
return index;
}
public static void sort(int arr[]){
ArrayList<Integer>list = new ArrayList<>();
for(int it:arr)list.add(it);
Collections.sort(list);
for(int i = 0;i<arr.length;i++)arr[i] = list.get(i);
}
static class Pair{
int x,y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
}
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String read()
{
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int readInt() { return Integer.parseInt(read()); }
public long readLong() { return Long.parseLong(read()); }
public double readDouble(){return Double.parseDouble(read());}
public String readLine() throws Exception { return br.readLine(); }
}
}
| java |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | import java.util.Scanner;
public class CF1009{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
while(testCases>0){
int indexOfEvenNumber = -1;
int indexOfFirstOddNumber = -1;
int indexOfSecondOddNumber = -1;
int arrayLength = scan.nextInt();
for(int i=1; i<=arrayLength; i++){
int num = scan.nextInt();
if(num%2==0){
indexOfEvenNumber = i;
scan.nextLine();
break;
}else if(indexOfFirstOddNumber==-1){
indexOfFirstOddNumber = i;
}else{
indexOfSecondOddNumber=i;
}
}
if(indexOfEvenNumber!=-1){
System.out.println(1);
System.out.println(indexOfEvenNumber);
}else if(indexOfFirstOddNumber>0 && indexOfSecondOddNumber>0){
System.out.println(2);
System.out.println(indexOfFirstOddNumber+" "+indexOfSecondOddNumber);
}else{
System.out.println(-1);
}
testCases--;
}
}
} | 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"
] | 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.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Abhishek Patel
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
String ls = in.nextString();
String rs = in.nextString();
LinkedList<Integer> larr[] = new LinkedList[27];
LinkedList<Integer> rarr[] = new LinkedList[27];
LinkedList<Pair<Integer, Integer>> ans = new LinkedList<>();
int i = 0, j;
for (i = 0; i < 27; i++) {
larr[i] = new LinkedList<>();
rarr[i] = new LinkedList<>();
}
for (i = 0; i < n; i++) {
char c = ls.charAt(i);
char d = rs.charAt(i);
if (c == '?')
larr[26].add(i);
else
larr[c - 'a'].add(i);
if (d == '?')
rarr[26].add(i);
else
rarr[d - 'a'].add(i);
}
for (i = 0; i < 26; i++) {
int d = Math.min(larr[i].size(), rarr[i].size());
for (j = 0; j < d; j++) {
int u = larr[i].remove(0) + 1;
int y = rarr[i].remove(0) + 1;
ans.add(new Pair(u, y));
}
}
for (i = 0; i < 26; i++) {
int d = Math.min(larr[i].size(), rarr[26].size());
for (j = 0; j < d; j++) {
int u = larr[i].remove(0) + 1;
int y = rarr[26].remove(0) + 1;
ans.add(new Pair(u, y));
}
if (rarr[26].size() == 0)
break;
}
for (i = 0; i < 26; i++) {
int d = Math.min(larr[26].size(), rarr[i].size());
for (j = 0; j < d; j++) {
int u = larr[26].remove(0) + 1;
int y = rarr[i].remove(0) + 1;
ans.add(new Pair(u, y));
}
if (larr[26].size() == 0)
break;
}
int d = Math.min(larr[26].size(), rarr[26].size());
for (j = 0; j < d; j++) {
int u = larr[26].remove(0) + 1;
int y = rarr[26].remove(0) + 1;
ans.add(new Pair(u, y));
}
out.println(ans.size());
for (Pair t : ans) {
out.println(t.getFirst() + " " + t.getSecond());
}
}
}
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 String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class Pair<A, B> {
A first;
B second;
public Pair(A first, B second) {
super();
this.first = first;
this.second = second;
}
public int hashCode() {
int hashFirst = first != null ? first.hashCode() : 0;
int hashSecond = second != null ? second.hashCode() : 0;
return (hashFirst + hashSecond) * hashSecond + hashFirst;
}
public boolean equals(Object other) {
if (other instanceof Pair) {
Pair otherPair = (Pair) other;
return
((this.first == otherPair.first ||
(this.first != null && otherPair.first != null &&
this.first.equals(otherPair.first))) &&
(this.second == otherPair.second ||
(this.second != null && otherPair.second != null &&
this.second.equals(otherPair.second))));
}
return false;
}
public String toString() {
return "(" + first + ", " + second + ")";
}
public A getFirst() {
return first;
}
public B getSecond() {
return second;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void println(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"
] | /*
Author: WORTH
#: 1295C
*/
import java.util.*;
import java.io.*;
public class ObtainTheString implements Runnable {
static ContestScanner sc = new ContestScanner();
static ContestPrinter out = new ContestPrinter();
public static void main(String[] args) throws Exception {
if (System.getProperty("ONLINE_JUDGE") == null) {
sc = new ContestScanner(new File("input.txt"));
out = new ContestPrinter(new File("output.txt"));
}
try {
new Thread(null, new ObtainTheString(), "main", 1 << 28).start();
} catch (Exception e) {
out.println("Exception!!!");
throw e;
}
}
@Override
public void run() {
int testCases = sc.nextInt();
for (int testCase = 1; testCase <= testCases; testCase++) {
String s = sc.next();
String t = sc.next();
out.println(solve(s, t));
}
out.flush();
out.close();
}
@SuppressWarnings("unchecked")
static int solve(String s, String t) {
ArrayList<Integer>[] pos = new ArrayList[26];
Arrays.setAll(pos, ind->new ArrayList<>());
for (int i = 0; i < s.length(); i++) {
pos[s.charAt(i) - 'a'].add(i);
}
int ans = 0, c = 0;
int i = 0, j = 0;
while (i < t.length()) {
j = -1;
c = 0;
while (true) {
if (j == s.length() || i == t.length()) {
if (c > 0)
ans++;
break;
}
ArrayList<Integer> temp=pos[t.charAt(i)-'a'];
int ind=LowerBound(temp, j+1);
if(ind == temp.size())
j=-1;
else
j=temp.get(ind);
if (j == -1 && c == 0)
return -1;
if (j == -1) {
ans++;
break;
}
c++;
i++;
}
}
return ans;
}
static int LowerBound(ArrayList<Integer> a, long x) { // x is the target value or key
int l=-1,r=a.size();
while(l+1<r) {
int m=(l+r)>>>1;
if(a.get(m)>=x) r=m;
else l=m;
}
return r;
}
}
//Credits: https://github.com/NASU41/AtCoderLibraryForJava
class ContestScanner {
private final InputStream in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private static final long LONG_MAX_TENTHS = 922337203685477580L;
private static final int LONG_MAX_LAST_DIGIT = 7;
private static final int LONG_MIN_LAST_DIGIT = 8;
public ContestScanner(InputStream in) {
this.in = in;
}
public ContestScanner(File file) throws FileNotFoundException {
this(new BufferedInputStream(new FileInputStream(file)));
}
public ContestScanner() {
this(System.in);
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
} else {
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte()) return buffer[ptr++];
else return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
public boolean hasNext() {
while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
return hasNextByte();
}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
int digit = b - '0';
if (n >= LONG_MAX_TENTHS) {
if (n == LONG_MAX_TENTHS) {
if (minus) {
if (digit <= LONG_MIN_LAST_DIGIT) {
n = -n * 10 - digit;
b = readByte();
if (!isPrintableChar(b)) {
return n;
} else if (b < '0' || '9' < b) {
throw new NumberFormatException(
String.format("%d%s... is not number", n, Character.toString(b))
);
}
}
} else {
if (digit <= LONG_MAX_LAST_DIGIT) {
n = n * 10 + digit;
b = readByte();
if (!isPrintableChar(b)) {
return n;
} else if (b < '0' || '9' < b) {
throw new NumberFormatException(
String.format("%d%s... is not number", n, Character.toString(b))
);
}
}
}
}
throw new ArithmeticException(
String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit)
);
}
n = n * 10 + digit;
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
long nl = nextLong();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long[] nextLongArray(int length) {
long[] array = new long[length];
for (int i = 0; i < length; i++) array[i] = this.nextLong();
return array;
}
public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) {
long[] array = new long[length];
for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong());
return array;
}
public int[] nextIntArray(int length) {
int[] array = new int[length];
for (int i = 0; i < length; i++) array[i] = this.nextInt();
return array;
}
public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) {
int[] array = new int[length];
for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt());
return array;
}
public double[] nextDoubleArray(int length) {
double[] array = new double[length];
for (int i = 0; i < length; i++) array[i] = this.nextDouble();
return array;
}
public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) {
double[] array = new double[length];
for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble());
return array;
}
public long[][] nextLongMatrix(int height, int width) {
long[][] mat = new long[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextLong();
}
return mat;
}
public int[][] nextIntMatrix(int height, int width) {
int[][] mat = new int[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextInt();
}
return mat;
}
public double[][] nextDoubleMatrix(int height, int width) {
double[][] mat = new double[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextDouble();
}
return mat;
}
public char[][] nextCharMatrix(int height, int width) {
char[][] mat = new char[height][width];
for (int h = 0; h < height; h++) {
String s = this.next();
for (int w = 0; w < width; w++) {
mat[h][w] = s.charAt(w);
}
}
return mat;
}
}
class ContestPrinter extends PrintWriter {
public ContestPrinter(PrintStream stream) {
super(stream);
}
public ContestPrinter(File file) throws FileNotFoundException {
super(new PrintStream(file));
}
public ContestPrinter() {
super(System.out);
}
private static String dtos(double x, int n) {
StringBuilder sb = new StringBuilder();
if (x < 0) {
sb.append('-');
x = -x;
}
x += Math.pow(10, -n) / 2;
sb.append((long) x);
sb.append(".");
x -= (long) x;
for (int i = 0; i < n; i++) {
x *= 10;
sb.append((int) x);
x -= (int) x;
}
return sb.toString();
}
@Override
public void print(float f) {
super.print(dtos(f, 20));
}
@Override
public void println(float f) {
super.println(dtos(f, 20));
}
@Override
public void print(double d) {
super.print(dtos(d, 20));
}
@Override
public void println(double d) {
super.println(dtos(d, 20));
}
public void printArray(int[] array, String separator) {
int n = array.length;
if (n == 0) {
super.println();
return;
}
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(int[] array) {
this.printArray(array, " ");
}
public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) {
int n = array.length;
if (n == 0) {
super.println();
return;
}
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsInt(array[i]));
super.print(separator);
}
super.println(map.applyAsInt(array[n - 1]));
}
public void printArray(int[] array, java.util.function.IntUnaryOperator map) {
this.printArray(array, " ", map);
}
public void printArray(long[] array, String separator) {
int n = array.length;
if (n == 0) {
super.println();
return;
}
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(long[] array) {
this.printArray(array, " ");
}
public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) {
int n = array.length;
if (n == 0) {
super.println();
return;
}
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsLong(array[i]));
super.print(separator);
}
super.println(map.applyAsLong(array[n - 1]));
}
public void printArray(long[] array, java.util.function.LongUnaryOperator map) {
this.printArray(array, " ", map);
}
public <T> void printArray(T[] array, String separator) {
int n = array.length;
if (n == 0) {
super.println();
return;
}
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public <T> void printArray(T[] array) {
this.printArray(array, " ");
}
public <T> void printArray(T[] array, String separator, java.util.function.UnaryOperator<T> map) {
int n = array.length;
if (n == 0) {
super.println();
return;
}
for (int i = 0; i < n - 1; i++) {
super.print(map.apply(array[i]));
super.print(separator);
}
super.println(map.apply(array[n - 1]));
}
public <T> void printArray(T[] array, java.util.function.UnaryOperator<T> map) {
this.printArray(array, " ", map);
}
}
| java |
1324 | B | B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes. | [
"brute force",
"strings"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
public class YetAnotherPalindromeProblem {
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
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++) {
if (testCase()) pw.println("YES");
else pw.println("NO");
}
pw.close();
}
private static boolean testCase() throws IOException {
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
int item = arr[i];
Integer prev = map.get(item);
if (prev != null) {
if (i - prev > 1) return true;
else continue;
}
map.put(item, i);
}
return false;
}
} | java |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] |
import java.util.Scanner;
public class ArrayWithOddSum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(t>0) {
t--;
int n = in.nextInt();
int[] a = new int[n];
int odd = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
if(a[i]%2==1) odd++;
}
if(odd%2==1 || (n-odd>0 && odd>0)) System.out.println("YES");
else System.out.println("NO");
}
}
}
| java |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. | [
"data structures",
"greedy",
"implementation",
"math"
] |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
/**
*
* @author eslam
*/
public class Solution {
// Beginning of the solution
static Kattio input = new Kattio();
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>();
static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>();
static ArrayList<LinkedList<String>> allprems = new ArrayList<>();
static ArrayList<Long> luc = new ArrayList<>();
static long mod = (long) (1e9 + 7);
static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}};
static int dp[][];
static double cmp = 1e-4;
static final double pi = 3.14159265359;
static int num = 0;
static int last = -1;
static ArrayList<Long> arr = new ArrayList<>();
static LinkedList<Integer> a;
static HashMap<Long, Long> d = new HashMap<>();
public static void main(String[] args) throws IOException {
// Kattio input = new Kattio("input");
// BufferedWriter log = new BufferedWriter(new FileWriter("output.txt"));
int test = 1;//input.nextInt();
loop:
for (int co = 1; co <= test; co++) {
int q = input.nextInt();
int x = input.nextInt();
int max = q;
LinkedList<Integer> fre[] = new LinkedList[q];
for (int i = 0; i < q; i++) {
fre[i] = new LinkedList<>();
}
HashSet<Integer> s = new HashSet<>();
for (int i = 0; i < max; i++) {
fre[i % x].add(i);
}
int mex = 0;
while (q-- > 0) {
int y = input.nextInt();
if (!fre[y % x].isEmpty()) {
s.add(fre[y % x].pollFirst());
}
while (s.contains(mex)) {
mex++;
}
log.write(mex + "\n");
}
}
log.flush();
}
static int upper(int a[], int l, int r, int v) {
int max = r;
int min = l;
int ans = l - 1;
while (max >= min) {
int mid = (max + min) / 2;
if (a[mid] <= v) {
min = mid + 1;
ans = mid;
} else {
max = mid - 1;
}
}
return ans;
}
static long solve(long n) {
if (d.get(n) == null) {
d.put(n, solve(n / 2) + solve(n / 3));
}
return d.get(n);
}
static class temp {
long x;
long y;
public temp(long x, long y) {
this.x = x;
this.y = y;
}
}
static int bs1(long v) {
int max = arr.size() - 1;
int min = 0;
int ans = max;
while (max >= min) {
int mid = (max + min) / 2;
if (arr.get(mid) > v) {
max = mid - 1;
} else {
min = mid + 1;
ans = mid;
}
}
return ans;
}
static int bs2(long v) {
int max = arr.size() - 1;
int min = 0;
int ans = min;
while (max >= min) {
int mid = (max + min) / 2;
if (arr.get(mid) >= v) {
ans = mid;
max = mid - 1;
} else {
min = mid + 1;
}
}
return ans;
}
static void dfs(int cur, ArrayList<pair> g[], boolean vi[], int a[], int mid) {
num++;
vi[cur] = true;
for (pair ch : g[cur]) {
if (!vi[ch.x] && ch.y >= mid) {
dfs(ch.x, g, vi, a, mid);
}
}
}
static void floodFill(int r, int c, int a[][], boolean vi[][], int w[][], int d) {
vi[r][c] = true;
for (int i = 0; i < 4; i++) {
int nr = grid[0][i] + r;
int nc = grid[1][i] + c;
if (isValid(nr, nc, a.length, a[0].length)) {
if (Math.abs(a[r][c] - a[nr][nc]) <= d && !vi[nr][nc]) {
floodFill(nr, nc, a, vi, w, d);
}
}
}
}
static int bs(ArrayList<Long> a, long s) {
int max = a.size() - 1;
int min = 0;
int ans = 0;
while (max >= min) {
int mid = (max + min) / 2;
if (a.get(mid) <= s) {
ans = mid;
min = mid + 1;
} else {
max = mid - 1;
}
}
return ans;
}
static boolean isdigit(char ch) {
return ch >= '0' && ch <= '9';
}
static boolean lochar(char ch) {
return ch >= 'a' && ch <= 'z';
}
static boolean cachar(char ch) {
return ch >= 'A' && ch <= 'Z';
}
static class Pa {
long x;
long y;
public Pa(long x, long y) {
this.x = x;
this.y = y;
}
}
static long sqrt(long v) {
long max = (long) 4e9;
long min = 0;
long ans = 0;
while (max >= min) {
long mid = (max + min) / 2;
if (mid * mid > v) {
max = mid - 1;
} else {
ans = mid;
min = mid + 1;
}
}
return ans;
}
static long cbrt(long v) {
long max = (long) 3e6;
long min = 0;
long ans = 0;
while (max >= min) {
long mid = (max + min) / 2;
if (mid * mid > v) {
max = mid - 1;
} else {
ans = mid;
min = mid + 1;
}
}
return ans;
}
static void prefixSum2D(long arr[][]) {
for (int i = 0; i < arr.length; i++) {
prefixSum(arr[i]);
}
for (int i = 0; i < arr[0].length; i++) {
for (int j = 1; j < arr.length; j++) {
arr[j][i] += arr[j - 1][i];
}
}
}
public static long baseToDecimal(String w, long base) {
long r = 0;
long l = 0;
for (int i = w.length() - 1; i > -1; i--) {
long x = (w.charAt(i) - '0') * (long) Math.pow(base, l);
r = r + x;
l++;
}
return r;
}
static int bs(int v, ArrayList<Integer> a) {
int max = a.size() - 1;
int min = 0;
int ans = 0;
while (max >= min) {
int mid = (max + min) / 2;
if (a.get(mid) >= v) {
ans = a.size() - mid;
max = mid - 1;
} else {
min = mid + 1;
}
}
return ans;
}
static Comparator<tri> cmpTri() {
Comparator<tri> c = new Comparator<tri>() {
@Override
public int compare(tri o1, tri o2) {
if (o1.x > o2.x) {
return 1;
} else if (o1.x < o2.x) {
return -1;
} else {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
if (o1.z > o2.z) {
return 1;
} else if (o1.z < o2.z) {
return -1;
} else {
return 0;
}
}
}
}
};
return c;
}
static Comparator<pair> cmpPair2() {
Comparator<pair> c = new Comparator<pair>() {
@Override
public int compare(pair o1, pair o2) {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
if (o1.x > o2.x) {
return -1;
} else if (o1.x < o2.x) {
return 1;
} else {
return 0;
}
}
}
};
return c;
}
static Comparator<pair> cmpPair() {
Comparator<pair> c = new Comparator<pair>() {
@Override
public int compare(pair o1, pair o2) {
if (o1.x > o2.x) {
return -1;
} else if (o1.x < o2.x) {
return 1;
} else {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
return 0;
}
}
}
};
return c;
}
static class rec {
long x1;
long x2;
long y1;
long y2;
public rec(long x1, long y1, long x2, long y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public long getArea() {
return (x2 - x1) * (y2 - y1);
}
}
static long sumOfRange(int x1, int y1, int x2, int y2, long a[][]) {
return (a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1]) + a[x1 - 1][y1 - 1];
}
public static int[][] bfs(int i, int j, String w[]) {
Queue<pair> q = new ArrayDeque<>();
q.add(new pair(i, j));
int dis[][] = new int[w.length][w[0].length()];
for (int k = 0; k < w.length; k++) {
Arrays.fill(dis[k], -1);
}
dis[i][j] = 0;
while (!q.isEmpty()) {
pair p = q.poll();
int cost = dis[p.x][p.y];
for (int k = 0; k < 4; k++) {
int nx = p.x + grid[0][k];
int ny = p.y + grid[1][k];
if (isValid(nx, ny, w.length, w[0].length())) {
if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') {
q.add(new pair(nx, ny));
dis[nx][ny] = cost + 1;
}
}
}
}
return dis;
}
public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException {
for (int i = 0; i < a.length; i++) {
a[i] = new ArrayList<>();
}
while (q-- > 0) {
int x = input.nextInt();
int y = input.nextInt();
a[x].add(y);
a[y].add(x);
}
}
public static boolean isValid(int i, int j, int n, int m) {
return (i > -1 && i < n) && (j > -1 && j < m);
}
// present in the left and right indices
public static int[] swap(int data[], int left, int right) {
// Swap the data
int temp = data[left];
data[left] = data[right];
data[right] = temp;
// Return the updated array
return data;
}
// Function to reverse the sub-array
// starting from left to the right
// both inclusive
public static int[] reverse(int data[], int left, int right) {
// Reverse the sub-array
while (left < right) {
int temp = data[left];
data[left++] = data[right];
data[right--] = temp;
}
// Return the updated array
return data;
}
// Function to find the next permutation
// of the given integer array
public static boolean findNextPermutation(int data[]) {
// If the given dataset is empty
// or contains only one element
// next_permutation is not possible
if (data.length <= 1) {
return false;
}
int last = data.length - 2;
// find the longest non-increasing suffix
// and find the pivot
while (last >= 0) {
if (data[last] < data[last + 1]) {
break;
}
last--;
}
// If there is no increasing pair
// there is no higher order permutation
if (last < 0) {
return false;
}
int nextGreater = data.length - 1;
// Find the rightmost successor to the pivot
for (int i = data.length - 1; i > last; i--) {
if (data[i] > data[last]) {
nextGreater = i;
break;
}
}
// Swap the successor and the pivot
data = swap(data, nextGreater, last);
// Reverse the suffix
data = reverse(data, last + 1, data.length - 1);
// Return true as the next_permutation is done
return true;
}
public static pair[] dijkstra(int node, ArrayList<pair> a[]) {
PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() {
@Override
public int compare(tri o1, tri o2) {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
return 0;
}
}
});
q.add(new tri(node, 0, -1));
pair distance[] = new pair[a.length];
while (!q.isEmpty()) {
tri p = q.poll();
int cost = p.y;
if (distance[p.x] != null) {
continue;
}
distance[p.x] = new pair(p.z, cost);
ArrayList<pair> nodes = a[p.x];
for (pair node1 : nodes) {
if (distance[node1.x] == null) {
tri pa = new tri(node1.x, cost + node1.y, p.x);
q.add(pa);
}
}
}
return distance;
}
public static String revs(String w) {
String ans = "";
for (int i = w.length() - 1; i > -1; i--) {
ans += w.charAt(i);
}
return ans;
}
public static boolean isPalindrome(String w) {
for (int i = 0; i < w.length() / 2; i++) {
if (w.charAt(i) != w.charAt(w.length() - i - 1)) {
return false;
}
}
return true;
}
public static void getPowerSet(Queue<Integer> a) {
int n = a.poll();
if (!a.isEmpty()) {
getPowerSet(a);
}
int s = powerSet.size();
for (int i = 0; i < s; i++) {
ArrayList<Integer> ne = new ArrayList<>();
ne.add(n);
for (int j = 0; j < powerSet.get(i).size(); j++) {
ne.add(powerSet.get(i).get(j));
}
powerSet.add(ne);
}
ArrayList<Integer> p = new ArrayList<>();
p.add(n);
powerSet.add(p);
}
public static int getlo(int va) {
int v = 1;
while (v <= va) {
if ((va&v) != 0) {
return v;
}
v <<= 1;
}
return 0;
}
static long fast_pow(long a, long p, long mod) {
long res = 1;
while (p > 0) {
if (p % 2 == 0) {
a = (a * a) % mod;
p /= 2;
} else {
res = (res * a) % mod;
p--;
}
}
return res;
}
public static int countPrimeInRange(int n, boolean isPrime[]) {
int cnt = 0;
Arrays.fill(isPrime, true);
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * 2; j <= n; j += i) {
isPrime[j] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
cnt++;
}
}
return cnt;
}
public static void create(long num) {
luc.add(num);
if (num > power(10, 9)) {
return;
}
create(num * 10 + 4);
create(num * 10 + 7);
}
public static long ceil(long a, long b) {
return (a + b - 1) / b;
}
public static long round(long a, long b) {
if (a < 0) {
return (a - b / 2) / b;
}
return (a + b / 2) / b;
}
public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) {
if (l.size() == st.size()) {
allprems.add(l);
}
for (int i = 0; i < st.size(); i++) {
if (!visited[i]) {
visited[i] = true;
LinkedList<String> nl = new LinkedList<>();
for (String x : l) {
nl.add(x);
}
nl.add(st.get(i));
allPremutationsst(nl, visited, st);
visited[i] = false;
}
}
}
public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) {
if (l.size() == a.length) {
allprem.add(l);
}
for (int i = 0; i < a.length; i++) {
if (!visited[i]) {
visited[i] = true;
LinkedList<Integer> nl = new LinkedList<>();
for (Integer x : l) {
nl.add(x);
}
nl.add(a[i]);
allPremutations(nl, visited, a);
visited[i] = false;
}
}
}
public static int binarySearch(long[] a, long value) {
int l = 0;
int r = a.length - 1;
while (l <= r) {
int m = (l + r) / 2;
if (a[m] == value) {
return m;
} else if (a[m] > value) {
r = m - 1;
} else {
l = m + 1;
}
}
return -1;
}
public static void reverse(int l, int r, char ch[]) {
for (int i = 0; i < r / 2; i++) {
char c = ch[i];
ch[i] = ch[r - i - 1];
ch[r - i - 1] = c;
}
}
public static long logK(long v, long k) {
int ans = 0;
while (v > 1) {
ans++;
v /= k;
}
return ans;
}
public static long power(long a, long p) {
long res = 1;
while (p > 0) {
if (p % 2 == 0) {
a = (a * a);
p /= 2;
} else {
res = (res * a);
p--;
}
}
return res;
}
public static long get(long max, long x) {
if (x == 1) {
return max;
}
int cnt = 0;
while (max > 0) {
cnt++;
max /= x;
}
return cnt;
}
public static int numOF0(long v) {
long x = 1;
int cnt = 0;
while (x <= v) {
if ((x & v) == 0) {
cnt++;
}
x <<= 1;
}
return cnt;
}
public static int log2(double n) {
int cnt = 0;
while (n > 1) {
n /= 2;
cnt++;
}
return cnt;
}
public static int[] bfs(int node, ArrayList<Integer> a[]) {
Queue<Integer> q = new LinkedList<>();
q.add(node);
int distances[] = new int[a.length];
Arrays.fill(distances, -1);
distances[node] = 0;
while (!q.isEmpty()) {
int parent = q.poll();
ArrayList<Integer> nodes = a[parent];
int cost = distances[parent];
for (Integer node1 : nodes) {
if (distances[node1] == -1) {
q.add(node1);
distances[node1] = cost + 1;
}
}
}
return distances;
}
public static void primeFactors(int n, HashMap<Integer, ArrayList<Integer>> h, int ind) {
boolean ca = true;
while (n % 2 == 0) {
if (ca) {
if (h.get(2) == null) {
h.put(2, new ArrayList<>());
}
h.get(2).add(ind);
ca = false;
}
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
ca = true;
while (n % i == 0) {
if (ca) {
if (h.get(i) == null) {
h.put(i, new ArrayList<>());
}
h.get(i).add(ind);
ca = false;
}
n /= i;
}
if (n < i) {
break;
}
}
if (n > 2) {
if (h.get(n) == null) {
h.put(n, new ArrayList<>());
}
h.get(n).add(ind);
}
}
// end of solution
public static BigInteger f(long n) {
if (n <= 1) {
return BigInteger.ONE;
}
long t = n - 1;
BigInteger b = new BigInteger(t + "");
BigInteger ans = new BigInteger(n + "");
while (t > 1) {
ans = ans.multiply(b);
b = b.subtract(BigInteger.ONE);
t--;
}
return ans;
}
public static long factorial(long n) {
if (n <= 1) {
return 1;
}
long t = n - 1;
while (t > 1) {
n = mod((mod(n, mod) * mod(t, mod)), mod);
t--;
}
return n;
}
public static long rev(long n) {
long t = n;
long ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans;
}
public static boolean isPalindrome(int n) {
int t = n;
int ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans == n;
}
static class tri {
int x, y, z;
public tri(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public String toString() {
return x + " " + y + " " + z;
}
}
static boolean isPrime(long num) {
if (num == 1) {
return false;
}
if (num == 2) {
return true;
}
if (num % 2 == 0) {
return false;
}
if (num == 3) {
return true;
}
for (long i = 3; i * i <= num; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void prefixSum(long[] a) {
for (int i = 1; i < a.length; i++) {
a[i] = a[i] + a[i - 1];
}
}
public static void suffixSum(long[] a) {
for (int i = a.length - 2; i > -1; i--) {
a[i] = a[i] + a[i + 1];
}
}
static long mod(long a, long b) {
long r = a % b;
return r < 0 ? r + b : r;
}
public static long binaryToDecimal(String w) {
long r = 0;
long l = 0;
for (int i = w.length() - 1; i > -1; i--) {
long x = (w.charAt(i) - '0') * (long) Math.pow(2, l);
r = r + x;
l++;
}
return r;
}
public static String decimalAnyBase(long n, long base) {
String w = "";
while (n > 0) {
w = n % base + w;
n /= base;
}
return w;
}
public static String decimalToBinary(long n) {
String w = "";
while (n > 0) {
w = n % 2 + w;
n /= 2;
}
return w;
}
public static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
public static void print(long[] a) throws IOException {
for (int i = 0; i < a.length; i++) {
log.write(a[i] + " ");
}
log.write("\n");
}
public static void read(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = input.nextInt();
}
}
static class gepair {
long x;
long y;
public gepair(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
static class pair {
int x;
int y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
static class pai {
long x;
int y;
public pai(long x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
public static long LCM(long x, long y) {
return x / GCD(x, y) * y;
}
public static long GCD(long x, long y) {
if (y == 0) {
return x;
}
return GCD(y, x % y);
}
public static void simplifyTheFraction(int a, int b) {
long GCD = GCD(a, b);
System.out.println(a / GCD + " " + b / GCD);
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() {
this(System.in, System.out);
}
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(problemName + ".out");
r = new BufferedReader(new FileReader(problemName + ".txt"));
}
// returns null if no more input
String nextLine() {
String str = "";
try {
str = r.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(r.readLine());
}
return st.nextToken();
} catch (Exception e) {
}
return null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| java |
1323 | B | B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is: | [
"binary search",
"greedy",
"implementation"
] |
import java.io.*;
import java.util.*;
// SCREAM AS LOUD AS YOU CAN
// FUCK !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public class Aqueous {
static MyScanner sc = new MyScanner();
static PrintWriter pw = new PrintWriter(System.out);
static class pair{
int k ;
String s;
public pair(int k , String s) {
this.k = k;
this.s = s;
}
}
public static void main(String[] args) {
int n = sc.nextInt();
int m = sc.nextInt();
int k =sc.nextInt();
int nn[] = new int[n];
for(int i = 0; i<n; i++) {
nn[i] = sc.nextInt();
}
int mm[] = new int[m];
for(int i = 0; i<m;i++) {
mm[i] = sc.nextInt();
}
int ans[] = gao(nn);
// for(int e : ans) {
// pw.print(e+" ");
// }
//
// pw.println();
int ans1[] = gao(mm);
// for(int e : ans1) {
// pw.print(e+" ");
// }
// pw.println();
ArrayList<Integer> al = factors(k);
long answer = 0;
for(int e: al) {
if(e<ans.length && (k/e)<ans1.length) {
answer += ans[e]*ans1[k/e];
}
}
pw.println(answer);
pw.close();
}
static int[] gao(int a[]) {
int n = a.length;
int res[] = new int[n+1];
int i = 0;
while(i<n) {
if(a[i]==0) {
i++;
continue;
}
int j = i;
while(j<n && a[j]==1) {
j++;
}
for(int len = 1; len<=j-i; len++) {
res[len] +=j-i-len+1;
}
i=j;
}
return res;
}
static ArrayList<Integer> factors(int k){
ArrayList<Integer> al = new ArrayList<>();
al.add(1);
for(int i = 2; i*i<=k; i++) {
if(k%i==0) {
al.add(i);
if((k/i)!=i) {
al.add(k/i);
}
}
}
if(!al.contains(k)) {
al.add(k);
}
return al;
}
static void ruffleSort(int a[]) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < n; i++) {
int oi = r.nextInt(n);
int temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long a[]) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < n; i++) {
int oi = r.nextInt(n);
long temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
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 |
1284 | D | D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2
1 2 3 6
3 4 7 8
OutputCopyYES
InputCopy3
1 3 2 4
4 5 6 7
3 4 5 5
OutputCopyNO
InputCopy6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
OutputCopyYES
NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist. | [
"binary search",
"data structures",
"hashing",
"sortings"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.function.LongBinaryOperator;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedOutputStream;
import java.io.UncheckedIOException;
import java.util.Objects;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author mikit
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
LightScanner in = new LightScanner(inputStream);
LightWriter out = new LightWriter(outputStream);
DNewYearAndConference solver = new DNewYearAndConference();
solver.solve(1, in, out);
out.close();
}
static class DNewYearAndConference {
public void solve(int testNumber, LightScanner in, LightWriter out) {
out.setBoolLabel(LightWriter.BoolLabel.YES_NO_ALL_UP);
int n = in.ints();
DNewYearAndConference.Event[] events = new DNewYearAndConference.Event[n];
for (int i = 0; i < n; i++)
events[i] = new DNewYearAndConference.Event(in.longs(), in.longs(), in.longs(), in.longs());
if (solve(n, events)) {
out.noln();
return;
}
for (int j = 0; j < n; j++) events[j].swap();
if (solve(n, events)) {
out.noln();
return;
}
out.yesln();
}
static boolean solve(int n, DNewYearAndConference.Event[] events) {
DNewYearAndConference.Event[] starts = events.clone(), ends = events.clone();
IntroSort.sort(starts, Comparator.comparing(event -> event.s1));
IntroSort.sort(ends, Comparator.comparing(event -> event.e1));
for (int j = 0; j < n; j++) ends[j].index = j;
IntSegmentTree min, max;
{
max = new IntSegmentTree(new long[n + 1], Math::max, -1, (x, u) -> u);
long[] tmp = new long[n + 1];
Arrays.fill(tmp, Long.MAX_VALUE);
min = new IntSegmentTree(tmp, Math::min, Long.MAX_VALUE, (x, u) -> u);
}
int cur = 0;
for (int i = 0; i < n; i++) {
while (cur < n && starts[cur].s1 <= ends[i].e1) {
max.update(starts[cur].index, starts[cur].s2);
min.update(starts[cur].index, starts[cur].e2);
cur++;
}
int ok = 0, ng = n;
while (ng - ok > 1) {
int mid = (ng + ok) / 2;
if (ends[i].s1 <= ends[mid].e1) ng = mid;
else ok = mid;
}
long maxStart = max.query(ng, n), minEnd = min.query(ng, n);
if (ends[i].e2 < maxStart || minEnd < ends[i].s2) {
return true;
}
}
return false;
}
private static class Event {
long s1;
long e1;
long s2;
long e2;
int index;
Event(long s1, long e1, long s2, long e2) {
this.s1 = s1;
this.e1 = e1;
this.s2 = s2;
this.e2 = e2;
}
void swap() {
long t = s1;
s1 = s2;
s2 = t;
t = e1;
e1 = e2;
e2 = t;
}
public String toString() {
return "Event{" +
"s1=" + s1 +
", e1=" + e1 +
", s2=" + s2 +
", e2=" + e2 +
", index=" + index +
'}';
}
}
}
static class InsertionSort {
private InsertionSort() {
}
static <T> void sort(T[] a, int low, int high, Comparator<? super T> comparator) {
for (int i = low; i < high; i++) {
for (int j = i; j > low && comparator.compare(a[j - 1], a[j]) > 0; j--) {
ArrayUtil.swap(a, j - 1, j);
}
}
}
}
static class IntSegmentTree {
private final int n;
private final int m;
private final long[] tree;
private final LongBinaryOperator op;
private final LongBinaryOperator up;
private final long zero;
public IntSegmentTree(long[] array, LongBinaryOperator op, long zero, LongBinaryOperator up) {
this.n = array.length;
int msb = BitMath.extractMsb(n);
this.m = n == msb ? msb : (msb << 1);
this.tree = new long[m * 2 - 1];
this.op = op;
this.up = up;
this.zero = zero;
Arrays.fill(tree, zero);
System.arraycopy(array, 0, this.tree, m - 1, array.length);
for (int i = m - 2; i >= 0; i--) {
tree[i] = op.applyAsLong(tree[2 * i + 1], tree[2 * i + 2]);
}
}
public void update(int i, long v) {
i += m - 1;
tree[i] = up.applyAsLong(tree[i], v);
while (i > 0) {
i = (i - 1) / 2;
tree[i] = op.applyAsLong(tree[2 * i + 1], tree[2 * i + 2]);
}
}
public long query(int l, int r) {
long left = zero, right = zero;
l += m - 1;
r += m - 1;
while (l < r) {
if ((l & 1) == 0) {
left = op.applyAsLong(left, tree[l]);
}
if ((r & 1) == 0) {
right = op.applyAsLong(tree[r - 1], right);
}
l = l / 2;
r = (r - 1) / 2;
}
return op.applyAsLong(left, right);
}
}
static interface Verified {
}
static class QuickSort {
private QuickSort() {
}
private static <T> void med(T[] a, int low, int x, int y, int z, Comparator<? super T> comparator) {
if (comparator.compare(a[z], a[x]) < 0) {
ArrayUtil.swap(a, low, x);
} else if (comparator.compare(a[y], a[z]) < 0) {
ArrayUtil.swap(a, low, y);
} else {
ArrayUtil.swap(a, low, z);
}
}
static <T> int step(T[] a, int low, int high, Comparator<? super T> comparator) {
int x = low + 1, y = low + (high - low) / 2, z = high - 1;
if (comparator.compare(a[x], a[y]) < 0) {
med(a, low, x, y, z, comparator);
} else {
med(a, low, y, x, z, comparator);
}
int lb = low + 1, ub = high;
while (true) {
while (comparator.compare(a[lb], a[low]) < 0) {
lb++;
}
ub--;
while (comparator.compare(a[low], a[ub]) < 0) {
ub--;
}
if (lb >= ub) {
return lb;
}
ArrayUtil.swap(a, lb, ub);
lb++;
}
}
}
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 void setBoolLabel(LightWriter.BoolLabel label) {
this.boolLabel = Objects.requireNonNull(label);
}
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 IntroSort {
private static int INSERTIONSORT_THRESHOLD = 16;
private IntroSort() {
}
static <T> void sort(T[] a, int low, int high, int maxDepth, Comparator<T> comparator) {
while (high - low > INSERTIONSORT_THRESHOLD) {
if (maxDepth-- == 0) {
HeapSort.sort(a, low, high, comparator);
return;
}
int cut = QuickSort.step(a, low, high, comparator);
sort(a, cut, high, maxDepth, comparator);
high = cut;
}
InsertionSort.sort(a, low, high, comparator);
}
public static <T> void sort(T[] a, Comparator<T> comparator) {
if (a.length <= INSERTIONSORT_THRESHOLD) {
InsertionSort.sort(a, 0, a.length, comparator);
} else {
sort(a, 0, a.length, 2 * BitMath.msb(a.length), comparator);
}
}
}
static final class BitMath {
private BitMath() {
}
public static int count(int v) {
v = (v & 0x55555555) + ((v >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
v = (v & 0x0f0f0f0f) + ((v >> 4) & 0x0f0f0f0f);
v = (v & 0x00ff00ff) + ((v >> 8) & 0x00ff00ff);
v = (v & 0x0000ffff) + ((v >> 16) & 0x0000ffff);
return v;
}
public static int msb(int v) {
if (v == 0) {
throw new IllegalArgumentException("Bit not found");
}
v |= (v >> 1);
v |= (v >> 2);
v |= (v >> 4);
v |= (v >> 8);
v |= (v >> 16);
return count(v) - 1;
}
public static int extractMsb(int v) {
v = (v & 0xFFFF0000) > 0 ? v & 0xFFFF0000 : v;
v = (v & 0xFF00FF00) > 0 ? v & 0xFF00FF00 : v;
v = (v & 0xF0F0F0F0) > 0 ? v & 0xF0F0F0F0 : v;
v = (v & 0xCCCCCCCC) > 0 ? v & 0xCCCCCCCC : v;
v = (v & 0xAAAAAAAA) > 0 ? v & 0xAAAAAAAA : v;
return v;
}
}
static final class ArrayUtil {
private ArrayUtil() {
}
public static <T> void swap(T[] a, int x, int y) {
T t = a[x];
a[x] = a[y];
a[y] = t;
}
}
static class HeapSort {
private HeapSort() {
}
private static <T> void heapfy(T[] a, int low, int high, int i, T val, Comparator<? super T> comparator) {
int child = 2 * i - low + 1;
while (child < high) {
if (child + 1 < high && comparator.compare(a[child], a[child + 1]) < 0) {
child++;
}
if (comparator.compare(val, a[child]) >= 0) {
break;
}
a[i] = a[child];
i = child;
child = 2 * i - low + 1;
}
a[i] = val;
}
static <T> void sort(T[] a, int low, int high, Comparator<T> comparator) {
for (int p = (high + low) / 2 - 1; p >= low; p--) {
heapfy(a, low, high, p, a[p], comparator);
}
while (high > low) {
high--;
T pval = a[high];
a[high] = a[low];
heapfy(a, low, high, low, pval, comparator);
}
}
}
}
| java |
1288 | E | E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3] | [
"data structures"
] | import java.util.*;
import java.io.*;
public class E80
{
public static void main(String [] args)
{
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt(); int m = sc.nextInt(); int [] a = new int [m];
for (int i = 0; i < m; i++) a[i] = sc.nextInt();
FenwickTree bit = new FenwickTree(m + 1); int [] max = new int [n+1]; int [] last = new int [n+1];
for (int i = 1; i <= n; i++) max[i] = i;
Arrays.fill(last, -1); FenwickTree bit2 = new FenwickTree(n + 1);
Map<Integer, Query> map = new HashMap<>();
for (int i = 0; i < m; i++) {
if (last[a[i]] != -1) {
map.put(i, new Query(last[a[i]], i));
} else {
map.put(i, new Query(-1, i));
}
last[a[i]] = i;
}
ArrayList<Query> q = new ArrayList<>();
for (int i = 1; i <= n; i++) {
q.add(new Query(last[i], m));
}
last = new int [n+1]; Arrays.fill(last, -1);
for (int i = 0; i < m; i++) {
int start = map.get(i).start; int end = map.get(i).end;
if (start == -1) {
int query = bit2.sum(a[end]);
max[a[end]] = Math.max(max[a[end]], a[end] + bit2.sum(n) - query);
bit2.update(a[end], 1); bit.update(i + 1, 1);
last[a[i]] = i;
} else {
if (start + 1 == end) {
bit.update(start + 1, -1);
bit.update(end + 1, 1); last[a[end]] = i;
continue;
}
int query = bit.rangeSum(start + 1, end + 1);
max[a[end]] = Math.max(max[a[end]], query); bit.update(start + 1, -1);
bit.update(end + 1, 1); last[a[end]] = i;
}
}
for (int i = 0; i < q.size(); i++) {
int start = q.get(i).start; int end = q.get(i).end;
if (start != -1) {
int query = bit.rangeSum(start + 1, m);
max[a[start]] = Math.max(max[a[start]], query);
}
}
for (int i = 1; i <= n; i++) {
if (last[i] == -1) {
int query = bit2.sum(i);
max[i] = Math.max(max[i], i + bit2.sum(n) - query);
}
}
int [] min = new int [n+1]; for (int i = 1; i <= n; i++) min[i] = last[i] == -1 ? i : 1;
for (int i = 1; i <= n; i++) out.println(min[i] + " " + max[i]);
out.close();
}
static class Query {
int start; int end;
Query(int start, int end) {
this.start = start; this.end = end;
}
}
static class FenwickTree
{
int size;
int [] table;
FenwickTree(int size)
{
table = new int [size];
this.size = size;
}
void init(int [] nums)
{
for (int i = 1; i < nums.length; i++)
{
update(i, nums[i]);
}
}
void update(int i, int delta)
{
while (i < size)
{
table[i] += delta;
i += Integer.lowestOneBit(i);
}
}
int sum(int i)
{
int sum = 0;
while (i > 0)
{
sum += table[i];
i -= Integer.lowestOneBit(i);
}
return sum;
}
int rangeSum(int i, int j)
{
return sum(j) - sum(i - 1);
}
}
//-----------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 |
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 JoeTv {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int n = console.nextInt();
double money = 0.0;
for (int i = n; i > 0; i--) {
money += (1.0/i);
}
System.out.print(money);
}
} | 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.lang.*;
public class Main {
/*------------------------ MAIN METHOD ---------------------*/
public static void main(String arg[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer enter = new StringTokenizer(in.readLine().strip());
int n = Integer.parseInt(enter.nextToken().strip());
int m = Integer.parseInt(enter.nextToken().strip());
if(m%n!=0){
out.print(-1+"\n");
out.flush();
}else{
int res = m/n;
int i = 0;
while(res%2==0){
i++;
res/=2;
}
int j = 0;
while(res%3==0){
j++;
res/=3;
}
if(res!=1){
out.print(-1+"\n");
out.flush();
}else{
out.print(i+j+"\n");
out.flush();
}
}
/*----------------------------------------*/
/*----------------------------------------*/ theEnd();
/*----------------------------------------*/
}
/*--------------------------------------------------------------------------------------------------------*/
public static void theEnd() {
System.exit(0);
}
}
| java |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | [
"implementation",
"math"
] | import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int sum=0;
for(int i=2;i<a;i++){
int t=a;
while(t>0){
sum+=(t%i);
t/=i;
}
}
int g=gcd(sum,a-2);
sum=sum/g;a=(a-2)/g;
System.out.println(sum+"/"+a);
}
public static int gcd(int a,int b){
if(b==0){
return a;
}
else return gcd(b,a%b);
}
} | java |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] |
import java.util.*;
import java.math.*;
import java.io.*;
public class NonZero {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int i = 0; i < t; i++) {
int n = in.nextInt(),sum=0,steps=0;
int[]arr=new int [n];
for(int j=0;j<n;j++){
arr[j]= in.nextInt();
if(arr[j]==0){
arr[j]=1;
steps++;
}
sum+=arr[j];
}
if(sum!=0)
System.out.println(steps);
else
System.out.println(steps+1);
}
}
}
| java |
1322 | C | C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11. | [
"graphs",
"hashing",
"math",
"number theory"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.BufferedInputStream;
import java.util.Random;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.FilterInputStream;
import java.util.Map;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CInstantNoodles solver = new CInstantNoodles();
solver.solve(1, in, out);
out.close();
}
static class CInstantNoodles {
long[] random;
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int t = in.scanInt();
random = new long[500005];
for (int i = 0; i < random.length; i++) random[i] = new Random().nextInt(1000000000) + 234792734l;
while (t-- > 0) {
int n = in.scanInt();
int m = in.scanInt();
long cost[] = new long[n + 1];
for (int i = 1; i <= n; i++) cost[i] = in.scanLong();
ArrayList<Integer> arrayList[] = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) arrayList[i] = new ArrayList<>();
// HashMap<Long, Long> hashMap = new HashMap<>();
Map<ArrayList<Integer>, Long> nums = new HashMap<>();
for (int i = 0; i < m; i++) {
int a = in.scanInt();
int b = in.scanInt();
arrayList[b].add(a);
}
for (int i = 1; i <= n; i++) {
if (arrayList[i].size() == 0) continue;
long hash = findHash(arrayList[i]);
Collections.sort(arrayList[i]);
nums.put(arrayList[i], nums.getOrDefault(arrayList[i], 0l) + cost[i]);
// hashMap.put(hash, cost[i] + hashMap.getOrDefault(hash, 0l));
}
long gcd = 0;
for (long kkk : nums.values()) {
gcd = CodeX.GCD(gcd, kkk);
}
out.println(gcd);
}
}
long findHash(ArrayList<Integer> arrayList) {
int p = 0;
long res = 0;
for (int k : arrayList) {
res = (res + ((k * random[p++]) % 792950153)) % 792950153;
}
return res;
}
}
static class CodeX {
public static long GCD(long A, long B) {
if (B == 0)
return A;
else
return GCD(B, A % B);
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
}
}
| java |
1325 | D | D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty. | [
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] |
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long u = sc.nextLong();
long v = sc.nextLong();
if (u % 2 != v % 2 || u > v) {
System.out.println(-1);
} else if (u == v) {
if (u == 0) {
System.out.println(0);
} else {
System.out.println(1);
System.out.println(v);
}
} else {
long x = (v - u) / 2;
if ((u & x) != 0) {
System.out.println(3);
System.out.println(u + " " + x + " " + x);
} else {
System.out.println(2);
System.out.println(u + x + " " + x);
}
}
}
} | java |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
| [
"brute force",
"data structures",
"sortings"
] | import java.io.*;
import java.util.Arrays;
import java.util.InputMismatchException;
public class E1320C {
static long INF = (long) 1e18;
static int A = (int) 1e6;
public static void main(String[] args) {
FastIO io = new FastIO();
int n = io.nextInt();
int m = io.nextInt();
int p = io.nextInt();
//addition, cost
int[][] weapons = new int[n][2];
//w, a
int[][] monsters = new int[p][3];
for (int i = 0; i < n; i++) weapons[i] = new int[]{io.nextInt(), io.nextInt()};
SegmentTree st = new SegmentTree(A + 2);
long[] initTree = new long[A + 2];
Arrays.fill(initTree, -INF);
for (int i = 0; i < m; i++) {
int addition = io.nextInt();
int cost = io.nextInt();
initTree[addition] = Math.max(initTree[addition], -cost);
}
for (int i = 0; i < p; i++)
monsters[i] = new int[]{io.nextInt(), io.nextInt(), io.nextInt()};
for (int i = 0; i <= A; i++) st.update(1, i, i, initTree[i]);
Arrays.sort(monsters, (a, b) -> a[0] - b[0]);
Arrays.sort(weapons, (a, b) -> a[0] - b[0]);
long ans = -INF;
for (int i = 0, j = 0; i < n; i++) {
for (; j < p && monsters[j][0] < weapons[i][0]; j++) {
st.update(1, monsters[j][1] + 1, A + 1, monsters[j][2]);
}
long localAns = st.query(1, 0, A) - weapons[i][1];
ans = Math.max(ans, localAns);
}
io.println(ans);
io.close();
}
private static class SegmentTree {
int[] hi, lo;
long[] modTree, tree;
static long treeId = -INF;
static int modId = 0;
public SegmentTree(int n) {
this.hi = new int[4 * n + 1];
this.lo = new int[4 * n + 1];
this.modTree = new long[4 * n + 1];
this.tree = new long[4 * n + 1];
init(1, 0, n - 1);
}
private void init(int i, int from, int to) {
lo[i] = from;
hi[i] = to;
if (from == to) return;
int mid = (from + to) >> 1;
init(i << 1, from, mid);
init((i << 1) + 1, mid + 1, to);
}
private long get(int i) {
return modTree[i] + tree[i];
}
private void prop(int i) {
modTree[2 * i] = modToMod(modTree[2 * i], modTree[i]);
modTree[2 * i + 1] = modToMod(modTree[2 * i + 1], modTree[i]);
modTree[i] = modId;
}
private long modToMod(long a, long b) {
return a + b;
}
private long valueToValue(long a, long b) {
return Math.max(a, b);
}
private void fix(int i) {
tree[i] = valueToValue(get(2 * i), get(2 * i + 1));
}
private void update(int i, int l, int r, long value) {
if (lo[i] >= l && hi[i] <= r) {
modTree[i] = modToMod(modTree[i], value);
return;
}
if (lo[i] > r || hi[i] < l) return;
prop(i);
update(2 * i, l, r, value);
update(2 * i + 1, l, r, value);
fix(i);
}
private long query(int i, int l, int r) {
if (lo[i] >= l && hi[i] <= r) return get(i);
if (lo[i] > r || hi[i] < l) return treeId;
prop(i);
long lTree = query(2 * i, l, r);
long rTree = query(2 * i + 1, l, r);
fix(i);
return valueToValue(lTree, rTree);
}
}
private static class FastIO extends PrintWriter {
private final InputStream stream;
private final byte[] buf = new byte[1 << 16];
private int curChar, numChars;
// standard input
public FastIO() {
this(System.in, System.out);
}
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c;
do {
c = nextByte();
} while (c <= ' ');
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nextByte();
} while (c > ' ');
return res.toString();
}
public int nextInt() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| java |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
| [
"dp",
"strings"
] | import java.io.*;
import java.util.*;
public class Main{
static char[]in1,in2;
static int[][]memo;
static int startSub1=0,endSub1,startSub2,endSub2,inf=10000;
static int[][]nxt;
static int dp(int i,int j) {
if(i<startSub1 && j<startSub2)return 0;
if(i<startSub1) {
int o2=dp(i,j-1);
int option2=o2>=in1.length?inf:nxt[o2][in2[j]-'a'];
return option2+1;
}
if(j<startSub2) {
int o1=dp(i-1,j);
int option1=o1>=in1.length?inf:nxt[o1][in2[i]-'a'];
return option1+1;
}
if(memo[i][j]!=-1)return memo[i][j];
int o1=dp(i-1,j),o2=dp(i,j-1);
int option1=o1>=in1.length?inf:nxt[o1][in2[i]-'a'];
int option2=o2>=in1.length?inf:nxt[o2][in2[j]-'a'];
return memo[i][j]=Math.min(option1, option2)+1;
}
public static void main(String[] args) throws Exception{
MScanner sc=new MScanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int tc=sc.nextInt();
while(tc-->0) {
in1=sc.nextLine().toCharArray();
in2=sc.nextLine().toCharArray();
nxt=new int[in1.length][26];
for(int i[]:nxt) {
Arrays.fill(i, inf);
}
for(int i=in1.length-1;i>=0;i--) {
if(i<in1.length-1)
nxt[i]=nxt[i+1].clone();
for(char c='a';c<='z';c++) {
if(in1[i]==c) {
nxt[i][c-'a']=i;
}
}
}
boolean yes=false;
endSub2=in2.length-1;
for(int cut=0;cut<in1.length;cut++) {
endSub1=cut;startSub2=cut+1;
memo=new int[in2.length][in2.length];
for(int i[]:memo)Arrays.fill(i, -1);
int len=dp(endSub1,endSub2);
if(len<=in1.length) {
yes=true;break;
}
}
pw.println(yes?"YES":"NO");
}
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[] intArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(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);
}
}
static void addX(int[]in,int x) {
for(int i=0;i<in.length;i++)in[i]+=x;
}
static void addX(long[]in,int x) {
for(int i=0;i<in.length;i++)in[i]+=x;
}
} | java |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
| [
"data structures",
"implementation"
] | import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = in.nextInt();
for (int tt = 0; tt < t; tt++) {
int n = in.nextInt();
char[] s = in.next().toCharArray();
TreeMap<XY, Integer> map = new TreeMap<>();
int start = -1, end = 1_000_000_000;;
XY cur = new XY(0, 0);
map.put(cur, -1);
/// debug(map);
for (int i = 0; i < n; i++) {
cur = new XY(cur.x, cur.y);
//debug(cur);
if (s[i] == 'U') cur.y++;
if (s[i] == 'D') cur.y--;
if (s[i] == 'L') cur.x--;
if (s[i] == 'R') cur.x++;
// debug(cur);
int last = map.getOrDefault(cur, -100_000_000);
if (i - last < end - start) {
end = i;
start = last;
}
map.put(cur, i);
}
/* debug(map);
debug(end, start);*/
if ((end - start + 1) < 1_000_000) {
pw.println((start + 2) + " " + (end + 1));
} else pw.println(-1);
}
pw.close();
}
static class XY implements Comparable<XY> {
int x, y;
XY(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(XY o) {
if (o.x != this.x) return Integer.compare(this.x, o.x);
return Integer.compare(this.y, o.y);
}
@Override
public String toString() {
return "[" +
"x:" + x +
", y:" + y +
']';
}
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
}
| java |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
| [
"brute force",
"data structures",
"sortings"
] | import java.util.*;
import java.io.*;
public class Y{
final static int M=(1<<20);
static long[] t1=new long[M*2+5];
static long[] t2=new long[M*2+5];
static long[] ca=new long[M], cb=new long[M];
static long ans;
static int n,m,p,x,y,i,j;
public static void upd(int i){
t1[i]=t1[i<<1]+t1[i<<1|1];
t2[i]=Math.max(t2[i<<1],t1[i<<1]+t2[i<<1|1]);
}
public static void add(int i,int v){
for(t1[i+=M]+=v;(i>>=1)>0;upd(i));
}
public static void main(String[] args) throws IOException{
Reader in = new Reader();
long Z= 1; Z<<=60;
for(i=0;i<M;++i)ca[i]=cb[i]=Z;ans=-Z;
n=in.nextInt();m=in.nextInt();p=in.nextInt();
mons[] a = new mons[p+1];a[0]=new mons(0, 0, 0);
for(i=1;i<=n;++i){x=in.nextInt();y=in.nextInt();ca[x]=Math.min(ca[x],y);}
for(i=1;i<=m;++i){x=in.nextInt();y=in.nextInt();cb[x]=Math.min(cb[x],y);}
for(i=0;i<M;++i)t2[i+M]=-cb[i];for(i=M-1;i!=0;--i)upd(i);
for(i=1;i<=p;++i){a[i]= new mons(in.nextInt(),in.nextInt(),in.nextInt());}
Arrays.sort(a);
for(i=0,j=1;i<M;++i){
for(;j<=p && a[j].x<i;++j)add(a[j].y,a[j].z);
ans=Math.max(ans,t2[1]-ca[i]);
}
System.out.println(ans);
in.close();
}
static class Reader{
final private int S = (1<<16);
private int bp,br;
private byte[] buff;
private DataInputStream din;
public Reader(){
din = new DataInputStream(System.in);
bp=br=0;buff= new byte[S];
}
private void fill() throws IOException{
br = din.read(buff,bp=0,S);
if(br==-1)buff[0]=-1;
}
private byte read() throws IOException{
if(bp==br)fill();
return buff[bp++];
}
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 void close() throws IOException {
if(din==null)return;
din.close();
}
}
}
class mons implements Comparable<mons>{
int x,y,z;
public mons(int x,int y, int z){
this.x=x;this.y=y;this.z=z;
}
@Override
public int compareTo(mons o) {
if(x>o.x){return 1;}
if(x<o.x){return -1;}
return 0;
}
} | java |
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 CodeForces_1312A_TwoRegularPolygon {
private static final Scanner STDIN_SCANNER = new Scanner(System.in);
private static void solve() {
int n = STDIN_SCANNER.nextInt();
int m = STDIN_SCANNER.nextInt();
if(n%m == 0) System.out.println("YES");
else System.out.println("NO");
}
public static void main(String[] args) {
int t = STDIN_SCANNER.nextInt();
while((t--) >0) {
solve();
}
}
} | java |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class edu130 {
//private static Object m;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static boolean func(long x,long k){
return (k-((x*x)+(x)+1))%(2*x)==0;
}
public static void gg(int [] arr, int l, int r, int count , int[] ans){
if(r<l){
return;
}
if(r==l){
ans[l]=count;
return;
}
int m=l;
for(int i=l+1;i<=r;i++){
if(arr[i]>arr[m]){
m=i;
}
}
ans[m]=count;
gg(arr,l,m-1,count+1,ans);
gg(arr,m+1,r,count+1,ans);
}
public static void main(String[] args) {
//RSRRSRSSSR
try {
FastReader sc = new FastReader();
FastWriter out = new FastWriter();
int n=sc.nextInt();
int [] arr=new int[n];
HashMap<Integer,Long> map=new HashMap<>();
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
map.put(i-arr[i],map.getOrDefault(i-arr[i],0L)+arr[i]);
}
long max=Long.MIN_VALUE;
for(int keys:map.keySet()){
max=Math.max(max,map.get(keys))
; }
System.out.println(max);
}catch(Exception e){
return;
}
}
public static int gfg(int [] arr,int n,int index,int i,int [] dp){
if(i>=n)return 0;
// if(i==n-1){
// if(index==-1)return arr[i];
// if(arr[i]<=arr[index])return 0;
// if(index-arr[index]!=i-arr[i])return 0;
// return arr[i];
// }
if(index!=-1)
if(dp[i]!=-1 && index-arr[index]==i-arr[i] )return dp[i];
int nottake= gfg(arr, n, index, i + 1, dp);
int take=0;
if(index==-1 || (arr[i]>arr[index]) && (index-arr[index]==i-arr[i])){
take=arr[i]+gfg(arr,n,i,i+1,dp);
}
return dp[i]=Math.max(dp[i],Math.max(take,nottake));
}
private static void swap(int[] arr, int i, int ii) {
int temp=arr[i];
arr[i]=arr[ii];
arr[ii]=temp;
}
public static int lcm(int a,int b){
return (a/gcd(a,b))*b;
}
private static int gcd(int a, int b) {
if(b==0)return a;
return gcd(b,a%b);
}
static class Pair {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
} | java |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
| [
"math"
] | import java.util.*;public class J{public static void main(String[]h){Scanner s=new Scanner(System.in);int x=s.nextInt();for(int i=0;i<x;i++){int a=s.nextInt(),b=s.nextInt(),c=s.nextInt(),n=s.nextInt();int m=Math.max(a,Math.max(b,c)),z=(n-(m*3-(a+b+c)));if(z%3==0&&z>-1)
System.out.println("YES");else
System.out.println("NO");}}} | java |
1324 | C | C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right. | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] | import java.util.Scanner;
public class AlgoAssignment {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int t=in.nextInt();
for(int i=0;i<t;i++){
String st=in.next();
st = "R" + st + "R";
int prev=0;
int max=0;
for(int j=0;j<st.length();j++){
if(st.charAt(j)=='R'){
max=Math.max(max, j-prev-1);
prev=j;
}
}
System.out.println(max+1);
}
}
}
| 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"
] | //package com.example.practice.codeforces.below2000;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
//A. Garland
public class Solution112 {
public static void main (String [] args) throws IOException {
// Use BufferedReader rather than RandomAccessFile; it's much faster
final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// input file name goes above
StringTokenizer st = new StringTokenizer(input.readLine());
final int n = Integer.parseInt(st.nextToken());
final int[] ns = readArrayInt(n, input);
out.println(calc(n, ns));
out.close(); // close the output file
}
private static int calc(final int n, final int[] ns) {
int[] rd = new int[n];
boolean[] seen = new boolean[n+1];
int pre = 0, odd = 0, even = 0;
for (int i=0;i<n;++i){
rd[i] = pre;
if (ns[i]==0)pre++;
seen[ns[i]] = true;
}
for (int i=1;i<=n;++i){
if (!seen[i]){
if (i%2==0)even++;
else odd++;
}
}
Integer[][][] dp = new Integer[2][n][odd+1];
return todo(dp, 0, 0, odd, rd, odd, even, ns);
}
private static int todo(Integer[][][] dp, int st, int idx, final int c, int[] rd, final int odd, final int even, int[] ns){
if (idx >= rd.length)return 0;
if (dp[st][idx][c] != null){
return dp[st][idx][c];
}
if (ns[idx] > 0){
dp[st][idx][c] = todo(dp, ns[idx]%2, idx+1, c, rd, odd, even, ns) + (idx==0 || st==(ns[idx]%2) ? 0 : 1);
}else {
dp[st][idx][c] = rd.length;
if (c > 0){
dp[st][idx][c] = todo(dp, 1, idx+1, c-1, rd, odd, even, ns) + (idx==0 || st==1 ? 0 : 1);
}
if (rd[idx]-(odd-c) < even){
dp[st][idx][c] = Math.min(dp[st][idx][c], todo(dp, 0, idx+1, c, rd, odd, even, ns) + (idx==0 || st==0 ? 0 : 1));
}
}
return dp[st][idx][c];
}
private static void printArray(long[] ns, final PrintWriter out){
for (int i=0;i<ns.length;++i){
out.print(ns[i]);
if (i+1<ns.length)out.print(" ");
else out.println();
}
}
private static void printArrayInt(int[] ns, final PrintWriter out){
for (int i=0;i<ns.length;++i){
out.print(ns[i]);
if (i+1<ns.length)out.print(" ");
else out.println();
}
}
private static void printArrayVertical(long[] ns, final PrintWriter out){
for (long a : ns){
out.println(a);
}
}
private static void printArrayVerticalInt(int[] ns, final PrintWriter out){
for (int a : ns){
out.println(a);
}
}
private static void printArray2D(long[][] ns, final int len, final PrintWriter out){
int cnt = 0;
for (long[] kk : ns){
cnt++;
if (cnt > len)break;
for (int i=0;i<kk.length;++i){
out.print(kk[i]);
if (i+1<kk.length)out.print(" ");
else out.println();
}
}
}
private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){
int cnt = 0;
for (int[] kk : ns){
cnt++;
if (cnt > len)break;
for (int i=0;i<kk.length;++i){
out.print(kk[i]);
if (i+1<kk.length)out.print(" ");
else out.println();
}
}
}
private static long[] readArray(final int n, final BufferedReader input) throws IOException{
long[] ns = new long[n];
StringTokenizer st = new StringTokenizer(input.readLine());
for (int i=0;i<n;++i){
ns[i] = Long.parseLong(st.nextToken());
}
return ns;
}
private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{
int[] ns = new int[n];
StringTokenizer st = new StringTokenizer(input.readLine());
for (int i=0;i<n;++i){
ns[i] = Integer.parseInt(st.nextToken());
}
return ns;
}
private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{
long[] ns = new long[n];
for (int i=0;i<n;++i){
ns[i] = Long.parseLong(input.readLine());
}
return ns;
}
private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{
long[][] ns = new long[len][];
for (int i=0;i<n;++i){
StringTokenizer st = new StringTokenizer(input.readLine());
ArrayList<Long> al = new ArrayList<>();
while (st.hasMoreTokens()){
al.add(Long.parseLong(st.nextToken()));
}
long[] kk = new long[al.size()];
for (int j=0;j<kk.length;++j){
kk[j] = al.get(j);
}
ns[i] = kk;
}
return ns;
}
private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{
int[][] ns = new int[len][];
for (int i=0;i<n;++i){
StringTokenizer st = new StringTokenizer(input.readLine());
ArrayList<Integer> al = new ArrayList<>();
while (st.hasMoreTokens()){
al.add(Integer.parseInt(st.nextToken()));
}
int[] kk = new int[al.size()];
for (int j=0;j<kk.length;++j){
kk[j] = al.get(j);
}
ns[i] = kk;
}
return ns;
}
} | java |
1307 | D | D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33. | [
"binary search",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | import java.io.*;
import java.util.*;
/*
*/
public class A {
static FastReader sc=null;
public static void main(String[] args) {
sc=new FastReader();
int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt();
int a[]=sc.readArray(k);
for(int i=0;i<k;i++)a[i]--;
ArrayList<Integer> adj[]=new ArrayList[n];
for(int i=0;i<n;i++)adj[i]=new ArrayList<>();
for(int i=0;i<m;i++) {
int v=sc.nextInt()-1,w=sc.nextInt()-1;
adj[v].add(w);
adj[w].add(v);
}
int dists[]=bfs(adj,0),diste[]=bfs(adj,n-1);
//print(dists);
//print(diste);
//maximize the minimum of (dist_s[u]+dist_e[v],dist_e[u]+dist_s[v])
//we have to choose a combination such that this distance is minimized
Pair ps[]=new Pair[k];
for(int i=0;i<k;i++) {
ps[i]=new Pair(a[i],dists[a[i]],diste[a[i]]);
}
Arrays.sort(ps);
//gives the maximum end until now
int suff[]=new int[k];
suff[k-1]=ps[k-1].e;
for(int i=k-2;i>=0;i--)suff[i]=Math.max(suff[i+1], ps[i].e);
int ans=0;
for(int i=0;i+1<k;i++) {
ans=Math.max(ps[i].s+suff[i+1]+1, ans);
}
// int max=0;
// for(int i=0;i<k;i++) {
// for(int j=i+1;j<k;j++) {
// int d=Math.min(dists[a[i]]+diste[a[j]]+1, dists[a[j]]+diste[a[i]]+1);
// max=Math.max(d,max);
// }
// }
// System.out.println(max);
ans=(Math.min(ans, dists[n-1]));
System.out.println(ans);
}
static class Pair implements Comparable<Pair>{
int id,s,e;
Pair(int id,int s,int e){
this.id=id;
this.s=s;
this.e=e;
}
public int compareTo(Pair o) {
return this.s-o.s;
}
}
static int[] bfs(ArrayList<Integer> adj[],int src) {
int n=adj.length;
int dist[]=new int[n];
Arrays.fill(dist, -1);
dist[src]=0;
ArrayDeque<Integer> bfs=new ArrayDeque<>();
bfs.add(src);
while(!bfs.isEmpty()) {
int q=bfs.remove();
for(int e:adj[q]) {
if(dist[e]==-1) {
dist[e]=dist[q]+1;
bfs.add(e);
}
}
}
return dist;
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader{
StringTokenizer st=new StringTokenizer("");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String next() {
while(!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
}
catch(IOException e){
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
return a;
}
}
}
| java |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | import java.io.*;
import java.util.*;
public class ProblemD {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
StringBuilder sb = new StringBuilder();
int test = in.readInt();
while(test-->0){
int a = in.readInt();
int b = in.readInt();
int c = in.readInt();
long min = Integer.MAX_VALUE;
String res = "";
for(int i =1;i<=10000;i++){
for(int j = 1;i*j<=c+100;j++){
long cost = Math.abs(i - a) + Math.abs(i*j - b);
long choice = (c/(i*j))*(i*j);
cost+=Math.abs(choice - c);
if(cost<min){
min = cost;
res = i+" "+(i*j)+" "+(choice);
}
cost -=Math.abs(choice - c);
choice+=(i*j);
cost+=Math.abs(choice-c);
if(cost<min){
min = cost;
res = i+" "+(i*j)+" "+(choice);
}
}
}
sb.append(min);
sb.append("\n");
sb.append(res);
sb.append("\n");
}
System.out.println(sb);
}
public static long nearest(TreeSet<Long> list,long target){
long nearest = -1,sofar = Integer.MAX_VALUE;
for(long it:list){
if(Math.abs(it - target)<sofar){
sofar = Math.abs(it - target);
nearest = it;
}
}
return nearest;
}
public static TreeSet<Long> factors(long n){
TreeSet<Long>set = new TreeSet<>();
for(long i = 1;i*i<=n;i++){
if(n%i == 0){
set.add(i);
if(n/i != i)set.add(n/i);
}
}
return set;
}
public static void swap(int a[],int i, int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static boolean sorted(int a[]){
for(int i =0;i<a.length;i++){
if(i+1<a.length && a[i]>a[i+1])return false;
}
return true;
}
public static int first(ArrayList<Long>list,long target){
int index = -1;
int l = 0,r = list.size()-1;
while(l<=r){
int mid = (l+r)/2;
if(list.get(mid) == target){
index = mid;
r = mid-1;
}else if(list.get(mid)>target){
r = mid-1;
}else l = mid+1;
}
return index;
}
public static int last(ArrayList<Long>list,long target){
int index = -1;
int l = 0,r = list.size()-1;
while(l<=r){
int mid = (l+r)/2;
if(list.get(mid) == target){
index= mid;
l = mid+1;
}else if(list.get(mid)<target){
l = mid+1;
}else r = mid-1;
}
return index;
}
public static void sort(int arr[]){
ArrayList<Integer>list = new ArrayList<>();
for(int it:arr)list.add(it);
Collections.sort(list);
for(int i = 0;i<arr.length;i++)arr[i] = list.get(i);
}
static class Pair{
int x,y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
}
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String read()
{
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int readInt() { return Integer.parseInt(read()); }
public long readLong() { return Long.parseLong(read()); }
public double readDouble(){return Double.parseDouble(read());}
public String readLine() throws Exception { return br.readLine(); }
}
}
| java |
1316 | B | B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. | [
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
/*
-> Give your 100%, that's it!
-> Rules To Solve Any Problem:
1. Read the problem.
2. Think About It.
3. Solve it!
*/
public class Template {
static int mod = 1000000007;
public static void main(String[] args){
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int yo = sc.nextInt();
while (yo-- > 0) {
int n = sc.nextInt();
char[] a = sc.next().toCharArray();
StringBuilder ans = new StringBuilder();
int kAns = 0;
for(int k = 1; k <= n; k++){
char[] temp = a.clone();
if(k % 2 == 1 && n % 2 == 1){
reverse(a,0,k-2,n);
}
if(k % 2 == 0 && n % 2 == 0){
reverse(a,0,k-2,n);
}
StringBuilder curr = new StringBuilder();
for(int i = k-1; i < n; i++){
curr.append(a[i]);
}
for(int i = 0; i < k-1; i++){
curr.append(a[i]);
}
// out.println(curr.toString() + " " + k + " " + (ans.toString().compareTo(curr.toString())));
if(ans.length() == 0 || ans.toString().compareTo(curr.toString()) > 0){
ans = new StringBuilder(curr);
kAns = k;
}
a = temp.clone();
}
out.println(ans.toString());
out.println(kAns);
}
out.close();
}
static void reverse(char[] a, int i, int j, int n){
if(j >= n){
return;
}
while(i <= j){
char temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
/*
abab
baab
k = 2
01234
abcde
bacde
bcade
bcdae
bcdea
k = 3
01245
abcde -> cdeba
cbade
cdabe
cdeba
k = 4
01245
abcde -> de -- abc
dcbae
deabc
k = 5
01245
abcde -> ed
012345
alaska -> kaalas
ksalaa
Source: hu_tao
Random stuff to try when stuck:
- use bruteforcer
- always check for n = 1, n = 2, so on
-if it's 2C then it's dp
-for combo/probability problems, expand the given form we're interested in
-make everything the same then build an answer (constructive, make everything 0 then do something)
-something appears in parts of 2 --> model as graph
-assume a greedy then try to show why it works
-find way to simplify into one variable if multiple exist
-treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them)
-find lower and upper bounds on answer
-figure out what ur trying to find and isolate it
-see what observations you have and come up with more continuations
-work backwards (in constructive, go from the goal to the start)
-turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements)
-instead of solving for answer, try solving for complement (ex, find n-(min) instead of max)
-draw something
-simulate a process
-dont implement something unless if ur fairly confident its correct
-after 3 bad submissions move on to next problem if applicable
-do something instead of nothing and stay organized
-write stuff down
Random stuff to check when wa:
-if code is way too long/cancer then reassess
-switched N/M
-int overflow
-switched variables
-wrong MOD
-hardcoded edge case incorrectly
Random stuff to check when tle:
-continue instead of break
-condition in for/while loop bad
Random stuff to check when rte:
-switched N/M
-long to int/int overflow
-division by 0
-edge case for empty list/data structure/N=1
*/
public static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void sort(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
for (int i = 0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] sieve(int N) {
boolean[] sieve = new boolean[N + 1];
for (int i = 2; i <= N; i++)
sieve[i] = true;
for (int i = 2; i <= N; i++) {
if (sieve[i]) {
for (int j = 2 * i; j <= N; j += i) {
sieve[j] = false;
}
}
}
return sieve;
}
public static long power(long x, long y, long p) {
long res = 1L;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y >>= 1;
x = (x * x) % p;
}
return res;
}
public static void print(int[] arr, PrintWriter out) {
//for debugging only
for (int x : arr)
out.print(x + " ");
out.println();
}
public static int log2(int a){
return (int)(Math.log(a)/Math.log(2));
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
// For Input.txt and Output.txt
// FileInputStream in = new FileInputStream("input.txt");
// FileOutputStream out = new FileOutputStream("output.txt");
// PrintWriter pw = new PrintWriter(out);
// Scanner sc = new Scanner(in);
} | java |
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"
] | /*
Rating: 1378
Date: 19-10-2022
Time: 19-24-09
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 Main {
// Returns (a * b) % mod
static long moduloMultiplication(long a, long b,
long mod)
{
// Initialize result
long res = 0;
// Update a if it is more than
// or equal to mod
a %= mod;
while (b > 0) {
// If b is odd, add a with result
if ((b & 1) != 0)
res = (res + a) % mod;
// Here we assume that doing 2*a
// doesn't cause overflow
a = (2 * a) % mod;
b >>= 1; // b = b / 2
}
return res;
}
// Global Variables
static long x, y;
// Function for extended Euclidean Algorithm
static long gcdExtended(long a, long b)
{
// Base Case
if (a == 0) {
x = 0;
y = 1;
return b;
}
// To store results of recursive call
long gcd = gcdExtended(b % a, a);
long x1 = x;
long y1 = y;
// Update x and y using results of recursive
// call
x = y1 - (b / a) * x1;
y = x1;
return gcd;
}
static long modInverse(long a, long m)
{
long g = gcdExtended(a, m);
// Return -1 if b and m are not co-prime
if (g != 1)
return -1;
// m is added to handle negative x
return (x % m + m) % m;
}
// Function to compute a/b under modulo m
static long modDivide(long a, long b, long m)
{
a = a % m;
long inv = modInverse(b, m);
if (inv == -1)
return 0;
else
return (inv * a) % m;
}
// Function to calculate nCr % p
static long nCr(long n, long r, long p)
{
// Edge Case which is not possible
if (r > n)
return 0;
// Optimization for the cases when r is large
if (r > n - r)
r = n - r;
// x stores the current result at
long x = 1;
// each iteration
// Initialized to 1 as nC0 is always 1.
for (long i = 1L; i <= r; i++) {
// Formula derived for calculating result is
// C(n,r-1)*(n-r+1)/r
// Function calculates x*(n-i+1) % p.
x = moduloMultiplication(x, (n + 1L - i), p);
// Function calculates x/i % p.
x = modDivide(x, i, p);
}
return x;
}
public static void s() {
int n = sc.nextInt();
int m = sc.nextInt();
long cans = nCr(m, n-1, MOD);
cans = cans*(n-2);
long pow = Functions.pow(2, n-3);
p.writeln(Functions.mod_mul(cans, pow));
}
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) 998244353 ;
static final FastReader sc = new FastReader();
static final Print p = new Print();
static class Functions {
static void sort(int... a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static void sort(long... a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static int max(int... a) {
int max = Integer.MIN_VALUE;
for (int val : a) max = Math.max(val, max);
return max;
}
static int min(int... a) {
int min = Integer.MAX_VALUE;
for (int val : a) min = Math.min(val, min);
return min;
}
static long min(long... a) {
long min = Long.MAX_VALUE;
for (long val : a) min = Math.min(val, min);
return min;
}
static long max(long... a) {
long max = Long.MIN_VALUE;
for (long val : a) max = Math.max(val, max);
return max;
}
static long sum(long... a) {
long sum = 0;
for (long val : a) sum += val;
return sum;
}
static int sum(int... a) {
int sum = 0;
for (int val : a) sum += val;
return sum;
}
public static long mod_add(long a, long b) {
return (a % MOD + b % MOD + MOD) % MOD;
}
public static long pow(long a, long b) {
long res = 1;
while (b > 0) {
if ((b & 1) != 0)
res = mod_mul(res, a);
a = mod_mul(a, a);
b >>= 1;
}
return res;
}
public static long mod_mul(long a, long b) {
long res = 0;
a %= MOD;
while (b > 0) {
if ((b & 1) > 0) {
res = mod_add(res, a);
}
a = (2 * a) % MOD;
b >>= 1;
}
return res;
}
public static long gcd(long a, long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
public static long factorial(long n) {
long res = 1;
for (int i = 1; i <= n; i++) {
res = (i % MOD * res % MOD) % MOD;
}
return res;
}
public static int count(int[] arr, int x) {
int count = 0;
for (int val : arr) if (val == x) count++;
return count;
}
public static ArrayList<Integer> generatePrimes(int n) {
boolean[] primes = new boolean[n];
for (int i = 2; i < primes.length; i++) primes[i] = true;
for (int i = 2; i < primes.length; i++) {
if (primes[i]) {
for (int j = i * i; j < primes.length; j += i) {
primes[j] = false;
}
}
}
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < primes.length; i++) {
if (primes[i]) arr.add(i);
}
return arr;
}
}
static class Print {
StringBuffer strb = new StringBuffer();
public void write(Object str) {
strb.append(str);
}
public void writes(Object str) {
char c = ' ';
strb.append(str).append(c);
}
public void writeln(Object str) {
char c = '\n';
strb.append(str).append(c);
}
public void writeln() {
char c = '\n';
strb.append(c);
}
public void yes() {
char c = '\n';
writeln("YES");
}
public void no() {
writeln("NO");
}
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 |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00. | [
"math",
"number theory"
] | import java.io.PrintWriter;
import java.util.Scanner;
//https://codeforces.com/contest/1295/problem/D
//maybe I would solve this problem if I know Euler's product formula before
// before I know one equation from Internet, it is that gcd(a, m) = gcd(a, a1) * gcd(a, a2) * gcd(a, a3) where a1 * a2 * a3 = m
// and a1, a2, a3 are coprime pairwise
//now we think about this, what makes gcd(a, m) = gcd(a + x, m). if we suppose gcd(a, a1) = y > 1, and rest of them is 1, which means
// we need to find a number a + x which should have gcd(a + x, a1) = y and gcd(a + x, a1) = 1...
//so that a + x should have y, but cannot hve a1, a2 or a1 ^ 1 or a2 ^2 and so on
//why we should do this ? : we can see that a1 should be the power of one prime, and a2 is as well which denotes that if gcd(a + x, a1) != gcd(a, a1)
//you cannot make gcd(a, a1) * gcd(a, a2) * gcd(a, a3) = gcd(a + x, a1) * gcd(a + x, a2) * gcd(a + x, a3) because output of these gcd number is coprime
//now we know that we just need to know how many value of a + x which makes gcd(a + x, a2) = 1 and gcd(a + x, a3) = 1
//well, we know x < m and gcd(𝑎+𝑥,𝑚)=gcd(𝑎+𝑥−𝑚,𝑚) therefore we need to find out x_neo = (a + x) % mod this means each value of a + x could find a reflect
//on the range of 0 to m, such that gcd(x_neo, m) = gcd(a, m)
//with the above mentioned conclusion we just need to find how many numbers of x_neo such that gcd(x_neo / (gcd(x_neo, m)), m / (gcd(x_neo, m))) = 1
// this is just gcd(a, a2) * gcd(a, a3) = 1 => gcd(a, a2 * a3) = 1, then this is Euler's totient function
//
public class SameGCDs {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
solve(sc, pw);
}
pw.close();
}
static void solve(Scanner in, PrintWriter out){
long a = in.nextLong(), m = in.nextLong();
long get = gcd(a, m);
out.println(phi(m / get));
}
// credits to LorDick for Euler's totient function which is used to calculate the number of coprime with m and smaller than m
static long phi(long x) {
long ans = x;
for(long i = 2; i * i <= x; i++) {
if(x % i == 0) {
while(x % i == 0) {
x /= i;
}
ans /= i;
ans *= (i - 1);
}
}
if(x > 1) {
ans /= x;
ans *= (x - 1);
}
return ans;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
}
| java |
1307 | C | C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l. | [
"brute force",
"dp",
"math",
"strings"
] | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class C_Cow_and_Message {
static long mod = Long.MAX_VALUE;
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = 1;
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
String s = f.nextLine();
int n = s.length();
int freq[] = new int[26];
for(int i = 0; i < n; i++) {
freq[s.charAt(i)-'a']++;
}
long ans = 0;
for(int i = 0; i < 26; i++) {
ans = max(ans, freq[i]);
}
for(int i = 0; i < 26; i++) {
for(int j = 0; j < 26; j++) {
long first = 0;
long curr = 0;
for(int k = 0; k < n; k++) {
if(s.charAt(k)-'a' == j) {
curr += first;
}
if(s.charAt(k)-'a' == i) {
first++;
}
}
ans = max(ans, curr);
}
}
out.println(ans);
}
// Sort an array
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
// Find all divisors of n
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
// Check if n is prime or not
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
// Find gcd of a and b
public static long gcd(long a, long b) {
long dividend = a > b ? a : b;
long divisor = a < b ? a : b;
while(divisor > 0) {
long reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
// Find lcm of a and b
public static long lcm(long a, long b) {
long lcm = gcd(a, b);
long hcf = (a * b) / lcm;
return hcf;
}
// Find factorial in O(n) time
public static long fact(int n) {
long res = 1;
for(int i = 2; i <= n; i++) {
res = res * i;
}
return res;
}
// Find power in O(logb) time
public static long power(long a, long b) {
long res = 1;
while(b > 0) {
if((b&1) == 1) {
res = (res * a)%mod;
}
a = (a * a)%mod;
b >>= 1;
}
return res;
}
// Find nCr
public static long nCr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / (fact(r) * fact(n-r));
return ans;
}
// Find nPr
public static long nPr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / fact(r);
return ans;
}
// sort all characters of a string
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// User defined class for fast I/O
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
boolean hasNext() {
if (st != null && st.hasMoreTokens()) {
return true;
}
String tmp;
try {
br.mark(1000);
tmp = br.readLine();
if (tmp == null) {
return false;
}
br.reset();
} catch (IOException e) {
return false;
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
// (a/b)%mod == (a * moduloInverse(b)) % mod;
// moduloInverse(b) = power(b, mod-2);
| java |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.nextLine());
String str = sc.nextLine().trim();
StringBuilder sb = new StringBuilder(str);
for (char ch = 'z'; ch > 'a'; ch--) {
for (int index = 0; index < sb.length(); index++) {
if (sb.charAt(index) == ch) {
if ((index - 1 >= 0 && sb.charAt(index - 1) == ch - 1)
|| (index + 1 < sb.length() && sb.charAt(index + 1) == ch - 1)) {
sb.deleteCharAt(index);
index = -1;
}
}
}
}
System.out.println(N - sb.length());
}
} | java |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| [
"greedy"
] |
import java.util.*;
public class MergeSort {
static int[][] move = {{1, 1}, {1, 0}, {1, -1}, {0, 1}, {-1, 1}, {0, -1}, {-1, -1}, {0, -1}};
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
while (test-- > 0) {
int n = sc.nextInt();
int[] bb = new int[n];
boolean[] used = new boolean[n * 2 + 1];
for (int i = 0; i < n; i++) {
int b = sc.nextInt();
bb[i] = b;
used[b] = true;
}
int[] aa = new int[n * 2];
boolean yes = true;
for (int i = 0; i < n; i++) {
int b = bb[i];
int c = b + 1;
while (c <= n * 2 && used[c])
c++;
if (c > n * 2) {
yes = false;
break;
}
used[c] = true;
aa[i << 1] = b;
aa[i << 1 | 1] = c;
}
if (yes) {
for (int i = 0; i < n * 2; i++)
System.out.print(aa[i] + " ");
System.out.println();
} else
System.out.println(-1);
}
}
static class Group implements Comparable<Group>{
int x;int y;
Group(int x, int y){
this.x=x;this.y=y;
}
@Override
public int compareTo(Group o) {
return x-o.x;
}
}
//////////Helper Functions////////////////////////////////////
private static char getCharFromASCII(int c) {
return (char) (c + 96);
}
private static boolean isValidPos(long x, long y, long i, long j) {
return i < x && i >= 0 && j >= 0 && j < y;
}
private static int getFactorial(int n) {
int res = 1;
for (int i = 2; i <= n; i++) res = res * i;
return res;
}
private static boolean isPalindrome(char[] s) {
int start = 0, last = s.length - 1;
while (start < last) {
if (s[start] != s[last]) return false;
start++;
last--;
}
return true;
}
private static void swap(int i, int j, long[] arr) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static void swap(int i, int j) {
int temp = i;
i = j;
j = temp;
}
private static boolean isEven(int a) {
return a % 2 == 0;
}
static int findGCD(int x, int y) {
int r = 0, a, b;
a = Math.max(x, y);
b = Math.min(x, y);
r = b;
while (a % b != 0) {
r = a % b;
a = b;
b = r;
}
return r;
}
static int findLcm(int a, int b) {
return (a * b) / findGCD(a, b);
}
private static boolean primalityTest(int n) {
if (n == 1) return false;
for (int i = 2; i * i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
private static void swap(int i, int j, char[] arr) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public static Pair asFraction(long a, long b) {
long gcd = gcd(a, b);
return new Pair(a / gcd, b / gcd);
}
static class Pair {
long x, y, z;
Pair(int x, int y){
this.x=(int)x;this.y=(int)y;
}
Pair(long x, long y) {
this.x = x;
this.y = y;
}
Pair(long x, long y, long z) {
this.x = x;
this.y = y;
this.z = z;
}
}
}
| java |
1312 | B | B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
| [
"constructive algorithms",
"sortings"
] | import java.io.*;
import java.util.*;
public class Bogosort
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int q = Integer.parseInt(in.readLine()); q > 0; --q) {
int n = Integer.parseInt(in.readLine());
int[] a = new int[n];
StringTokenizer st = new StringTokenizer(in.readLine());
for (int i = 0; i < n; ++i) {
a[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(a);
for (int i = n; --i >= 0;) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}
} | java |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6
| [
"greedy",
"sortings"
] | import java.util.*;
public class class398 {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a=sc.nextInt();
int b=sc.nextInt();
int k=sc.nextInt();
int i;
int sum=a+b;
PriorityQueue<Integer> pq=new PriorityQueue<>();
for(i=0;i<n;i++)
{
int x=sc.nextInt();
if(x%sum==0)
{
int c=(int)Math.ceil((double)sum/a);
c--;
pq.add(c);
}
else
{
int rem=x%sum;
int c=(int)Math.ceil((double)rem/a);
c--;
pq.add(c);
}
}
int ans=0;
while(pq.size()>0)
{
int val=pq.poll();
if(k-val>=0)
{
ans++;
k-=val;
}
else
break;
}
System.out.println(ans);
}
}
| java |
1288 | E | E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3] | [
"data structures"
] | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
PrintWriter out = new PrintWriter(System.out);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer("");
String next() throws IOException {
if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }
return tok.nextToken();
}
int ni() throws IOException { return Integer.parseInt(next()); }
long nl() throws IOException { return Long.parseLong(next()); }
long mod=1000000007;
void solve() throws IOException {
int n=ni(),m=ni();
int[]min=new int[n+1];
for (int i=1;i<=n;i++) min[i]=i;
int[]max=new int[n+1];
int[]lastmove=new int[n+1];
st1 pre=new st1(1,n);
st2 post=new st2(1,m);
for (int i=1;i<=m;i++) {
int u=ni();
min[u]=1;
if (lastmove[u]==0) {
max[u]=u+pre.query(u);
pre.update(u);
}
else {
max[u]=Math.max(max[u],post.query(lastmove[u]));
}
post.update(lastmove[u]+1,i);
lastmove[u]=i;
}
for (int i=1;i<=n;i++) {
out.print(min[i]+" ");
if (lastmove[i]==0) max[i]=i+pre.query(i);
else {
max[i]=Math.max(max[i],post.query(lastmove[i]));
}
out.println(max[i]);
}
out.flush();
}
class st2 {
int lt,rt,s;
st2 lc,rc;
st2(int p,int q) {
lt=p; rt=q;
if (lt==rt) return;
int mid=(p+q)/2;
lc=new st2(p,mid);
rc=new st2(mid+1,q);
}
void update(int p,int q) {
if (q<lt || p>rt) return;
if (p<=lt && q>=rt) { s++; return; }
distrib();
lc.update(p,q);
rc.update(p,q);
}
int query(int u) {
if (lt==rt) return s;
distrib();
if (u>lc.rt) return rc.query(u);
else return lc.query(u);
}
void distrib() {
if (s>0) {
lc.s+=s;
rc.s+=s;
s=0;
}
}
}
class st1 {
int mid,s;
boolean f;
st1 lc,rc;
st1(int p,int q) {
if (p==q) { f=true; return; }
mid=(p+q)/2;
lc=new st1(p,mid);
rc=new st1(mid+1,q);
}
void update(int u) {
if (f) { s++; return; }
distrib();
if (u<=mid) lc.update(u);
else { lc.s+=1; rc.update(u); }
}
int query(int u) {
if (f) { return s; }
distrib();
if (u>mid) return rc.query(u);
else return lc.query(u);
}
void distrib() {
if (s>0) {
lc.s+=s;
rc.s+=s;
s=0;
}
}
}
int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); }
long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); }
long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; }
public static void main(String[] args) throws IOException {
new Main().solve();
}
} | java |
1304 | D | D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS. | [
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] | import java.util.*;
import java.io.*;
public class LIS {
public static void main(String[] args) throws Exception {
FastIO in = new FastIO();
int t = in.nextInt();
for (int tc=0; tc<t; tc++) {
int n = in.nextInt();
String s = in.next();
int[] min = new int[n];
int[] max = new int[n];
for (int i=0; i<n; i++) {
max[i] = i+1;
min[n-i-1] = i+1;
}
int start = -1;
boolean prev = false;
for (int i=0; i<n-1; i++) {
if (s.charAt(i)=='>') {
if (start<0) start = i;
}
else {
if (start>=0) {
reverse(max, start, i);
start = -1;
}
}
}
if (start>=0) reverse(max, start, n-1);
start = -1;
// boolean prev = false;
for (int i=0; i<n-1; i++) {
if (s.charAt(i)=='<') {
if (start<0) start = i;
}
else {
// in.pr.println(start+" "+i);
if (start>=0) {
reverse(min, start, i);
start = -1;
}
}
}
if (start>=0) reverse(min, start, n-1);
// reverse(min, 2, 3);
for (int i: min) {
in.pr.print(i+" ");
}
in.pr.println();
for (int i: max) {
in.pr.print(i+" ");
}
in.pr.println();
}
in.pr.close();
}
public static void reverse(int[] arr, int l, int r) {
for (int i=l; i<=(l+r)/2; i++) {
int temp = arr[i];
arr[i] = arr[r-(i-l)];
arr[r-(i-l)] = temp;
}
}
static class FastIO {
BufferedReader br;
StringTokenizer st;
PrintWriter pr;
public FastIO() throws IOException
{
br = new BufferedReader(
new InputStreamReader(System.in));
pr = new PrintWriter(System.out);
}
public String next() throws IOException
{
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); }
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public String nextLine() throws IOException
{
String str = br.readLine();
return str;
}
}
}
| java |
13 | E | E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3 | [
"data structures",
"dsu"
] | //package over2400;
import java.io.*;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;
public class Round13E {
InputStream is;
FastWriter out;
String INPUT = "";
void solve()
{
int n = ni(), Q = ni();
int[] a = na(n);
final int S = 300;
int[][] qs = new int[Q][];
for(int i = 0;i < Q;i++){
int t = ni();
if(t == 1){
qs[i] = new int[]{t, ni()-1};
}else{
qs[i] = new int[]{t, ni()-1, ni()};
}
}
for(int i = 0;i < Q;i+=S){
boolean[] touched = new boolean[n];
for(int j = i;j < i+S && j < Q;j++){
if(qs[j][0] == 0){
touched[qs[j][1]] = true;
}
}
int[] num = new int[n];
int[] last = new int[n];
for(int j = n-1;j >= 0;j--){
if(!touched[j]){
int ne = j + a[j];
if(ne >= n || touched[ne]){
last[j] = j;
num[j] = 1;
}else{
last[j] = last[ne];
num[j] = num[ne] + 1;
}
}
}
for(int j = i;j < i+S && j < Q;j++){
int[] q = qs[j];
if(q[0] == 0){
a[q[1]] = q[2];
}else{
int cur = q[1];
int las = cur;
int ans = 0;
while(cur < n) {
if (!touched[cur]) {
ans += num[cur];
las = last[cur];
cur = last[cur] + a[last[cur]];
}else{
ans++;
las = cur;
cur += a[cur];
}
}
out.println((las+1) + " " + ans);
}
}
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new FastWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new Round13E().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 int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private long[] nal(int n)
{
long[] a = new long[n];
for(int i = 0;i < n;i++)a[i] = nl();
return a;
}
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[][] nmi(int n, int m) {
int[][] map = new int[n][];
for(int i = 0;i < n;i++)map[i] = na(m);
return map;
}
private int ni() { return (int)nl(); }
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public static class FastWriter
{
private static final int BUF_SIZE = 1<<13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter(){out = null;}
public FastWriter(OutputStream os)
{
this.out = os;
}
public FastWriter(String path)
{
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b)
{
buf[ptr++] = b;
if(ptr == BUF_SIZE)innerflush();
return this;
}
public FastWriter write(char c)
{
return write((byte)c);
}
public FastWriter write(char[] s)
{
for(char c : s){
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
}
return this;
}
public FastWriter write(String s)
{
s.chars().forEach(c -> {
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x)
{
if(x == Integer.MIN_VALUE){
return write((long)x);
}
if(ptr + 12 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x)
{
if(x == Long.MIN_VALUE){
return write("" + x);
}
if(ptr + 21 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision)
{
if(x < 0){
write('-');
x = -x;
}
x += Math.pow(10, -precision)/2;
// if(x < 0){ x = 0; }
write((long)x).write(".");
x -= (long)x;
for(int i = 0;i < precision;i++){
x *= 10;
write((char)('0'+(int)x));
x -= (int)x;
}
return this;
}
public FastWriter writeln(char c){
return write(c).writeln();
}
public FastWriter writeln(int x){
return write(x).writeln();
}
public FastWriter writeln(long x){
return write(x).writeln();
}
public FastWriter writeln(double x, int precision){
return write(x, precision).writeln();
}
public FastWriter write(int... xs)
{
boolean first = true;
for(int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs)
{
boolean first = true;
for(long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln()
{
return write((byte)'\n');
}
public FastWriter writeln(int... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(long... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(char[] line)
{
return write(line).writeln();
}
public FastWriter writeln(char[]... map)
{
for(char[] line : map)write(line).writeln();
return this;
}
public FastWriter writeln(String s)
{
return write(s).writeln();
}
private void innerflush()
{
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush()
{
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) { return write(b); }
public FastWriter print(char c) { return write(c); }
public FastWriter print(char[] s) { return write(s); }
public FastWriter print(String s) { return write(s); }
public FastWriter print(int x) { return write(x); }
public FastWriter print(long x) { return write(x); }
public FastWriter print(double x, int precision) { return write(x, precision); }
public FastWriter println(char c){ return writeln(c); }
public FastWriter println(int x){ return writeln(x); }
public FastWriter println(long x){ return writeln(x); }
public FastWriter println(double x, int precision){ return writeln(x, precision); }
public FastWriter print(int... xs) { return write(xs); }
public FastWriter print(long... xs) { return write(xs); }
public FastWriter println(int... xs) { return writeln(xs); }
public FastWriter println(long... xs) { return writeln(xs); }
public FastWriter println(char[] line) { return writeln(line); }
public FastWriter println(char[]... map) { return writeln(map); }
public FastWriter println(String s) { return writeln(s); }
public FastWriter println() { return writeln(); }
}
public void trnz(int... o)
{
for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" ");
System.out.println();
}
// print ids which are 1
public void trt(long... o)
{
Queue<Integer> stands = new ArrayDeque<>();
for(int i = 0;i < o.length;i++){
for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x));
}
System.out.println(stands);
}
public void tf(boolean... r)
{
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
public void tf(boolean[]... b)
{
for(boolean[] r : b) {
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
System.out.println();
}
public void tf(long[]... b)
{
if(INPUT.length() != 0) {
for (long[] r : b) {
for (long x : r) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
System.out.println();
}
}
public void tf(long... b)
{
if(INPUT.length() != 0) {
for (long x : b) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| java |
1287 | B | B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES" | [
"brute force",
"data structures",
"implementation"
] | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static final PrintWriter out =new PrintWriter(System.out);
static final FastReader sc = new FastReader();
/*
_oo0oo_
o8888888o
88" . "88
(| -_- |)
0\ = /0
___/`---'\___
.' \\| |// '.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' |_/ |
\ .-\__ '-' ___/-. /
___'. .' /--.--\ `. .'___
."" '< `.___\_<|>_/___.' >' "".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `_. \_ __\ /__ _/ .-` / /
=====`-.____`.___ \_____/___.-`___.-'=====
`=---='
*/
public static boolean sorted(int a[])
{
int n=a.length,i;
int b[]=new int[n];
for(i=0;i<n;i++)
b[i]=a[i];
Arrays.sort(b);
for(i=0;i<n;i++)
{
if(a[i]!=b[i])
return false;
}
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
int tes=1;
while(tes-->0)
{
int n=sc.nextInt();
int x=sc.nextInt();
String a[]=new String[n];
HashSet<String> set=new HashSet<>();
int i,j,k,ans=0;
for(i=0;i<n;i++)
{
a[i]=sc.next();
set.add(a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
StringBuilder s=new StringBuilder();
for(k=0;k<x;k++)
{
if(a[i].charAt(k)==a[j].charAt(k))
s.append(a[i].charAt(k));
else{
String tmp=a[i].charAt(k)+""+a[j].charAt(k);
if(tmp.equals("ST")||tmp.equals("TS"))
s.append("E");
else if(tmp.equals("ET")||tmp.equals("TE"))
s.append("S");
else
s.append("T");
}
}
if(set.contains(s.toString()))
ans++;
}
}
System.out.println(ans/3);
}
}
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 |
1307 | D | D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33. | [
"binary search",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
static int MAX = 200005, INF = 1000000007;
static Map<Integer, List<Integer>> graph = new HashMap<>();
// shortestDistance[0][i] -> shortest distance from node 1 to i.
// shortestDistance[1][i] -> shortest distance from node n to i.
static int[][] shortestDistance = new int[2][MAX];
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 0; t < test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
for (int i = 0; i < 2; i++) {
Arrays.fill(shortestDistance[i], INF);
}
List<Integer> specialNodes = new ArrayList<>();
for (int i = 0; i < k; i++) {
int node = sc.nextInt();
specialNodes.add(node);
}
for (int i = 1; i <= n; i++) {
graph.put(i, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
graph.get(u).add(v);
graph.get(v).add(u);
}
bfs(1, 0);
bfs(n, 1);
/*
Select two special nodes (say x and y) to connect such that (the shortest distance from 1 to x) + (the shortest distance from x to n) is maximized.
*/
specialNodes.sort(Comparator.comparingInt(a -> (shortestDistance[0][a] - shortestDistance[1][a])));
int maxShortestPath = 0, maxSpecialDistanceFromStart = -INF;
for (int node : specialNodes) {
maxShortestPath = Math.max(maxShortestPath, maxSpecialDistanceFromStart + shortestDistance[1][node]);
maxSpecialDistanceFromStart = Math.max(maxSpecialDistanceFromStart, shortestDistance[0][node]);
}
maxShortestPath++; // special edge length
out.println(Math.min(maxShortestPath, shortestDistance[0][n]));
}
private static void bfs(int startNode, int index) {
Queue<Integer> q = new LinkedList<>();
shortestDistance[index][startNode] = 0;
q.add(startNode);
while (!q.isEmpty()) {
int currNode = q.poll();
for (int adjacentNode : graph.get(currNode)) {
if (shortestDistance[index][adjacentNode] > shortestDistance[index][currNode] + 1) {
shortestDistance[index][adjacentNode] = shortestDistance[index][currNode] + 1;
q.add(adjacentNode);
}
}
}
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
}
| java |
1303 | 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.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int z = 0; z < t; z++){
String s = in.next();
int ans = 0;
boolean start = false;
int length = 0;
for(int i = 0; i < s.length(); i++){
char curr = s.charAt(i);
if(start){
if(curr == '0') length++;
else{
ans += length;
length = 0;
}
}
if(curr == '1') start = true;
}
System.out.println(ans);
}
}
}
/*
* BAN
* */ | java |
1305 | E | E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5) | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | import java.io.*;
import java.util.*;
public class Contest1 {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// /////////
//////// /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// /////////
//////// /////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
int [] steps = new int[n+1];
if (n<3){
if (m==0){
int val =(int)1e9-100000;
while (n-->0){
pw.println(val+" ");
val+=1000;
}
}
else pw.println(-1);
pw.flush();
return;
}
steps[2]=1;
for (int i =3;i<n;i++){
steps[i]=steps[i-1];
if (i%2==0)steps[i]++;
}
int last=0;
while (last<n&&steps[last]<=m)m-=steps[last++];
if (last>=n&&m!=0){
pw.println(-1);
pw.flush();
return;
}
if (m==0)last--;
int[] ans= new int[n+1];
int i =0;
while (i<last){
ans[i]=(i+1);
i++;
}
if (m==0){
ans[last]=last+1;
int val=(int)1e9;
int id=n-1;
while (id>last){
ans[id]=val;
val-=10000;
id--;
}
}
else {
int low= ans[last-1]+1;
int hi = 15000;
while (low<=hi){
int k = low+hi>>1;
int size=0;
HashSet<Integer>hs = new HashSet<>();
for (int j=0;j<last;j++){
if (hs.contains(k-ans[j]))size++;
hs.add(ans[j]);
}
if (size>=m){
ans[last]=k;
low=k+1;
}
else hi=k-1;
}
int val =(int)1e9;
i=n-1;
while (i>last){
ans[i--]=val;
val-=10000;
}
}
for (i =0;i<n;i++){
pw.print(ans[i]+" ");
}
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | java |
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 CF1562C extends PrintWriter {
CF1562C() { super(System.out); }
public static Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1562C o = new CF1562C(); o.main(); o.flush();
}
static long calculate(long p, long q)
{
long mod = 1000000007, expo;
expo = mod - 2;
// Loop to find the value
// until the expo is not zero
while (expo != 0)
{
// Multiply p with q
// if expo is odd
if ((expo & 1) == 1)
{
p = (p * q) % mod;
}
q = (q * q) % mod;
// Reduce the value of
// expo by 2
expo >>= 1;
}
return p;
}
static String longestPalSubstr(String str)
{
// The result (length of LPS)
int maxLength = 1;
int start = 0;
int len = str.length();
int low, high;
// One by one consider every
// character as center
// point of even and length
// palindromes
for (int i = 1; i < len; ++i) {
// Find the longest even
// length palindrome with
// center points as i-1 and i.
low = i - 1;
high = i;
while (low >= 0 && high < len
&& str.charAt(low)
== str.charAt(high)) {
--low;
++high;
}
// Move back to the last possible valid palindrom substring
// as that will anyway be the longest from above loop
++low; --high;
if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {
start = low;
maxLength = high - low + 1;
}
// Find the longest odd length
// palindrome with center point as i
low = i - 1;
high = i + 1;
while (low >= 0 && high < len
&& str.charAt(low)
== str.charAt(high)) {
--low;
++high;
}
// Move back to the last possible valid palindrom substring
// as that will anyway be the longest from above loop
++low; --high;
if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {
start = low;
maxLength = high - low + 1;
}
}
return str.substring(start, start + maxLength - 1);
}
long check(long a){
long ret=0;
for(long k=2;(k*k*k)<=a;k++){
ret=ret+(a/(k*k*k));
}
return ret;
}
/*public static int getFirstSetBitPos(int n)
{
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
public static int bfsq(int n, int m, HashMap<Integer,ArrayList<Integer>>h,boolean v ){
v[n]=true;
if(n==m)
return 1;
else
{
int a=h.get(n).get(0);
int b=h.get(n).get(1);
if(b>m)
return(m-n);
else
{
int a1=bfsq(a,m,h,v);
int b1=bfsq(b,m,h,v);
return 1+Math.min(a1,b1);
}
}
}*/
static long nCr(int n, int r)
{ return fact(n) / (fact(r) *
fact(n - r));
}
// Returns factorial of n
static long fact(long n)
{
long res = 1;
for (long i = 2; i <= n; i++)
res = res * i;
return res;
}
/*void bfs(int src, HashMap<Integer,ArrayList<Integer,Integer>>h,int deg, boolean v[] ){
a[src]=deg;
Queue<Integer>= new LinkedList<Integer>();
q.add(src);
while(!q.isEmpty()){
(int a:h.get(src)){
if()
}
}
}*/
/* void dfs(int root, int par, HashMap<Integer,ArrayList<Integer>>h,int dp[], int child[]) {
dp[root]=0;
child[root]=1;
for(int x: h.get(root)){
if(x == par) continue;
dfs(x,root,h,in,dp);
child[root]+=child[x];
}
ArrayList<Integer> mine= new ArrayList<Integer>();
for(int x: h.get(root)) {
if(x == par) continue;
mine.add(x);
}
if(mine.size() >=2){
int y= Math.max(child[mine.get(0)] - 1 + dp[mine.get(1)] , child[mine.get(1)] -1 + dp[mine.get(0)]);
dp[root]=y;}
else if(mine.size() == 1)
dp[root]=child[mine.get(0)] - 1;
}
*/
class Pair implements Comparable<Pair>{
int i;
int j;
Pair (int a, int b){
i = a;
j = b;
}
public int compareTo(Pair A){
return (int)(this.i-A.i);
}}
/*static class Pair {
int i;
int j;
Pair() {
}
Pair(int i, int j) {
this.i = i;
this.j = j;
}
}*/
/*ArrayList<Integer> check(int a[], int b){
int n=a.length;
long ans=0;int k=0;
ArrayList<Integer>ab= new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(a[i]%m==0)
{k=a[i];
while(a[i]%m==0){
a[i]=a[i]/m;
}
for(int z=0;z<k/a[i];z++){
ab.add(a[i]);
}
}
else{
ab.add(a[i]);
}
}
return ab;
} */
/*int check[];
int tree[];
static void build( int []arr)
{
// insert leaf nodes in tree
for (int i = 0; i < n; i++)
tree[n + i] = arr[i];
// build the tree by calculating
// parents
for (int i = n - 1; i > 0; --i){
int ans= Math.min(tree[i << 1],
tree[i << 1 | 1]);
int ans1=Math.max((tree[i << 1],
tree[i << 1 | 1]));
if(ans==0)
}
}*/
/*static void ab(long n)
{
// Note that this loop runs till square root
for (long i=1; i<=Math.sqrt(n); i++)
{
if(i==1)
{
p.add(n/i);
continue;
}
if (n%i==0)
{
// If divisors are equal, print only one
if (n/i == i)
p.add(i);
else // Otherwise print both
{
p.add(i);
p.add(n/i);
}
}
}
}*/
void main() {
//int g=sc.nextInt();
//int mod=1000000007;
//for(int w=0;w<g;w++){
int n=sc.nextInt();
int a[]= new int[n+1];
ArrayList<Pair>ar= new ArrayList<Pair>();
for(int i=0;i<n-1;i++){
int b=sc.nextInt();
int c=sc.nextInt();
ar.add(new Pair(b,c));
a[b]++;
a[c]++;
}
int res=-1;
for(int i=0;i<=n;i++){
if(a[i]>2){
res=i;
break;}
}
int w=0;
int w1=n-2;
for(int i=0;i<n-1;i++){
Pair d=ar.get(i);
if(d.i!=res&&d.j!=res)
println(w1--);
else
println(w++);
}
}
}
| 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 static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class B_Longest_Palindrome {
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = 1;
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
int n = f.nextInt();
int m = f.nextInt();
String arr[] = f.nextArray(n);
HashSet<Integer> hs = new HashSet<>();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++) {
if(hs.contains(i)) {
continue;
}
for(int j = i+1; j < n; j++) {
if(hs.contains(j)) {
continue;
}
if(isDoublePal(arr[i], arr[j], m)) {
sb.insert(0, arr[i]);
sb.append(arr[j]);
hs.add(i);
hs.add(j);
break;
}
}
}
for(int i = 0; i < n; i++) {
if(hs.contains(i)) {
continue;
}
if(isPal(arr[i], m)) {
sb.insert(sb.length()/2, arr[i]);
break;
}
}
out.println(sb.length());
out.println(sb);
}
public static boolean isDoublePal(String a, String b, int m) {
for(int i = 0; i < m ; i++) {
if(a.charAt(i) != b.charAt(m-1-i)) {
return false;
}
}
return true;
}
public static boolean isPal(String a, int m) {
int i = 0;
int j = m-1;
while(j > i) {
if(a.charAt(i) != a.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
public static int gcd(int a, int b) {
int dividend = a > b ? a : b;
int divisor = a < b ? a : b;
while(divisor > 0) {
int reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
public static int lcm(int a, int b) {
int lcm = gcd(a, b);
int hcf = (a * b) / lcm;
return hcf;
}
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
String[] nextArray(int n) {
String[] a = new String[n];
for(int i=0; i<n; i++) {
a[i] = nextLine();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
| java |
1324 | A | A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process. | [
"implementation",
"number theory"
] | import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class YetAnotherTetrisProblem {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for ( int p = 0; p < t; p++){
int n = in.nextInt();
int count = 0;
ArrayList <Integer> list = new ArrayList<>(1);
for (int i = 0; i < n; i++){
list.add(in.nextInt());
}
int min = Collections.min(list);
for ( int i = 0; i < n; i++){
list.set(i,list.get(i) - min);
if(list.get(i) % 2 == 0){
count++;
}
else{
System.out.println("NO");
break;
}
}
if ( count == n){
System.out.println("YES");
}
}
}
} | java |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | [
"dp",
"greedy",
"implementation"
] | import java.io.*;
import java.util.InputMismatchException;
public class E1285B {
static int INF = 0;
public static void main(String[] args) {
FastIO io = new FastIO();
int t = io.nextInt();
while (t-- > 0) {
int n = io.nextInt();
long[] prefix = new long[n + 1];
for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + io.nextInt();
long ans = 0;
long minPre = 0;
for (int i = 1; i < n; i++) {
minPre = Math.min(prefix[i], minPre);
ans = Math.max(prefix[i] - minPre, ans);
ans = Math.max(prefix[n] - prefix[i], ans);
}
io.println(ans >= prefix[n] ? "NO" : "YES");
}
io.close();
}
private static class FastIO extends PrintWriter {
private final InputStream stream;
private final byte[] buf = new byte[1 << 16];
private int curChar, numChars;
// standard input
public FastIO() {
this(System.in, System.out);
}
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c;
do {
c = nextByte();
} while (c <= ' ');
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nextByte();
} while (c > ' ');
return res.toString();
}
public int nextInt() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
int res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
long res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| java |
1315 | C | C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
| [
"greedy"
] | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static final PrintWriter out =new PrintWriter(System.out);
static final FastReader sc = new FastReader();
//I invented a new word!Plagiarism!
//Did you hear about the mathematician who’s afraid of negative numbers?He’ll stop at nothing to avoid them
//What do Alexander the Great and Winnie the Pooh have in common? Same middle name.
//I finally decided to sell my vacuum cleaner. All it was doing was gathering dust!
//ArrayList<Integer> a=new ArrayList <Integer>();
//PriorityQueue<Integer> pq=new PriorityQueue<>();
//char[] a = s.toCharArray();
// char s[]=sc.next().toCharArray();
public static boolean sorted(int a[])
{
int n=a.length,i;
int b[]=new int[n];
for(i=0;i<n;i++)
b[i]=a[i];
Arrays.sort(b);
for(i=0;i<n;i++)
{
if(a[i]!=b[i])
return false;
}
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
int tes=sc.nextInt();
label:while(tes-->0)
{
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[2*n];
int i;
for(i=0;i<n;i++)
a[i]=sc.nextInt();
TreeSet<Integer> set1=new TreeSet<>(); TreeSet<Integer> set2=new TreeSet<>();
for(i=0;i<n;i++)
{
set1.add(a[i]);
b[2*i]=a[i];
}
for(i=1;i<=2*n;i++)
{
if(!set1.contains(i))
set2.add(i);
}
//System.out.println(set2);
for(i=0;i<n;i++)
{
//System.out.print(set2.ceiling(a[i])+" ");
// int f=set2.ceiling(a[i]);
if(set2.ceiling(a[i])==null)
b[(2*i)+1]=-1;
else
{
b[(2*i)+1]=set2.ceiling(a[i]);
set2.remove(b[(2*i)+1]);
}
}
for(i=0;i<2*n;i++)
{
if(b[i]==-1)
{
System.out.println(-1);
continue label;
}
}
for(i=0;i<2*n;i++)
System.out.print(b[i]+" ");
System.out.println();
}
}
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 |
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.Arrays;
import java.util.Scanner;
public class A_Nonzero {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int tc = 0; tc < t; ++tc) {
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; ++i) {
a[i] = sc.nextInt();
}
System.out.println(solve(a));
}
sc.close();
}
static int solve(int[] a) {
int zeroCount = (int) Arrays.stream(a).filter(x -> x == 0).count();
return zeroCount + ((Arrays.stream(a).sum() + zeroCount == 0) ? 1 : 0);
}
} | java |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | import java.util.*;
import java.io.*;
public class Practice {
static boolean multipleTC = true;
final static int mod = 1000000007;
final static int mod2 = 998244353;
final double E = 2.7182818284590452354;
final double PI = 3.14159265358979323846;
int MAX = 3001;
int N = 3001;
void pre() throws Exception {
}
// All the best
void solve(int TC) throws Exception {
int n = ni();
int m = ni();
int sum = 0;
for (int i = 1; i <= n; i++)
sum += ni();
pn(Math.min(sum, m));
}
// 2 3 4 5 1
// 1 2 3 4 5
// 1 2 3 4
// 2 1 4 3
// 1 2 4 3
//
double dist(int x1, int y1, int x2, int y2) {
double a = x1 - x2, b = y1 - y2;
return Math.sqrt((a * a) + (b * b));
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(int arr[], int left, int right) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = left; i <= right; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = left; i <= right; i++)
arr[i] = list.get(i - left);
}
void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
String bin(long n) {
return Long.toBinaryString(n);
}
String bin(int n) {
return Integer.toBinaryString(n);
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
void p(Object o) {
out.print(o);
}
void pn(Object o) {
out.println(o);
}
void pni(Object o) {
out.println(o);
out.flush();
}
void pn(int[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
void pn(long[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
String n() throws Exception {
return in.next();
}
String nln() throws Exception {
return in.nextLine();
}
int ni() throws Exception {
return Integer.parseInt(in.next());
}
long nl() throws Exception {
return Long.parseLong(in.next());
}
double nd() throws Exception {
return Double.parseDouble(in.next());
}
public static void main(String[] args) throws Exception {
new Practice().run();
}
FastReader in;
PrintWriter out;
void run() throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++)
solve(t);
out.flush();
out.close();
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
} | java |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32. | [
"combinatorics",
"math"
] | import java.io.*;
import java.util.*;
public class tank {
static final FastScanner fs = new FastScanner();
//static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int t = 1;
while(t-->0) {
run_case();
}
//out.close();
}
static void run_case() {
int n = fs.nextInt(), mod = fs.nextInt(), sum = 0, tmp;
int[] fact = new int[n + 1];
fact[0] = fact[1] = 1;
for (int i = 2; i <= n; i++) {
fact[i] = (int) ((i * (long) fact[i - 1]) % mod);
}
for (int i = 1; i <= n; i++) {
tmp = (int) ((fact[i] * (long) fact[n - i]) % mod);
tmp = (int) ((tmp * (long)(n - i + 1)) % mod);
tmp = (int) ((tmp * (long)(n - i + 1)) % mod);
sum = (sum + tmp) % mod;
}
System.out.println(sum);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String nextLine(){
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | java |
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.io.*;
import java.math.*;
import java.util.*;
// @author : Dinosparton
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuffer res = new StringBuffer();
int tc = sc.nextInt();
while(tc-->0) {
int n = sc.nextInt();
int d = sc.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++) {
a[i] = sc.nextInt();
}
int ans = 0;
ans += a[0];
for(int i=1;i<n;i++) {
if(i*a[i]<=d) {
ans += a[i];
d -= i*a[i];
}
else {
ans += d/i;
break;
}
}
System.out.println(ans);
}
System.out.println(res);
}
}
| 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"
] | //package primitiveprimes;
import java.util.*;
import java.io.*;
public class primitiveprimes {
public static void main(String[] args) throws IOException {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(fin.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int p = Integer.parseInt(st.nextToken());
int a = -1;
int b = -1;
st = new StringTokenizer(fin.readLine());
for(int i = 0; i < n; i++) {
if(Integer.parseInt(st.nextToken()) % p != 0) {
a = i;
break;
}
}
st = new StringTokenizer(fin.readLine());
for(int i = 0; i < m; i++) {
if(Integer.parseInt(st.nextToken()) % p != 0) {
b = i;
break;
}
}
System.out.println(a + b);
}
}
| java |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] | import java.util.*;
public class ArrayWithOddSum {
public static void main(String [] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int[] ar=new int[n];
for(int i=0;i<ar.length;i++)
{
ar[i]=sc.nextInt();
}
int eve=0;
int odd=0;
for(int i=0;i<ar.length;i++)
{
if(ar[i]%2==0)
{
eve++;
}
else
{
odd++;
}
}
if(odd%2==1)
{
System.out.println("YES");
continue;
}
if(odd==n || odd==0)
{
System.out.println("NO");
continue;
}
System.out.println("YES");
}
}
}
| 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 static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1316d {
public static void main(String[] args) throws IOException {
int n = ri(), x[][] = new int[n][n], y[][] = new int[n][n], visited = 0;
char[][] ans = new char[n][n];
boolean[][] vis = new boolean[n][n];
Set<Integer> sink = new HashSet<>();
for (int i = 0; i < n; ++i) {
r();
for (int j = 0; j < n; ++j) {
x[i][j] = ni() - 1;
y[i][j] = ni() - 1;
if (x[i][j] >= 0) {
sink.add(x[i][j] * n + y[i][j]);
}
}
}
for (int s : sink) {
int si = s / n, sj = s % n;
/* if (x[i][j] == i && y[i][j] == j) {
visited += dfs(i, j, i, j, x, y, vis, ans);
} */
if (x[si][sj] == si && y[si][sj] == sj) {
Queue<int[]> bfs = new LinkedList<>();
bfs.offer(new int[] {si, sj, si, sj});
while (!bfs.isEmpty()) {
int i = bfs.peek()[0], j = bfs.peek()[1], pi = bfs.peek()[2], pj = bfs.poll()[3];
if (vis[i][j]) {
continue;
}
vis[i][j] = true;
ans[i][j] = pi > i ? 'D' : pi < i ? 'U' : pj > j ? 'R' : pj < j ? 'L' : 'X';
++visited;
if (i > 0 && !vis[i - 1][j] && x[i - 1][j] == x[i][j] && y[i - 1][j] == y[i][j]) {
bfs.offer(new int[] {i - 1, j, i, j});
}
if (j > 0 && !vis[i][j - 1] && x[i][j - 1] == x[i][j] && y[i][j - 1] == y[i][j]) {
bfs.offer(new int[] {i, j - 1, i, j});
}
if (i < vis.length - 1 && !vis[i + 1][j] && x[i + 1][j] == x[i][j] && y[i + 1][j] == y[i][j]) {
bfs.offer(new int[] {i + 1, j, i, j});
}
if (j < vis.length - 1 && !vis[i][j + 1] && x[i][j + 1] == x[i][j] && y[i][j + 1] == y[i][j]) {
bfs.offer(new int[] {i, j + 1, i, j});
}
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (x[i][j] < 0) {
++visited;
if (i > 0 && x[i - 1][j] < 0) {
ans[i][j] = 'U';
} else if (j > 0 && x[i][j - 1] < 0) {
ans[i][j] = 'L';
} else if (i < n - 1 && x[i + 1][j] < 0) {
ans[i][j] = 'D';
} else if (j < n - 1 && x[i][j + 1] < 0) {
ans[i][j] = 'R';
} else {
--visited;
}
}
}
}
if (visited < n * n) {
prln("INVALID");
} else {
prln("VALID");
for (char[] row : ans) {
prln(row);
}
}
close();
}
// stack overflow
static int dfs(int i, int j, int pi, int pj, int[][] x, int[][] y, boolean[][] vis, char[][] ans) {
vis[i][j] = true;
ans[i][j] = pi > i ? 'D' : pi < i ? 'U' : pj > j ? 'R' : pj < j ? 'L' : 'X';
int ret = 1;
if (i > 0 && !vis[i - 1][j] && x[i - 1][j] == x[i][j] && y[i - 1][j] == y[i][j]) {
ret += dfs(i - 1, j, i, j, x, y, vis, ans);
}
if (j > 0 && !vis[i][j - 1] && x[i][j - 1] == x[i][j] && y[i][j - 1] == y[i][j]) {
ret += dfs(i, j - 1, i, j, x, y, vis, ans);
}
if (i < vis.length - 1 && !vis[i + 1][j] && x[i + 1][j] == x[i][j] && y[i + 1][j] == y[i][j]) {
ret += dfs(i + 1, j, i, j, x, y, vis, ans);
}
if (j < vis.length - 1 && !vis[i][j + 1] && x[i][j + 1] == x[i][j] && y[i][j + 1] == y[i][j]) {
ret += dfs(i, j + 1, i, j, x, y, vis, ans);
}
return ret;
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int)d;}
static int cei(double d) {return (int)ceil(d);}
static long fll(double d) {return (long)d;}
static long cel(double d) {return (long)ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// graph util
static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for(int i = 0; i < n; ++i) a[i] = nl(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(double... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();}
static void h() {__out.println("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | java |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static int mod = (int) (1e9 + 7);
static void solve() {
int n=i();
String s=s();
// ...../////..........
ArrayList<Character> arr=new ArrayList<>();
for(int i=0;i<n;i++){
arr.add(s.charAt(i));
}
boolean b=true;
while(b&&arr.size()>1){
HashMap<Character,ArrayList<Integer>> hm=new HashMap<>();
for(int j=0;j<26;j++){
char temp=(char)(j+'a');
hm.put(temp,new ArrayList<>());
}
for(int i=0;i<arr.size();i++){
char ch=arr.get(i);
if(i==0){
char ch1=arr.get(i+1);
if((char)(ch1+1)==(ch)){
hm.get(ch).add(i);
}
}
else if(i==arr.size()-1){
char ch1=arr.get(i-1);
if((char)(ch1+1)==(ch)){
hm.get(ch).add(i);
}
}
else{
char ch1=arr.get(i+1);
if((char)(ch1+1)==(ch)){
hm.get(ch).add(i);
}
else{
ch1=arr.get(i-1);
if((char)(ch1+1)==(ch)){
hm.get(ch).add(i);
}
}
}
}
ArrayList<Integer> tr=new ArrayList<>();
char curr='a';
boolean b1=false;
for(char ch: hm.keySet()){
if(hm.get(ch).size()==0)continue;
b1=true;
if(ch>=curr){
curr=ch;
tr=hm.get(ch);
}
}
HashSet<Integer> hs=new HashSet<>();
for(int t:tr)hs.add(t);
ArrayList<Character> final2=new ArrayList<>();
for(int j=0;j<arr.size();j++){
if( !hs.contains(j) ){
final2.add(arr.get(j));
}
}
arr=new ArrayList<>();
for(char t:final2){
arr.add(t);
}
b=b1;
}
sb.append(n-arr.size()+"\n");
}
public static void main(String[] args) {
sb = new StringBuilder();
int test =1;
fact=new long[(int)1e6+10];
fact[0]=fact[1]=1;
for(int i=2;i<fact.length;i++)
{ fact[i]=((long)(i%mod)*(long)(fact[i-1]%mod))%mod; }
while (test-- > 0) {
solve();
}
System.out.println(sb);
}
//**************NCR%P******************
static long ncr(int n, int r) {
if (r > n)
return (long) 1;
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 dx;
int dy;
Pair() {
}
public int compareTo(Pair o) {
if(this.dx!=o.dx) return (int) (this.dx - o.dx);
else return (int) (this.dy - o.dy);
}
}
static class Pair1 implements Comparable<Pair1> {
int idx;
long w;
Pair1(int idx, long w) {
this.idx = idx;
this.w = w;
}
public int compareTo(Pair1 o) {
return (int) (this.w - o.w);
}
}
static class PairF implements Comparable<PairF> {
int i;
long x;
PairF( int i,long x) {
this.x = x;
this.i=i;
}
public int compareTo(PairF o) {
return (int) (this.x - o.x);
}
}
//****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 |
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"
] |
/*
It's always like another kick for me to make sure I get what I want to get done,
because honestly you never know.
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main extends PrintWriter {
Main() { super(System.out); }
static boolean cases = true;
// Solution
void solve() {
char a[] = sc.next().toCharArray();
char b[] = sc.next().toCharArray();
int ans = 0, j = 0;
HashMap<Character, TreeSet<Integer>> map = new HashMap<>();
for (int i = 0; i < a.length; i++) {
map.putIfAbsent(a[i], new TreeSet<>());
map.get(a[i]).add(i);
}
while (j < b.length) {
int pos = j;
int i = -1;
while (i < a.length && j < b.length) {
if (!map.containsKey(b[j])) { break; }
Integer x = map.get(b[j]).higher(i);
if (x == null) break;
j++;
i = x;
}
if (pos == j) {
System.out.println(-1);
return;
}
ans++;
}
System.out.println(ans);
}
int solve(String str[]) {
int mask = 0;
for (String s : str) { for (char ch : s.toCharArray()) mask |= (1 << ch - 'a'); }
return mask != (1 << 25) ? 0 : 1;
}
void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
public static void main(String[] args) {
Main obj = new Main();
int c = 1;
for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve();
obj.solve();
obj.flush();
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
char[] readCharArray(int n) {
char a[] = new char[n];
String s = sc.next();
for (int i = 0; i < n; i++) { a[i] = s.charAt(i); }
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() { return Long.parseLong(next()); }
}
final int ima = Integer.MAX_VALUE;
final int imi = Integer.MIN_VALUE;
final long lma = Long.MAX_VALUE;
final long lmi = Long.MIN_VALUE;
static final long mod = (long) 1e9 + 7;
private static final FastScanner sc = new FastScanner();
private PrintWriter out = new PrintWriter(System.out);
} | java |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | import org.w3c.dom.xpath.XPathResult;
import java.io.*;
import java.util.*;
public class Solution {
private static final int MAX = 1000000;
public void solve() {
List<Integer> prime = sieve(MAX);
HashMap<Integer, Integer> idx = new HashMap<>();
int cnt = 0;
int n = reader.nextInt();
int[][] edges = new int[n][2];
HashSet<Integer> root = new HashSet<>();
for (int i = 0; i < n; i++) {
int[] a = simplify(prime, reader.nextInt());
int x = a[0], y = a[1];
if (x * y == 1) {
writer.println(1);
return;
}
if (!idx.containsKey(x)) idx.put(x, cnt++);
if (!idx.containsKey(y)) idx.put(y, cnt++);
int u = idx.get(x);
int v = idx.get(y);
edges[i][0] = u;
edges[i][1] = v;
if (x <= MAX / x) root.add(u);
if (y <= MAX / y) root.add(v);
}
List<Integer>[] adj = new List[cnt];
for (int i = 0; i < cnt; i++) adj[i] = new ArrayList<>();
for (int i = 0; i < n; i++) {
int u = edges[i][0];
int v = edges[i][1];
adj[u].add(v);
adj[v].add(u);
}
writer.println(shortestCycle(adj, root));
}
private int shortestCycle(List<Integer>[] adj, HashSet<Integer> root) {
int res = MAX;
int n = adj.length;
int[] parent = new int[n];
int[] level = new int[n];
Deque<Integer> queue = new LinkedList<>();
for (int start : root) {
Arrays.fill(level, -1);
parent[start] = start;
level[start] = 0;
queue.add(start);
while (!queue.isEmpty()) {
int u = queue.poll();
if (level[u] >= res) continue;
for (int v : adj[u]) {
if (level[v] == -1) {
parent[v] = u;
level[v] = level[u] + 1;
queue.add(v);
continue;
}
if (v == parent[u]) continue;
res = Math.min(res, level[u] + level[v] + 1);
}
}
}
return res < MAX ? res : -1;
}
private int[] simplify(List<Integer> prime, int a) {
for (int p : prime) {
int q = p * p;
if (q > a) break;
while (a % q == 0) a /= q;
}
for (int p : prime) {
if (p * p > a) break;
if (a % p == 0) return new int[]{p, a / p};
}
return new int[]{1, a};
}
private List<Integer> sieve(int n) {
boolean[] removed = new boolean[n + 1];
for (int i = 2; i * i <= n; i++) {
for (int j = i * i; j <= n; j += i) {
removed[j] = true;
}
}
List<Integer> prime = new LinkedList<>();
prime.add(2);
for (int i = 3; i <= n; i += 2) {
if (!removed[i]) prime.add(i);
}
return prime;
}
private InputReader reader;
private PrintWriter writer;
public Solution(InputReader reader, PrintWriter writer) {
this.reader = reader;
this.writer = writer;
}
public static void main(String[] args) {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out);
Solution solution = new Solution(reader, writer);
solution.solve();
writer.flush();
}
static class InputReader {
private static final int BUFFER_SIZE = 1 << 20;
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE);
tokenizer = null;
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
}
}
| java |
1325 | A | A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100) — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14. | [
"constructive algorithms",
"greedy",
"number theory"
] | import java.util.*;
public class EhAbAnDgCd
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
int n = sc.nextInt();
System.out.println("1" + " " + (n-1));
}
}
} | java |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | import java.util.*;
public class grade {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t > 0) {
int s = 0;
int n = sc.nextInt();
double m = sc.nextDouble();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
s = s + a[i];
}
double avg = s / n;
if (s > m)
System.out.println((int) m);
else
System.out.println(s);
t--;
}
}
}
| java |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232. | [
"math",
"strings"
] | import java.io.*;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class copy {
static int log=18;
static int[][] ancestor;
static int[] depth;
static void sieveOfEratosthenes(int n, ArrayList<Integer> arr) {
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a
// prime
if (prime[p]) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++) {
if (prime[i]) {
arr.add(i);
}
}
}
public static long fac(long N, long mod) {
if (N == 0)
return 1;
if(N==1)
return 1;
return ((N % mod) * (fac(N - 1, mod) % mod)) % mod;
}
static long power(long x, long y, long p) {
// Initialize result
long res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static long nCrModPFermat(long n, long r,
long p) {
if (n < r)
return 0;
// Base case
if (r == 0)
return 1;
return ((fac(n, p) % p * (modInverse(fac(r, p), p)
% p)) % p * (modInverse(fac(n - r, p), p)
% p)) % p;
}
public static int find(int[] parent, int x) {
if (parent[x] == x)
return x;
return find(parent, parent[x]);
}
public static void merge(int[] parent, int[] rank, int x, int y,int[] child) {
int x1 = find(parent, x);
int y1 = find(parent, y);
if (rank[x1] > rank[y1]) {
parent[y1] = x1;
child[x1]+=child[y1];
} else if (rank[y1] > rank[x1]) {
parent[x1] = y1;
child[y1]+=child[x1];
} else {
parent[y1] = x1;
child[x1]+=child[y1];
rank[x1]++;
}
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static int power(int x, int y, int p)
{
int res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static int nCrModPFermat(int n, int r,
int p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
public static long[][] ncr(int n,int r)
{
long[][] dp=new long[n+1][r+1];
for(int i=0;i<=n;i++)
dp[i][0]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=r;j++)
{
if(j>i)
continue;
dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
}
}
return dp;
}
public static boolean prime(long N)
{
int c=0;
for(int i=2;i*i<=N;i++)
{
if(N%i==0)
++c;
}
return c==0;
}
public static int sparse_ancestor_table(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[] child)
{
int c=0;
for(int i:arr.get(x))
{
if(i!=parent)
{
// System.out.println(i+" hello "+x);
depth[i]=depth[x]+1;
ancestor[i][0]=x;
// if(i==2)
// System.out.println(parent+" hello");
for(int j=1;j<log;j++)
ancestor[i][j]=ancestor[ancestor[i][j-1]][j-1];
c+=sparse_ancestor_table(arr,i,x,child);
}
}
child[x]=1+c;
return child[x];
}
public static int lca(int x,int y)
{
if(depth[x]<depth[y])
{
int temp=x;
x=y;
y=temp;
}
x=get_kth_ancestor(depth[x]-depth[y],x);
if(x==y)
return x;
// System.out.println(x+" "+y);
for(int i=log-1;i>=0;i--)
{
if(ancestor[x][i]!=ancestor[y][i])
{
x=ancestor[x][i];
y=ancestor[y][i];
}
}
return ancestor[x][0];
}
public static int get_kth_ancestor(int K,int x)
{
if(K==0)
return x;
int node=x;
for(int i=0;i<log;i++)
{
if(K%2!=0)
{
node=ancestor[node][i];
}
K/=2;
}
return node;
}
public static void main(String[] args) throws IOException {
Reader.init(System.in);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int T=Reader.nextInt();
A:for(int m=1;m<=T;m++)
{
int N=Reader.nextInt();
int d=Reader.nextInt();
int zeroes=0,ones=0;
String s=Reader.next();
for(int i=0;i<N;i++)
{
if(s.charAt(i)=='0')
++zeroes;
else
++ones;
}
int diff=zeroes-ones;
int z1=0,o1=0;
if(diff==0)
{
for(int i=0;i<N;i++)
{
if(s.charAt(i)=='0')
++z1;
else
++o1;
if(z1-o1==d)
{
output.write(-1+"\n");
continue A;
}
}
if(d!=0)
output.write(0+"\n");
else
output.write(1+"\n");
}
else
{
int ans=0;
for(int i=0;i<N;i++)
{
if(s.charAt(i)=='0')
++z1;
else
++o1;
if((long)(d-z1+o1)*(long)diff>=0 && (d-z1+o1)%diff==0)
++ans;
// System.out.println(ans);
}
if(d==0)
++ans;
output.write(ans+"\n");
}
}
output.flush();
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
class sortat implements Comparator<div>
{
public int compare(div o1,div o2)
{
return o1.x-o2.x;
}
}
class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
left=null;
right=null;
this.data=data;
}
}
class div {
int x;
int y;
int z;
div(int x,int y,int z) {
this.x = x;
this.y=y;
this.z=z;
}
}
| 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"
] | //package com.example.practice.codeforces.below2000;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
//A. Recommendations
public class Solution16 {
public static void main (String [] args) throws IOException {
// Use BufferedReader rather than RandomAccessFile; it's much faster
final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
// input file name goes above
//PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("inflate.out")));
int n = Integer.parseInt(input.readLine());
int[][] ns = new int[n][];
StringTokenizer st = new StringTokenizer(input.readLine());
for (int i=0;i<n;++i){
ns[i] = new int[]{Integer.parseInt(st.nextToken()), 0};
}
st = new StringTokenizer(input.readLine());
for (int i=0;i<n;++i){
ns[i][1] = Integer.parseInt(st.nextToken());
}
out.println(calc(n, ns));
out.close(); // close the output file
}
private static long calc(final int n, final int[][] ns) {
if (n<2)return 0;
Arrays.sort(ns, Comparator.comparingInt(a -> a[0]));
int pre = ns[0][0];
long res = 0;
for (int i=0,j=1;j<n;++j){
pre++;
if (ns[j][0] >= pre){
res += calcGroup(ns, i, j-1);
pre = ns[j][0];
i = j;
}else if (j+1==n){
res += calcGroup(ns, i, j);
}
}
return res;
}
private static long calcGroup(final int[][] ns, int l, int r){
if (l>=r)return 0;
long res = 0;
PriorityQueue<Integer> heap = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return ns[o2][1] - ns[o1][1];
}
});
int p = l;
for (int i=ns[l][0],j=i+(r-l);i<=j;++i){
while (p<=r && ns[p][0]<=i){
heap.offer(p++);
}
int t = heap.poll();
res += ((long)(i-ns[t][0])) * ns[t][1];
}
return res;
}
}
| java |
1324 | B | B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes. | [
"brute force",
"strings"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
public class YetAnotherPalindromeProblem {
static BufferedReader br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
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++) {
if (testCase()) pw.println("YES");
else pw.println("NO");
}
pw.close();
}
private static boolean testCase() throws IOException {
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
int item = arr[i];
Integer prev = map.get(item);
if (prev != null) {
if (i - prev > 1) return true;
else continue;
}
map.put(item, i);
}
return false;
}
}
| 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"
] | //<———My cp————
//https://takeuforward.org/interview-experience/strivers-cp-sheet/?utm_source=youtube&utm_medium=striver&utm_campaign=yt_video
import java.util.*;
import java.io.*;
import java.lang.reflect.Array;
public class Solution{
static PrintWriter pw = new PrintWriter(System.out);
private static long MOD = 1_000_000_007;
public static void main(String[] args) throws Exception{
FastReader fr = new FastReader(System.in);
int t = fr.nextInt();
while(t-->0){
int n = fr.nextInt();
int[] vals = new int[n];
int total = 0;
int count = 0;
for(int i=0;i<n;i++){
vals[i]=fr.nextInt();
total=total+vals[i];
if(vals[i]==0){
total++;
count++;
}
}
if(total==0){
count++;
}
pw.println(count);
}
pw.close();
}
public static long opNeeded(long c,long[] vals){
long tempResult = 0;
for(int j = 0;j<vals.length;j++){
tempResult=tempResult+Math.abs((long)(vals[j]-Math.pow(c,j)));
}
if(tempResult<0){
tempResult=Long.MAX_VALUE;
}
return tempResult;
}
private static long pow(long a, long b) {
long res = 1;
while (b > 0) {
if (b % 2 == 0) {
a = (a * a) % MOD;
b /= 2;
} else {
res = (res * a) % MOD;
b--;
}
}
return res;
}
static class DSU{
int[] rank,parent;
int n;
public DSU(int n){
this.n = n;
rank = new int[n];
parent = new int[n];
makeSet();
}
void makeSet(){
for(int i = 0;i<n;i++){
parent[i] = i;
}
}
int find(int x){
if(parent[x]==x){
return x;
}
int p = find(parent[x]);
parent[x]=p;
return p;
}
void union(int x,int y){
int xRoot = find(x);
int yRoot = find(y);
if(xRoot==yRoot){
return;
}
if(rank[xRoot]>rank[yRoot]){
parent[yRoot]=xRoot;
}else if(rank[xRoot]<rank[yRoot]){
parent[xRoot]=yRoot;
}else{
parent[yRoot]=xRoot;
rank[xRoot]+=1;
}
}
}
static int lowerBound(int left,int right,int[] vals,int value){
int mid = (left+right)/2;
while(left<right){
mid = (left+right)/2;
if(vals[mid]<value){
left = mid+1;
}else{
right = mid;
}
}
return left;
}
static int upperBound(int left,int right,int[] vals,int value){
while(left<right){
int mid = (left+right+1)/2;
if(vals[mid]<=value){
left=mid;
}else{
right=mid-1;
}
}
return left;
}
static class Pair{
int min;
int max;
public Pair(int min,int max){
this.min = min;
this.max = max;
}
}
static int isPerfectSquare(int vals){
int lastPow=1;
while(lastPow*lastPow<vals){
lastPow++;
}
if(lastPow*lastPow==vals){
return lastPow*lastPow;
}else{
return -1;
}
}
public static int[] sort(int[] vals){
ArrayList<Integer> values = new ArrayList<>();
for(int i = 0;i<vals.length;i++){
values.add(vals[i]);
}
Collections.sort(values);
for(int i =0;i<values.size();i++){
vals[i] = values.get(i);
}
return vals;
}
public static long[] sort(long[] vals){
ArrayList<Long> values = new ArrayList<>();
for(int i = 0;i<vals.length;i++){
values.add(vals[i]);
}
Collections.sort(values);
for(int i =0;i<values.size();i++){
vals[i] = values.get(i);
}
return vals;
}
public static void reverseArray(long[] vals){
int startIndex = 0;
int endIndex = vals.length-1;
while(startIndex<=endIndex){
long temp = vals[startIndex];
vals[startIndex] = vals[endIndex];
vals[endIndex] = temp;
startIndex++;
endIndex--;
}
}
public static void reverseArray(int[] vals){
int startIndex = 0;
int endIndex = vals.length-1;
while(startIndex<=endIndex){
int temp = vals[startIndex];
vals[startIndex] = vals[endIndex];
vals[endIndex] = temp;
startIndex++;
endIndex--;
}
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
public static int GCD(int numA, int numB){
if(numA==0){
return numB;
}else if(numB==0){
return numA;
}else{
if(numA>numB){
return GCD(numA%numB,numB);
}else{
return GCD(numA,numB%numA);
}
}
}
}
| java |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00. | [
"math",
"number theory"
] | import java.io.*;
import java.util.*;
public class Contest1295D
{
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() { // reads in the next string
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() { // reads in the next int
return Integer.parseInt(next());
}
public long nextLong() { // reads in the next long
return Long.parseLong(next());
}
public double nextDouble() { // reads in the next double
return Double.parseDouble(next());
}
}
static InputReader r = new InputReader(System.in);
static PrintWriter pw = new PrintWriter(System.out);
static long mod = 1000000007;
public static void main(String[] args)
{
int t = r.nextInt();
while (t > 0)
{
t--;
long a = r.nextLong();
long m = r.nextLong();
long g = gcd(a,m);
m/=g;
long ans = 1;
for (long i = 2; i * i <= m; i ++)
{
if (m%i == 0)
{
ans *= (i-1);
m/=i;
while (m%i==0)
{
m/=i;
ans*=i;
}
}
}
if (m > 1)
{
ans *= (m-1);
}
pw.println(ans);
}
pw.close();
}
static long gcd(long a, long b) { return b==0 ? a : gcd(b, a%b); }
} | java |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.*;
import java.util.StringTokenizer;
public class RemoveAdjacent {
static class Pair {
int f;
int s; //
Pair() {
}
Pair(int f, int s) {
this.f = f;
this.s = s;
}
}
static class Fast {
BufferedReader br;
StringTokenizer st;
public Fast() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] readArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readArray1(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine().trim();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
/* static long noOfDivisor(long a)
{
long count=0;
long t=a;
for(long i=1;i<=(int)Math.sqrt(a);i++)
{
if(a%i==0)
count+=2;
}
if(a==((long)Math.sqrt(a)*(long)Math.sqrt(a)))
{
count--;
}
return count;
}*/
static boolean isPrime(long a) {
for (long i = 2; i <= (long) Math.sqrt(a); i++) {
if (a % i == 0)
return false;
}
return true;
}
static void primeFact(int n) {
int temp = n;
HashMap<Integer, Integer> h = new HashMap<>();
for (int i = 2; i * i <= n; i++) {
if (temp % i == 0) {
int c = 0;
while (temp % i == 0) {
c++;
temp /= i;
}
h.put(i, c);
}
}
if (temp != 1)
h.put(temp, 1);
}
static void reverseArray(int a[]) {
int n = a.length;
for (int i = 0; i < n / 2; i++) {
a[i] = a[i] ^ a[n - i - 1];
a[n - i - 1] = a[i] ^ a[n - i - 1];
a[i] = a[i] ^ a[n - i - 1];
}
}
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 b) {
return a > b ? a : b;
}
static int min(int a, int b) {
return a < b ? a : b;
}
public static int[] constructST(int arr[], int n) {
// Add your code here
int st[] = new int[4 * n];
build(arr, 0, n - 1, 0, st);
return st;
}
static int build(int arr[], int l, int r, int idx, int st[]) {
if (l == r) {
return st[idx] = arr[l] & 1;
}
int mid = (l + r) / 2;
int p1 = build(arr, l, mid, 2 * idx + 1, st);
int p2 = build(arr, mid + 1, r, 2 * idx + 2, st);
if (p1 == p2 && p1 != -1)
return st[idx] = p1 & p2;
else if (p1 == -1 || p2 == -1)
return st[idx] = -1;
else
return st[idx] = -1;
}
/* The functions returns the
min element in the range
from l and r */
public static int RMQ(int st[], int n, int l, int r) {
// Add your code here
return solve(st, l, r, 0, n - 1, 0);
}
static int solve(int st[], int l, int r, int low1, int high1, int idx) {
if (low1 >= l && high1 <= r)//lies // we need to find min number in range [l,r] low,high is range in segment tree.. consider the first case
return st[idx];
if (high1 < l || low1 > r)//not lie
return Integer.MAX_VALUE;
int mid = (low1 + high1) / 2;
int left = solve(st, l, r, low1, mid, 2 * idx + 1);
int right = solve(st, l, r, mid + 1, high1, 2 * idx + 2);
if (left == right && left != -1 && left != Integer.MAX_VALUE)
return left;
else if (left == -1 || right == -1)
return -1;
else if (left != right && left != Integer.MAX_VALUE && right != Integer.MAX_VALUE)
return -1;
else if (left == Integer.MAX_VALUE)
return right;
else
return left;
}
static int rec(char s[], int i, int prev, int next, int n) {
if (i == n) {
return 0;
}
// if(dp[i][prev][next]!=-1)
// return dp[i][prev][next];
int f = 0;
if (prev != -1 && s[prev] - s[i] == -1)
f = 1;
else if (next != n && s[next] - s[i] == -1)
f = 1;
int l = Integer.MIN_VALUE;
int r = Integer.MIN_VALUE;
if (f == 1) {
// int ans=1+rec(s,next,prev,next+1,n);
if (prev != -1) {
int t = prev - 1;
while (t != -1 && s[t] != s[prev])
t--;
l = 1 + rec(s, prev, t, next, n);
} else
l = 1 + rec(s, next, prev, next + 1, n);
}
r = rec(s, next, i, next + 1, n);
return max(l, r);
}
static int rec(char s[], int i, int prev, int next, int n, int dp[][][]) {
if (i > n) {
return 0;
}
if (dp[i][prev][next] != -1)
return dp[i][prev][next];
int f = 0;
if (prev != 0 && s[prev - 1] - s[i - 1] == -1)
f = 1;
else if (next != n + 1 && s[next - 1] - s[i - 1] == -1)
f = 1;
int l = Integer.MIN_VALUE;
int r = Integer.MIN_VALUE;
if (f == 1) {
// int ans=1+rec(s,next,prev,next+1,n);
if (prev != 0)
l = 1 + rec(s, prev, prev - 1, next, n, dp);
else
l = 1 + rec(s, next, prev, next + 1, n, dp);
}
r = rec(s, next, i, next + 1, n, dp);
return dp[i][prev][next] = max(l, r);
}
/* public static void main(String args[]) throws IOException {
Fast sc = new Fast();
PrintWriter out = new PrintWriter(System.out);
int n=sc.nextInt();
char s[]=sc.next().toCharArray();
int dp[][][]=new int[n+1][n+1][n+2];
for(int row[][]:dp)
{
for(int row1[]:row)
Arrays.fill(row1,-1);
}
// int ans=rec(s,1,0,2,n,dp);
int ans=rec(s,0,-1,1,n);
out.println(ans);
out.close();
}
}*/
public static void main(String args[]) throws IOException {
Fast sc = new Fast();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
StringBuffer s = new StringBuffer(sc.next());
for (int i = 0; i < n; i++) {
int id = -1;
int le = -1;int l1=s.length();
for (int j = 0; j < l1; j++)
{
char ch = s.charAt(j);
if ((j!=l1-1 && ch-s.charAt(j + 1) == 1 )||(j!=0&& ch - s.charAt(j - 1) == 1) )
{
if (le < ch)
{
le = ch;
id = j;
}
}
}
if (id == -1)
break;
s.delete(id, id + 1);
// out.println(s);
}
// out.println(s);
out.println(n - s.length());
out.close();
}
}
/*
100
aaaaaabbcccccccddffffhhhhhhhhiiiiiikkkkkkkkmmmmmmooooooopppprrrrrrrrrttttttvvvvvvvvvvvvxxxxxxxzzzzzz
p-4 i-6 d-2 c-7 b-2
a-6 f-4
*/
| java |
13 | E | E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3 | [
"data structures",
"dsu"
] | import java.util.*;
import java.io.*;
public class EHoles2 {
// static InputReader in = new InputReader();
static OutputWriter out = new OutputWriter(System.out);
static int[] getArr(String s) {
String[] st = s.split(" ");
int ar[] = new int[st.length];
for (int i = 0; i < ar.length; i++)
ar[i] = Integer.parseInt(st[i]);
return ar;
}
public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int[] ar = getArr(read.readLine());
int N = ar[0];
int Q = ar[1];
int pow[] = getArr(read.readLine());
int sqrt = (int) Math.sqrt(pow.length);
int next[] = new int[pow.length];
int ans[] = new int[pow.length];
for (int i = pow.length - 1; i >= 0; i--) {
int nextt = i + pow[i];
int nextfac = (i / sqrt + 1) * sqrt;
if (nextt >= N) {
next[i] = nextt;
ans[i] = 1;
} else {
if (nextt >= nextfac) {
// can jump to next block
next[i] = nextt;
ans[i] = 1;
} else {
// can jump to same block
next[i] = next[nextt];
ans[i] = 1 + ans[nextt];
}
}
}
while (Q-- > 0) {
int arg[] = getArr(read.readLine());
if (arg[0] == 0) {
int hole = arg[1] - 1;
int newpower = arg[2];
pow[hole] = newpower;
int myfac = (hole / sqrt) * sqrt;
while (hole >= myfac) {
int i = hole;
int nextt = i + pow[i];
int nextfac = (hole / sqrt + 1) * sqrt;
if (nextt >= N) {
next[i] = nextt;
ans[i] = 1;
} else {
if (nextt >= nextfac) {
// can jump to next block
next[i] = nextt;
ans[i] = 1;
} else {
// can jump to same block
next[i] = next[nextt];
ans[i] = 1 + ans[nextt];
}
}
hole--;
}
} else {
// 1 hole
int hole = arg[1] - 1;
int curr = hole;
int jumps = ans[curr];
while (next[curr] < N) {
curr = next[curr];
jumps += ans[curr];
}
while (curr + pow[curr] < N) {
curr += pow[curr];
}
out.printLine((curr + 1) + " " + jumps);
}
}
// in.close();
out.flush();
out.close();
}
private static class InputReader implements AutoCloseable {
private static final int DEFAULT_BUFFER_SIZE = 1 << 16;
private static final InputStream DEFAULT_STREAM = System.in;
private static final int MAX_DECIMAL_PRECISION = 21;
private int c;
private final byte[] buf;
private final int bufferSize;
private int bufIndex;
private int numBytesRead;
private final InputStream stream;
// End Of File (EOF) character
private static final byte EOF = -1;
// New line character: '\n'
private static final byte NEW_LINE = 10;
// Space character: ' '
private static final byte SPACE = 32;
// Dash character: '-'
private static final byte DASH = 45;
// Dot character: '.'
private static final byte DOT = 46;
// A reusable character buffer when reading string data.
private char[] charBuffer;
// Primitive data type lookup tables used for optimizations
private static final byte[] bytes = new byte[58];
private static final int[] ints = new int[58];
private static final char[] chars = new char[128];
static {
char ch = ' ';
int value = 0;
byte _byte = 0;
for (int i = 48; i < 58; i++)
bytes[i] = _byte++;
for (int i = 48; i < 58; i++)
ints[i] = value++;
for (int i = 32; i < 128; i++)
chars[i] = ch++;
}
private static final double[][] doubles = {
{ 0.0d, 0.00d, 0.000d, 0.0000d, 0.00000d, 0.000000d, 0.0000000d, 0.00000000d, 0.000000000d,
0.0000000000d, 0.00000000000d, 0.000000000000d, 0.0000000000000d, 0.00000000000000d,
0.000000000000000d, 0.0000000000000000d, 0.00000000000000000d, 0.000000000000000000d,
0.0000000000000000000d, 0.00000000000000000000d, 0.000000000000000000000d },
{ 0.1d, 0.01d, 0.001d, 0.0001d, 0.00001d, 0.000001d, 0.0000001d, 0.00000001d, 0.000000001d,
0.0000000001d, 0.00000000001d, 0.000000000001d, 0.0000000000001d, 0.00000000000001d,
0.000000000000001d, 0.0000000000000001d, 0.00000000000000001d, 0.000000000000000001d,
0.0000000000000000001d, 0.00000000000000000001d, 0.000000000000000000001d },
{ 0.2d, 0.02d, 0.002d, 0.0002d, 0.00002d, 0.000002d, 0.0000002d, 0.00000002d, 0.000000002d,
0.0000000002d, 0.00000000002d, 0.000000000002d, 0.0000000000002d, 0.00000000000002d,
0.000000000000002d, 0.0000000000000002d, 0.00000000000000002d, 0.000000000000000002d,
0.0000000000000000002d, 0.00000000000000000002d, 0.000000000000000000002d },
{ 0.3d, 0.03d, 0.003d, 0.0003d, 0.00003d, 0.000003d, 0.0000003d, 0.00000003d, 0.000000003d,
0.0000000003d, 0.00000000003d, 0.000000000003d, 0.0000000000003d, 0.00000000000003d,
0.000000000000003d, 0.0000000000000003d, 0.00000000000000003d, 0.000000000000000003d,
0.0000000000000000003d, 0.00000000000000000003d, 0.000000000000000000003d },
{ 0.4d, 0.04d, 0.004d, 0.0004d, 0.00004d, 0.000004d, 0.0000004d, 0.00000004d, 0.000000004d,
0.0000000004d, 0.00000000004d, 0.000000000004d, 0.0000000000004d, 0.00000000000004d,
0.000000000000004d, 0.0000000000000004d, 0.00000000000000004d, 0.000000000000000004d,
0.0000000000000000004d, 0.00000000000000000004d, 0.000000000000000000004d },
{ 0.5d, 0.05d, 0.005d, 0.0005d, 0.00005d, 0.000005d, 0.0000005d, 0.00000005d, 0.000000005d,
0.0000000005d, 0.00000000005d, 0.000000000005d, 0.0000000000005d, 0.00000000000005d,
0.000000000000005d, 0.0000000000000005d, 0.00000000000000005d, 0.000000000000000005d,
0.0000000000000000005d, 0.00000000000000000005d, 0.000000000000000000005d },
{ 0.6d, 0.06d, 0.006d, 0.0006d, 0.00006d, 0.000006d, 0.0000006d, 0.00000006d, 0.000000006d,
0.0000000006d, 0.00000000006d, 0.000000000006d, 0.0000000000006d, 0.00000000000006d,
0.000000000000006d, 0.0000000000000006d, 0.00000000000000006d, 0.000000000000000006d,
0.0000000000000000006d, 0.00000000000000000006d, 0.000000000000000000006d },
{ 0.7d, 0.07d, 0.007d, 0.0007d, 0.00007d, 0.000007d, 0.0000007d, 0.00000007d, 0.000000007d,
0.0000000007d, 0.00000000007d, 0.000000000007d, 0.0000000000007d, 0.00000000000007d,
0.000000000000007d, 0.0000000000000007d, 0.00000000000000007d, 0.000000000000000007d,
0.0000000000000000007d, 0.00000000000000000007d, 0.000000000000000000007d },
{ 0.8d, 0.08d, 0.008d, 0.0008d, 0.00008d, 0.000008d, 0.0000008d, 0.00000008d, 0.000000008d,
0.0000000008d, 0.00000000008d, 0.000000000008d, 0.0000000000008d, 0.00000000000008d,
0.000000000000008d, 0.0000000000000008d, 0.00000000000000008d, 0.000000000000000008d,
0.0000000000000000008d, 0.00000000000000000008d, 0.000000000000000000008d },
{ 0.9d, 0.09d, 0.009d, 0.0009d, 0.00009d, 0.000009d, 0.0000009d, 0.00000009d, 0.000000009d,
0.0000000009d, 0.00000000009d, 0.000000000009d, 0.0000000000009d, 0.00000000000009d,
0.000000000000009d, 0.0000000000000009d, 0.00000000000000009d, 0.000000000000000009d,
0.0000000000000000009d, 0.00000000000000000009d, 0.000000000000000000009d } };
public InputReader() {
this(DEFAULT_STREAM, DEFAULT_BUFFER_SIZE);
}
public InputReader(int bufferSize) {
this(DEFAULT_STREAM, bufferSize);
}
public InputReader(InputStream stream) {
this(stream, DEFAULT_BUFFER_SIZE);
}
public InputReader(InputStream stream, int bufferSize) {
if (stream == null || bufferSize <= 0)
throw new IllegalArgumentException();
buf = new byte[bufferSize];
charBuffer = new char[128];
this.bufferSize = bufferSize;
this.stream = stream;
}
private byte read() throws IOException {
if (numBytesRead == EOF)
throw new IOException();
if (bufIndex >= numBytesRead) {
bufIndex = 0;
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return EOF;
}
return buf[bufIndex++];
}
private int readJunk(int token) throws IOException {
if (numBytesRead == EOF)
return EOF;
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > token)
return 0;
bufIndex++;
}
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return EOF;
bufIndex = 0;
} while (true);
}
public byte nextByte() throws IOException {
return (byte) nextInt();
}
public int nextInt() throws IOException {
if (readJunk(DASH - 1) == EOF)
throw new IOException();
int sgn = 1, res = 0;
c = buf[bufIndex];
if (c == DASH) {
sgn = -1;
bufIndex++;
}
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > SPACE) {
res = (res << 3) + (res << 1);
res += ints[buf[bufIndex++]];
} else {
bufIndex++;
return res * sgn;
}
}
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return res * sgn;
bufIndex = 0;
} while (true);
}
public long nextLong() throws IOException {
if (readJunk(DASH - 1) == EOF)
throw new IOException();
int sgn = 1;
long res = 0L;
c = buf[bufIndex];
if (c == DASH) {
sgn = -1;
bufIndex++;
}
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > SPACE) {
res = (res << 3) + (res << 1);
res += ints[buf[bufIndex++]];
} else {
bufIndex++;
return res * sgn;
}
}
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return res * sgn;
bufIndex = 0;
} while (true);
}
private void doubleCharBufferSize() {
char[] newBuffer = new char[charBuffer.length << 1];
for (int i = 0; i < charBuffer.length; i++)
newBuffer[i] = charBuffer[i];
charBuffer = newBuffer;
}
public String nextLine() throws IOException {
try {
c = read();
} catch (IOException e) {
return null;
}
if (c == NEW_LINE)
return ""; // Empty line
if (c == EOF)
return null; // EOF
int i = 0;
charBuffer[i++] = (char) c;
do {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] != NEW_LINE) {
if (i == charBuffer.length)
doubleCharBufferSize();
charBuffer[i++] = (char) buf[bufIndex++];
} else {
bufIndex++;
return new String(charBuffer, 0, i);
}
}
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return new String(charBuffer, 0, i);
bufIndex = 0;
} while (true);
}
public String nextString() throws IOException {
if (numBytesRead == EOF)
return null;
if (readJunk(SPACE) == EOF)
return null;
for (int i = 0;;) {
while (bufIndex < numBytesRead) {
if (buf[bufIndex] > SPACE) {
if (i == charBuffer.length)
doubleCharBufferSize();
charBuffer[i++] = (char) buf[bufIndex++];
} else {
bufIndex++;
return new String(charBuffer, 0, i);
}
}
numBytesRead = stream.read(buf);
if (numBytesRead == EOF)
return new String(charBuffer, 0, i);
bufIndex = 0;
}
}
public double nextDouble() throws IOException {
String doubleVal = nextString();
if (doubleVal == null)
throw new IOException();
return Double.valueOf(doubleVal);
}
public double nextDoubleFast() throws IOException {
c = read();
int sgn = 1;
while (c <= SPACE)
c = read(); // while c is either: ' ', '\n', EOF
if (c == DASH) {
sgn = -1;
c = read();
}
double res = 0.0;
while (c > DOT) {
res *= 10.0;
res += ints[c];
c = read();
}
if (c == DOT) {
int i = 0;
c = read();
while (c > SPACE && i < MAX_DECIMAL_PRECISION) {
res += doubles[ints[c]][i++];
c = read();
}
}
return res * sgn;
}
public byte[] nextByteArray(int n) throws IOException {
byte[] ar = new byte[n];
for (int i = 0; i < n; i++)
ar[i] = nextByte();
return ar;
}
public int[] nextIntArray(int n) throws IOException {
int[] ar = new int[n];
for (int i = 0; i < n; i++)
ar[i] = nextInt();
return ar;
}
public long[] nextLongArray(int n) throws IOException {
long[] ar = new long[n];
for (int i = 0; i < n; i++)
ar[i] = nextLong();
return ar;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] ar = new double[n];
for (int i = 0; i < n; i++)
ar[i] = nextDouble();
return ar;
}
public double[] nextDoubleArrayFast(int n) throws IOException {
double[] ar = new double[n];
for (int i = 0; i < n; i++)
ar[i] = nextDoubleFast();
return ar;
}
public String[] nextStringArray(int n) throws IOException {
String[] ar = new String[n];
for (int i = 0; i < n; i++) {
String str = nextString();
if (str == null)
throw new IOException();
ar[i] = str;
}
return ar;
}
public byte[] nextByteArray1(int n) throws IOException {
byte[] ar = new byte[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextByte();
return ar;
}
public int[] nextIntArray1(int n) throws IOException {
int[] ar = new int[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextInt();
return ar;
}
public long[] nextLongArray1(int n) throws IOException {
long[] ar = new long[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextLong();
return ar;
}
public double[] nextDoubleArray1(int n) throws IOException {
double[] ar = new double[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextDouble();
return ar;
}
public double[] nextDoubleArrayFast1(int n) throws IOException {
double[] ar = new double[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextDoubleFast();
return ar;
}
public String[] nextStringArray1(int n) throws IOException {
String[] ar = new String[n + 1];
for (int i = 1; i <= n; i++)
ar[i] = nextString();
return ar;
}
public byte[][] nextByteMatrix(int rows, int cols) throws IOException {
byte[][] matrix = new byte[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextByte();
return matrix;
}
public int[][] nextIntMatrix(int rows, int cols) throws IOException {
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextInt();
return matrix;
}
public long[][] nextLongMatrix(int rows, int cols) throws IOException {
long[][] matrix = new long[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextLong();
return matrix;
}
public double[][] nextDoubleMatrix(int rows, int cols) throws IOException {
double[][] matrix = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextDouble();
return matrix;
}
public double[][] nextDoubleMatrixFast(int rows, int cols) throws IOException {
double[][] matrix = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextDoubleFast();
return matrix;
}
public String[][] nextStringMatrix(int rows, int cols) throws IOException {
String[][] matrix = new String[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextString();
return matrix;
}
public byte[][] nextByteMatrix1(int rows, int cols) throws IOException {
byte[][] matrix = new byte[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextByte();
return matrix;
}
public int[][] nextIntMatrix1(int rows, int cols) throws IOException {
int[][] matrix = new int[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextInt();
return matrix;
}
public long[][] nextLongMatrix1(int rows, int cols) throws IOException {
long[][] matrix = new long[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextLong();
return matrix;
}
public double[][] nextDoubleMatrix1(int rows, int cols) throws IOException {
double[][] matrix = new double[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextDouble();
return matrix;
}
public double[][] nextDoubleMatrixFast1(int rows, int cols) throws IOException {
double[][] matrix = new double[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextDoubleFast();
return matrix;
}
public String[][] nextStringMatrix1(int rows, int cols) throws IOException {
String[][] matrix = new String[rows + 1][cols + 1];
for (int i = 1; i <= rows; i++)
for (int j = 1; j <= cols; j++)
matrix[i][j] = nextString();
return matrix;
}
public void close() throws IOException {
stream.close();
}
}
private static class OutputWriter implements AutoCloseable {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
} | java |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | import java.util.*;
public class aa
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
outer : while(t-->0)
{
int n = sc.nextInt();
int a[] = new int[n];
boolean flag = false;
for(int i = 0; i<n; i++)
{
a[i] = sc.nextInt();
}
for(int i = 0; i<n; i++)
{
if(a[i]%2==0)
{
System.out.println("1\n" + (i+1));
continue outer;
}
}
if(n>1)System.out.println("2\n1 2");
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.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static long mod = (long) 1e9 + 7;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// long t=Long.parseLong(br.readLine());
// while(t-->0){
// int n=Integer.parseInt(br.readLine());
String[] in=br.readLine().split(" ");
String[] in1=br.readLine().split(" ");
int n=Integer.parseInt(in[0]);
int m=Integer.parseInt(in[1]);
// String[] in2=br.readLine().split(" ");
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(in1[i]);
}
// String[] in1=br.readLine().split(" ");
// HashMap<String,Integer>m1=new HashMap<>();
if(n<=m){
long prod=1;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
prod=prod*Math.abs(a[i]-a[j])%m;
}
}
System.out.println(prod%m);
}
else System.out.println(0);
// }
}
static long n_of_factors(long[][] a) {
long ans = 1;
for (int i = 0; i < a.length; i++) {
ans = ans * (a[i][1] + 1) % mod;
}
return ans % mod;
}
static long sum_of_factors(long[][] a) {
long ans = 1;
for (int i = 0; i < a.length; i++) {
long res = (((expo(a[i][0], a[i][1] + 1) - 1) % mod) * (modular_inverse(a[i][0] - 1)) % mod) % mod;
ans = ((res % mod) * (ans % mod)) % mod;
}
return (ans % mod);
}
static long prod_of_divisors(long[][] a) {
long ans = 1;
long d = 1;
for (int i = 0; i < a.length; i++) {
long res = expo(a[i][0], (a[i][1] * (a[i][1] + 1) / 2));
ans = ((expo(ans, a[i][1] + 1) % mod) * (expo(res, d) % mod)) % mod;
d = (d * (a[i][1] + 1)) % (mod - 1);
}
return ans % mod;
}
static long expo(long a, long b) {
long ans = 1;
a = a % mod;
while (b > 0) {
if ((b & 1) == 1) {
ans = ans * a % mod;
}
a = a * a % mod;
b >>= 1;
}
return ans % mod;
}
static long modular_inverse(long a) {
return expo(a, mod - 2) % mod;
}
static long phin(long a) {
if (isPrime(a))
return a - 1;
long res = a;
for (int i = 2; i * i <= (int) a; i++) {
if (a % i == 0) {
while (a % i == 0) {
a = a / i;
}
res -= res / i;
}
}
if (a > 1) {
res -= res / a;
}
return res;
}
static boolean isPrime(long a) {
if (a < 2)
return false;
for (int i = 2; i * i <= (int) a; i++) {
if (a % i == 0)
return false;
}
return true;
}
static long catlan(long a) {
long ans = 1;
for (int i = 1; i <= a; i++) {
ans = ans * (4 * i - 2) % mod;
ans = ((ans % mod) * modular_inverse(i + 1)) % mod;
}
return ans % mod;
}
static HashMap<Long, Long> primeFactors(long n) {
HashMap<Long, Long> m1 = new HashMap<>();
for (int i = 2; (long) i * (long) i <= n; i++) {
if (n % i == 0) {
while (n % i == 0) {
m1.put((long) i, m1.getOrDefault(i, 0l) + 1);
n = n / i;
}
}
}
return m1;
}
static long gcd(long a,long b){
a=Math.abs(a);
b=Math.abs(b);
if(b==0) return a;
return gcd(b,a%b);
}
// }
}
class pair{
long a;
long b;
pair(long a,long b){
this.a=a;
this.b=b;
}
} | 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) {
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 |
1295 | E | E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2
| [
"data structures",
"divide and conquer"
] | import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
void run(){
work();
out.flush();
}
long mod=998244353;
long gcd(long a,long b) {
return a==0?b:gcd(b%a,a);
}
void work() {
int n=ni();
int[] A=nia(n);
long[] W=na(n);
long[] sum=new long[n];
for(int i=0;i<n;i++) {
sum[A[i]]=W[i];
}
for(int i=1;i<n;i++) {
sum[i]+=sum[i-1];
}
Node root=new Node();
for(int i=0;i<n;i++) {
update(root,0,n-1,i,i,sum[i]);
}
long ret=Long.MAX_VALUE;
long s=0;
for(int i=0;i<n-1;i++) {
int node=A[i];
long w=W[i];
s+=w;//前缀空集
update(root,0,n-1,node,n-1,-w);
if(node!=0)update(root,0,n-1,0,node-1,w);
ret=Math.min(ret, root.min);
ret=Math.min(ret, s);
}
out.println(ret);
}
void u2(Node node,long v) {
node.min+=v;
node.lazy+=v;
}
void updatelazy(Node node) {
u2(getLnode(node),node.lazy);
u2(getRnode(node),node.lazy);
node.lazy=0;
}
private void update(Node node, int l, int r, int s,int e,long v) {
if(l>=s&&r<=e) {
node.min+=v;
node.lazy+=v;
return;
}
updatelazy(node);
int m=l+(r-l)/2;
if(m>=s) {
update(getLnode(node),l,m,s,e,v);
}
if(m+1<=e) {
update(getRnode(node),m+1,r,s,e,v);
}
node.min=Math.min(getLnode(node).min,getRnode(node).min);//左右节点可能有lazy标记
}
private Node getLnode(Node node) {
if(node.lnode==null)node.lnode=new Node();
return node.lnode;
}
private Node getRnode(Node node) {
if(node.rnode==null)node.rnode=new Node();
return node.rnode;
}
class Node{
Node lnode,rnode;
long lazy;
long min;
}
//input
private ArrayList<Integer>[] ng(int n, int m) {
ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n];
for(int i=0;i<n;i++) {
graph[i]=new ArrayList<>();
}
for(int i=1;i<=m;i++) {
int s=in.nextInt()-1,e=in.nextInt()-1;
graph[s].add(e);
graph[e].add(s);
}
return graph;
}
private int ni() {
return in.nextInt();
}
private long nl() {
return in.nextLong();
}
private long[] na(int n) {
long[] A=new long[n];
for(int i=0;i<n;i++) {
A[i]=in.nextLong();
}
return A;
}
private int[] nia(int n) {
int[] A=new int[n];
for(int i=0;i<n;i++) {
A[i]=in.nextInt()-1;//
}
return A;
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
while(st==null || !st.hasMoreElements())//回车,空行情况
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
| java |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | import java.util.Scanner;
public class CF1009{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
while(testCases>0){
int indexOfEvenNumber = -1;
int indexOfFirstOddNumber = -1;
int indexOfSecondOddNumber = -1;
int arrayLength = scan.nextInt();
for(int i=1; i<=arrayLength; i++){
int num = scan.nextInt();
if(num%2==0){
indexOfEvenNumber = i;
}else if(indexOfFirstOddNumber==-1){
indexOfFirstOddNumber = i;
}else{
indexOfSecondOddNumber=i;
}
}
if(indexOfEvenNumber!=-1){
System.out.println(1);
System.out.println(indexOfEvenNumber);
}else if(indexOfFirstOddNumber>0 && indexOfSecondOddNumber>0){
System.out.println(2);
System.out.println(indexOfFirstOddNumber+" "+indexOfSecondOddNumber);
}else{
System.out.println(-1);
}
testCases--;
}
}
} | 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 static java.lang.Math.*;
public class Main implements Runnable
{
boolean multiple = false;
long MOD = 998244353;
@SuppressWarnings("Duplicates")
void solve() throws Exception
{
int n = sc.nextInt();
int[][] x = new int[n][n];
int[][] y = new int[n][n];
int[][] ans = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
x[i][j] = max(-1, sc.nextInt() - 1);
y[i][j] = max(-1, sc.nextInt() - 1);
}
boolean gay = true;
boolean[][] visited = new boolean[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (visited[i][j]) continue;
if (x[i][j] == -1)
{
if (i > 0 && x[i - 1][j] == -1) ans[i][j] = 1;
else if (i < n - 1 && x[i + 1][j] == -1) ans[i][j] = 2;
else if (j > 0 && x[i][j - 1] == -1) ans[i][j] = 3;
else if (j < n - 1 && x[i][j + 1] == -1) ans[i][j] = 4;
else
{
gay = false;
break;
}
}
else
{
int start = p(x[i][j], y[i][j]);
// System.out.println(i + " " + j);
ans[x[i][j]][y[i][j]] = 5;
HashSet<Integer> fringe = new HashSet<>();
fringe.add(start);
visited[f(start)][s(start)] = true;
int tx = f(start), ty = s(start);
if (x[x[i][j]][y[i][j]] != x[i][j] || y[x[i][j]][y[i][j]] != y[i][j])
{
gay = false;
break;
}
while (!fringe.isEmpty())
{
HashSet<Integer> next = new HashSet<>();
// System.out.println("fringe:" + fringe);
for (Integer u : fringe)
{
// System.out.println(u);
// System.out.println(next);
int ux = f(u), uy = s(u);
int qx = ux - 1, qy = uy;
if (qx >= 0 && qx < n && qy >= 0 && qy < n
&& !visited[qx][qy] && x[qx][qy] == tx && y[qx][qy] == ty)
{
// System.out.println("1");
visited[qx][qy] = true;
ans[qx][qy] = 2;
next.add(p(qx, qy));
}
qx = ux + 1;
if (qx >= 0 && qx < n && qy >= 0 && qy < n
&& !visited[qx][qy] && x[qx][qy] == tx && y[qx][qy] == ty)
{
// System.out.println(2);
visited[qx][qy] = true;
ans[qx][qy] = 1;
next.add(p(qx, qy));
}
qx = ux;
qy = uy - 1;
if (qx >= 0 && qx < n && qy >= 0 && qy < n
&& !visited[qx][qy] && x[qx][qy] == tx && y[qx][qy] == ty)
{
// System.out.println(3);
visited[qx][qy] = true;
ans[qx][qy] = 4;
next.add(p(qx, qy));
}
qy = uy + 1;
if (qx >= 0 && qx < n && qy >= 0 && qy < n
&& !visited[qx][qy] && x[qx][qy] == tx && y[qx][qy] == ty)
{
// System.out.println(4);
visited[qx][qy] = true;
ans[qx][qy] = 3;
next.add(p(qx, qy));
}
// System.out.println(next);
// System.out.println();
}
fringe = next;
}
}
visited[i][j] = true;
}
if (!gay) break;
}
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (ans[i][j] == 0) gay = false;
if (!gay) System.out.println("INVALID");
else
{
System.out.println("VALID");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (ans[i][j] == 1) sb.append('U');
if (ans[i][j] == 2) sb.append('D');
if (ans[i][j] == 3) sb.append('L');
if (ans[i][j] == 4) sb.append('R');
if (ans[i][j] == 5) sb.append('X');
}
sb.append('\n');
}
System.out.print(sb);
}
}
int p(int i, int j)
{
return (i * 1000) + j;
}
int f(int key)
{
return key / 1000;
}
int s(int key)
{
return key % 1000;
}
class Node implements Comparable<Node>
{
int idx, val;
Node(int I, int V)
{
idx = I;
val = V;
}
@Override
public int compareTo(Node o)
{
if (val != o.val) return Integer.compare(val, o.val);
return Integer.compare(o.idx, idx);
}
}
long inv(long a, long b) { return 1 < a ? b - inv(b % a, a) * b / a : 1; }
long gcd(long a, long b) { return a == 0 ? b : gcd(b % a, a); }
long powmod(long x, long pow) { if (pow == 0) return 1L;long temp = powmod(x,pow / 2);if (pow % 2 == 0) return (temp * temp) % MOD;return (((x * temp) % MOD) * temp) % MOD; }
long lcm(long a, long b) { return (a * b) / gcd(a , b); }
void printarr(int[] arr) { for (int t : arr) System.out.print(t + " ");System.out.println(); }
TreeMap<Integer, TreeSet<Integer>> buildGraph(int n, int m) throws Exception{TreeMap<Integer, TreeSet<Integer>> graph = new TreeMap<>();for (int i = 1; i <= n; i++) graph.put(i, new TreeSet<>());for (int i = 0; i < m; i++) { int u = sc.nextInt();int v = sc.nextInt();graph.get(u).add(v);graph.get(v).add(u); }return graph; }
TreeMap<Integer, TreeSet<Integer>> buildDirGraph(int n, int m) throws Exception { TreeMap<Integer, TreeSet<Integer>> graph = new TreeMap<>();for (int i = 1; i <= n; i++) graph.put(i, new TreeSet<>());for (int i = 0; i < m; i++) graph.get(sc.nextInt()).add(sc.nextInt());return graph; }
TreeMap<Integer, TreeSet<Integer>> revGraph(TreeMap<Integer, TreeSet<Integer>> graph) { TreeMap<Integer, TreeSet<Integer>> rev = new TreeMap<>();for (Integer u : graph.keySet()) rev.put(u, new TreeSet<>());for (Integer u : graph.keySet()) for (Integer v : graph.get(u)) rev.get(v).add(u);return rev; }
int[] iarr(int n) throws Exception { int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = sc.nextInt();return a; }
Integer[] Iarr(int n) throws Exception { Integer[] a = new Integer[n];for (int i = 0; i < n; i++) a[i] = sc.nextInt();return a; }
long[] larr(int n) throws Exception { long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = sc.nextLong();return a; }
TreeMap<Long, Integer> counts(long[] arr) { TreeMap<Long, Integer> counts = new TreeMap<>(); for (long a : arr) { if (!counts.containsKey(a)) counts.put(a, 0); counts.put(a, counts.get(a) + 1);} return counts; }
String reverse(String s, int i, int j) /*[i, j] closed*/ { return (i > j) ? reverse(s, j, i) : s.substring(0, i) + (new StringBuilder(s.substring(i, j + 1))).reverse() + ((j + 1 <= s.length() - 1) ? s.substring(j + 1) : "");}
@Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);sc = new FastScanner(in);if (multiple) { int q = sc.nextInt();for (int i = 0; i < q; i++) solve(); } else solve(); } catch (Throwable uncaught) { Main.uncaught = uncaught; } finally { out.close(); }} public static void main(String[] args) throws Throwable{ Thread thread = new Thread(null, new Main(), "", (1 << 26));thread.start();thread.join();if (Main.uncaught != null) {throw Main.uncaught;} } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) {this.in = in;}public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); }return st.nextToken(); }public int nextInt() throws Exception { return Integer.parseInt(nextToken()); }public long nextLong() throws Exception { return Long.parseLong(nextToken()); }public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); }
} | java |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int test = input.nextInt();
for( int i = 0; i < test; i++ ){
int a = input.nextInt();
int b = input.nextInt();
if( a == b ) System.out.println("0");
else{
if( (a % 2 == 0 && b % 2 == 0) || ( a % 2 == 1 && b % 2 == 1 )){
if( a > b ) System.out.println("1");
else System.out.println("2");
}
else{
if( a > b ) System.out.println("2");
else System.out.println("1");
}
}
}
//input.close();
}
}
| java |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | // package codeforces;
import java.io.*;
import java.util.*;
public class practice {
static FastScanner fs = new FastScanner();
public static void main(String[] args) {
int t = 1;
t = fs.nextInt();
for(int i=1;i<=t;i++) {
solve(t);
}
}
public static void solve(int tt) {
int a = fs.nextInt();
int b = fs.nextInt();
int x = fs.nextInt();
int y = fs.nextInt();
int f[] = new int[4];
f[0] = x * b;
f[1] = (a - x - 1) * b;
f[2] = y * a;
f[3] = (b - y -1) * a;
int c = 0;
for(int i=0;i<4;i++)c=Math.max(c,f[i]);
System.out.println(c);
return;
}
public static int [] sortarray(int a[]) {
ArrayList<Integer> L = new ArrayList<Integer>();
for(int i:a) {
L.add(i);
}
Collections.sort(L);
for(int i=0;i<L.size();i++)a[i]=L.get(i);
return a;
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
ArrayList<Integer> readList(int n) {
ArrayList<Integer> a = new ArrayList<Integer>();
int x;
for(int i=0;i<n;i++) {
x=fs.nextInt();
a.add(x);
}
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| java |
1296 | E2 | E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1
| [
"data structures",
"dp"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Set;
import java.util.HashSet;
public class Solution {
static Reader input = new Reader();
static int n;
static char[] s;
static int[] colors;
static int color = 1;
public static void main(String[] args) throws IOException {
n = input.nextInt();
s = input.next().toCharArray();
colors = new int[n];
coloring();
StringBuilder output = new StringBuilder();
output.append(color-1);
output.append("\n");
for(int i = 0; i < n; ++i) {
output.append(colors[i]);
output.append(" ");
}
System.out.print(output);
}
static void coloring() {
Set<Integer>[] used = new Set[26];
for(int i = 0; i < 26; ++i) used[i] = new HashSet<Integer>();
for(int i = 0; i < n; ++i) {
boolean[] set = new boolean[color];
for(int j = s[i]-'a'+1; j < 26; ++j) {
for(int u : used[j]) {
set[u] = true;
}
}
int x = -1;
for(int j = 1; j < color; ++j) {
if(!set[j]) {
x = j;
break;
}
}
if(x == -1) {
x = color;
++color;
}
colors[i] = x;
used[s[i]-'a'].add(x);
}
}
static class Reader {
BufferedReader bufferedReader;
StringTokenizer string;
public Reader() {
InputStreamReader inr = new InputStreamReader(System.in);
bufferedReader = new BufferedReader(inr);
}
public String next() throws IOException {
while(string == null || ! string.hasMoreElements()) {
string = new StringTokenizer(bufferedReader.readLine());
}
return string.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public String nextLine() throws IOException {
return bufferedReader.readLine();
}
}
} | java |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"data structures",
"greedy"
] | import java.io.*;
import java.util.*;
public class ProblemA {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
int n = in.readInt();
int a[] = new int[n];
for(int i = 0;i<n;i++)a[i] = in.readInt();
ArrayList<Pair>res = new ArrayList<>();
HashMap<Long,ArrayList<Pair>>mp = new HashMap<>();
long t = 0;
for(int i = 0;i<n;i++){
long sum =0;
for(int j = i;j<n;j++){
sum+=a[j];
ArrayList<Pair>l = mp.getOrDefault(sum,new ArrayList<Pair>());
l.add(new Pair(i+1,j+1));
mp.put(sum, l);
}
}
Comparator<Pair>cmp = new Comparator<Pair>(){
@Override
public int compare(Pair o1, Pair o2) {
return o1.y != o2.y?o1.y-o2.y:o2.x - o1.x;
}
};
for(Map.Entry<Long, ArrayList<Pair>>m:mp.entrySet()){
Collections.sort(m.getValue(),cmp);
ArrayList<Pair> temp = m.getValue();
ArrayList<Pair>cur = new ArrayList<>();
int r = -1;
for(int i = 0;i<temp.size();i++){
if(temp.get(i).x>r){
cur.add(temp.get(i));
r = temp.get(i).y;
}
}
if(cur.size()>res.size()){
res = cur;
}
}
System.out.println(res.size());
for(Pair it:res)System.out.println(it.x+" "+it.y);
}
public static void build(int seg[],int ind,int l,int r,int a[]){
if(l == r){
seg[ind] = a[l];
return;
}
int mid = (l+r)/2;
build(seg,(2*ind)+1,l,mid,a);
build(seg,(2*ind)+2,mid+1,r,a);
seg[ind] = Math.min(seg[(2*ind)+1],seg[(2*ind)+2]);
}
public static long gcd(long a, long b){
return b ==0 ?a:gcd(b,a%b);
}
public static long nearest(TreeSet<Long> list,long target){
long nearest = -1,sofar = Integer.MAX_VALUE;
for(long it:list){
if(Math.abs(it - target)<sofar){
sofar = Math.abs(it - target);
nearest = it;
}
}
return nearest;
}
public static ArrayList<Long> factors(long n){
ArrayList<Long>l = new ArrayList<>();
for(long i = 1;i*i<=n;i++){
if(n%i == 0){
l.add(i);
if(n/i != i)l.add(n/i);
}
}
Collections.sort(l);
return l;
}
public static void swap(int a[],int i, int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static boolean isSorted(long a[]){
for(int i =0;i<a.length;i++){
if(i+1<a.length && a[i]>a[i+1])return false;
}
return true;
}
public static int first(ArrayList<Long>list,long target){
int index = -1;
int l = 0,r = list.size()-1;
while(l<=r){
int mid = (l+r)/2;
if(list.get(mid) == target){
index = mid;
r = mid-1;
}else if(list.get(mid)>target){
r = mid-1;
}else l = mid+1;
}
return index;
}
public static int last(ArrayList<Long>list,long target){
int index = -1;
int l = 0,r = list.size()-1;
while(l<=r){
int mid = (l+r)/2;
if(list.get(mid) == target){
index= mid;
l = mid+1;
}else if(list.get(mid)<target){
l = mid+1;
}else r = mid-1;
}
return index;
}
public static void sort(int arr[]){
ArrayList<Integer>list = new ArrayList<>();
for(int it:arr)list.add(it);
Collections.sort(list);
for(int i = 0;i<arr.length;i++)arr[i] = list.get(i);
}
static class Pair{
int x,y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
}
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String read()
{
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int readInt() { return Integer.parseInt(read()); }
public long readLong() { return Long.parseLong(read()); }
public double readDouble(){return Double.parseDouble(read());}
public String readLine() throws Exception { return br.readLine(); }
}
}
| java |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. | [
"data structures",
"greedy",
"implementation",
"math"
] | import java.io.*;
import java.util.*;
public class ProblemD {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
int test = in.readInt();
int x = in.readInt();
int count[] = new int[x];
StringBuilder sb = new StringBuilder();
HashMap<Integer,Integer>map = new HashMap<>();
int mx = 0;
while(test-->0){
int a = in.readInt();
count[a%x]++;
map.put(a%x, map.getOrDefault(a%x, 0)+1);
while(map.containsKey(mx%x) && map.get(mx%x)>0){
map.put(mx%x,map.get(mx%x)-1);
mx++;
}
sb.append(mx);
sb.append("\n");
}
System.out.println(sb);
}
public static void sort(int arr[]){
ArrayList<Integer>list = new ArrayList<>();
for(int it:arr)list.add(it);
Collections.sort(list);
for(int i = 0;i<arr.length;i++)arr[i] = list.get(i);
}
static class Pair{
int x,y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
}
static class Scanner{
BufferedReader br;
StringTokenizer st;
public Scanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String read()
{
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int readInt() { return Integer.parseInt(read()); }
public long readLong() { return Long.parseLong(read()); }
public double readDouble(){return Double.parseDouble(read());}
public String readLine() throws Exception { return br.readLine(); }
}
}
| java |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6
| [
"greedy",
"sortings"
] | // package c1296;
//
// Codeforces Round #617 (Div. 3) 2020-02-04 06:35
// D. Fight with Monsters
// https://codeforces.com/contest/1296/problem/D
// time limit per test 1 second; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There are n monsters standing in a row numbered from 1 to n. The i-th monster has h_i health
// points (hp). You have your attack power equal to a hp and your opponent has his attack power
// equal to b hp.
//
// You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first
// monster and fight it till his death, then you and your opponent go the second monster and fight
// it till his death, and so on. A monster is considered dead if its hp is less than or equal to 0.
//
// The fight with a monster happens in turns.
// 1. You hit the monster by a hp. If it is dead after your hit, and you both proceed to the next
// monster.
// 2. Your opponent hits the monster by b hp. If it is dead after his hit, and you both proceed to
// the next monster.
//
// You have some secret technique to force your opponent to skip his turn. You can use this
// technique at most k times (for example, if there are two monsters and k=4, then you can use the
// technique 2 times on the first monster and 1 time on the second monster, but not 2 times on the
// first monster and 3 times on the second monster).
//
// Your task is to determine the maximum number of points you can gain if you use the secret
// technique optimally.
//
// Input
//
// The first line of the input contains four integers n, a, b and k (1 <= n <= 2 * 10^5, 1 <= a, b,
// k <= 10^9) -- the number of monsters, your attack power, the opponent's attack power and the
// number of times you can use the secret technique.
//
// The second line of the input contains n integers h_1, h_2, ..., h_n (1 <= h_i <= 10^9), where h_i
// is the health points of the i-th monster.
//
// Output
//
// Print one integer -- the maximum number of points you can gain if you use the secret technique
// optimally.
//
// Example
/*
input:
6 2 3 3
7 10 50 12 1 8
output:
5
input:
1 1 100 99
100
output:
1
input:
7 4 2 1
1 3 5 4 2 7 6
output:
6
*/
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
public class C1296D {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int solve(int[] h, int a, int b, int k) {
int n = h.length;
int ans = 0;
List<Integer> nums = new ArrayList<>();
for (int v : h) {
v %= a + b;
if (v == 0) {
v = a + b;
}
if (v <= a) {
ans++;
} else {
nums.add(v);
}
}
Collections.sort(nums);
if (test) System.out.format(" nums:%s\n", nums.toString());
for (int v : nums) {
int w = (v + a - 1) / a;
// need b skip for w - 1 times
if (k >= w - 1) {
k -= w - 1;
ans++;
} else {
break;
}
}
return ans;
}
static void test(int exp, int[] h, int a, int b, int k) {
int ans = solve(h, a, b, k);
System.out.format("%s %d %d %d => %d %s\n", Arrays.toString(h), a, b, k, ans,
ans == exp ? "":"Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(5, new int[] {7, 10, 50, 12, 1, 8}, 2, 3, 3);
test(1, new int[] {100}, 1, 100, 99);
test(6, new int[] {1,3,5,4,2,7,6}, 4,2,1);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int k = in.nextInt();
int[] h = new int[n];
for (int i = 0; i < n; i++) {
h[i] = in.nextInt();
}
int ans = solve(h, a, b, k);
System.out.println(ans);
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 4000) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| java |
1320 | A | A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6]. | [
"data structures",
"dp",
"greedy",
"math",
"sortings"
] | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class A_Journey_Planning {
static long mod = Long.MAX_VALUE;
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = 1;
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
int n = f.nextInt();
int arr[] = f.nextArray(n);
int sub[] = new int[n];
for(int i = 0; i < n; i++) {
sub[i] = arr[i] - i;
}
HashMap<Integer, Long> hm = new HashMap<>();
for(int i = 0; i < n; i++) {
hm.put(sub[i], hm.getOrDefault(sub[i], 0l) + arr[i]);
}
long ans = 0;
for(Map.Entry<Integer, Long> e: hm.entrySet()) {
ans = max(ans, e.getValue());
}
out.println(ans);
}
// Sort an array
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
// Find all divisors of n
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
// Check if n is prime or not
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
// Find gcd of a and b
public static long gcd(long a, long b) {
long dividend = a > b ? a : b;
long divisor = a < b ? a : b;
while(divisor > 0) {
long reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
// Find lcm of a and b
public static long lcm(long a, long b) {
long lcm = gcd(a, b);
long hcf = (a * b) / lcm;
return hcf;
}
// Find factorial in O(n) time
public static long fact(int n) {
long res = 1;
for(int i = 2; i <= n; i++) {
res = res * i;
}
return res;
}
// Find power in O(logb) time
public static long power(long a, long b) {
long res = 1;
while(b > 0) {
if((b&1) == 1) {
res = (res * a)%mod;
}
a = (a * a)%mod;
b >>= 1;
}
return res;
}
// Find nCr
public static long nCr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / (fact(r) * fact(n-r));
return ans;
}
// Find nPr
public static long nPr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / fact(r);
return ans;
}
// sort all characters of a string
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// User defined class for fast I/O
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
boolean hasNext() {
if (st != null && st.hasMoreTokens()) {
return true;
}
String tmp;
try {
br.mark(1000);
tmp = br.readLine();
if (tmp == null) {
return false;
}
br.reset();
} catch (IOException e) {
return false;
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
// (a/b)%mod == (a * moduloInverse(b)) % mod;
// moduloInverse(b) = power(b, mod-2);
| java |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all. | [
"dp",
"greedy"
] | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import java.beans.Visibility;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.lang.Thread.State;
import java.lang.reflect.Field;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
public class Main {
static final long MOD1=1000000007;
static final long MOD=998244353;
static long ans=0;
static long[] two;
public static void main(String[] args){
PrintWriter out = new PrintWriter(System.out);
InputReader sc=new InputReader(System.in);
int n = sc.nextInt();
int[] a = sc.nextIntArray(n);
int[][] dp = new int[n][n];
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp.length; j++) {
dp[i][j] = Integer.MAX_VALUE/2;
}
}
for (int i = 0; i < dp.length; i++) {
dp[i][i] = -a[i];
}
for (int i = 2; i <= n; i++) {
for (int l = 0; l + i - 1 < n; l++) {
int r = l + i - 1;
for (int k = l; k < r; k++) {
int a_l = dp[l][k];
int a_r = dp[k+1][r];
if (a_l<=0&&a_r<=0){
if(a_l==a_r) {
dp[l][r] = -(-a_l+1);
}else {
dp[l][r] = 2;
}
}else {
a_l = Math.max(1, a_l);
a_r = Math.max(1, a_r);
dp[l][r] = Math.min(dp[l][r], a_l+a_r);
}
}
}
}
System.out.println(Math.max(1, dp[0][n-1]));
}
static class InputReader {
private InputStream in;
private byte[] buffer = new byte[1024];
private int curbuf;
private int lenbuf;
public InputReader(InputStream in) {
this.in = in;
this.curbuf = this.lenbuf = 0;
}
public boolean hasNextByte() {
if (curbuf >= lenbuf) {
curbuf = 0;
try {
lenbuf = in.read(buffer);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return false;
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[curbuf++];
else
return -1;
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private void skip() {
while (hasNextByte() && isSpaceChar(buffer[curbuf]))
curbuf++;
}
public boolean hasNext() {
skip();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (!isSpaceChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
int c = readByte();
while (isSpaceChar(c))
c = readByte();
boolean minus = false;
if (c == '-') {
minus = true;
c = readByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = readByte();
} while (!isSpaceChar(c));
return (minus) ? -res : res;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = nextDouble();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public char[][] nextCharMap(int n, int m) {
char[][] map = new char[n][m];
for (int i = 0; i < n; i++)
map[i] = next().toCharArray();
return map;
}
}
}
class MinCostFlow {
private static final class InternalWeightedCapEdge {
final int to, rev;
long cap;
final long cost;
InternalWeightedCapEdge(int to, int rev, long cap, long cost) { this.to = to; this.rev = rev; this.cap = cap; this.cost = cost; }
}
public static final class WeightedCapEdge {
public final int from, to;
public final long cap, flow, cost;
WeightedCapEdge(int from, int to, long cap, long flow, long cost) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; this.cost = cost; }
@Override
public boolean equals(Object o) {
if (o instanceof WeightedCapEdge) {
WeightedCapEdge e = (WeightedCapEdge) o;
return from == e.from && to == e.to && cap == e.cap && flow == e.flow && cost == e.cost;
}
return false;
}
}
private static final class IntPair {
final int first, second;
IntPair(int first, int second) { this.first = first; this.second = second; }
}
public static final class FlowAndCost {
public final long flow, cost;
FlowAndCost(long flow, long cost) { this.flow = flow; this.cost = cost; }
@Override
public boolean equals(Object o) {
if (o instanceof FlowAndCost) {
FlowAndCost c = (FlowAndCost) o;
return flow == c.flow && cost == c.cost;
}
return false;
}
}
static final long INF = Long.MAX_VALUE;
private final int n;
private final java.util.ArrayList<IntPair> pos;
private final java.util.ArrayList<InternalWeightedCapEdge>[] g;
@SuppressWarnings("unchecked")
public MinCostFlow(int n) {
this.n = n;
this.pos = new java.util.ArrayList<>();
this.g = new java.util.ArrayList[n];
for (int i = 0; i < n; i++) {
this.g[i] = new java.util.ArrayList<>();
}
}
public int addEdge(int from, int to, long cap, long cost) {
rangeCheck(from, 0, n);
rangeCheck(to, 0, n);
nonNegativeCheck(cap, "Capacity");
nonNegativeCheck(cost, "Cost");
int m = pos.size();
pos.add(new IntPair(from, g[from].size()));
int fromId = g[from].size();
int toId = g[to].size();
if (from == to) toId++;
g[from].add(new InternalWeightedCapEdge(to, toId, cap, cost));
g[to].add(new InternalWeightedCapEdge(from, fromId, 0L, -cost));
return m;
}
private InternalWeightedCapEdge getInternalEdge(int i) {
return g[pos.get(i).first].get(pos.get(i).second);
}
private InternalWeightedCapEdge getInternalEdgeReversed(InternalWeightedCapEdge e) {
return g[e.to].get(e.rev);
}
public WeightedCapEdge getEdge(int i) {
int m = pos.size();
rangeCheck(i, 0, m);
InternalWeightedCapEdge e = getInternalEdge(i);
InternalWeightedCapEdge re = getInternalEdgeReversed(e);
return new WeightedCapEdge(re.to, e.to, e.cap + re.cap, re.cap, e.cost);
}
public WeightedCapEdge[] getEdges() {
WeightedCapEdge[] res = new WeightedCapEdge[pos.size()];
java.util.Arrays.setAll(res, this::getEdge);
return res;
}
public FlowAndCost minCostMaxFlow(int s, int t) {
return minCostFlow(s, t, INF);
}
public FlowAndCost minCostFlow(int s, int t, long flowLimit) {
return minCostSlope(s, t, flowLimit).getLast();
}
java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t) {
return minCostSlope(s, t, INF);
}
public java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t, long flowLimit) {
rangeCheck(s, 0, n);
rangeCheck(t, 0, n);
if (s == t) {
throw new IllegalArgumentException(
String.format("%d and %d is the same vertex.", s, t)
);
}
long[] dual = new long[n];
long[] dist = new long[n];
int[] pv = new int[n];
int[] pe = new int[n];
boolean[] vis = new boolean[n];
long flow = 0;
long cost = 0, prev_cost = -1;
java.util.LinkedList<FlowAndCost> result = new java.util.LinkedList<>();
result.addLast(new FlowAndCost(flow, cost));
while (flow < flowLimit) {
if (!dualRef(s, t, dual, dist, pv, pe, vis)) break;
long c = flowLimit - flow;
for (int v = t; v != s; v = pv[v]) {
c = Math.min(c, g[pv[v]].get(pe[v]).cap);
}
for (int v = t; v != s; v = pv[v]) {
InternalWeightedCapEdge e = g[pv[v]].get(pe[v]);
e.cap -= c;
g[v].get(e.rev).cap += c;
}
long d = -dual[s];
flow += c;
cost += c * d;
if (prev_cost == d) {
result.removeLast();
}
result.addLast(new FlowAndCost(flow, cost));
prev_cost = cost;
}
return result;
}
private boolean dualRef(int s, int t, long[] dual, long[] dist, int[] pv, int[] pe, boolean[] vis) {
java.util.Arrays.fill(dist, INF);
java.util.Arrays.fill(pv, -1);
java.util.Arrays.fill(pe, -1);
java.util.Arrays.fill(vis, false);
class State implements Comparable<State> {
final long key;
final int to;
State(long key, int to) { this.key = key; this.to = to; }
public int compareTo(State q) {
return key > q.key ? 1 : -1;
}
};
java.util.PriorityQueue<State> pq = new java.util.PriorityQueue<>();
dist[s] = 0;
pq.add(new State(0L, s));
while (pq.size() > 0) {
int v = pq.poll().to;
if (vis[v]) continue;
vis[v] = true;
if (v == t) break;
for (int i = 0, deg = g[v].size(); i < deg; i++) {
InternalWeightedCapEdge e = g[v].get(i);
if (vis[e.to] || e.cap == 0) continue;
long cost = e.cost - dual[e.to] + dual[v];
if (dist[e.to] - dist[v] > cost) {
dist[e.to] = dist[v] + cost;
pv[e.to] = v;
pe[e.to] = i;
pq.add(new State(dist[e.to], e.to));
}
}
}
if (!vis[t]) {
return false;
}
for (int v = 0; v < n; v++) {
if (!vis[v]) continue;
dual[v] -= dist[t] - dist[v];
}
return true;
}
private void rangeCheck(int i, int minInlusive, int maxExclusive) {
if (i < 0 || i >= maxExclusive) {
throw new IndexOutOfBoundsException(
String.format("Index %d out of bounds for length %d", i, maxExclusive)
);
}
}
private void nonNegativeCheck(long cap, java.lang.String attribute) {
if (cap < 0) {
throw new IllegalArgumentException(
String.format("%s %d is negative.", attribute, cap)
);
}
}
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.