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 |
---|---|---|---|---|---|
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 A {
static class Pair {
long x;
long y;
public Pair(long x, long y) {
this.x = x;
this.y = y;
}
}
static long gcd(long n, long m) {
if (m == 0)
return n;
else
return gcd(m, n % m);
}
static long lcm(long n, long m) {
return (n * m) / gcd(n, m);
}
static void dfs(ArrayList<ArrayList<Integer>> adj, int s, int[] vis, int[] cnt) {
for (int i : adj.get(s)) {
if (vis[i] == 1) {
continue;
}
cnt[0]++;
vis[i] = 1;
dfs(adj, i, vis, cnt);
}
}
public static long solve(long a, long b, long x, long y, long n) {
if (a - n >= x) {
return ((a - n) * b);
} else {
n -= a - x;
a = x;
if (b - n >= y) {
return (a * (b - n));
} else {
b = y;
return (a * b);
}
}
}
static int high(int n) {
int p = (int) (Math.log(n) / Math.log(2));
return (int) Math.pow(2, p);
}
static int lbs(Pair[] pow, Pair target) {
int low = 0;
int idx = -1;
int high = pow.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (pow[mid].x >= target.x || pow[mid].y >= target.y) {
high = mid - 1;
} else {
low = mid + 1;
idx = mid;
}
}
return idx;
}
static int ubs(Pair[] pow, Pair target) {
int low = 0;
int idx = -1;
int high = pow.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (pow[mid].x <= target.x || pow[mid].y <= target.y) {
low = mid + 1;
} else {
idx = mid;
high = mid - 1;
}
}
return idx;
}
static boolean prime(int n) {
int m = (int) Math.sqrt(n);
for (int i = 2; i <= m; i++)
if (n % i == 0)
return false;
return true;
}
static long recurr(int[] weight, int[] item, int n, int w, long[][] dp)// recursive solution
{
if (n == 0)
return 0;
if (dp[n][w] != -1)
return dp[n][w];
long k = 0;
if (weight[n - 1] <= w)
k = item[n - 1] + recurr(weight, item, n - 1, w - weight[n - 1], dp);
long k1 = recurr(weight, item, n - 1, w, dp);
dp[n][w] = Math.max(k, k1);
return dp[n][w];
}
public static void main(String[] args) {
StringBuilder str = new StringBuilder();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] arr = new long[n];
long a = sc.nextInt();
long b = sc.nextInt();
long k = sc.nextInt();
for (int i = 0; i < n; i++) {
long c = sc.nextInt();
long r = 0;
if (c % (a + b) != 0)
r = c % (a + b);
else
r = a + b;
arr[i] = ((r + a - 1) / a) - 1;
}
Arrays.sort(arr);
long c = 0;
int cnt = 0;
for (int i = 0; i < n; i++) {
c += arr[i];
if (c <= k) {
cnt = i + 1;
}
}
str.append(cnt + "\n");
System.out.println(str);
sc.close();
}
} | java |
1299 | C | C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence. | [
"data structures",
"geometry",
"greedy"
] | import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
Stack<double[]> stack = new Stack();
for (int i = n - 1; i >= 0; i--) {
double sum = a[i];
int len = 1;
while (!stack.isEmpty()) {
double[] top = stack.peek();
if (sum / len > top[0]) {
sum += top[0] * top[1];
len += top[1];
stack.pop();
} else
break;
}
double curr = sum / len;
stack.push(new double[] { curr, len });
}
while (!stack.isEmpty()) {
double[] curr = stack.pop();
while (curr[1]-- > 0)
out.printf("%.10f\n", curr[0]);
}
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
static void shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
}
} | java |
1313 | C1 | C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"brute force",
"data structures",
"dp",
"greedy"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
public class Round12 {
public static void main(String[] args) {
FastReader fastReader = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;
while (t-- > 0) {
int n = fastReader.nextInt();
int[] a = fastReader.ria(n);
int[] ans = new int[n];
long countMax = 0;
for (int i = 0; i < n; i++) {
int[] h = new int[n];
h[i] = a[i];
long count = h[i];
int curMax = h[i];
for (int j = i - 1; j >= 0; j--) {
h[j] = Math.min(a[j], curMax);
count += h[j];
curMax = Math.min(curMax, h[j]);
}
curMax = h[i];
for (int j = i + 1; j < n; j++) {
h[j] = Math.min(a[j], curMax);
count += h[j];
curMax = Math.min(curMax, h[j]);
}
if (countMax < count) {
countMax = count;
ans = h;
}
}
for (int val : ans) {
out.print(val + " ");
}
}
out.close();
}
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
static Random __r = new Random();
// math util
static int minof(int a, int b, int c) {
return min(a, min(b, c));
}
static int minof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
int min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static long minof(long a, long b, long c) {
return min(a, min(b, c));
}
static long minof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
long min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static int maxof(int a, int b, int c) {
return max(a, max(b, c));
}
static int maxof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
int max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static long maxof(long a, long b, long c) {
return max(a, max(b, c));
}
static long maxof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
long max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static int powi(int a, int b) {
if (a == 0) return 0;
int ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static long powl(long a, int b) {
if (a == 0) return 0;
long ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static int fli(double d) {
return (int) d;
}
static int cei(double d) {
return (int) ceil(d);
}
static long fll(double d) {
return (long) d;
}
static long cel(double d) {
return (long) ceil(d);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static int[] exgcd(int a, int b) {
if (b == 0) return new int[]{1, 0};
int[] y = exgcd(b, a % b);
return new int[]{y[1], y[0] - y[1] * (a / b)};
}
static long[] exgcd(long a, long b) {
if (b == 0) return new long[]{1, 0};
long[] y = exgcd(b, a % b);
return new long[]{y[1], y[0] - y[1] * (a / b)};
}
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static long mix(long x) {
x += 0x9e3779b97f4a7c15L;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
return x ^ (x >> 31);
}
public static boolean[] findPrimes(int limit) {
assert limit >= 2;
final boolean[] nonPrimes = new boolean[limit];
nonPrimes[0] = true;
nonPrimes[1] = true;
int sqrt = (int) Math.sqrt(limit);
for (int i = 2; i <= sqrt; i++) {
if (nonPrimes[i]) continue;
for (int j = i; j < limit; j += i) {
if (!nonPrimes[j] && i != j) nonPrimes[j] = true;
}
}
return nonPrimes;
}
// array util
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] ria(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = Integer.parseInt(next());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] rla(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = Long.parseLong(next());
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| java |
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 cf {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void readArr(int[] ar, int n) {
for (int i = 0; i < n; i++) {
ar[i] = nextInt();
}
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static boolean binary_search(long[] a, long k) {
long low = 0;
long high = a.length - 1;
long mid = 0;
while (low <= high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == k) {
return true;
} else if (a[(int) mid] < k) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;
}
public static int bSearchDiff(long[] a, int low, int high) {
int mid = low + ((high - low) / 2);
int hight = high;
int lowt = low;
while (lowt < hight) {
mid = lowt + (hight - lowt) / 2;
if (a[high] - a[mid] <= 5) {
hight = mid;
} else {
lowt = mid + 1;
}
}
return lowt;
}
public static long lowerbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == ddp) {
return mid;
}
if (a[(int) mid] < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
if (low + 1 < a.length && a[(int) low + 1] <= ddp) {
low++;
}
if (low == a.length && low != 0) {
low--;
return low;
}
if (a[(int) low] > ddp && low != 0) {
low--;
}
return low;
}
public static long lowerbound(long a[], long ddp, long factor) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if ((a[(int) mid] + (mid * factor)) == ddp) {
return mid;
}
if ((a[(int) mid] + (mid * factor)) < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
if (low == a.length && low != 0) {
low--;
return low;
}
if (a[(int) low] > ddp - (low * factor) && low != 0) {
low--;
}
return low;
}
public static long lowerbound(List<Long> a, long ddp) {
long low = 0;
long high = a.size();
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
// if (a.get((int) mid) == ddp) {
// return mid;
// }
if (a.get((int) mid) < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
// if (low == a.size() && low != 0) {
// low--;
// return low;
// }
// if (a.get((int) low) >= ddp && low != 0) {
// low--;
// }
return low;
}
public static long lowerboundforpairs(pair a[], double pr) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid].w <= pr) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
// if(low == a.length && low != 0){
// low--;
// return low;
// }
// if(a[(int)low].w > pr && low != 0){
// low--;
// }
return low;
}
public static long upperbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == ddp) {
return mid;
}
if (a[(int) mid] < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if (low == a.length) {
// return a.length - 1;
// }
return low;
}
public static long upperbound(ArrayList<Long> a, long ddp) {
long low = 0;
long high = a.size();
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a.get((int) mid) <= ddp) {
low = mid + 1;
} else {
high = mid;
}
}
if (low == a.size()) {
return a.size() - 1;
}
// System.out.println(a.get((int) low) + " " + ddp);
if (low + 1 < a.size() && a.get((int) low) <= ddp) {
low++;
}
return low;
}
// public static class pair implements Comparable<pair> {
// long w;
// long h;
// public pair(long w, long h) {
// this.w = w;
// this.h = h;
// }
// public int compareTo(pair b) {
// if (this.w != b.w)
// return (int) (this.w - b.w);
// else
// return (int) (this.h - b.h);
// }
// }
public static class pairs {
char w;
int h;
public pairs(char w, int h) {
this.w = w;
this.h = h;
}
}
public static class pair {
long w;
long h;
public pair(long w, long h) {
this.w = w;
this.h = h;
}
@Override
public int hashCode() {
return Objects.hash(w, h);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof pair)) {
return false;
}
pair c = (pair) o;
return Long.compare(this.w, c.w) == 0 && Long.compare(this.h, h) == 0;
}
}
public static class trinary {
long a;
long b;
long c;
public trinary(long a, long b, long c) {
this.a = a;
this.b = b;
this.c = c;
}
}
public static class fourthary {
long a;
long b;
long c;
long d;
public fourthary(long a, long b, long c, long d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
}
public static pair[] sortpair(pair[] a) {
Arrays.sort(a, new Comparator<pair>() {
public int compare(pair p1, pair p2) {
if (p1.w != p2.w) {
return (int) (p1.w - p2.w);
}
return (int) (p1.h - p2.h);
}
});
return a;
}
public static trinary[] sortpair(trinary[] a) {
Arrays.sort(a, new Comparator<trinary>() {
public int compare(trinary p1, trinary p2) {
if (p1.b != p2.b) {
return (int) (p1.b - p2.b);
} else if (p1.a != p2.a) {
return (int) (p1.a - p2.a);
}
return (int) (p1.c - p2.c);
}
});
return a;
}
public static fourthary[] sortpair(fourthary[] a) {
Arrays.sort(a, new Comparator<fourthary>() {
public int compare(fourthary p1, fourthary p2) {
if (p1.b != p2.b) {
return (int) (p1.b - p2.b);
} else if (p1.a != p2.a) {
return (int) (p1.a - p2.a);
}
return (int) (p1.c - p2.c);
}
});
return a;
}
public static void sort(long[] arr) {
ArrayList<Long> a = new ArrayList<>();
for (long i : arr) {
a.add(i);
}
Collections.sort(a);
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
public static void sortForObjecttypes(pair[] arr) {
ArrayList<pair> a = new ArrayList<>();
for (pair i : arr) {
a.add(i);
}
Collections.sort(a, new Comparator<pair>() {
@Override
public int compare(pair a, pair b) {
return (int) (a.h - b.h);
}
});
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
public static boolean ispalindrome(String s) {
long i = 0;
long j = s.length() - 1;
boolean is = false;
while (i < j) {
if (s.charAt((int) i) == s.charAt((int) j)) {
is = true;
i++;
j--;
} else {
is = false;
return is;
}
}
return is;
}
public static long power(long base, long pow, long mod) {
long result = base;
long temp = 1;
while (pow > 1) {
if (pow % 2 == 0) {
result = ((result % mod) * (result % mod)) % mod;
pow /= 2;
} else {
temp = temp * base;
pow--;
}
}
result = ((result % mod) * (temp % mod));
// System.out.println(result);
return result;
}
public static long sqrt(long n) {
long res = 1;
long l = 1, r = (long) 10e9;
while (l <= r) {
long mid = (l + r) / 2;
if (mid * mid <= n) {
res = mid;
l = mid + 1;
} else
r = mid - 1;
}
return res;
}
public static boolean is[] = new boolean[1000000];
public static int a[] = new int[1000000];
public static Vector<Integer> seiveOfEratosthenes() {
Vector<Integer> listA = new Vector<>();
for (int i = 2; i * i <= a.length; i++) {
if (a[i] != 1) {
for (long j = i * i; j < a.length; j += i) {
a[(int) j] = 1;
}
}
}
for (int i = 2; i < a.length; i++) {
if (a[i] == 0) {
is[i] = true;
listA.add(i);
}
}
return listA;
}
public static Vector<Integer> ans = seiveOfEratosthenes();
public static long sumOfDigits(long n) {
long ans = 0;
while (n != 0) {
ans += n % 10;
n /= 10;
}
return ans;
}
public static long gcdTotal(long a[]) {
long t = a[0];
for (int i = 1; i < a.length; i++) {
t = gcd(t, a[i]);
}
return t;
}
public static ArrayList<Long> al = new ArrayList<>();
public static void makeArr() {
long t = 1;
while (t <= 10e17) {
al.add(t);
t *= 2;
}
}
public static boolean isBalancedBrackets(String s) {
if (s.length() == 1) {
return false;
}
Stack<Character> sO = new Stack<>();
int id = 0;
while (id < s.length()) {
if (s.charAt(id) == '(') {
sO.add('(');
}
if (s.charAt(id) == ')') {
if (!sO.isEmpty()) {
sO.pop();
} else {
return false;
}
}
id++;
}
if (sO.isEmpty()) {
return true;
}
return false;
}
public static long kadanesAlgo(long a[], int start, int end) {
long maxSoFar = Long.MIN_VALUE;
long maxEndingHere = 0;
for (int i = start; i < end; i++) {
maxEndingHere += a[i];
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
}
if (maxEndingHere < 0) {
maxEndingHere = 0;
}
}
return maxSoFar;
}
public static Vector<Integer> prime = new Vector<>();
public static int components = 0;
public static void search(HashMap<Integer, Integer> hm, int max, int start, int high) {
if (start == 0) {
components++;
return;
}
int t = max;
boolean is = false;
for (int i = start; i < high; i++) {
if (hm.get(t) >= start) {
t--;
is = true;
} else {
// System.out.println(start + " " + high + " " + hm.get(t) + " " + hm.get(max));
is = false;
break;
}
}
// System.out.println(max + " " + is + " " + t);
if (is) {
search(hm, t, hm.get(t), start);
components++;
} else {
// System.out.println(t);
search(hm, max, hm.get(t), high);
}
}
public static void helper(String s, Stack<Character> left, Stack<Character> right) {
int id = 0;
while (id < s.length()) {
if (s.charAt(id) == '(') {
left.add('(');
}
if (s.charAt(id) == ')') {
right.add(')');
if (left.size() > 0) {
left.pop();
right.pop();
}
}
id++;
}
}
public static long helperCounterFactor(long n, int fac, long m) {
long max = (long) 10e9;
long min = 0;
long mid = max + (max - min) / 2;
while (min < max) {
mid = max + (max - min) / 2;
if (n * mid > m) {
max = mid;
} else {
min = mid + 1;
}
}
return min;
}
public static long helperBS(long a[], long pref[], long d, long c) {
long start = 0;
long end = d;
long mid = 0;
long earn = 0;
long ct = 0;
long ans = 0;
while (start < end) {
mid = start + (end - start) / 2;
earn = 0;
ct = (d / (mid + 1));
if (mid >= a.length) {
earn = ct * (pref[pref.length - 1]);
earn += pref[(int) Math.min(a.length, (d % (mid + 1)))];
} else {
earn = ct * pref[(int) mid + 1];
earn += pref[(int) (d % (mid + 1))];
}
if (earn >= c) {
start = mid + 1;
ans = mid;
} else {
end = mid;
}
}
return ans;
}
public static void solve(FastReader sc, PrintWriter w, StringBuilder sb) throws Exception {
int n = sc.nextInt();
int m = sc.nextInt();
String s = sc.nextLine();
int p[] = new int[m + 1];
for (int i = 0; i < m; i++) {
p[i] = sc.nextInt();
}
p[m] = n;
long ans[][] = new long[n + 1][26];
for (int i = 1; i <= n; i++) {
for (int j = 0; j < 26; j++) {
if (s.charAt(i - 1) - 'a' == j) {
ans[i][j] = ans[i - 1][j] + 1;
} else {
ans[i][j] = ans[i - 1][j];
}
}
}
long ansF[] = new long[26];
for (int i = 0; i <= m; i++) {
int t = p[i];
for (int j = 0; j < 26; j++) {
ansF[j] += ans[t][j];
}
}
for (int i = 0; i < 26; i++) {
sb.append(ansF[i] + " ");
}
sb.append("\n");
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter w = new PrintWriter(System.out);
StringBuilder sb = new StringBuilder();
// prime = seiveOfEratosthenes();
long o = sc.nextLong();
// makeArr();
while (o > 0) {
solve(sc, w, sb);
o--;
}
System.out.print(sb.toString());
w.close();
}
} | java |
1288 | C | C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1]. | [
"combinatorics",
"dp"
] | import java.io.*;
import java.util.*;
public class Main extends PrintWriter {
Main() { super(System.out); }
public static Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
Main o = new Main(); 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);
}
}
}
}*/
long dp[][];
int m;
int mod=(int)Math.pow(10,9)+7;
long rec(int in, int n){
if(in==m)
return 1;
if(dp[in][n]!=0)
return dp[in][n];
long ans=0;
for(int i=1;i<=n;i++){
ans+=rec(in+1,i);
}
ans%=mod;
dp[in][n]=ans;
return dp[in][n];
}
void main() {
// int g=sc.nextInt();
// int mod=1000000007;
// sc.nextLine();
// for(int w1=0;w1<g;w1++){
int n=sc.nextInt();
m=sc.nextInt();
m=2*m;
dp= new long[m+1][n+1];
println(rec(0,n));
}
}
| 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.*;
import java.io.*;
public class B_EhAb_AnD_gCd
{
static long mod = 1000000007;
public static void main(String[] args) {
var sc = new Kattio(System.in, System.out);
int t=1;
t = sc.nextInt();
for (int i = 0; i < t; i++) solve(sc);
sc.close();
}
public static void solve(Kattio sc) {
int n = sc.nextInt();
System.out.println(1+" "+(n-1));
}
}
class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public String next() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) { }
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
} | java |
1316 | B | B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. | [
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] | import java.util.*;
public class String_Modification {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
sc.nextLine();
String s = sc.nextLine();
String ans = s;
int k = 1;
int count = 1;
for(int i=1;i<n;i++) {
count++;
String str = s.substring(i, n);
if((n-count+1)%2==1) {
str += new StringBuilder(s.substring(0, i)).reverse().toString();
}else {
str += s.substring(0,i);
}
if(str.compareTo(ans)<0) {
ans = str;
k = count;
}
}
System.out.println(ans);
System.out.println(k);
}
}
}
| 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.util.*;
import java.io.*;
public class A {
public static void main(String[] args) throws Exception {
int n = i();
int[] a = a(n);
int[][] reduce = new int[n][n];
for (int i = 0; i < n; i++) {
reduce[i][i] = a[i];
}
for (int l = 2; l <= n; l++) {
for (int i = 0; i + l - 1 < n; i++) {
int j = i + l - 1;
for (int k = i; k < j; k++) {
if (reduce[i][k] != 0 && reduce[k + 1][j] != 0 && reduce[i][k] == reduce[k + 1][j]) {
reduce[i][j] = reduce[i][k] + 1;
break;
}
}
}
}
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
ans[i] = i + 1;
for (int j = 0; j <= i; j++) {
if (reduce[j][i] > 0) {
ans[i] = Math.min(j == 0 ? 1 : ans[j - 1] + 1, ans[i]);
}
}
}
out.println(ans[n - 1]);
finish();
}
static BufferedReader in;
static StringTokenizer st = new StringTokenizer("");
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static {
try {
in = new BufferedReader(new FileReader("test.in"));
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
}
}
static void check() throws Exception {
while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine());
}
static int i() throws Exception {check(); return Integer.parseInt(st.nextToken());}
static String s() throws Exception {check(); return st.nextToken();}
static double d() throws Exception {check(); return Double.parseDouble(st.nextToken());}
static long l() throws Exception {check(); return Long.parseLong(st.nextToken());}
static int[] a(int n) throws Exception {check(); int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = i(); return b;}
static void finish(boolean b, Object o) {if (b) finish(o);}
static void finish(Object o) {out.println(o); finish();}
static void finish() {out.close(); System.exit(0);}
}
| java |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | import 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_WeirdSort {
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = f.nextInt();
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
int n = f.nextInt();
int m = f.nextInt();
int a[] = f.nextArray(n);
HashSet<Integer> hs = new HashSet<>();
for(int i = 0; i < m; i++) {
hs.add(f.nextInt()-1);
}
int temp[] = new int[n];
for(int i = 0; i < n; i++) {
temp[i] = a[i];
}
sort(temp);
for(int i = 0; i < n; i++) {
if(!hs.contains(i) && !hs.contains(i-1)) {
if(a[i] != temp[i]) {
out.println("NO");
return;
}
}
}
HashMap<Integer, Integer> hma = new HashMap<>();
HashMap<Integer, Integer> hmtemp = new HashMap<>();
for(int i = 0; i < n; i++) {
if(hs.contains(i)) {
hma.put(a[i], hma.getOrDefault(a[i], 0)+1);
hmtemp.put(temp[i], hmtemp.getOrDefault(temp[i], 0)+1);
} else if(hs.contains(i-1)) {
hma.put(a[i], hma.getOrDefault(a[i], 0)+1);
hmtemp.put(temp[i], hmtemp.getOrDefault(temp[i], 0)+1);
if(!hma.equals(hmtemp)) {
out.println("NO");
return;
}
hma.clear();
hmtemp.clear();
}
}
if(!hma.equals(hmtemp)) {
out.println("NO");
return;
}
out.println("YES");
}
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
public static int gcd(int a, int b) {
int dividend = a > b ? a : b;
int divisor = a < b ? a : b;
while(divisor > 0) {
int reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
public static int lcm(int a, int b) {
int lcm = gcd(a, b);
int hcf = (a * b) / lcm;
return hcf;
}
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
| java |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22. | [
"math"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// import java.util.Scanner;
import java.util.StringTokenizer;
public class mezo
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader s=new FastReader();
int n = s.nextInt();
String str = s.nextLine();
System.out.println(n+1);
}
} | java |
1288 | F | F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours: for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it; for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
OutputCopy35
BUURRU
InputCopy3 1 3 4 5
RRR
B
2 1
1 1
3 1
OutputCopy-1
InputCopy3 1 3 4 5
URU
B
2 1
1 1
3 1
OutputCopy14
RBB
| [
"constructive algorithms",
"flows"
] | // upsolve with rainboy
import java.io.*;
import java.util.*;
public class CF1288F extends PrintWriter {
CF1288F() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1288F o = new CF1288F(); o.main(); o.flush();
}
static final int INF = 0x3f3f3f3f;
int[] oo, oh; int __ = 1;
int link(int o, int h) {
oo[__] = o; oh[__] = h;
return __++;
}
int[] ii, jj, cc, ww, ww_; int m_;
int[] ae, dd, kk, ff; int n_;
int[] pq, iq; int cnt;
void init() {
oo = new int[1 + m_ * 2]; oh = new int[1 + m_ * 2];
ii = new int[m_]; jj = new int[m_];
cc = new int[m_ * 2];
ww = new int[m_]; ww_ = new int[m_];
ae = new int[n_]; dd = new int[n_]; kk = new int[n_]; ff = new int[n_];
pq = new int[1 + n_]; iq = new int[n_];
m_ = 0;
}
void link_(int i, int j, int c, int w) {
int h = m_++;
ii[h] = i; jj[h] = j; cc[h << 1] = c; ww[h] = w;
ae[i] = link(ae[i], h << 1);
ae[j] = link(ae[j], h << 1 | 1);
}
boolean less(int u, int v) {
return dd[u] < dd[v] || dd[u] == dd[v] && kk[u] < kk[v];
}
int i2(int i) {
return (i *= 2) > cnt ? 0 : i < cnt && less(pq[i + 1], pq[i]) ? i + 1 : i;
}
void pq_up(int u) {
int i, j, v;
for (i = iq[u]; (j = i / 2) > 0 && less(u, v = pq[j]); i = j)
pq[iq[v] = i] = v;
pq[iq[u] = i] = u;
}
void pq_dn(int u) {
int i, j, v;
for (i = iq[u]; (j = i2(i)) > 0 && less(v = pq[j], u); i = j)
pq[iq[v] = i] = v;
pq[iq[u] = i] = u;
}
void pq_add_last(int u) {
pq[iq[u] = ++cnt] = u;
}
int pq_remove_first() {
int u = pq[1], v = pq[cnt--];
if (v != u) {
iq[v] = 1; pq_dn(v);
}
iq[u] = 0;
return u;
}
boolean dijkstra(int s, int t) {
Arrays.fill(dd, INF);
dd[s] = 0; pq_add_last(s);
while (cnt > 0) {
int i = pq_remove_first();
int k = kk[i] + 1;
for (int o = ae[i]; o != 0; o = oo[o]) {
int h_ = oh[o];
if (cc[h_] > 0) {
int h = h_ >> 1;
int j = i ^ ii[h] ^ jj[h];
int d = dd[i] + ((h_ & 1) == 0 ? ww_[h] : -ww_[h]);
if (dd[j] > d || (dd[j] == d && kk[j] > k)) {
if (dd[j] == INF)
pq_add_last(j);
dd[j] = d; kk[j] = k; ff[j] = h_;
pq_up(j);
}
}
}
}
return dd[t] != INF;
}
boolean trace(int s, int t) {
int sum = 0;
for (int i = t; i != s; ) {
int h_ = ff[i], h = h_ >> 1;
sum += (h_ & 1) == 0 ? ww[h] : -ww[h];
i ^= ii[h] ^ jj[h];
}
if (sum >= 0)
return false;
for (int i = t; i != s; ) {
int h_ = ff[i], h = h_ >> 1;
cc[h_]--; cc[h_ ^ 1]++;
i ^= ii[h] ^ jj[h];
}
return true;
}
int edmonds_karp(int s, int t) {
for (int h = 0; h < m_; h++)
ww_[h] = ww[h];
while (dijkstra(s, t)) {
if (!trace(s, t))
break;
for (int h = 0; h < m_; h++) {
int i = ii[h], j = jj[h];
if (dd[i] != INF && dd[j] != INF) {
// dd[j] <= dd[i] + ww_[h]
// ww_[h] + dd[i] - dd[j] >= 0
ww_[h] += dd[i] - dd[j];
}
}
}
int sum = 0;
for (int h = 0; h < m_; h++)
sum += ww[h] * cc[h << 1 | 1];
return sum;
}
void main() {
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int m = sc.nextInt();
int r = sc.nextInt();
int b = sc.nextInt();
int inf = m * (r + b) + 1;
n_ = 1 + n1 + n2 + 1;
m_ = (m + n1 + n2) * 2;
init();
byte[] c1 = sc.next().getBytes();
byte[] c2 = sc.next().getBytes();
for (int h = 0; h < m; h++) {
int i = sc.nextInt() - 1;
int j = sc.nextInt() - 1;
int i_ = 1 + i;
int j_ = 1 + n1 + j;
link_(i_, j_, 1, r);
link_(j_, i_, 1, b);
}
int s = 0, t = n_ - 1;
for (int i = 0; i < n1; i++) {
int i_ = 1 + i;
if (c1[i] == 'R') {
link_(s, i_, 1, -inf);
link_(s, i_, m, 0);
} else if (c1[i] == 'B') {
link_(i_, t, 1, -inf);
link_(i_, t, m, 0);
} else {
link_(s, i_, m, 0);
link_(i_, t, m, 0);
}
}
for (int j = 0; j < n2; j++) {
int j_ = 1 + n1 + j;
if (c2[j] == 'R') {
link_(j_, t, 1, -inf);
link_(j_, t, m, 0);
} else if (c2[j] == 'B') {
link_(s, j_, 1, -inf);
link_(s, j_, m, 0);
} else {
link_(s, j_, m, 0);
link_(j_, t, m, 0);
}
}
int ans = edmonds_karp(s, t);
for (int h = 0; h < m_; h++)
if (ww[h] == -inf) {
if (cc[h << 1 | 1] == 0) {
println(-1);
return;
}
ans += inf;
}
println(ans);
char[] colors = new char[m];
for (int h = 0; h < m; h++) {
int hr = h << 1, hb = h << 1 | 1;
if (cc[hr << 1 | 1] > 0)
colors[h] = 'R';
else if (cc[hb << 1 | 1] > 0)
colors[h] = 'B';
else
colors[h] = 'U';
}
println(colors);
}
}
| java |
1325 | C | C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample: | [
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
//------------------------------------------------input class---------------------------------------//
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;
}
}
//---------------------------------------------absolute----------------------------------------------//
public static long abs(long a){
return a<0?-a:a;
}
public static int abs(int a){
return a<0?-a:a;
}
//-------------------------------------------topological sort--------------------------------------//
public static int[] topo(List<List<Integer>> a , int n , int[] in){
int[] ans = new int[n+1];
PriorityQueue<Integer> p = new PriorityQueue<>((x,y)->a.get(x).size()-a.get(y).size());
for(int i =1;i<=n;i++) if(in[i]==0) p.add(i);
int i =1;
while(p.size()>0){
int e = p.poll();
ans[i++]= e;
for(int temp : a.get(e)){
in[temp]--;
if(in[temp]==0)
p.add(temp);
}
}
return ans;
}
//-------------------------------------------max--------------------------------------------------//
public static int max (int a, int b){
return a>=b?a:b;
}
public static long max (long a, long b){
return a>=b?a:b;
}
public static int max (int a, int b, int c){
return Math.max(a,Math.max(b,c));
}
public static long max (long a, long b, long c){
return Math.max(a,Math.max(b,c));
}
//------------------------------------------min---------------------------------------------------//
public static int min (int a, int b){
return a<=b?a:b;
}
public static long min (long a, long b){
return a<=b?a:b;
}
public static int min (int a, int b, int c){
return Math.min(a,Math.min(b,c));
}
public static long min (long a, long b, long c){
return Math.min(a,Math.min(b,c));
}
//----------------------------------------- gcd-----------------------------------------//
public static int gcd(int a, int b){
if(a==0) return b;
if(b==0 ) return a;
if(a<b) return gcd(b%a,a);
return gcd(a%b,b);
}
public static long gcd(long a, long b){
if(a==0) return b;
if(b==0 ) return a;
if(a<b) return gcd(b%a,a);
return gcd(a%b,b);
}
//-------------------------------------lcm------------------------------------------------------//
public static int lcm(int a, int b){
return (a*b)/gcd(a,b);
}
public static long lcm(long a, long b){
return (a*b)/gcd(a,b);
}
//---------------------------------------------binary search--------------------------------------//
public static int binary(int arr[], int x)
{
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x) return m;
if (arr[m] < x) l = m + 1;
else r = m - 1;
}
return -1;
}
public static int binary(long arr[], long x)
{
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x) return m;
if (arr[m] < x) l = m + 1;
else r = m - 1;
}
return -1;
}
//----------------------------------------sorting function---------------------------------------------//
private static void sort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void sort(char[] arr) {
int n = arr.length;
List<Character> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void rsort(char[] arr) {
int n = arr.length;
List<Character> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void rsort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void sort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void rsort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
//-----------------------------------prime-----------------------------------------------------------//
static boolean[] arr;
public static void seive(int n){
arr = new boolean[n+1];
arr[0]=true;
arr[1]=true;
for(int i =2;i*i<=n;i++){
if(!arr[i])
for(int j = i+i;j<=n;j+=i){
arr[j]= true;
}
}
}
public static boolean isprime(int n){
return !arr[n];
}
public static boolean prime(int n){
if(n==1) return false;
for(int i=2;i*i<=n;i++) if(n%i==0) return false;
return true;
}
public static boolean prime(long n){
if(n==1) return false;
for(long i =2;i*i<=n;i++) if(n%i==0) return false;
return true;
}
//---------------------------------------power------------------------------------------------------//
public static long pow(long a, int b){
long ans = 1L;
while(b>0){
if((b&1)>0) ans*=a;
a*=a;
b>>=1;
}
return b;
}
//-------------------------------------------segment tree-----------------------------------------//
static int[] segment;
static void constructSt(int n, int[] arr){
segment = new int[n*4+1];
formSt(arr, 1,0,n-1);
}
public static void formSt(int[] arr, int node, int s, int e){
if(s==e){
segment[node]= arr[s];
return;
}
formSt(arr, node*2,s,s+(e-s)/2);
formSt(arr, node*2+1,s+(e-s)/2+1,e);
segment[node]=Math.max(segment[node*2],segment[node*2+1]);
}
public static int findMax( int node, int s, int e,int l , int r){
if(l>e||s>r) return -1;
if(s==e) return segment[node];
if(l<=s&&r>=e) return segment[node];
int mid = s+(e-s)/2;
return Math.max(findMax(node*2,s,mid,l,r),findMax(node*2+1,mid+1,e,l,r));
}
//----------------------------------------binary_exponentiation------------------------------------//
public static long exp(long a, long b, long mod){
long ans = 1L;
while(b>0){
if((b&1)>0) ans = (ans*a)%mod;
a= (a*a)%mod;
b>>=1;
}
return ans;
}
//-------------------------------------factorial----------------------------------------------------//
static long[] fact;
static long[] invfact;
public static void formfactorial(int n){
long mod = (long)998244353;
fact = new long[n+1];
invfact= new long[n+1];
fact[0]=1;
invfact[0]=1;
for(int i=1;i<=n;i++) fact[i]= (fact[i-1]*i)%mod;
for(int i =1;i<=n;i++) invfact[i]= exp(fact[i], mod-2,mod);
}
public static long factorial(int n){
return fact[n];
}
public static long invfactorial(int n){
return invfact[n];
}
//------------------------------------ncr------------------------------------------------------------//
public static long ncr(int n, int e, long mod){
long k = (invfact[n-e]*invfact[e])%mod;
return (fact[n]*k)%mod;
}
//-----------------------------------------dsu-----------------------------------------//
static int[] parent,rank;
public static void dsu(int n){
parent = new int[n]; rank = new int[n];
for(int i =0;i<n;i++) parent[i]=i;
}
public static int find(int i){
if(i==parent[i] ) return i;
return parent[i]=find(parent[i]);
}
public static void merge(int i, int j){
if(rank[i]>=rank[j]){
rank[i]+=rank[j];
parent[j]=i;
}
else {
rank[j]+=rank[i];
parent[i]=j;
}
}
//---------------------------------------helping methods---------------------------------------------//
//------------------------------------------main------------------------------------------------------//
public static void main (String[] args) throws java.lang.Exception
{
OutputStream outputStream =System.out;
PrintWriter out =new PrintWriter(outputStream);
FastReader sc =new FastReader();
int t =1;
while(t-->0){
int n = sc.nextInt();
int[] deg= new int[n+10];
int[][] a = new int[n-1][2];
for(int i=0;i<n-1;i++){
a[i][0]= sc.nextInt(); a[i][1]=sc.nextInt();
deg[a[i][0]]++;
deg[a[i][1]]++;
}
// out.println
int l=0, e=n-2;
for(int[] o:a){
if(deg[o[0]]<=1||deg[o[1]]<=1) out.println(l++ +" ");
else out.println(e-- +" ");
}
out.print("\n");
}
out.close();
// your code goes here"
}
}
class pair
{
long x;
long y;
public pair(long x , long y)
{
this.x= x;
this.y= y;
}
}
class node{
int x, y;
public node(int x , int y)
{
this.x= x;
this.y= y;
}
}
class solution{
} | 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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class code6 {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws CloneNotSupportedException {
// TODO Auto-generated method stub
FastReader scn = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;
//int p = t;
while(t-->0) {
int n = scn.nextInt();
int m = scn.nextInt();
if(n == 1) {
if(m>0)
out.print(-1);
else
out.print(1);
continue;
}
if(n == 2) {
if(m>0)
out.print(-1);
else
out.print("1 2");
continue;
}
int a = (int) Math.sqrt(m);
int p = 2*a+1;
if(n<p) {
System.out.println(-1);
continue;
}
int[] dp = new int[n];
for(int i=0; i<p; i++)
dp[i] = i+1;
int k = m-(int)Math.pow(a, 2);
if(k>0 && n<p+1) {
System.out.println(-1);
continue;
}
if(k>dp[p-1]/2 && n<p+2) {
System.out.println(-1);
continue;
}
int j = p;
if(k>=dp[p-1]/2) {
dp[p] = p+1;
j = p+1;
k -= dp[p-1]/2;
}
if(k>0) {
dp[j] = dp[j-1]+dp[j-1]-2*k;
j++;
}
int v = dp[j-1]+1;
while(j<n) {
dp[j] = dp[j-1]+v;
j++;
}
for(int i=0; i<n; i++)
out.print(dp[i] + " ");
}
out.flush();
}
public static boolean check(int mid, int c, int[] arr, int k) {
int ans = 0;
for(int i=0; i<arr.length; i++) {
if(c==0) {
ans++;
c = (c+1)%2;
}else {
if(arr[i]<=mid) {
ans++;
c = (c+1)%2;
}
}
}
return ans>=k;
}
public static int power(int x, int y, int p)
{
// Initialize result
int res = 1;
// Update x if it is more
// than or equal to p
x = x % p;
if (x == 0) return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x
// with result
if((y & 1)==1)
res = (res * x) % p;
// y must be even now
// y = y / 2
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static class Pair implements Comparable<Pair>{
int i;
int t;
int a;
int b;
Pair(int i,int m, int s, int k){
this.i = i;
t = m;
a = s;
b = k;
}
public int compareTo(Pair p) {
return this.t-p.t;
}
}
}
| java |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3
| [
"dfs and similar",
"graphs",
"shortest paths"
] | import java.util.*;
import java.io.*;
public class A {
static boolean tests = false;
static class Graph{
ArrayList<Integer>[] graph;
int[] dist;
int destination, highestNode;
Graph(int highestNode){
this.highestNode = highestNode;
this.graph = new ArrayList[highestNode+5];
this.dist = new int[highestNode+5];
Arrays.fill(dist, int_max);
}
void addEdge(int u, int v){
if (graph[v] == null) graph[v] = new ArrayList<>();
graph[v].add(u);
}
void clear(){
for (int i = 0; i <= highestNode; ++i){
if (graph[i] == null) continue;
graph[i].clear();
}
}
void calcDistFrom(int destination){
this.destination = destination;
ArrayDeque<Node> pq = new ArrayDeque<>();
pq.add(new Node(destination, 0));
dist[destination] = 0;
while (!pq.isEmpty()){
Node node = pq.poll();
for (int u : graph[node.v]){
if (dist[u] > node.d+1){
dist[u] = node.d+1;
pq.addLast(new Node(u, node.d+1));
}
}
}
}
int nodeDist(int v){
return dist[v];
}
ArrayList<Integer> adj(int v){
return graph[v];
}
class Node{
int v, d;
public Node(int v, int d){
this.v = v;
this.d = d;
}
}
}
static void printPath(int v, Graph g, int av, int bv){
int node = v;
while (node != g.destination){
System.out.println(node);
for (int u : g.adj(node)){
if (g.nodeDist(node) == g.nodeDist(u)+1 && u != av && u != bv){
node = u;
break;
}
}
}
System.out.println(node);
}
static void solve(){
int n = fs.nextInt();
int m = fs.nextInt();
Graph graph = new Graph(n);
int[][] edges = new int[m][2];
for (int i = 0; i < m; ++i){
edges[i][0] = fs.nextInt();
edges[i][1] = fs.nextInt();
graph.addEdge(edges[i][0], edges[i][1]);
}
int k = fs.nextInt();
int[] path = fs.readIntArray(k);
graph.calcDistFrom(path[k-1]);
graph.clear();
for (int[] edge : edges){
graph.addEdge(edge[1], edge[0]);
}
int min = 0, max = 0;
for (int i = 0; i < k-1; ++i){
int dist = graph.nodeDist(path[i]);
int nextDist = graph.nodeDist(path[i+1]);
if (dist != nextDist+1){
++min;
}
for (int v : graph.adj(path[i])){
if (v == path[i+1]){
continue;
}
if (graph.nodeDist(v)+1 == dist){
++max;
break;
}
}
}
System.out.println(min+" "+max);
}
static FastScanner fs = new FastScanner();
static int int_max = (int)1e9+5;
public static void main(String[] args) {
int t = 1;
if (tests) t = fs.nextInt();
while (t-- > 0) solve();
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readIntArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readLongArray(int n){
long a[] = new long[n];
for (int i = 0; i < n; ++i){
a[i] = nextLong();
}
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
}
} | java |
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 |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] | import java.util.HashSet;
import java.util.Scanner;
public class practice_582 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-->0){
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
a=Math.min(a,4);
b=Math.min(b,4);
c=Math.min(c,4);
HashSet<String> s = new HashSet<>();
while(a>0 || b>0 || c>0){
if(a>0){
s.add("100");
a-=1;
}
if(b>0){
s.add("010");
b-=1;
}
if(c>0){
s.add("001");
c-=1;
}
if(a+b>=a+c) {
if (a > 0 && b > 0) {
s.add("110");
a -= 1;
b -= 1;
}
}
else {
if (a > 0 && c > 0) {
s.add("101");
a -= 1;
c -= 1;
}
if (a > 0 && b > 0) {
s.add("110");
a -= 1;
b -= 1;
}
}
if (a > 0 && c > 0) {
s.add("101");
a -= 1;
c -= 1;
}
if(b>0 && c>0){
s.add("011");
b-=1;
c-=1;
}
if(a>0 && b>0 && c>0){
s.add("111");
}
}
boolean check=true;
System.out.println(s.size());
}
}
}
| java |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | import java.io.*;
import java.util.*;
public class Main {
InputReader in;
final long mod=1000000007;
StringBuilder sb;
public static void main(String[] args) throws java.lang.Exception {
new Main().run();
}
void run() throws Exception {
in=new InputReader(System.in);
sb = new StringBuilder();
int t=1;
for(int i=1;i<=t;i++)
solve();
System.out.print(sb);
}
ArrayList<Integer> adj[];
int dis[], p[];
void dfs(int v, int par) {
p[v]=par;
dis[v]=dis[par]+1;
for(Integer x : adj[v]) {
if(x!=par)
dfs(x, v);
}
}
void solve() {
int i, j;
int n=i();
adj=new ArrayList[n+1];
dis=new int[n+1];
p=new int[n+1];
dis[0]=-1;
for(i=0;i<=n;i++)
adj[i]=new ArrayList<>();
for(i=1;i<n;i++) {
int x=i(), y=i();
adj[x].add(y);
adj[y].add(x);
}
dfs(1, 0);
int max=0, a=0, b=0;
for(i=2;i<=n;i++) {
if(dis[i]>max) {
max=dis[i];
a=i;
}
}
dfs(a, 0);
int ans=0;
for(i=1;i<=n;i++) {
if(ans<dis[i]) {
ans=dis[i];
b=i;
}
}
ArrayList<Integer> diam = new ArrayList<>();
while(b!=a) {
diam.add(b);
b=p[b];
}
diam.add(a);
if(diam.size()==n) {
sb.append((n-1)+"\n");
sb.append(diam.get(0)+" "+diam.get(1)+" "+a+"\n");
return;
}
boolean vis[]=new boolean[n+1];
LinkedList<Integer> queue = new LinkedList<>();
for(i=0;i<diam.size();i++) {
queue.add(diam.get(i));
vis[diam.get(i)]=true;
}
dis=new int[n+1];
while(queue.size()!=0) {
int v=queue.poll();
for(Integer u : adj[v]) {
if(!vis[u]) {
queue.add(u);
dis[u]=dis[v]+1;
vis[u]=true;
}
}
}
max=0;
int pos=0;
for(i=1;i<=n;i++) {
if(max<dis[i]) {
max=dis[i];
pos=i;
}
}
sb.append((diam.size()+max-1)+"\n");
sb.append(diam.get(0)+" "+pos+" "+a+"\n");
}
long mul(long x, long y) {long ans = x*y;return (ans>=mod ? ans%mod : ans);}
long power(long x, long y, long p) {
long res = 1;
x = x % p;
if (x == 0) return 0;
while (y > 0) {
if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res%p;
}
long gcd(long a, long b) { return (b==0)?a:gcd(b,a%b); }
int gcd(int a, int b) { return (b==0)?a:gcd(b,a%b); }
String s() { return in.next(); }
int i() { return in.nextInt(); }
long l() {return in.nextLong();}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public void skip(int x) {
while (x-->0)
read();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextString() {
return next();
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean hasNext() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value != -1;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
} | java |
1323 | A | A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | [
"brute force",
"dp",
"greedy",
"implementation"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
r.init(System.in);
int t = r.nextInt();
while (t-- > 0) {
int n = r.nextInt();
int[] arr = new int[n];
int even, odd;
even = odd = 0;
int[] ans = new int[2];
for (int i = 0; i < n; i++) arr[i] = r.nextInt();
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
even++;
ans[0] = i + 1;
break;
}else{
ans[odd] = i + 1;
odd++;
if (odd == 2) break;
}
}
if (even != 0){
System.out.println(1);
System.out.println(ans[0]);
}else if (odd == 2){
System.out.println(2);
System.out.println(ans[0] + " " + ans[1]);
}else System.out.println(-1);
}
}
}
class r {
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()) {
//TODO add check for eof if necessary
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());
}
}
| java |
1307 | A | A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Next 2t2t lines contain a description of test cases — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100) — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day. | [
"greedy",
"implementation"
] |
import java.util.Scanner;
public class CowAndHaybales {
public static void main(String[]args) {
Scanner sn = new Scanner(System.in);
int t = sn.nextInt();
for(int i=0; i<t; i++) {
int n = sn.nextInt();
int k = sn.nextInt();
int arr[] = new int[n];
for(int j =0; j<n; j++) {
arr[j] = sn.nextInt();
}
if(n==1) {
System.out.println(arr[0]);
} else {
for(int j=1; j<arr.length && k>0; j++) {
int max_bales = arr[j]*j;
int max_K = (k/j)*j;
int energyUsed = Math.min(max_K, max_bales);
int balesShifted = energyUsed/j;
k-=energyUsed;
arr[0]+=balesShifted;
}
System.out.println(arr[0]);
}
}
}
}
| java |
1292 | A | A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. | [
"data structures",
"dsu",
"implementation"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Nekos_Maze_Game {
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader sc = new FastReader();
StringBuilder sb = new StringBuilder();
int n = sc.nextInt();
int q = sc.nextInt();
HashSet<String> set = new HashSet<>();
int blocks = 0;
while(q-->0) {
int r = sc.nextInt();
int c = sc.nextInt();
String s = String.valueOf(r)+","+String.valueOf(c);
if(!set.isEmpty()&&set.contains(s)) {
set.remove(s);
int x = func(set,r,c);
blocks -= x;
}else {
set.add(s);
int x = func(set,r,c);
blocks += x;
}
if(blocks>0)
System.out.println("No");
else
System.out.println("Yes");
}
}
public static int func(HashSet<String> set,int r,int c) {
int count = 0;
for(int i=-1;i<=1;i++) {
String s = String.valueOf(r-1)+","+String.valueOf(c+i);
if(!set.isEmpty()&&set.contains(s))
count++;
}
for(int i=-1;i<=1;i++) {
String s = String.valueOf(r+1)+","+String.valueOf(c+i);
if(!set.isEmpty()&&set.contains(s))
count++;
}
return count;
}
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 |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | [
"constructive algorithms",
"math",
"ternary search"
] | import java.io.*;
import java.util.*;
public class new1{
static FastReader s = new FastReader();
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void main(String[] args) throws IOException{
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int t = 1;//s.nextInt();
for(int z = 0; z < t; z++) {
int n = s.nextInt();
int m = s.nextInt();
int p = s.nextInt();
int[] arr1 = new int[n];
int[] arr2 = new int[m];
for(int i = 0; i < n; i++) arr1[i] = s.nextInt();
for(int i = 0; i < m; i++) arr2[i] = s.nextInt();
int ind = -1;
for(int i = 0; i < n; i++) {
if(arr1[i] % p != 0) {
ind = i; break;
}
}
int ind2 = -1;
for(int i = 0; i < m; i++) {
if(arr2[i] % p != 0) {
ind2 = i; break;
}
}
System.out.println(ind + ind2);
}
//output.flush();
}
}
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();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}} | java |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0
| [
"binary search",
"data structures",
"sortings",
"two pointers"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
public class Main {
static BiFunction<Integer, Integer, Integer> ADD = (x, y) -> (x + y);
static BiFunction<ArrayList<Integer>, ArrayList<Integer>, ArrayList<Integer>> ADD_ARRAY_LIST = (x, y) -> {
x.addAll(y);
return x;
};
static Function<Pair<Integer, Integer>, Integer> GET_FIRST = (x) -> (x.first);
static Function<Pair<Integer, Integer>, Integer> GET_SECOND = (x) -> (x.second);
static Comparator<Pair<Integer, Integer>> C = Comparator.comparing(x -> x.first);
static long MOD = 1_000_000_000 + 7;
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
int t = 1;
while (t-- > 0) {
solve();
}
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms");
exit(0);
}
static void solve() {
int n = in.nextInt();
int[] a = in.readAllInts(n);
int[] b = in.readAllInts(n);
OrderStatisticTree ost = new OrderStatisticTree();
long ans = 0;
for (int i = n - 1; i >= 0; i--) {
if (i == n - 1) {
ost.insert(b[i] - a[i]);
} else {
ans += ost.lowerBound(a[i] - b[i]);
ost.insert(b[i] - a[i]);
}
}
out.println(ans);
}
static class OrderStatisticTree {
Node root;
int size;
OrderStatisticTree() {
root = null;
size = 0;
}
void insert(int x) {
root = insert(root, x);
}
Node insert(Node node, int x) {
if (node == null) {
size++;
return new Node(x);
}
if (x < node.val) {
node.left = insert(node.left, x);
} else {
node.right = insert(node.right, x);
}
update(node);
return balance(node);
}
int lowerBound(int x) {
return lowerBound(root, x);
}
int lowerBound(Node node, int x) {
if (node == null) {
return 0;
}
if (x <= node.val) {
return lowerBound(node.left, x);
} else {
return size(node.left) + 1 + lowerBound(node.right, x);
}
}
Node balance(Node node) {
if (balanceFactor(node) == 2) {
if (balanceFactor(node.right) < 0) {
node.right = rotateRight(node.right);
}
return rotateLeft(node);
}
if (balanceFactor(node) == -2) {
if (balanceFactor(node.left) > 0) {
node.left = rotateLeft(node.left);
}
return rotateRight(node);
}
return node;
}
int balanceFactor(Node node) {
return height(node.right) - height(node.left);
}
void update(Node node) {
node.height = Math.max(height(node.left), height(node.right)) + 1;
node.size = size(node.left) + size(node.right) + 1;
}
Node rotateRight(Node node) {
Node q = node.left;
node.left = q.right;
q.right = node;
update(node);
update(q);
return q;
}
Node rotateLeft(Node node) {
Node q = node.right;
node.right = q.left;
q.left = node;
update(node);
update(q);
return q;
}
int height(Node node) {
return node == null ? 0 : node.height;
}
int size(Node node) {
return node == null ? 0 : node.size;
}
static class Node {
int val;
int height;
int size;
Node left;
Node right;
Node(int val) {
this.val = val;
left = null;
right = null;
height = 1;
size = 1;
}
}
}
static void debug(Object... args) {
for (Object a : args) {
out.println(a);
}
}
static int dist(Pair<Integer, Integer> a, Pair<Integer, Integer> b) {
return Math.abs(a.first - b.first) + Math.abs(a.second - b.second);
}
static void y() {
out.println("YES");
}
static void n() {
out.println("NO");
}
static int[] stringToArray(String s) {
return s.chars().map(x -> Character.getNumericValue(x)).toArray();
}
static <T> T min(T a, T b, Comparator<T> C) {
if (C.compare(a, b) <= 0) {
return a;
}
return b;
}
static <T> T max(T a, T b, Comparator<T> C) {
if (C.compare(a, b) >= 0) {
return a;
}
return b;
}
static void fail() {
out.println("-1");
}
static class Pair<T, R> {
public T first;
public R second;
public Pair(T first, R second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Pair<?, ?> pair = (Pair<?, ?>) o;
return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "Pair{" + "a=" + first + ", b=" + second + '}';
}
public T getFirst() {
return first;
}
public R getSecond() {
return second;
}
}
static <T, R> Pair<T, R> make_pair(T a, R b) {
return new Pair<>(a, b);
}
static long mod_inverse(long a, long m) {
Number x = new Number(0);
Number y = new Number(0);
extended_gcd(a, m, x, y);
return (m + x.v % m) % m;
}
static long extended_gcd(long a, long b, Number x, Number y) {
long d = a;
if (b != 0) {
d = extended_gcd(b, a % b, y, x);
y.v -= (a / b) * x.v;
} else {
x.v = 1;
y.v = 0;
}
return d;
}
static class Number {
long v = 0;
public Number(long v) {
this.v = v;
}
}
static int lcm(long a, long b) {
long p = a * b;
return (int) (p / gcd(a, b));
}
static int gcd(long a, long b) {
while (b != 0) {
long t = b;
b = a % b;
a = t;
}
return (int) a;
}
static class ArrayUtils {
static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(char[] a, int i, int j) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void print(char[] a) {
for (char c : a) {
out.print(c);
}
out.println("");
}
static int[] reverse(int[] data) {
int[] p = new int[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static void prefixSum(long[] data) {
for (int i = 1; i < data.length; i++) {
data[i] += data[i - 1];
}
}
static void prefixSum(int[] data) {
for (int i = 1; i < data.length; i++) {
data[i] += data[i - 1];
}
}
static long[] reverse(long[] data) {
long[] p = new long[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static char[] reverse(char[] data) {
char[] p = new char[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static int[] MergeSort(int[] A) {
if (A.length > 1) {
int q = A.length / 2;
int[] left = new int[q];
int[] right = new int[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
int[] left_sorted = MergeSort(left);
int[] right_sorted = MergeSort(right);
return Merge(left_sorted, right_sorted);
} else {
return A;
}
}
static int[] Merge(int[] left, int[] right) {
int[] A = new int[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
static long[] MergeSort(long[] A) {
if (A.length > 1) {
int q = A.length / 2;
long[] left = new long[q];
long[] right = new long[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
long[] left_sorted = MergeSort(left);
long[] right_sorted = MergeSort(right);
return Merge(left_sorted, right_sorted);
} else {
return A;
}
}
static long[] Merge(long[] left, long[] right) {
long[] A = new long[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
static int upper_bound(int[] data, int num, int start) {
int low = start;
int high = data.length - 1;
int mid = 0;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (data[mid] < num) {
low = mid + 1;
} else if (data[mid] >= num) {
high = mid - 1;
ans = mid;
}
}
if (ans == -1) {
return 100000000;
}
return ans + 1;
}
static int lower_bound(int[] data, int num, int start) {
int low = start;
int high = data.length - 1;
int mid = 0;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (data[mid] <= num) {
low = mid + 1;
ans = mid;
} else if (data[mid] > num) {
high = mid - 1;
}
}
if (ans == -1) {
return data.length;
}
return ans + 1;
}
// Reverse the segment from index a to b, both inclusive
public static void reverse(int[] data, int minIndexChanged, int maxIndexChanged) {
int temp;
while (minIndexChanged < maxIndexChanged) {
temp = data[minIndexChanged];
data[minIndexChanged] = data[maxIndexChanged];
data[maxIndexChanged] = temp;
minIndexChanged++;
maxIndexChanged--;
}
}
}
static boolean[] primeSieve(int n) {
boolean[] primes = new boolean[n + 1];
Arrays.fill(primes, true);
primes[0] = false;
primes[1] = false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (primes[i]) {
for (int j = i * i; j <= n; j += i) {
primes[j] = false;
}
}
}
return primes;
}
// Iterative Version
static HashMap<Integer, Boolean> subsets_sum_iter(int[] data) {
HashMap<Integer, Boolean> temp = new HashMap<Integer, Boolean>();
temp.put(data[0], true);
for (int i = 1; i < data.length; i++) {
HashMap<Integer, Boolean> t1 = new HashMap<Integer, Boolean>(temp);
t1.put(data[i], true);
for (int j : temp.keySet()) {
t1.put(j + data[i], true);
}
temp = t1;
}
return temp;
}
static HashMap<Integer, Integer> subsets_sum_count(int[] data) {
HashMap<Integer, Integer> temp = new HashMap<>();
temp.put(data[0], 1);
for (int i = 1; i < data.length; i++) {
HashMap<Integer, Integer> t1 = new HashMap<>(temp);
t1.merge(data[i], 1, ADD);
for (int j : temp.keySet()) {
t1.merge(j + data[i], temp.get(j) + 1, ADD);
}
temp = t1;
}
return temp;
}
static class Graph {
ArrayList<Integer>[] g;
boolean[] visited;
ArrayList<Integer>[] graph(int n) {
g = new ArrayList[n];
visited = new boolean[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
return g;
}
void BFS(int s) {
Queue<Integer> Q = new ArrayDeque<>();
visited[s] = true;
Q.add(s);
while (!Q.isEmpty()) {
int v = Q.poll();
for (int a : g[v]) {
if (!visited[a]) {
visited[a] = true;
Q.add(a);
}
}
}
}
}
static class SparseTable {
int[] log;
int[][] st;
public SparseTable(int n, int k, int[] data, BiFunction<Integer, Integer, Integer> f) {
log = new int[n + 1];
st = new int[n][k + 1];
log[1] = 0;
for (int i = 2; i <= n; i++) {
log[i] = log[i / 2] + 1;
}
for (int i = 0; i < data.length; i++) {
st[i][0] = data[i];
}
for (int j = 1; j <= k; j++)
for (int i = 0; i + (1 << j) <= data.length; i++)
st[i][j] = f.apply(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
}
public int query(int L, int R, BiFunction<Integer, Integer, Integer> f) {
int j = log[R - L + 1];
return f.apply(st[L][j], st[R - (1 << j) + 1][j]);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 2048);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readAllInts(int n) {
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextInt();
}
return p;
}
public int[] readAllInts(int n, int s) {
int[] p = new int[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextInt();
}
return p;
}
public long[] readAllLongs(int n) {
long[] p = new long[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextLong();
}
return p;
}
public long[] readAllLongs(int n, int s) {
long[] p = new long[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextLong();
}
return p;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static void exit(int a) {
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
} | java |
1295 | A | A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
| [
"greedy"
] | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Submit {
public static void main(String[] args) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
try (InputReader ir = new InputReader()) {
int t = ir.nextInt();
while (t-- > 0) {
int n = ir.nextInt();
if (n % 2 == 1) {
n -= 3;
writer.append("7");
}
while (n > 0) {
n -= 2;
writer.append("1");
}
writer.append(System.lineSeparator());
writer.flush();
}
}
}
}
class InputReader implements AutoCloseable {
private BufferedReader bufferedReader;
private StringTokenizer tokenizer;
public InputReader() {
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreElements()) {
try {
tokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException ex) {
ex.printStackTrace();
}
}
return tokenizer.nextToken();
}
public char nextChar() {
char character = ' ';
try {
character = (char) bufferedReader.read();
} catch (IOException e) {
e.printStackTrace();
}
return character;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String line = "";
try {
line = bufferedReader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
return line;
}
@Override
public void close() {
try {
this.bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| java |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class MemeProb {
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
var st = new StringTokenizer(r.readLine());
var t = Integer.parseInt(st.nextToken());
for (int i = 0; i < t; i++) {
st = new StringTokenizer(r.readLine());
var first = Integer.parseInt(st.nextToken());
var str = st.nextToken();
var len = 0L;
for (char j : str.toCharArray()) {
if (j=='9') {
len++;
}
}
if(len!=str.length()) {
len= str.length()-1;
}
System.out.println(first*len);
}
}
} | java |
1310 | F | F. Bad Cryptographytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows: Let's fix a finite field and two it's elements aa and bb. One need to fun such xx that ax=bax=b or detect there is no such x. It is most likely that modern mankind cannot solve the problem of discrete logarithm for a sufficiently large field size. For example, for a field of residues modulo prime number, primes of 1024 or 2048 bits are considered to be safe. However, calculations with such large numbers can place a significant load on servers that perform cryptographic operations. For this reason, instead of a simple module residue field, more complex fields are often used. For such field no fast algorithms that use a field structure are known, smaller fields can be used and operations can be properly optimized. Developer Nikolai does not trust the generally accepted methods, so he wants to invent his own. Recently, he read about a very strange field — nimbers, and thinks it's a great fit for the purpose. The field of nimbers is defined on a set of integers from 0 to 22k−122k−1 for some positive integer kk . Bitwise exclusive or (⊕⊕) operation is used as addition. One of ways to define multiplication operation (⊙⊙) is following properties: 0⊙a=a⊙0=00⊙a=a⊙0=0 1⊙a=a⊙1=a1⊙a=a⊙1=a a⊙b=b⊙aa⊙b=b⊙a a⊙(b⊙c)=(a⊙b)⊙ca⊙(b⊙c)=(a⊙b)⊙c a⊙(b⊕c)=(a⊙b)⊕(a⊙c)a⊙(b⊕c)=(a⊙b)⊕(a⊙c) If a=22na=22n for some integer n>0n>0, and b<ab<a, then a⊙b=a⋅ba⊙b=a⋅b. If a=22na=22n for some integer n>0n>0, then a⊙a=32⋅aa⊙a=32⋅a. For example: 4⊙4=64⊙4=6 8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13.8⊙8=4⊙2⊙4⊙2=4⊙4⊙2⊙2=6⊙3=(4⊕2)⊙3=(4⊙3)⊕(2⊙(2⊕1))=(4⊙3)⊕(2⊙2)⊕(2⊙1)=12⊕3⊕2=13. 32⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=14132⊙64=(16⊙2)⊙(16⊙4)=(16⊙16)⊙(2⊙4)=24⊙8=(16⊕8)⊙8=(16⊙8)⊕(8⊙8)=128⊕13=141 5⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=85⊙6=(4⊕1)⊙(4⊕2)=(4⊙4)⊕(4⊙2)⊕(4⊙1)⊕(1⊙2)=6⊕8⊕4⊕2=8 Formally, this algorithm can be described by following pseudo-code. multiply(a, b) { ans = 0 for p1 in bits(a) // numbers of bits of a equal to one for p2 in bits(b) // numbers of bits of b equal to one ans = ans xor multiply_powers_of_2(1 << p1, 1 << p2) return ans;}multiply_powers_of_2(a, b) { if (a == 1 or b == 1) return a * b n = maximal value, such 2^{2^{n}} <= max(a, b) power = 2^{2^{n}}; if (a >= power and b >= power) { return multiply(power * 3 / 2, multiply_powers_of_2(a / power, b / power)) } else if (a >= power) { return multiply_powers_of_2(a / power, b) * power } else { return multiply_powers_of_2(a, b / power) * power }}It can be shown, that this operations really forms a field. Moreover, than can make sense as game theory operations, but that's not related to problem much. With the help of appropriate caching and grouping of operations, it is possible to calculate the product quickly enough, which is important to improve speed of the cryptoalgorithm. More formal definitions as well as additional properties can be clarified in the wikipedia article at link. The authors of the task hope that the properties listed in the statement should be enough for the solution. Powering for such muliplication is defined in same way, formally a⊙k=a⊙a⊙⋯⊙ak timesa⊙k=a⊙a⊙⋯⊙a⏟k times.You need to analyze the proposed scheme strength. For pairs of numbers aa and bb you need to find such xx, that a⊙x=ba⊙x=b, or determine that it doesn't exist. InputIn the first line of input there is single integer tt (1≤t≤1001≤t≤100) — number of pairs, for which you need to find the discrete logarithm.In each of next tt line there is a pair of integers aa bb (1≤a,b<2641≤a,b<264). OutputFor each pair you should print one integer xx (0≤x<2640≤x<264), such that a⊙x=ba⊙x=b, or -1 if no such x exists. It can be shown, that if any such xx exists, there is one inside given bounds. If there are several good values, you can output any of them. ExampleInputCopy7
2 2
1 1
2 3
8 10
8 2
321321321321 2
123214213213 4356903202345442785
OutputCopy1
1
2
4
-1
6148914691236517205
68943624821423112
| [
"math",
"number theory"
] | import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import static java.util.Arrays.fill;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class F {
static void sortBy(int a[], int n, long v[]) {
if (n == 0) {
return;
}
for (int i = 1; i < n; i++) {
int j = i;
int ca = a[i];
long cv = v[ca];
do {
int nj = (j - 1) >> 1;
int na = a[nj];
if (cv <= v[na]) {
break;
}
a[j] = na;
j = nj;
} while (j != 0);
a[j] = ca;
}
int ca = a[0];
for (int i = n - 1; i > 0; i--) {
int j = 0;
while ((j << 1) + 2 + Integer.MIN_VALUE < i + Integer.MIN_VALUE) {
j <<= 1;
j += (v[a[j + 2]] > v[a[j + 1]]) ? 2 : 1;
}
if ((j << 1) + 2 == i) {
j = (j << 1) + 1;
}
int na = a[i];
a[i] = ca;
ca = na;
long cv = v[ca];
while (j != 0 && v[a[j]] < cv) {
j = (j - 1) >> 1;
}
while (j != 0) {
na = a[j];
a[j] = ca;
ca = na;
j = (j - 1) >> 1;
}
}
a[0] = ca;
}
static final long MUL_BIT_TABLE[] = new long[64 * 64];
static long mulBits(int i, int j) {
int key = i * 64 + j;
long res = MUL_BIT_TABLE[key];
if (res == 0) {
res = 1;
for (int k = 5; k >= 0; k--) {
if (((i ^ j) & (1 << k)) != 0) {
res <<= 1 << k;
}
}
for (int k = 5; k >= 0; k--) {
if ((i & j & (1 << k)) != 0) {
res = mul(res, 3L << ((1 << k) - 1));
}
}
MUL_BIT_TABLE[key] = res;
}
return res;
}
static long mulSlow(long a, long b) {
long res = 0;
for (int i = 0; i < 64; i++) {
if ((a & (1L << i)) == 0) {
continue;
}
for (int j = 0; j < 64; j++) {
if ((b & (1L << j)) == 0) {
continue;
}
res ^= mulBits(i, j);
}
}
return res;
}
static long mulCached(int i, int vi, int j, int vj) {
int key = ((i * 8 + j) * 256 + vi) * 256 + vj;
long res = MUL_TABLE[key];
if (res == 0) {
if ((vi & 0xf) != 0 && (vi & 0xf0) != 0) {
res = mulCached(i, vi & 0xf, j, vj) ^ mulCached(i, vi & 0xf0, j, vj);
} else if ((vj & 0xf) != 0 && (vj & 0xf0) != 0) {
res = mulCached(i, vi, j, vj & 0xf) ^ mulCached(i, vi, j, vj & 0xf0);
} else {
res = mulSlow((long) vi << (8 * i), (long) vj << (8 * j));
}
MUL_TABLE[key] = res;
}
return res;
}
static final long MUL_TABLE[] = new long[8 * 8 * 256 * 256];
static long mul(long a, long b) {
long res = 0;
for (int i = 0; i < 8; i++) {
int vi = (int) ((a >> (8 * i)) & 255);
if (vi == 0) {
continue;
}
for (int j = 0; j < 8; j++) {
int vj = (int) ((b >> (8 * j)) & 255);
if (vj == 0) {
continue;
}
res ^= mulCached(i, vi, j, vj);
}
}
return res;
}
static long pow(long a, long e) {
if (e == 0) {
return 1;
}
long r = a;
for (int i = 62 - Long.numberOfLeadingZeros(e); i >= 0; i--) {
r = mul(r, r);
if ((e & (1L << i)) != 0) {
r = mul(r, a);
}
}
return r;
}
static final long PRE_TABLE[] = new long[16 * 16];
static void preClear() {
fill(PRE_TABLE, 0);
}
static long preMul(long a, long b) {
long res = 0;
for (int i = 0; i < 16; i++) {
int vi = (int) ((a >> (4 * i)) & 15);
if (vi == 0) {
continue;
}
int pkey = i * 16 + vi;
long pres = PRE_TABLE[pkey];
if (pres == 0) {
int ii = i >> 1, vii = (i & 1) == 0 ? vi : vi << 4;
for (int j = 0; j < 8; j++) {
int vj = (int) ((b >> (8 * j)) & 255);
if (vj == 0) {
continue;
}
pres ^= mulCached(ii, vii, j, vj);
}
PRE_TABLE[pkey] = pres;
}
res ^= pres;
}
return res;
}
static final long GEN = -Long.MAX_VALUE;
static final int PRIMES[] = {3, 5, 17, 257, 641, 65537, 6700417};
static final int PRIME_STEP[] = {1, 1, 1, 1, 1, 20, 200};
static final long POW_VALS[][] = new long[PRIMES.length][];
static final int POW_IDX[][] = new int[PRIMES.length][];
static {
for (int i = 0; i < PRIMES.length; i++) {
int p = PRIMES[i];
int s = PRIME_STEP[i];
int l = (p + s - 1) / s;
POW_VALS[i] = new long[l];
POW_IDX[i] = new int[l];
POW_VALS[i][0] = 1;
long cgen = pow(GEN, Long.divideUnsigned(-1, p) * s);
preClear();
for (int j = 1; j < l; j++) {
POW_VALS[i][j] = preMul(POW_VALS[i][j - 1], cgen);
POW_IDX[i][j] = j;
}
sortBy(POW_IDX[i], l, POW_VALS[i]);
}
}
static final BigInteger bMod = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE);
static BigInteger dlog(long v) {
BigInteger res = BigInteger.ZERO;
for (int i = 0; i < PRIMES.length; i++) {
int p = PRIMES[i];
int s = PRIME_STEP[i];
int len = POW_VALS[i].length;
long vv = pow(v, Long.divideUnsigned(-1, p));
long cgen = pow(GEN, -1 - Long.divideUnsigned(-1, p));
int cres = -1;
preClear();
for (int j = 0; j < s; j++) {
int l = 0, r = len;
while (l < r) {
int mid = (l + r) >> 1;
if (POW_VALS[i][POW_IDX[i][mid]] < vv) {
l = mid + 1;
} else {
r = mid;
}
}
if (l < len && POW_VALS[i][POW_IDX[i][l]] == vv) {
cres = POW_IDX[i][l] * s + j;
break;
}
vv = preMul(vv, cgen);
}
if (cres < 0) {
throw new AssertionError();
}
BigInteger bp = BigInteger.valueOf(p);
BigInteger md = bMod.divide(bp);
res = res.add(md.modInverse(bp).multiply(md).multiply(BigInteger.valueOf(cres)));
}
return res.mod(bMod);
}
static void solve() throws Exception {
int tests = scanInt();
// int tests = 100;
// Random rng = new Random(42);
for (int test = 0; test < tests; test++) {
long a = new BigInteger(scanString()).longValue(),
b = new BigInteger(scanString()).longValue();
// long a = test * 12345678901L + 12345678901234567L, b = pow(a, 1999);
// long a = rng.nextLong(), b = rng.nextLong();
BigInteger logA = dlog(a), logB = dlog(b);
BigInteger x;
if (logB.signum() == 0) {
x = BigInteger.ZERO;
} else {
BigInteger gcd = logA.gcd(logB).gcd(bMod);
logA = logA.divide(gcd);
logB = logB.divide(gcd);
BigInteger curMod = bMod.divide(gcd);
if (logA.gcd(curMod).compareTo(BigInteger.ONE) != 0) {
x = BigInteger.ONE.negate();
} else {
x = logA.modInverse(curMod).multiply(logB).mod(curMod);
}
}
// if (x.signum() >= 0 && pow(a, x.longValue()) != b) {
// throw new AssertionError();
// }
out.println(x);
}
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static String scanString() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
} | java |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] | import java.util.*;
import java.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();
while(tes-->0)
{
long n=sc.nextLong();
long k=sc.nextLong();
k++;
int len=(Long.toString(k)).length();
System.out.println(n*(len-1));
}
}
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 |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;
public class ArraySharpening {
public static void main(String[] args) {
ASSolution assolution = new ASSolution();
assolution.solve();
}
}
class ASSolution {
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new RuntimeException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new RuntimeException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String readString() {
final StringBuilder stringBuilder = new StringBuilder();
int c = read();
while (isSpaceChar(c))
c = read();
do {
stringBuilder.append((char) c);
c = read();
} while (!isSpaceChar(c));
return stringBuilder.toString();
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
void solve() {
var out = new PrintWriter(System.out);
var ir = new InputReader(System.in);
int t = ir.readInt();
while (t-- > 0) {
int n = ir.readInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = ir.readInt();
int front = -1, back = n;
for (int i = 0, j = n - 1; i < n; i++, j--) {
if (arr[i] >= i)
front++;
else
break;
}
for(int j = n - 1, i = 0; j >= 0; j--, i++) {
if (arr[j] >= i)
back--;
else
break;
}
if (front >= back)
out.println("YES");
else
out.println("NO");
}
out.close();
}
}
| java |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications. | [
"data structures",
"greedy",
"sortings"
] | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
public class A {
static class Pair implements Comparable<Pair>{
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(x, o.x);
}
}
static class Bag {
PriorityQueue<Integer> all = new PriorityQueue<Integer>(Comparator.reverseOrder());
long sum = 0;
void add(int x) {
all.add(x);
sum += x;
}
void poll() {
sum -= all.poll();
}
}
void submit() {
int n = nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
for (int i = 0; i < n; i++) {
b[i] = nextInt();
}
Pair[] c = new Pair[n];
for (int i = 0; i < n; i++) {
c[i] = new Pair(a[i], b[i]);
}
Arrays.sort(c);
Bag bag = new Bag();
long ans = 0;
for (int i = 0; i < c.length; ) {
int j = i;
while (j < n && c[i].x == c[j].x) {
bag.add(c[j].y);
j++;
}
int iters = Math.min(bag.all.size(), j == n ? Integer.MAX_VALUE : c[j].x - c[i].x);
for (int x = 0; x < iters; x++) {
bag.poll();
ans += bag.sum;
}
i = j;
}
out.println(ans);
}
void test() {
}
void stress() {
for (int tst = 0;; tst++) {
if (false) {
throw new AssertionError();
}
System.err.println(tst);
}
}
A() throws IOException {
is = System.in;
out = new PrintWriter(System.out);
submit();
// stress();
// test();
out.close();
}
static final Random rng = new Random();
static final int C = 5;
static int rand(int l, int r) {
return l + rng.nextInt(r - l + 1);
}
public static void main(String[] args) throws IOException {
new A();
}
private InputStream is;
PrintWriter out;
private byte[] buf = new byte[1 << 14];
private int bufSz = 0, bufPtr = 0;
private int readByte() {
if (bufSz == -1)
throw new RuntimeException("Reading past EOF");
if (bufPtr >= bufSz) {
bufPtr = 0;
try {
bufSz = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufSz <= 0)
return -1;
}
return buf[bufPtr++];
}
private boolean isTrash(int c) {
return c < 33 || c > 126;
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isTrash(b))
;
return b;
}
String nextToken() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!isTrash(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextString() {
int b = readByte();
StringBuilder sb = new StringBuilder();
while (!isTrash(b) || b == ' ') {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
char nextChar() {
return (char) skip();
}
int nextInt() {
int ret = 0;
int b = skip();
if (b != '-' && (b < '0' || b > '9')) {
throw new InputMismatchException();
}
boolean neg = false;
if (b == '-') {
neg = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
ret = ret * 10 + (b - '0');
} else {
if (b != -1 && !isTrash(b)) {
throw new InputMismatchException();
}
return neg ? -ret : ret;
}
b = readByte();
}
}
long nextLong() {
long ret = 0;
int b = skip();
if (b != '-' && (b < '0' || b > '9')) {
throw new InputMismatchException();
}
boolean neg = false;
if (b == '-') {
neg = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
ret = ret * 10 + (b - '0');
} else {
if (b != -1 && !isTrash(b)) {
throw new InputMismatchException();
}
return neg ? -ret : ret;
}
b = readByte();
}
}
} | java |
1315 | B | B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
| [
"binary search",
"dp",
"greedy",
"strings"
] | import java.util.*;
import java.io.*;
public class Practice {
static boolean multipleTC = true;
FastReader in;
PrintWriter out;
final static int mod = 1000000007;
final static int mod2 = 998244353;
final double E = 2.7182818284590452354;
final double PI = 3.14159265358979323846;
int MAX = 100005;
public static void main(String[] args) throws Exception {
new Practice().run();
}
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();
}
void pre() throws Exception {
}
// All the best
void solve(int TC) throws Exception {
int a = ni(), b = ni(), p = ni();
char s[] = nln().toCharArray();
int n = s.length;
ArrayList<pair> ls = new ArrayList<>();
long cost = 0;
for (int i = n - 2; i >= 0;) {
int j = i;
while (j >= 0 && s[i] == s[j]) {
j--;
}
cost += s[i] == 'A' ? a : b;
ls.add(new pair(j + 1, cost));
i = j;
}
// dbg(ls);
Collections.reverse(ls);
int sz = ls.size();
int starting = n;
for (int i = 0; i < sz; i++) {
if (ls.get(i).y <= p) {
starting = ls.get(i).x + 1;
break;
}
}
pn(starting);
}
class pair {
int x;
long y;
pair(int x, long y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
}
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[]) {
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();
}
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());
}
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 |
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 Fields {
static int n, m, k;
static ArrayList<ArrayList<Integer>> adj;
static boolean[] special, visited;
static int[] distance1, distanceN;
public static void main(String[] args) throws Exception {
FastIO in = new FastIO();
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
special = new boolean[n];
visited = new boolean[n];
distance1 = new int[n];
distanceN = new int[n];
adj = new ArrayList<ArrayList<Integer>>();
for (int i=0; i<k; i++) {
int s = in.nextInt()-1;
special[s] = true;
}
for (int i=0; i<n; i++) {
adj.add(new ArrayList<Integer>());
}
for (int i=0; i<m; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
adj.get(a).add(b);
adj.get(b).add(a);
}
bfs(0, distance1);
visited = new boolean[n];
bfs(n-1, distanceN);
Pair[] specialPairs = new Pair[k];
int index = 0;
for (int i=0; i<n; i++) {
if (special[i]) {
specialPairs[index] = new Pair(distance1[i], distanceN[i]);
index++;
}
}
Arrays.parallelSort(specialPairs, (o1, o2) -> Integer.compare(o1.x, o2.x));
int[] suffixMaxY = new int[k];
suffixMaxY[k-1] = specialPairs[k-1].y;
for (int i=k-2; i>=0; i--) {
suffixMaxY[i] = Math.max(specialPairs[i].y, suffixMaxY[i+1]);
}
int maxDist = 0;
for (int i=0; i<k-1; i++) {
int longestPath = specialPairs[i].x+1+Math.min(specialPairs[i].y, suffixMaxY[i+1]);
maxDist = Math.max(maxDist, longestPath);
}
System.out.println(Math.min(maxDist, distance1[n-1]));
}
public static void bfs(int node, int[] distance) {
Queue<Pair> queue = new LinkedList<Pair>();
queue.add(new Pair(node, 0));
while (!queue.isEmpty()) {
Pair curr = queue.poll();
if (visited[curr.x]) continue;
// if (curr.x==3) System.out.println(curr.y);
distance[curr.x] = curr.y;
visited[curr.x] = true;
for (int next: adj.get(curr.x)) {
if (!visited[next]) {
queue.add(new Pair(next, curr.y+1));
}
}
}
}
static class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
static class FastIO {
BufferedReader br;
StringTokenizer st;
public FastIO() throws IOException
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); }
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public String nextLine() throws IOException
{
String str = br.readLine();
return str;
}
}
}
| java |
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"
] | // Author : RegalBeast
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
public class Main implements Runnable {
static Input in = new Input();
static PrintWriter out = Output();
public static void main(String[] args) {
new Thread(null, new Main(), String.join(
"All that is gold does not glitter,",
"Not all those who wander are lost;",
"The old that is strong does not wither,",
"Deep roots are not reached by the frost.",
"From the ashes a fire shall be woken,",
"A light from the shadows shall spring;",
"Renewed shall be blade that was broken,",
"The crownless again shall be king."
), 1<<25).start();
}
public void run() {
int a = in.nextInt();
int sum = getSum(a);
int den = a-2;
int g = gcd(sum, den);
sum /= g;
den /= g;
out.println(String.format("%d/%d", sum, den));
in.close();
out.close();
}
static int getSum(int a) {
int sum = 0;
for (int base = 2; base < a; base++) {
sum += getSum(a, base);
}
return sum;
}
static int getSum(int num, int base) {
int sum = 0;
while (num > 0) {
sum += num % base;
num /= base;
}
return sum;
}
static int gcd(int num1, int num2) {
if (num1 == 0) {
return num2;
}
return gcd(num2 % num1, num1);
}
static PrintWriter Output() {
return new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
}
static PrintWriter Output(String fileName) {
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
} catch (IOException ex) {
ex.printStackTrace();
}
return pw;
}
}
class Input {
BufferedReader br;
StringTokenizer st;
public Input() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public Input(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException ex) {
ex.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Float nextFloat() {
return Float.parseFloat(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
if (st != null && st.hasMoreElements()) {
StringBuilder sb = new StringBuilder();
while (st.hasMoreElements()) {
sb.append(next());
}
return sb.toString();
}
String str = null;
try {
str = br.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
return str;
}
public void close() {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| 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"
] | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 0; t < test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
Set<Long> set = new HashSet<>();
for (int i = 0; i < n; i++) {
long val = sc.nextLong();
set.add(val);
}
out.println(drEvilUnderscores(set, 30));
}
private static long drEvilUnderscores(Set<Long> set, int bitPosition) {
if (bitPosition < 0) {
return 0;
}
Set<Long> set0 = new HashSet<>();
Set<Long> set1 = new HashSet<>();
long currMask = (1 << bitPosition);
for (long val : set) {
if ((currMask & val) == 0) {
set0.add(val);
}else {
set1.add(val);
}
}
if (set0.size() == 0) {
return drEvilUnderscores(set1, bitPosition - 1);
}
if (set1.size() == 0) {
return drEvilUnderscores(set0, bitPosition - 1);
}
return (1 << bitPosition) + Math.min(drEvilUnderscores(set0, bitPosition - 1), drEvilUnderscores(set1, bitPosition - 1));
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException end)
{
end.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException end)
{
end.printStackTrace();
}
return str;
}
}
} | java |
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.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);
DSameGCDs solver = new DSameGCDs();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class DSameGCDs {
public void solve(int testNumber, InputReader in, OutputWriter out) {
long a = in.nextLong(), m = in.nextLong();
long g = gcd(a, m);
a /= g;
m /= g;
long ans = countCoprime(m, a + m) - countCoprime(m, a - 1);
out.println(ans - 1);
}
public static long gcd(long a, long b) {
return b == 0 ? (a < 0 ? -a : a) : gcd(b, a % b);
}
static long countCoprime(long n, long r) {
ArrayList<Long> primes = new ArrayList<>();
for (long i = 2; i * i <= n; ++i)
if (n % i == 0) {
primes.add(i);
while (n % i == 0) n /= i;
}
if (n > 1)
primes.add(n);
long sum = 0, size = primes.size();
for (long msk = 1L, end = 1L << size; msk < end; ++msk) {
long mult = 1, bits = 0;
for (int i = 0; i < size; ++i)
if ((msk & 1L << i) != 0) {
++bits;
mult *= primes.get(i);
}
if (bits % 2 == 1)
sum += r / mult;
else
sum -= r / mult;
}
return r - sum;
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
| java |
1294 | C | C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
| [
"greedy",
"math",
"number theory"
] |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class ProductOfThreeNumbersAgain {
static FastScanner fs;
static PrintWriter pw;
public static void main(String[] args) {
// TODO Auto-generated method stub
fs = new FastScanner();
pw = new PrintWriter(System.out);
int T = fs.nextInt();
while (T-- > 0)
{
int N = fs.nextInt();
solve(N);
}
pw.close();
}
private static void solve(int N)
{
int a = -1, b = -1;
boolean ok = false;
for (int i = 2; i * i <= N; i++)
{
if (N%i == 0)
{
if (a == -1)
{
a = i;
N /= a;
}
else
{
b = i;
N /= b;
if (N > b)
{
pw.println("YES");
pw.println(a + " " + b + " " + N);
ok = true;
break;
}
else
{
break;
}
}
}
}
if (!ok)
{
pw.println("NO");
}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next() {
while (!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
long[] readArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
| java |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. | [
"dp",
"greedy",
"sortings"
] | import java.util.*;
public class _1286A_garland {
static int solve(int[] nums) {
int n = nums.length;
if (n == 1) return 0;
Set<Integer> existing = new HashSet<>();
int ans = 0;
existing.add(nums[0]);
for (int i = 1; i < n; i++) {
existing.add(nums[i]);
if (nums[i - 1] != 0 && nums[i] != 0 && nums[i] % 2 != nums[i - 1] % 2) {
ans++;
}
}
// all zeros
if(existing.size() == 1) return 1;
// no zeros
if (existing.size() == n) return ans;
// System.out.println("init ans: " + String.valueOf(ans));
int[] counts = new int[2];
for (int i = 1; i <= n; i++) {
if (!existing.contains(i)) {
counts[i % 2]++;
}
}
// System.out.println(Arrays.toString(counts));
// [type, count, odd/even]
List<int[]> spans = new ArrayList<>();
int pre = 0;
for (int i = 0; i < n; ) {
while (i < n && nums[i] != 0) {
i++;
pre = i;
}
while (i < n && nums[i] == 0) {
i++;
}
if (pre == 0) {
// left side: type = 1
spans.add(new int[]{1, i, nums[i] % 2});
} else if (i == n) {
// right side type = 1
spans.add(new int[]{1, i - pre, nums[pre - 1] % 2});
} else if (nums[pre - 1] % 2 != nums[i] % 2) {
// different type = 2, don't care odd/even
spans.add(new int[]{2, i - pre, 0});
} else {
// same type = 0
spans.add(new int[]{0, i - pre, nums[pre - 1] % 2});
}
}
Collections.sort(spans, (int[] a, int[] b) -> {
if (a[0] == b[0]) {
return a[1] - b[1];
}
return a[0] - b[0];
});
for (int i = 0; i < spans.size(); i++) {
int[] span = spans.get(i);
if (span[1] == 0) continue;
int type = span[0];
if (span[1] > counts[span[2]] && type == 0) {
// fill type 1 first with the same odd/even
for (int j = i+1; j < spans.size(); j++) {
if (spans.get(j)[0] == 1 && spans.get(j)[2] == span[2] && spans.get(j)[1] <= counts[span[2]]) {
counts[span[2]] -= spans.get(j)[1];
spans.get(j)[1] = 0;
}
}
}
int toFill = Math.min(span[1], counts[span[2]]);
span[1] -= toFill;
counts[span[2]] -= toFill;
if (span[1] > 0) {
counts[(span[2] + 1) % 2] -= span[1];
if (type == 0) {
ans += 2;
}
if (type == 1) {
ans++;
}
}
if (type == 2) {
ans++;
}
}
return ans;
}
public static void main(String[] args) {
// int res = _1286A_garland.solve(new int[]{0, 5, 0, 2, 3});
// System.out.println(res);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
int res = _1286A_garland.solve(nums);
System.out.println(res);
}
}
| java |
1304 | A | A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward. | [
"math"
] | import java.util.*;
public class MyClass {
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
int t = kb.nextInt();
while(t-- > 0)
{
int x = kb.nextInt();
int y = kb.nextInt();
int a = kb.nextInt();
int b = kb.nextInt();
int total = y-x;
int jump = a+b;
if(total%jump == 0)
{
System.out.println(total/jump);
}
else
{
System.out.println(-1);
}
}
}
} | java |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
public class C1325E_1 {
static final int NO_ANSWER = (int) 1e9;
private static boolean debug = false;
public static void main(String[] args) throws IOException {
// {
// long t = System.nanoTime();
// var limit = (int) 1e6;
// var oneFactor = new int[limit + 1];
// var primeFactorCounts = new int[limit + 1];
// var factors = new ArrayList<List<Integer>>(limit + 1);
// factors.add(List.of());
// factors.add(List.of(1));
// var ans = new int[limit + 1][2];
//// var ans = new int[2][limit + 1];
//// var ans = new int[s2 * limit];
// System.out.println((System.nanoTime() - t) / 1e9);
// }
// {
// long t = System.nanoTime();
// int[] a = new int[(int) 1e6];
// System.out.println((System.nanoTime() - t) / 1e9);
// t = System.nanoTime();
// Arrays.fill(a, -1);
// System.out.println((System.nanoTime() - t) / 1e9);
// }
// {
// long t = System.nanoTime();
// int[][] ints = new int[(int) 1e6 + 1][];
// System.out.println((System.nanoTime() - t) / 1e9);
// }
var scanner = new BufferedScanner();
var writer = new BufferedWriter(new PrintWriter(System.out));
var t = System.nanoTime();
// var primes0 = primes((long) 1e6);
// debug("primes 1e12: " + (System.nanoTime() - t) / 1e9);
// t = System.nanoTime();
var n = scanner.nextInt();
// debug = n == 80106; // == 35965;// || n == 78500;
// var n = 35965;
var a = new int[n];
// var aa = new ArrayList<Integer>();
// for (int i = 0; i < primes0.size(); i++) {
// aa.add(primes0.get(i));
// for (int j = i + 1; j < primes0.size(); j++) {
// aa.add(primes0.get(i) * primes0.get(j));
// }
// }
// var a = aa.stream().mapToInt(i -> i).toArray();
// var n = a.length;
// debug("n: " + n);
var maxA = -1;
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
// a[i] = randomA(primes0, (int) 1e6);
maxA = Math.max(maxA, a[i]);
}
debug("maxA: " + maxA);
// debug("random1: " + random1count);
// debug("random2: " + random2count);
t = System.nanoTime();
var factors = factors((int) 1e6);
debug("factors: " + (System.nanoTime() - t) / 1e9);
// debug("maxA: " + maxA);
// debug("randomA: " + (System.nanoTime() - t) / 1e9);
// t = System.nanoTime();
// var primes = primes(maxA);
// debug("primes: " + (System.nanoTime() - t) / 1e9);
t = System.nanoTime();
var connect = new HashMap<Integer, Set<Integer>>();
var ans = NO_ANSWER;
for (int x : a) {
var fs = factors.get(x);
if (fs.size() == 0) {
ans = 1;
break;
}
int p, q;
if (fs.size() == 1) {
p = 1;
q = fs.get(0);
} else {
p = fs.get(0);
q = fs.get(1);
}
if (put(connect, p, q) || put(connect, q, p)) {
ans = 2;
}
}
debug("connect: " + (System.nanoTime() - t) / 1e9);
debug("connect size: " + connect.size());
if (ans == NO_ANSWER) {
var nodes = connect.keySet().stream()
.filter(k -> connect.get(k).size() > 1)
.sorted()
.collect(Collectors.toList());
var connect2 = new HashMap<Integer, List<Integer>>();
var connect3 = new HashMap<Integer, int[]>();
for (Map.Entry<Integer, Set<Integer>> entry : connect.entrySet()) {
connect2.put(entry.getKey(), List.copyOf(entry.getValue()));
connect3.put(entry.getKey(), entry.getValue().stream().mapToInt(i -> i).toArray());
}
var dist = new int[maxA + 1];
var from = new int[maxA + 1];
for (int start : nodes) {
if (start <= maxA / start) {
t = System.nanoTime();
init(dist, from, connect.keySet());
ans = Math.min(ans, bfs(start, connect2, connect3, dist, from, ans));
if (bfsCount0 > 160) {
debug("bfs " + bfsCount0 + " for " + start + " done for " + (System.nanoTime() - t) / 1e9);
}
}
}
// debug("bfs: " + (System.nanoTime() - t) / 1e9);
debug("bfsCount: " + bfsCount);
debug("bfsCount0: " + bfsCount0);
}
ans = ans < NO_ANSWER ? ans : -1;
writer.write(String.valueOf(ans));
scanner.close();
writer.flush();
writer.close();
}
private static void init(int[] dist, int[] from, Set<Integer> nodes) {
for (Integer node : nodes) {
dist[node] = 0;
from[node] = 0;
}
}
private static void debug(String s) {
if (debug) {
System.out.println(s);
}
}
private static List<List<Integer>> factors(int limit) {
var oneFactor = new int[limit + 1];
var factors = new ArrayList<List<Integer>>(limit + 1);
factors.add(List.of());
factors.add(List.of());
var t1 = 0;
var t2 = 0;
for (int i = 2; i <= limit; i++) {
if (oneFactor[i] == 0) {
var t = System.nanoTime();
oneFactor[i] = i;
factors.add(List.of(i));
int multiple = i + i;
while (multiple <= limit) {
oneFactor[multiple] = i;
multiple += i;
}
t2 += System.nanoTime() - t;
} else {
var t = System.nanoTime();
var subFactors = factors.get(i / oneFactor[i]);
var thisFactors = new ArrayList<>(subFactors);
if (thisFactors.contains(oneFactor[i])) {
thisFactors.remove(Integer.valueOf(oneFactor[i]));
} else {
thisFactors.add(oneFactor[i]);
}
factors.add(thisFactors);
t1 += System.nanoTime() - t;
}
}
// debug("t1: " + t1 / 1e9);
// debug("t2: " + t2 / 1e9);
return factors;
}
static int random1count = 0;
static int random2count = 0;
private static int randomA(List<Integer> primes, int limit) {
var a = primes.get((int) (Math.random() * primes.size()));
var b = primes.get((int) (Math.random() * primes.size()));
if ((long) a * b > limit) {
random1count++;
return a;
} else {
random2count++;
return a * b;
}
}
private static boolean put(Map<Integer, Set<Integer>> connect, int a, int b) {
Set<Integer> cs = connect.get(a);
if (cs != null && cs.contains(b)) {
return true;
}
connect.putIfAbsent(a, new HashSet<>());
connect.get(a).add(b);
return false;
}
static int bfsCount0 = 0;
static int bfsCount = 0;
private static int bfs(int start, Map<Integer, List<Integer>> connect,
Map<Integer, int[]> connect3, int[] dist, int[] from, int ans) {
var q = new LinkedList<Integer>();
// var dist = new HashMap<Integer, Integer>();
// var from = new HashMap<Integer, Integer>();
bfsCount0++;
q.add(start);
// dist.put(start, 0);
// from.put(start, start);
from[start] = start;
while (!q.isEmpty()) {
bfsCount++;
var h = q.poll();
var d0 = dist[h];
if (2 * d0 >= ans) {
break;
}
var hFrom = from[h];
// for (int next : connect.get(h)) {
var nextList = connect3.get(h);
for (int next : nextList) {
// var d1 = dist.get(next);
if (from[next] == 0) {
q.add(next);
// dist.put(next, d0 + 1);
// from.put(next, h);
dist[next] = d0 + 1;
from[next] = h;
} else if (next != hFrom) {
var d = d0 + 1 + dist[next];
ans = Math.min(ans, d);
}
}
}
// debug("bfs " + bfsCount0 + " done");
return ans;
}
private static List<Integer> primes(long upperBound) {
var limit = (int) Math.sqrt(upperBound);
var isComposite = new boolean[limit + 1];
var primes = new ArrayList<Integer>();
for (int i = 2; i <= limit; i++) {
if (isComposite[i]) {
continue;
}
primes.add(i);
int j = i + i;
while (j <= limit) {
isComposite[j] = true;
j += i;
}
}
return primes;
}
public static class BufferedScanner {
BufferedReader br;
StringTokenizer st;
public BufferedScanner(Reader reader) {
br = new BufferedReader(reader);
}
public BufferedScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b > 0) {
long tmp = b;
b = a % b;
a = tmp;
}
return a;
}
static long inverse(long a, long m) {
long[] ans = extgcd(a, m);
return ans[0] == 1 ? (ans[1] + m) % m : -1;
}
private static long[] extgcd(long a, long m) {
if (m == 0) {
return new long[]{a, 1, 0};
} else {
long[] ans = extgcd(m, a % m);
long tmp = ans[1];
ans[1] = ans[2];
ans[2] = tmp;
ans[2] -= ans[1] * (a / m);
return ans;
}
}
}
| 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"
] | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class CodeChef {
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 p = sc.nextInt();
int[] A = new int[n];
int[] B = new int[m];
int ai = 0, bi = 0;
for (int i = 0; i < n; i++) {
A[i] = sc.nextInt();
}
for (int i = 0; i < m; i++) {
B[i] = sc.nextInt();
}
while (A[ai] % p == 0) {
ai++;
}
while (B[bi] % p == 0) {
bi++;
}
out.println(ai + bi);
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | java |
1284 | E | E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213 | [
"combinatorics",
"geometry",
"math",
"sortings"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.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);
ENewYearAndCastleConstruction solver = new ENewYearAndCastleConstruction();
solver.solve(1, in, out);
out.close();
}
static class ENewYearAndCastleConstruction {
public void solve(int testNumber, LightScanner in, LightWriter out) {
int n = in.ints();
Vec2l[] points = new Vec2l[n];
for (int i = 0; i < n; i++) points[i] = new Vec2l(in.longs(), in.longs());
long ans = n * (n - 1L) * (n - 2L) * (n - 3L) * (n - 4L) / 24;
for (int t = 0; t < n; t++) {
int m = 0;
Vec2l[] angles = new Vec2l[n - 1];
{
Vec2l now = points[t];
for (int i = 0; i < n; i++) {
if (i != t) {
angles[m] = new Vec2l(points[i].x - now.x, points[i].y - now.y);
m++;
}
}
IntroSort.sort(angles, Vec2l::compareToByAngle);
}
//System.out.println(Arrays.stream(angles).map(angle -> Double.toString(Math.atan2(angle.y, angle.x))).collect(Collectors.joining(", ")));
int hi = 0;
for (int j = 0; j < m; j++) {
while (hi < j + m && (hi <= j || angles[j].det(angles[hi % m]) > 0)) {
hi++;
}
int cnt = hi - j;
ans -= (cnt - 1L) * (cnt - 2L) * (cnt - 3L) / 6;
}
}
out.ans(ans).ln();
}
}
static class 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 interface Verified {
}
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;
}
}
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 LightWriter implements AutoCloseable {
private final Writer out;
private boolean autoflush = false;
private boolean breaked = true;
public LightWriter(Writer out) {
this.out = out;
}
public LightWriter(OutputStream out) {
this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));
}
public LightWriter print(char c) {
try {
out.write(c);
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter print(String s) {
try {
out.write(s, 0, s.length());
breaked = false;
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
public LightWriter ans(String s) {
if (!breaked) {
print(' ');
}
return print(s);
}
public LightWriter ans(long l) {
return ans(Long.toString(l));
}
public LightWriter ln() {
print(System.lineSeparator());
breaked = true;
if (autoflush) {
try {
out.flush();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
return this;
}
public void close() {
try {
out.close();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
static class Vec2l implements Comparable<Vec2l> {
public long x;
public long y;
public Vec2l(long x, long y) {
this.x = x;
this.y = y;
}
public long det(Vec2l other) {
return x * other.y - other.x * y;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vec2l vec2i = (Vec2l) o;
return x == vec2i.x &&
y == vec2i.y;
}
public int hashCode() {
return Objects.hash(x, y);
}
public String toString() {
return "(" + x + ", " + y + ")";
}
public int compareTo(Vec2l o) {
if (x == o.x) {
return Long.compare(y, o.y);
}
return Long.compare(x, o.x);
}
public int compareToByAngle(Vec2l o) {
if ((y >= 0) != (o.y >= 0)) {
return y >= 0 ? 1 : -1;
} else {
return Long.compare(0, x * o.y - o.x * y);
}
}
}
static class 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);
}
}
}
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 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 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);
}
}
}
}
| java |
1296 | E1 | E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000
| [
"constructive algorithms",
"dp",
"graphs",
"greedy",
"sortings"
] | // package c1296;
//
// Codeforces Round #617 (Div. 3) 2020-02-04 06:35
// E1. String Coloring (easy version)
// https://codeforces.com/contest/1296/problem/E1
// 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+).*'
//
// .
//
// You are given a string s consisting of n lowercase Latin letters.
//
// You have to color its characters (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 s).
//
// After coloring, you can swap two neighboring characters of the string that are colored colors.
// You can perform such an operation arbitrary (possibly, zero) number of times.
//
// The goal is to make the string sorted, i.e. all characters should be in alphabetical order.
//
// Your task is to say if it is possible to color the given string so that after coloring it can
// become sorted by sequence of swaps. Note that you have to restore only coloring, not the sequence
// of swaps.
//
// Input
//
// The first line of the input contains one integer n (1 <= n <= 200) -- the length of s.
//
// The second line of the input contains the string s consisting of exactly n lowercase Latin
// letters.
//
// Output
//
// If it is impossible to color the given string so that after coloring it can become sorted by
// sequence of swaps, print "NO" (without quotes) in the first line.
//
// Otherwise, print "YES" in the first line and correct coloring in the second line (the coloring is
// the string consisting of n characters, the i-th character should be '0' if the i-th character is
// colored the first color and '1' otherwise).
//
// Example
/*
input:
9
abacbecfd
output:
YES
001010101
input:
8
aaabbcbb
output:
YES
01011011
input:
7
abcdedc
output:
NO
input:
5
abcde
output:
YES
00000
*/
//
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.Collections;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
public class C1296E1 {
static final int MOD = 998244353;
static final Random RAND = new Random();
static final int NOCOLOR = 2;
static String solve(String s) {
int n = s.length();
// Array of (src_index, character, color, dst_index)
List<int[]> arr = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr.add(new int[] {i, s.charAt(i) - 'a', NOCOLOR, 0});
}
Collections.sort(arr, (x,y)->x[1] != y[1] ? x[1] - y[1] : x[0] - y[0]);
if (test) System.out.format(" arr:%s %s\n", traceListIntArray(arr), getStr(arr));
for (int i = 0; i < n; i++) {
arr.get(i)[3] = i;
}
Collections.sort(arr, (x,y) -> x[0] - y[0]);
if (test) System.out.format(" arr:%s %s\n", traceListIntArray(arr), getStr(arr));
for (int i = 0; i < n; i++) {
if (arr.get(i)[3] == i) {
continue;
}
// src: a a b b c e c f d
// dst: a a b b c c d e f
// ^
// i
//
int j = i + 1;
for (; j < n; j++) {
if (arr.get(j)[3] == i) {
break;
}
}
if (test) System.out.format(" i:%d j:%d\n", i, j);
myAssert(j > i);
myAssert(j < n);
// j should be moved to position i
// . . . . . . .
// ^ ^
// i j
// -----
// ^ ^
// b e
if (arr.get(j)[2] != NOCOLOR) {
// j is already colored
int color = 1 - arr.get(j)[2];
for (int h = i; h < j; h++) {
if (arr.get(h)[2] != NOCOLOR && arr.get(h)[2] != color) {
return null;
}
arr.get(h)[2] = color;
}
} else {
int color = NOCOLOR;
for (int h = i; h < j; h++) {
if (arr.get(h)[2] != NOCOLOR) {
color = arr.get(h)[2];
break;
}
}
if (color != NOCOLOR) {
for (int h = i; h < j; h++) {
if (arr.get(h)[2] != NOCOLOR && arr.get(h)[2] != color) {
return null;
}
arr.get(h)[2] = color;
}
arr.get(j)[2] = 1 - color;
} else {
for (int h = i; h < j; h++) {
arr.get(h)[2] = 0;
}
arr.get(j)[2] = 1;
}
int[] t = arr.get(j);
arr.remove(j);
arr.add(i, t);
if (test) System.out.format(" i:%d j:%d %s %s\n", i, j, traceListIntArray(arr), getStr(arr));
}
}
char[] ans = new char[n];
for (int[] v : arr) {
ans[v[0]] = v[2] == NOCOLOR ? '0' : (char) ('0' + v[2]);
}
return new String(ans);
}
public static String traceListIntArray(List<int[]> points) {
StringBuilder sb = new StringBuilder();
sb.append('[');
boolean first = true;
for (int[] v : points) {
if (!first) {
sb.append(',');
}
first = false;
sb.append('[');
boolean first2 = true;
for (int w : v) {
if (!first2) {
sb.append(',');
}
sb.append(w);
first2 = false;
}
sb.append(']');
}
sb.append(']');
return sb.toString();
}
static String getStr(List<int[]> arr) {
StringBuilder sb = new StringBuilder();
for (int[] v : arr) {
sb.append((char)('a' + v[1]));
}
return sb.toString();
}
static void test(boolean ok, String s) {
String ans = solve(s);
if (ans == null) {
System.out.format("%s => NO\n", s);
} else {
System.out.format("%s => YES %s\n", s, ans);
}
myAssert((ok && ans != null) || (!ok && ans == null));
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(true, "abacbecfd");
test(true, "aaabbcbb");
test(false, "abcdedc");
test(true, "abcde");
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();
String s = in.next();
String ans = solve(s);
System.out.println(ans == null ? "NO" : "YES\n" + 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 |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | import java.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][2];
int b[][]=new int[n][2];
int i,j;
for(i=0;i<n;i++)
{
a[i][0]=sc.nextInt();
a[i][1]=sc.nextInt();
}
for(i=0;i<n-1;i++)
{
int x,y;
for(j=i+1;j<n;j++)
{
if(a[i][0]>=a[j][0] && a[i][1]>=a[j][1])
{
int t1=a[j][0];
a[j][0]=a[i][0];
a[i][0]=t1;
int t2=a[j][1];
a[j][1]=a[i][1];
a[i][1]=t2;
}
if((a[j][0]>a[i][0] && a[j][1]<a[i][1])||(a[j][0]<a[i][0] && a[j][1]>a[i][1]))
{
System.out.println("NO");
continue label;
}
}
}
System.out.println("YES");
int X=0,Y=0;
String ans="";
for(i=0;i<n;i++)
{
while(X<a[i][0])
{
X++;
ans+='R';
}
while(Y<a[i][1])
{
Y++;
ans+='U';
}
}
System.out.println(ans);
}
}
public static int first(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)
return mid;
else if (x > arr.get(mid))
return first(arr, (mid + 1), high, x, n);
else
return first(arr, low, (mid - 1), x, n);
}
return -1;
}
public static int last(ArrayList<Integer> arr, int low, int high, int x, int n)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)
return mid;
else if (x < arr.get(mid))
return last(arr, low, (mid - 1), x, n);
else
return last(arr, (mid + 1), high, x, n);
}
return -1;
}
public static int lis(int[] arr) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>=x) {
al.add(arr[i]);
}else {
int v = upper_bound(al, 0, al.size(), arr[i]);
al.set(v, arr[i]);
}
}
return al.size();
}
public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get((int)mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)
{
Collections.sort(ar);
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (ar.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==ar.size())
{
return -1;
}
return s;
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long mod=1000000007;
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | java |
1307 | E | E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000) — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n) — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n) — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2
1 1 1 1 1
1 2
1 3
OutputCopy2 2
InputCopy5 2
1 1 1 1 1
1 2
1 4
OutputCopy1 4
InputCopy3 2
2 3 2
3 1
2 1
OutputCopy2 4
InputCopy5 1
1 1 1 1 1
2 5
OutputCopy0 1
NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side. | [
"binary search",
"combinatorics",
"dp",
"greedy",
"implementation",
"math"
] | import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.stream.IntStream;
public class Main {
static {
Locale.setDefault(Locale.ENGLISH);
}
private static DecimalFormat decimalFormat = new DecimalFormat("#0.00000000");
private static class Reader implements Closeable {
private BufferedReader reader;
private StringTokenizer tokenizer;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String fileName) {
try {
reader = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
throw new IllegalStateException("There is no file with given name");
}
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String nextLine = reader.readLine();
if (nextLine == null) {
return null;
}
tokenizer = new StringTokenizer(nextLine);
} catch (IOException e) {
throw new IllegalStateException("I/O Error");
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
@Override
public void close() throws IOException {
reader.close();
}
}
private static class Pair implements Comparable<Pair> {
private int x;
private int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public int compareTo(Pair o) {
if (this.x != o.x) return Integer.compare(this.x, o.x);
return Integer.compare(this.y, o.y);
}
}
private <T> ArrayList<T> createArrayList(int n, T value) {
ArrayList<T> result = new ArrayList<>();
IntStream.range(0, n).forEach(i -> result.add(value));
return result;
}
public static void main(String[] args) throws IOException {
Reader reader = new Reader();
//Reader reader = new Reader("input.txt");
PrintWriter writer = new PrintWriter(System.out);
new Main().solve(reader, writer);
reader.close();
writer.close();
}
private static class Cow {
private int l;
private int r;
public Cow(int l, int r) {
this.l = l;
this.r = r;
}
public int getL() {
return l;
}
public int getR() {
return r;
}
}
private void solve(Reader reader, PrintWriter writer) {
int n = reader.nextInt();
int m = reader.nextInt();
ArrayList<Integer> s = new ArrayList<>();
boolean[] s1 = new boolean[5001];
boolean[] s2 = new boolean[5001];
for (int i = 0; i < n; ++i) {
s.add(reader.nextInt());
s1[s.get(s.size() - 1)] = true;
}
ArrayList<Cow>[] cowsByF = new ArrayList[5001];
for (int i = 1; i <= n; ++i) {
cowsByF[i] = new ArrayList<>();
}
boolean[] used = new boolean[5000];
for (int i = 0; i < m; ++i) {
int f = reader.nextInt();
int h = reader.nextInt();
int l = -1;
int r = -1;
s2[f] = true;
int counter = 0;
for (int j = 0; j < n; ++j) {
if (s.get(j) == f) {
counter++;
if (counter == h) {
l = j;
break;
}
}
}
counter = 0;
for (int j = n - 1; j >= 0; --j) {
if (s.get(j) == f) {
counter++;
if (counter == h) {
r = j;
break;
}
}
}
if (l != -1) {
used[l] = true;
cowsByF[f].add(new Cow(l, r));
}
}
int bestResult = 0;
long bestCount = 0;
for (int i = -1; i < n; ++i) { //граница разделения
if (i > -1 && !used[i]) {
continue;
}
int result = 0;
long count = 1;
boolean usedProperCow = false;
for (int j = 1; j <= n; ++j) { //уровень сладости
//if (!s1[j] && !s2[j]) {
// continue;
//}
boolean usedProperCowAtJ = false;
int l = 0;
int r = 0;
int mixed = 0;
for (Cow cow : cowsByF[j]) {
if (cow.l == i) {
usedProperCow = true;
usedProperCowAtJ = true;
continue;
}
if (cow.l <= i && cow.r <= i) {
l++;
}
if (cow.l > i && cow.r > i) {
r++;
}
if (cow.l <= i && cow.r > i) {
mixed++;
}
}
if (usedProperCowAtJ) {
if (r + mixed == 0) {
result += 1;
continue;
} else {
result += 2;
int mult = r + mixed;
count *= mult;
if (count > 1000000007) {
count %= 1000000007;
}
continue;
}
}
if (l + r + mixed == 0) {
continue;
}
if (mixed + (l > 0 ? 1 : 0) + (r > 0 ? 1 : 0) > 1) {
result += 2;
int mult = l * mixed + r * mixed + mixed * (mixed - 1);
count *= mult;
} else {
result += 1;
int mult = l + r + mixed * 2;
count *= mult;
}
if (count > 1000000007) {
count %= 1000000007;
}
}
if (result > bestResult) {
bestResult = result;
bestCount = count;
} else if (result == bestResult && (i == -1 || usedProperCow)) {
bestCount += count;
bestCount %= 1000000007;
}
}
writer.println(bestResult + " " + bestCount);
}
}
| java |
1296 | F | F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1
| [
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] | import java.io.*;
import java.util.*;
public class Task {
public static void main(String[] args) throws Exception {
new Task().go();
}
PrintWriter out;
Reader in;
BufferedReader br;
Task() throws IOException {
try {
//br = new BufferedReader( new FileReader("input.txt") );
//in = new Reader("input.txt");
in = new Reader("input.txt");
out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );
}
catch (Exception e) {
//br = new BufferedReader( new InputStreamReader( System.in ) );
in = new Reader();
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
}
}
void go() throws Exception {
//int t = in.nextInt();
int t = 1;
while (t > 0) {
solve();
t--;
}
out.flush();
out.close();
}
int inf = 2000000000;
int mod = 1000000007;
double eps = 0.000000001;
int n;
int m;
ArrayList<Integer>[] g;
int[][] buity = new int[5000][5000];
void solve() throws IOException {
int n = in.nextInt();
g = new ArrayList[n];
Pair[] edges = new Pair[n - 1];
for (int i = 0; i < n; i++)
g[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
g[x].add(y);
g[y].add(x);
buity[x][y] = 1;
buity[y][x] = 1;
edges[i] = new Pair(x, y);
}
boolean ok = true;
int m = in.nextInt();
int[][] paths = new int[m][n + 1];
int[] gs = new int[m];
int[] p = new int[n];
ArrayDeque<Integer> q = new ArrayDeque<>();
int[] queue = new int[n + 1];
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
int z = in.nextInt();
gs[i] = z;
int h = 0;
int t = 0;
queue[h] = a;
t++;
Arrays.fill(p, -1);
p[a] = a;
while (h < t) {
int v = queue[h];
h++;
for (int u : g[v]) {
if (p[u] == -1) {
p[u] = v;
queue[t] = u;
t++;
}
}
}
int pos = 1;
while (b != a) {
paths[i][pos] = b;
pos++;
int prev = b;
b = p[b];
if (buity[prev][b] < z) {
buity[prev][b] = z;
buity[b][prev] = z;
}
}
paths[i][pos] = a;
pos++;
paths[i][0] = pos;
}
for (int i = 0; i < m; i++) {
int min = 1000000;
int len = paths[i][0];
for (int j = 2; j < len; j++) {
int x = paths[i][j - 1];
int y = paths[i][j];
min = Math.min(min, buity[x][y]);
}
ok &= min == gs[i];
}
if (ok) {
for (int i = 0; i < n - 1; i++)
out.print(buity[edges[i].a][edges[i].b] + " ");
} else {
out.println(-1);
}
}
class Pair implements Comparable<Pair> {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair p) {
if (a != p.a)
return Integer.compare(a, p.a);
else
return Integer.compare(-b, -p.b);
}
}
class Item {
int a;
int b;
int c;
Item(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Reader {
BufferedReader br;
StringTokenizer tok;
Reader(String file) throws IOException {
br = new BufferedReader( new FileReader(file) );
}
Reader() throws IOException {
br = new BufferedReader( new InputStreamReader(System.in) );
}
String next() throws IOException {
while (tok == null || !tok.hasMoreElements())
tok = new StringTokenizer(br.readLine());
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.valueOf(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.valueOf(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
static class InputReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public InputReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public InputReader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
} | java |
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 gcdAndLcm {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
for(int j=1;j<=t;j++){
int x=sc.nextInt();
System.out.println(1+" "+(x-1));
}
}
}
| 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"
] | // A Java program to convert an ArrayList to arr[]
import java.util.Scanner;
public class code{
public static long count_3(long n , int t){
long count_t = 0;
while(n>0 && n%t==0){
count_t+=1;
n = n/t;
}
return count_t;
}
public static void main(String args[]){
Scanner s = new Scanner(System.in);
long n = s.nextLong();
long m = s.nextLong();
if(m%n!=0){
System.out.println(-1);
}else{
// division is possible so
long ans1 = m/n;
// now this number ans1 should have only two prime factor one 3 or 2
long k = ans1;
int count = 0;
while(k%2==0 && k>0){
k = k/2;
count+=1;
}
while(k%3==0 && k>0){
k = k/3;
count+=1;
}
if(k==1){
System.out.println(count);
}else{
System.out.println(-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.HashMap;
import java.util.ArrayList;
import java.io.FilterInputStream;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Collections;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CInstantNoodles solver = new CInstantNoodles();
int testCount = in.scanInt();
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class CInstantNoodles {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int m = in.scanInt();
long[] values = new long[n];
for (int i = 0; i < n; i++) values[i] = in.scanLong();
int[][] edges = new int[m][2];
ArrayList<Integer>[] neighbours = new ArrayList[n];
for (int i = 0; i < n; i++) neighbours[i] = new ArrayList<>();
for (int[] edge : edges) {
edge[0] = in.scanInt();
edge[1] = in.scanInt();
neighbours[edge[1] - 1].add(edge[0] - 1);
}
Map<ArrayList<Integer>, Long> map = new HashMap<>();
for (int i = 0; i < n; i++) {
if (neighbours[i].size() == 0) continue;
Collections.sort(neighbours[i]);
map.put(neighbours[i], map.getOrDefault(neighbours[i], 0l) + values[i]);
}
long ans = 0;
for (Map.Entry<ArrayList<Integer>, Long> temp : map.entrySet()) {
ans = CodeHash.gcd(ans, temp.getValue());
}
out.println(ans);
}
}
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 integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
}
static class CodeHash {
public static long gcd(long a, long b) {
while (b != 0) {
long t = b;
b = (a % b);
a = t;
}
return a;
}
}
}
| java |
1313 | C2 | C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"data structures",
"dp",
"greedy"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer zer = new StringTokenizer(br.readLine());
long[] a = new long[n];
for(int i = 0; i < n; i++){
a[i] = Long.parseLong(zer.nextToken());
}
int pse[], nse[];
pse = new int[n];
Arrays.fill(pse, -1);
nse = new int[n];
Arrays.fill(nse, -1);
Stack<Integer> stk = new Stack<>();
stk.push(0);
for(int i = 1; i < n; i++){
while(!stk.empty() && a[stk.peek()] > a[i]){
nse[stk.pop()] = i;
}
stk.push(i);
}
while(!stk.empty()){
stk.pop();
}
stk.push(n - 1);
for(int i = n - 2; i >= 0; i--){
while(!stk.empty() && a[stk.peek()] > a[i]){
pse[stk.pop()] = i;
}
stk.push(i);
}
long[] dlr = new long[n];
long[] drl = new long[n];
dlr[0] = a[0];
for(int i = 1; i < n; i++){
if(pse[i] == -1){
dlr[i] = a[i] * (i + 1);
}else{
dlr[i] = dlr[pse[i]] + a[i] * (i - pse[i]);
}
}
drl[n - 1] = a[n - 1];
for(int i = n - 2; i >= 0; i--){
if(nse[i] == -1){
drl[i] = a[i] * (n - i);
}else{
drl[i] = drl[nse[i]] + a[i] * (nse[i] - i);
}
}
int aidx = 0;
long maxans = -1;
for(int i = 0; i < n; i++){
long curans = dlr[i] + drl[i] - a[i];
if(curans > maxans){
maxans = curans;
aidx = i;
}
}
long[] ans = new long[n];
ans[aidx] = a[aidx];
for(int i = aidx + 1; i < n; i++){
ans[i] = Math.min(ans[i - 1], a[i]);
}
for(int i = aidx - 1; i >= 0; i--){
ans[i] = Math.min(ans[i + 1], a[i]);
}
for(long e : ans){
System.out.print(e + " ");
}
System.out.println();
}
}
| java |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements. | [
"geometry"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.HashSet;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author ilyakor
*/
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);
TaskBReal solver = new TaskBReal();
solver.solve(1, in, out);
out.close();
}
static class TaskBReal {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] X = new int[n];
int[] Y = new int[n];
long sx = 0, sy = 0;
HashSet<ComparablePair<Long, Long>> S = new HashSet<>();
for (int i = 0; i < n; ++i) {
X[i] = in.nextInt();
Y[i] = in.nextInt();
S.add(new ComparablePair<Long, Long>((long) X[i], (long) Y[i]));
sx += X[i];
sy += Y[i];
}
if (n % 2 != 0) {
out.printLine("NO");
return;
}
sx *= 2L;
sy *= 2L;
if (sx % n != 0 || sy % n != 0) {
out.printLine("NO");
return;
}
sx /= n;
sy /= n;
for (int i = 0; i < n; ++i) {
long x = sx - X[i], y = sy - Y[i];
if (!S.contains(new ComparablePair<>(x, y))) {
out.printLine("NO");
return;
}
}
// long l2 = len2(X[0], Y[0], X[1], Y[1]);
// for (int i = 0; i < n; ++i) {
// int j = (i + 1) % n;
// long cl2 = len2(X[i], Y[i], X[j], Y[j]);
// if (l2 != cl2) {
// out.printLine("NO");
// return;
// }
// }
// long ang = crossProd(X[0], Y[0], X[1], Y[1], X[2], Y[2]);
// for (int i = 0; i < n; ++i) {
// int j = (i + 1) % n;
// int k = (i + 2) % n;
// long cang = crossProd(X[i], Y[i], X[j], Y[j], X[k], Y[k]);
// if (ang != cang) {
// out.printLine("NO");
// return;
// }
// }
out.printLine("YES");
}
}
static class Pair<P, Q> {
public P first;
public Q second;
public Pair() {
}
public Pair(P first, Q second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair pair = (Pair) o;
if (first != null ? !first.equals(pair.first) : pair.first != null) {
return false;
}
if (second != null ? !second.equals(pair.second) : pair.second != null) {
return false;
}
return true;
}
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
}
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();
}
}
static class ComparablePair<P extends Comparable, Q extends Comparable> extends
Pair<P, Q> implements Comparable<Pair<P, Q>> {
public ComparablePair() {
}
public ComparablePair(P first, Q second) {
super(first, second);
}
public int compareTo(Pair<P, Q> other) {
int valP = first.compareTo(other.first);
if (valP != 0) {
return valP;
}
return second.compareTo(other.second);
}
}
static class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0) {
return -1;
}
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
}
| java |
1285 | A | A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22. | [
"math"
] | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String numOfCommands = scanner.nextLine();
String command = scanner.nextLine();
// System.out.println(numOfCommands);
// System.out.println(command);
int cntL = 0, cntR = 0;
for (int i =0; i < command.length(); i++ ){
if (command.charAt(i)=='L')
cntL--;
else if (command.charAt(i)=='R')
cntR++;
}
if (command.length()==0) {
System.out.println(1);
}
else{
int diff = cntR-cntL +1;
System.out.println(diff);
}
}
} | java |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2. | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | import java.io.*;
import java.util.*;
public class zia
{
static boolean prime[] = new boolean[25001];
static void shuffleArray(long[] arr){
int n = arr.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
public static int Lcm(int a,int b)
{ int max=Math.max(a,b);
for(int i=1;;i++)
{
if((max*i)%a==0&&(max*i)%b==0)
return (max*i);
}
}
static void sieve(int n,boolean prime[])
{
// boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i =i+ p)
prime[i] = false;
}
}
}
// public static String run(int ar[],int n)
// {
// }
public static long lcm(long a,long b)
{
long max=Math.max(a, b);
long min=Math.min(a, b);
for(int i=1;;i++)
{
if((max*i)%min==0)
return max;
}
}
public static long calculate(long a,long b,long x,long y,long n)
{
if(a-x>=n)
{
a-=n;
}
else
{
b=b-(n-(a-x));
a=x;
if(b<y)
b=y;
}
return a*b;
}
public static int upperbound(int s,int e, long ar[],long x)
{
int res=-1;
while(s<=e)
{ int mid=((s-e)/2)+e;
if(ar[mid]>x)
{e=mid-1;res=mid;}
else if(ar[mid]<x)
{s=mid+1;}
else
{e=mid-1;res=mid;
if(mid>0&&ar[mid]==ar[mid-1])
e=mid-1;
else
break;
}
}
return res;
}
public static int lowerbound(int s,int e, long ar[],long x)
{
int res=-1;
while(s<=e)
{ int mid=((s-e)/2)+e;
if(ar[mid]>x)
{e=mid-1;}
else if(ar[mid]<x)
{s=mid+1;res=mid;}
else
{res=mid;
if(mid+1<ar.length&&ar[mid]==ar[mid+1])
s=mid+1;
else
break;}
}
return res;
}
static long modulo=1000000007;
public static long power(long a, long b)
{
if(b==0) return 1;
long temp=power(a,b/2)%modulo;
if((b&1)==0)
return (temp*temp)%modulo;
else
return (((temp*temp)%modulo)*a)%modulo;
}
public static long powerwithoutmod(long a, long b)
{
if(b==0) return 1;
long temp=power(a,b/2);
if((b&1)==0)
return (temp*temp);
else
return ((temp*temp)*a);
}
public static int log2(int a)
{ double d=Math.log(a)/Math.log(2);
return (int)d+1;
}
public static int log10(long a)
{ double d=Math.log(a)/Math.log(10);
return (int)d;
}
public static int find(int ar[],int x)
{
int count=0;
for(int i=0;i<ar.length;i+=2)
{
if((ar[i]&1)!=x)
count++;
}
return count;
}
public static void main(String[] args) throws Exception
{
FastIO sc = new FastIO();
//sc.println();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
int test=sc.nextInt();
// // double c=Math.log(10);
// boolean prime[]=new boolean[1000001];
// sieve(1000000, prime);
while(test-->0)
{
int n=sc.nextInt();
long k=sc.nextLong();
long ar[]=new long[n];
long max=0;
for(int i=0;i<n;i++)
{
ar[i]=sc.nextLong();
if(ar[i]>max)
max=ar[i];
}
// long maxPower=(long)(Math.ceil(((double)Math.log(max))/Math.log(k)));
long maxPower=(long)Math.ceil(16.0/Math.log10(k));
// sc.println(maxPower+" "+k);
long maxK=powerwithoutmod(k,maxPower);
while(maxK!=0)
{
// sc.println(maxK);
for(int i=0;i<n;i++)
{
if(ar[i]>=maxK)
{ar[i]=ar[i]-maxK;break;}
}
maxK=maxK/k;
}
String res="YES";
for(int i=0;i<n;i++)
{
if(ar[i]>0)
{res="NO";break;}
}
sc.println(res);
}
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sc.close();
}
}
class pair implements Comparable<pair>{
char value;
int frequency;
pair(char value,int frequency)
{this.value=value;
this.frequency=frequency;
}
public int compareTo(pair p)
{return -this.frequency+p.frequency;}
}
class triplet implements Comparable<triplet>{
int first,second,third;
triplet(int first,int second,int third)
{this.first=first;
this.second=second;
this.third=third;
}
public int compareTo(triplet p)
{return this.third-p.third;}
}
// class triplet
// {
// int x1,x2,i;
// triplet(int a,int b,int c)
// {x1=a;x2=b;i=c;}
// }
class FastIO extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1<<16];
private int curChar, numChars;
// standard input
public FastIO() { this(System.in,System.out); }
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
public String nextLine() {
int c; do { c = nextByte(); } while (c <= '\n');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n');
return res.toString();
}
public String next() {
int c; do { c = nextByte(); } while (c <= ' ');
StringBuilder res = new StringBuilder();
do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');
return res.toString();
}
public int nextInt() {
int c; do { c = nextByte(); } while (c <= ' ');
int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() {
int c; do { c = nextByte(); } while (c <= ' ');
long sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10*res+c-'0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() { return Double.parseDouble(next()); }
}
| java |
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.*;
import java.util.*;
public class Main {
static Reader in;
static PrintWriter out;
int n;
Integer[] a;
Main() {
n = in.nextInt();
a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
ArrayList<Integer>[] dp = new ArrayList[n + 1];
for (int i = 0; i <= n; i++)
dp[i] = new ArrayList<>();
for (int i = 0; i < n; i++)
dp[i].add(i + 1);
for (int i = n - 1; i >= 0; i--)
for (int x = a[i]; x - a[i] < dp[i].size(); x++) {
int j = dp[i].get(x - a[i]);
if (j < n && 0 <= x - a[j] && x - a[j] < dp[j].size())
dp[i].add(dp[j].get(x - a[j]));
}
Integer[] dp2 = new Integer[n + 1];
dp2[0] = 0;
for (int i = 0; i < n; i++)
for (int j : dp[i])
if (dp2[j] == null)
dp2[j] = 1 + dp2[i];
else
dp2[j] = Math.min(dp2[j], 1 + dp2[i]);
out.println(dp2[n]);
}
public static void main(String[] args) throws Exception {
// FileIO();
in = new Reader();
out = new PrintWriter(System.out);
new Main();
out.flush();
}
static void FileIO() throws Exception {
System.setIn(new FileInputStream("In.txt"));
System.setOut(new PrintStream(new FileOutputStream("Out.txt")));
System.setErr(new PrintStream(new FileOutputStream("Error.txt")));
}
}
class Reader {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.readLine());
return st.nextToken();
} catch (Exception e) {
}
return null;
}
double nextDouble() {
return Double.parseDouble(next());
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
} | 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"
] | //********************(Writer-Aagam)*******************************
//*******************(User-getlost01)******************************
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
//------------------------Main_class-------------------------------
public class Codechef
{
static AagamReader ar=new AagamReader();
//----------------------Main_Function------------------------------
public static void main (String[] args) throws java.lang.Exception
{
// long start=System.currentTimeMillis();
int t=ar.nextInt();
while(t-->0)
{
int a=ar.nextInt();
int b=ar.nextInt();
int i=ar.nextInt();
int j=ar.nextInt();
int temp1=i*b;
int temp2=j*a;
int temp3=(a-i-1)*b;
int temp4=(b-j-1)*a;
System.out.println(Math.max(temp1,Math.max(temp2,Math.max(temp3,temp4))));
}
// long end=System.currentTimeMillis();
// System.out.println(end-start+" Millisec");
}
//--------------------Solving_Function---------------------------
static void solve(String s)
{
System.out.println(s);
}
//------------------------Reverse----------------------------------
public static int[] reverses(int data[], int left, int right)
{
while (left < right)
{
int temp = data[left];
data[left++] = data[right];
data[right--] = temp;
}
return data;
}
//----------------------------Swap-----------------------------------
public static int[] swap(int data[], int left, int right)
{
int temp = data[left];
data[left] = data[right];
data[right] = temp;
return data;
}
//--------------------------Factorial---------------------------------
public static long factorials(long n)
{
if(n==0) return 1;
return n*factorials(n-1);
}
//-------------------------G.C.D---------------------------------------
public static long gcd(long a,long b)
{
if(b==0) return a;
return gcd(b,a%b);
}
//-------------------------ModularG.C.D-------------------------------
static long gcd(long a,long b,long n,long mod)
{
if(a==b)
return (mod_expo(a,n,mod)+mod_expo(b,n,mod))%mod;
long c=1;long diff=a-b;
for(long i=1;i<=Math.sqrt(diff);i++)
{
if(diff%i==0)
{
long temp=(mod_expo(a,n,i)+mod_expo(b,n,i))%i;
if(temp==0)
c=Math.max(c,i);
temp=(mod_expo(a,n,diff/i)+mod_expo(b,n,diff/i))%(diff/i);
if(temp==0)
c=Math.max(c,diff/i);
}
}
return c%mod;
}
//------------------------ l.C.M--------------------------------------
public static long lcm(long a,long b)
{
return (a*b)/gcd(a,b);
}
//---------------------------Prime-----------------------------------
public static boolean[] seive(int n)
{
boolean isPrime[]=new boolean[n+1];
Arrays.fill(isPrime,true);
isPrime[0]=false;
isPrime[1]=false;
for(int i=2;i*i<=n;i++)
{
for(int j=2*i;j<=n;j+=i)
{
isPrime[j]=false;
}
}
return isPrime;
}
//----------------------Modular_Exponentiation-------------------------
static long mod_expo(long a,long b,long n)
{
long res=1;
while(b>0)
{
if((b&1)!=0)
{res=(res*a%n)%n;}
a=(a%n*a%n)%n;
b=b>>1;
}
return res;
}
//-------------------------Power-----------------------------------------
static int fastpower(int a,int b)
{
int res=1;
while(b>0)
{
if((b&1)!=0)
res=res*a;
a=a*a;
b=b>>1;
}
return res;
}
//---------------------Modular_Arithmetic---------------------------------
public long modularSubtraction(long a,long b,long MOD) // Modular Subtraction
{ return (a%MOD-b%MOD+MOD)%MOD; }
public long modularMultiplication(long a,long b,long MOD) // Modular Multiplication
{ return ((a%MOD)*(b%MOD))%MOD; }
public long modularAddition(long a,long b,long MOD) // Modular Addition
{ return (a%MOD+b%MOD)%MOD; }
//-----------------------Binary_Searching-----------------------------------
public static int binarySearch(int arr[], int first, int last, int num)
{
int mid = (first + last) / 2;
while (first <= last)
{
if (arr[mid] < num) {first = mid + 1;}
else if (arr[mid] == num) {return mid;}
else {last = mid - 1;}
mid = (first + last) / 2;
}
return -1;
}
//-------------------------------------Node--------------------------------
static class Node<E>
{
protected E data;
protected Node link; //link====>next/linked address
public Node() {data=null; link=null;}
public Node(E d,Node n) {data=d; link=n;}
public void setLink(Node n) {link=n;}
public void setData(E d) {data=d;}
public Node getLink() {return link;}
public E getData() {return data;}
}
//--------------------------------------Aaagmlist-----------------------------
static class aagamList<E>
{
protected Node start;
protected Node end;
public int size;
public aagamList() {start=null;end=null;size=0;}
public boolean isEmpty() {return start==null;}
public int size() {return size;}
public E get(int pos)
{ Node<E> curr=start; int c=0;
while(curr!=null) {if(c==pos) return curr.data; c++; curr=curr.link;}
return null;}
public void push_lr(E val) { Node<E> cnode=new Node<>(val,null); cnode.link=start; start=cnode;}
public void prepend(E val)
{ Node<E> cnode=new Node<E>(val,null); size++;
if(start==null) {start=cnode;end=start;}
else {cnode.setLink(start);start=cnode;}
}
public void append(E val)
{ Node<E> cnode=new Node<E>(val,null); size++;
if(start==null) {start=cnode;end=start;}
else {end.setLink(cnode);end=cnode;}
}
public void insert(E val,int pos)
{ Node<E> cnode=new Node<>(val,null); Node temp=start; --pos;
for(int i=1;i<size;i++)
{ if(i==pos) {Node tmp=temp.getLink(); temp.setLink(cnode); cnode.setLink(tmp); break;}
temp=temp.getLink(); } size++;
}
public void remove(int pos)
{ if(pos==1) {start=start.getLink(); size--; return;}
if(pos==size) {Node s=start; Node t=start; while(s!=end) {t=s; s=s.getLink();}
end=t; end.setLink(null); size--; return;}
Node temp=start; --pos;
for(int i=0;i<size-1;i++)
{ if(i==pos) {Node tmp=temp.getLink(); tmp=tmp.getLink(); temp.setLink(tmp); break;}
temp=temp.getLink(); }size--;
}
public void display()
{ if(size==0) {System.out.println(" "); return;}
if(start.getLink()==null) {System.out.println(start.getData()); return;}
Node<E> temp=start; System.out.print(temp.getData()+" ");
temp=start.getLink();
while(temp.getLink()!=null) {System.out.print(temp.getData()+" "); temp=temp.getLink();}
System.out.print(temp.getData()+"\n");
}
}
//----------------------------------------Stack------------------------------
static class Astack<E>
{
aagamList<E> a=new aagamList<>();
public void push(E val) {a.append(val); return;}
public void pop() {a.remove(a.size()-1); return;}
public void display() {a.display(); return;}
}
//---------------------------------------Dequeue------------------------------
static class Adequeue<E>
{
aagamList<E> a=new aagamList<>();
public void push_f(E val) {a.prepend(val); return;}
public void push_b(E val) {a.append(val); return;}
public void pop_f() {a.remove(0); return;}
public void pop_b() {a.remove(a.size()-1); return;}
public void display() {a.display(); return;}
}
//-----------------------AagamReader_class------------------------------------
public static class AagamReader
{
BufferedReader br;
StringTokenizer st;
public AagamReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() //ReadNextToken
{
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()); } //ReadInt
long nextLong() { return Long.parseLong(next()); } //ReadLong
double nextDouble() { return Double.parseDouble(next());} //ReadDouble
int[] get_arr(int n) //ReadArray
{
int arr[]=new int [n];
for(int i=0;i<n;i++)
arr[i]= Integer.parseInt(next());
return arr;
}
String nextLine() //Readline
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
//=>->->->-->->->-[>>>>>>ENDING_WITH_HAPPY_CODING<<<<<<]-<-<-<-<-<-<-<-<-<-<=
| 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.util.*;
public class cowHaybales
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine().trim());
int t=Integer.parseInt(st.nextToken());
for(int e=1;e<=t;e++)
{
st=new StringTokenizer(br.readLine());
int n=Integer.parseInt(st.nextToken());
int d=Integer.parseInt(st.nextToken());
st=new StringTokenizer(br.readLine());
int sum=Integer.parseInt(st.nextToken());
for(int i=1;i<n;i++)
{
int a=Integer.parseInt(st.nextToken());
if(a*(i)<=d)
{
d=d-(a*i);
sum+=a;
}
else
{
sum+=d/i;
break;
}
}
System.out.println(sum);
}
}
} | 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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;
public class Main {
// static final File ip = new File("input.txt");
// static final File op = new File("output.txt");
// static {
// try {
// System.setOut(new PrintStream(op));
// System.setIn(new FileInputStream(ip));
// } catch (Exception e) {
// }
// }
public static void main(String[] args) {
FastReader sc = new FastReader();
int n = sc.nextInt();
long mod = sc.nextLong();
long[] fact = new long[n + 1];
fact[0] = 1;
for (int i = 1; i <= n; i++)
fact[i] = fact[i - 1] * i % mod;
long ret = 0;
for (int i = 1; i <= n; i++) {
ret += (n - i + 1) * (fact[i] * fact[n - i + 1] % mod);
ret %= mod;
}
System.out.println(ret);
}
static long power(long x, long y, long p) {
long res = 1;
x = x % p;
if (x == 0)
return 0;
while (y > 0) {
if ((y & 1) != 0)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static int countSetBits(long number) {
int count = 0;
while (number > 0) {
++count;
number &= number - 1;
}
return count;
}
static int lower_bound(long target, pair[] a, int pos) {
if (pos >= a.length)
return -1;
int low = pos, high = a.length - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (a[mid].a < target)
low = mid + 1;
else
high = mid;
}
return a[low].a >= target ? low : -1;
}
private static <T> void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static class pair {
long a;
int b;
pair(long x, int y) {
this.a = x;
this.b = y;
}
}
static class first implements Comparator<pair> {
public int compare(pair p1, pair p2) {
if (p1.a > p2.a)
return 1;
else if (p1.a < p2.a)
return -1;
return 0;
}
}
static class second implements Comparator<pair> {
public int compare(pair p1, pair p2) {
if (p1.b > p2.b)
return 1;
else if (p1.b < p2.b)
return -1;
return 0;
}
}
private static long getSum(int[] array) {
long sum = 0;
for (int value : array) {
sum += value;
}
return sum;
}
private static boolean isPrime(Long x) {
if (x < 2)
return false;
for (long d = 2; d * d <= x; ++d) {
if (x % d == 0)
return false;
}
return true;
}
static int[] reverse(int a[], int n) {
int i, k, t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
return a;
}
private static boolean isPrimeInt(int x) {
if (x < 2)
return false;
for (int d = 2; d * d <= x; ++d) {
if (x % d == 0)
return false;
}
return true;
}
public static String reverse(String input) {
StringBuilder str = new StringBuilder("");
for (int i = input.length() - 1; i >= 0; i--) {
str.append(input.charAt(i));
}
return str.toString();
}
private static int[] getPrimes(int n) {
boolean[] used = new boolean[n + 1];
used[0] = used[1] = true;
int size = 0;
for (int i = 2; i <= n; ++i) {
if (!used[i]) {
++size;
for (int j = 2 * i; j <= n; j += i) {
used[j] = true;
}
}
}
int[] primes = new int[size];
for (int i = 0, cur = 0; i <= n; ++i) {
if (!used[i]) {
primes[cur++] = i;
}
}
return primes;
}
private static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
private static long gcd(long a, long b) {
return (a == 0 ? b : gcd(b % a, a));
}
static void sortI(int[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
Arrays.sort(arr);
}
static void shuffleList(ArrayList<Long> arr) {
int n = arr.size();
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
long tmp = arr.get(i);
int randomPos = i + rnd.nextInt(n - i);
arr.set(i, arr.get(randomPos));
arr.set(randomPos, tmp);
}
}
static void factorize(long n) {
int count = 0;
while (!(n % 2 > 0)) {
n >>= 1;
count++;
}
if (count > 0) {
// System.out.println("2" + " " + count);
}
long i = 0;
for (i = 3; i <= (long) Math.sqrt(n); i += 2) {
count = 0;
while (n % i == 0) {
count++;
n = n / i;
}
if (count > 0) {
// System.out.println(i + " " + count);
}
}
if (n > 2) {
// System.out.println(i + " " + count);
}
}
static void sortL(long[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
long tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
Arrays.sort(arr);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public boolean hasNext() {
return false;
}
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 | 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 java.io.*;
import java.lang.*;
import java.util.*;
public class Main {
public static int mod = (int)1e9 + 7;
// **** -----> Disjoint Set Union(DSU) Start **********
public static int findPar(int node, int[] parent) {
if (parent[node] == node)
return node;
return parent[node] = findPar(parent[node], parent);
}
public static boolean union(int u, int v, int[] rank, int[] parent) {
u = findPar(u, parent);
v = findPar(v, parent);
if(u == v) return false;
if (rank[u] < rank[v])
parent[u] = v;
else if (rank[u] > rank[v])
parent[v] = u;
else {
parent[u] = v;
rank[v]++;
}
return true;
}
// **** DSU Ends ***********
//Pair with int int
public static class Pair{
public int a;
public int b;
Pair(int a , int b){
this.a = a;
this.b = b;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
public static String toBinary(int n) {return Integer.toBinaryString(n);}
public static boolean isPalindrome(String s) {int i = 0, j = s.length() - 1;while (i < j) {if (s.charAt(i) != s.charAt(j))return false;i++;j--;}return true;}
public static boolean isPalindrome(int[] arr) {int i = 0, j = arr.length - 1;while (i < j) {if (arr[i] != arr[j])return false;}return true;}
public static int pow(int x, int y) {int res = 1;x = x % mod;if (x == 0)return 0;while (y > 0) {if ((y & 1) != 0)res = (res * x) % mod;y = y >> 1;x = (x * x) % mod;}return res;}
public static int gcd(int a, int b) {if (b == 0)return a;return gcd(b, a % b);}
public static long gcd(long a, long b) {if (b == 0)return a;return gcd(b, a % b);}
public static void sort(long[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);long temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);}
public static void reverse(int a[]) {int i, k, t, n = a.length;for (i = 0; i < n / 2; i++) {t = a[i];a[i] = a[n - i - 1];a[n - i - 1] = t;}}
public static void sort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);}
public static void revSort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);reverse(a);}
public static long LCM(long a, long b) {if (a > b) {long t = a;a = b;b = t;}a /= gcd(a, b);return (a * b);}
public static int findMax(int[] a, int left, int right) {int res = left;int max = a[left];for (int i = left + 1; i <= right; i++) {if (a[i] > max) {max = a[i];res = i;}}return res;}
public static long findClosest(long arr[], long target) {int n = arr.length;if (target <= arr[0])return arr[0];if (target >= arr[n - 1])return arr[n - 1];int i = 0, j = n, mid = 0;while (i < j) {mid = (i + j) / 2;if (arr[mid] == target)return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];}
public static long getClosest(long val1, long val2, long target) {if (target - val1 >= val2 - target)return val2;else return val1;}
public static int findClosest(int arr[], int target) { int n = arr.length; if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];}
public static int getClosest(int val1, int val2, int target) {if (target - val1 >= val2 - target)return val2;else return val1;}
public static String reverse(String str) {StringBuilder sb = new StringBuilder(str);sb.reverse();return sb.toString();}
public static boolean isPrime(int n){if (n <= 1)return false;if (n <= 3)return true;if (n % 2 == 0 || n % 3 == 0)return false;for (int i = 5; i * i <= n; i = i + 6)if (n % i == 0 || n % (i + 2) == 0)return false;return true;}
public static int xorSum(int arr[], int n){int bits = 0;for (int i = 0; i < n; ++i)bits |= arr[i];int ans = bits * (int)Math.pow(2, n-1);return ans;}
public static ArrayList<Integer> primeFactors(int n) { ArrayList<Integer> res = new ArrayList<>();while (n%2 == 0) { res.add(2); n = n/2; } for (int i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;}
public static ArrayList<Long> primeFactors(long n) { ArrayList<Long> res = new ArrayList<>();while (n%2 == 0) { res.add(2L); n = n/2; } for (long i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;}
static int lower_bound(int array[], int low, int high, int key){
int mid;
while (low < high) {
mid = low + (high - low) / 2;
if (key <= array[mid]) high = mid;
else low = mid + 1;
}
if (low < array.length && array[low] < key) low++;
return low;
}
static long fastPower(long a, long b, long mod){
long ans = 1 ;
while (b > 0)
{
if ((b&1) != 0) ans = (ans%mod * a%mod) %mod;
b >>= 1 ;
a = (a%mod * a%mod)%mod ;
}
return ans ;
}
/********************************* Start Here ***********************************/
// int mod = 1000000007;
static HashMap<String, Integer> map;
static boolean[] vis;
public static void main(String[] args) throws java.lang.Exception {
if (System.getProperty("ONLINE_JUDGE") == null) {
PrintStream ps = new PrintStream(new File("output.txt"));
System.setOut(ps);
}
FastScanner sc = new FastScanner("input.txt");
StringBuilder result = new StringBuilder();
// sieveOfEratosthenes(1000000);
// int T = sc.nextInt();
int T = 1;
for(int test = 1; test <= T; test++){
String s = sc.next();
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0; i < s.length(); i++)
map.put(s.charAt(i), map.getOrDefault(s.charAt(i),0)+1);
long res = 1;
for(char ch : map.keySet()){
long n2 = map.get(ch);
res = Math.max(res, n2);
}
long[][] arr = new long[26][26];
map = new HashMap<>();
for(int i = 0; i < s.length(); i++){
int idx = s.charAt(i)-'a';
for(char ch = 'a'; ch <= 'z'; ch++){
arr[idx][ch-'a'] += map.getOrDefault(ch,0);
}
map.put(s.charAt(i), map.getOrDefault(s.charAt(i),0)+1);
}
for(int i = 0; i < 26; i++){
for(int j = 0; j < 26; j++) res = Math.max(res, arr[i][j]);
}
result.append(res+"\n");
}
System.out.println(result);
System.out.close();
}
public static int solve(List<List<Integer>> tree, int node, HashMap<String, Integer> map, boolean[]vis){
vis[node] = true;
if(tree.get(node).size() > 2) {
int i = 0;
for(int nb : tree.get(node)){
map.put(node+"-"+nb, i);
map.put(nb+"-"+node, i);
i++;
}
return i;
}
for(int nb : tree.get(node)){
if(!vis[nb]){
int i = solve(tree, nb, map,vis);
if(i != -1) return i;
}
}
return -1;
}
// static void sieveOfEratosthenes(int n){
// boolean prime[] = new boolean[n + 1];
// for (int i = 0; i <= n; i++)
// prime[i] = true;
// for (int p = 2; p * p <= n; p++){
// if (prime[p] == true){
// for (int i = p * p; i <= n; i += p)
// prime[i] = false;
// }
// }
// for (int i = 2; i <= n; i++){
// if (prime[i] == true)
// set.add(i);
// }
// }
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
if (st == null || !st.hasMoreTokens()) {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken("\n");
}
public String[] readStringArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = next();
}
return a;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
String next() {
return nextToken();
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] read2dArray(int n, int m) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextInt();
}
}
return a;
}
long[][] read2dlongArray(int n, int m) {
long[][] a = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextLong();
}
}
return a;
}
}
}
| java |
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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
public final class CFPS {
static FastReader fr = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static final int gigamod = 1000000007;
static final int mod = 998244353;
static int t = 1;
static boolean[] isPrime;
static int[] smallestFactorOf;
static final int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3;
static int cmp;
@SuppressWarnings({"unused"})
public static void main(String[] args) throws Exception {
OUTER:
for (int tc = 0; tc < t; tc++) {
int n = fr.nextInt();
int[] does1 = fr.nextIntArray(n);
int[] does2 = fr.nextIntArray(n);
// make upper win
int[] arr = new int[n];
Arrays.fill(arr, 1);
int sum1 = 0;
for (int i = 0; i < n; i++)
if (does1[i] > 0)
sum1++;
int sum2 = 0;
for (int i = 0; i < n; i++)
if (does2[i] > 0)
sum2++;
if (sum1 > sum2) {
out.println(1);
continue OUTER;
} else {
// we need to give this one more
// --
// we need to find the number of
// such places that ONE does but
// TWO doesn't
int toAdd = sum2 - sum1 + 1;
int plcCnt = 0;
for (int i = 0; i < n; i++)
if (does1[i] > 0 && does2[i] == 0)
plcCnt++;
if (plcCnt == 0) {
out.println(-1);
continue OUTER;
}
// we need to evenly have all those
// places add to our score
int eachPlcEat = toAdd / plcCnt;
toAdd -= eachPlcEat * plcCnt;
int maxVal = 1 + eachPlcEat;
if (toAdd != 0)
maxVal++;
out.println(maxVal);
}
}
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 |
1295 | F | F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3
1 2
1 2
1 2
OutputCopy499122177
InputCopy2
42 1337
13 420
OutputCopy578894053
InputCopy2
1 1
0 0
OutputCopy1
InputCopy2
1 1
1 1
OutputCopy1
NoteThe real answer in the first test is 1212. | [
"combinatorics",
"dp",
"probabilities"
] | //package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static class Task {
int mod = 998244353;
int add(int a, int b) {
int c = a + b;
if (c >= mod) return c - mod;
if (c < 0) return c + mod;
return c;
}
int mult(int a, int b) {
return (int) ((long) a * b % mod);
}
int pow(int a, int b) {
int r = 1;
while (b != 0) {
if (b % 2 == 1) r = mult(r, a);
a = mult(a, a);
b >>= 1;
}
return r;
}
private static final int N = 55;
private final int inv2 = pow(2, mod - 2);
int[] bernoli;
int[][] cnk;
int[] factorial;
int[] invfact;
void gen() {
bernoli = new int[N];
cnk = new int[N][N];
for (int i = 0; i < N; i++) {
cnk[i][0] = cnk[i][i] = 1;
}
for (int i = 2; i < N; i++) {
for (int j = 1; j < i; j++) {
cnk[i][j] = add(cnk[i - 1][j - 1], cnk[i - 1][j]);
}
}
factorial = new int[N];
invfact = new int[N];
factorial[0] = 1;
for (int i = 1; i < N; i++) {
factorial[i] = mult(i, factorial[i - 1]);
}
for (int i = 0; i < N; i++) {
invfact[i] = pow(factorial[i], mod - 2);
}
bernoli[0] = 1;
for (int m = 1; m < N; m++) {
int tmp = 0;
for (int k = 0; k < m; k++) {
int z = cnk[m][k];
z = mult(z, bernoli[k]);
z = mult(z, pow(m - k + 1, mod - 2));
tmp = add(tmp, z);
}
bernoli[m] = add(1, -tmp);
}
if (bernoli[1] != inv2) throw new RuntimeException();
}
public class Polynomial {
int[] coef;
public Polynomial(int[] coef) {
this.coef = coef;
if (coef.length != N) throw new RuntimeException();
}
int evalAt(int x) {
int r = 0;
for (int i = 0; i < coef.length; i++) {
r = add(r, mult(coef[i], pow(x, i)));
}
return r;
}
Polynomial integrate(int L) {
int[] newCoef = new int[N];
for (int m = 0; m < N; m++) {
for (int k = 0; k <= m; k++) {
if (m + 1 - k < N) {
int co = mult(factorial[m], invfact[k]);
co = mult(co, invfact[m + 1 - k]);
co = mult(co, bernoli[k]);
newCoef[m + 1 - k] = add(newCoef[m + 1 - k], mult(coef[m], co));
}
}
}
int invL = pow(L, mod - 2);
for (int i = 0; i < N; i++) {
newCoef[i] = mult(newCoef[i], invL);
}
return new Polynomial(newCoef);
}
void addFrom(Polynomial p) {
for (int i = 0; i < coef.length; i++) {
coef[i] = add(coef[i], p.coef[i]);
}
}
}
Polynomial uniform(int totalProb, int L) {
int[] coef = new int[N];
coef[1] = mult(totalProb, pow(L, mod - 2));
return new Polynomial(coef);
}
public class Segment {
int l, r;
Polynomial p;
public Segment(int l, int r, Polynomial p) {
this.l = l;
this.r = r;
this.p = p;
}
}
Segment[] get(List<Integer> breakDown) {
Segment[] probs = new Segment[breakDown.size() - 1];
for (int i = 0; i < breakDown.size() - 1; i++) {
probs[i] = new Segment(breakDown.get(i), breakDown.get(i + 1), new Polynomial(new int[N]));
}
return probs;
}
List<Integer> activeSegs(List<Integer> breakDown, int L, int R) {
List<Integer> ret = new ArrayList<>();
for (int i = 0; i < breakDown.size() - 1; i++) {
if (breakDown.get(i) >= L && breakDown.get(i + 1) <= R) {
ret.add(i);
}
}
return ret;
}
void checkFind(int p) {
for (int i = 1; i < 2000; i++) {
for (int j = i; j < 2000; j++) {
if (mult(i, pow(j, mod - 2)) == p) {
System.err.println("Found for " + p + ": " + i + "/" + j);
return;
}
}
}
System.err.println("Not Found " + p);
}
public void solve(Scanner sc, PrintWriter pw) throws IOException {
// checkFind(578894053);
// int p1 = mult(917, pow(1296, mod - 2));
// int p2 = mult(mult(379, pow(1296, mod - 2)), mult(29, pow(408, mod - 2)));
// int p3 = add(578894053, -add(p1, p2));
// int mp3 = mult(95, pow(648, mod - 2));
// System.err.println(add(p1, add(p2, mp3)));
// checkFind(add(578894053, -p1));
// checkFind(p3);
gen();
int n = sc.nextInt();
int[][] lr= new int[n][2];
TreeSet<Integer> critical = new TreeSet<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2; j++) {
lr[i][j] = sc.nextInt();
if (j == 1) lr[i][j]++;
critical.add(lr[i][j]);
}
}
List<Integer> breakDown = new ArrayList<>();
while (critical.size() > 0) {
breakDown.add(critical.first());
critical.pollFirst();
}
Segment[] segs = get(breakDown);
int tp = 0;
for (int i = 0; i < n; i++) {
List<Integer> active = activeSegs(breakDown, lr[i][0], lr[i][1]);
int LL = lr[i][1] - lr[i][0];
if (i == 0) {
for (int s: active) {
int sz = segs[s].r - segs[s].l;
segs[s].p = uniform(mult(pow(LL, mod - 2), sz), sz);
}
} else {
Segment[] nextSegs = get(breakDown);
for (Segment s: segs) {
if (s.p.evalAt(1) == 0) continue;
// System.err.println(s.l + " " + s.r);
// int zrf = 0;
for (int ss: active) {
if (segs[ss].r == s.r) {
Polynomial np = s.p.integrate(LL);
// System.err.println("adwdqwdqw");
// checkFind(np.evalAt(segs[ss].r - segs[ss].l));
nextSegs[ss].p.addFrom(np);
} else if (segs[ss].r < s.r) {
int totalProb = s.p.evalAt(s.r - s.l);
// System.err.println(s.l + " " + s.r + " " + segs[ss].l + " " + segs[ss].r);
// checkFind(totalProb);
// 917 / 1296 * (43 - 13) / (421 - 13)
Polynomial np = uniform(mult(totalProb, mult(pow(LL, mod - 2), segs[ss].r - segs[ss].l)), segs[ss].r - segs[ss].l);
// int ntf = np.evalAt(segs[ss].r - segs[ss].l);
// zrf = add(zrf, ntf);
nextSegs[ss].p.addFrom(np);
}
}
// checkFind(zrf);
}
segs = nextSegs;
}
tp = 0;
for (Segment ss: segs) {
tp = add(tp, ss.p.evalAt(ss.r - ss.l));
}
// System.err.println(tp);
// checkFind(tp);
}
pw.println(tp);
}
}
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("input"));
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
// PrintWriter pw = new PrintWriter(new FileOutputStream("input"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);
System.err.println("Time used: " + (TIME_END - TIME_START) + ".");
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | java |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
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.HashSet;
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);
DKuroniAndTheCelebration solver = new DKuroniAndTheCelebration();
solver.solve(1, in, out);
out.close();
}
static class DKuroniAndTheCelebration {
int n;
int m;
HashSet<Integer>[] g;
int[] dist;
boolean[] vis;
public void solve(int testNumber, InputReader in, OutputWriter out) {
pre(in);
// TreeSet<Pair> set= new TreeSet<>();
// for(int i=0;i<n;i++) set.add(new Pair(g[i].size(),i));
int curr = 0;
while (true) {
ArrayList<Integer> list = new ArrayList<>();
for (int a : g[curr]) list.add(a);
int s = list.size();
int val = -1;
for (int i = 1; i < s; i += 2) {
int x = query(list.get(i), list.get(i - 1), in);
g[curr].remove(list.get(i));
g[curr].remove(list.get(i - 1));
if (x != curr) {
val = x;
break;
}
}
if (val == -1 && s % 2 == 1) {
if (g[curr].size() == 1 && g[list.get(s - 1)].size() == 1) {
int x = query(curr, list.get(s - 1), in);
curr = x;
break;
} else {
curr = list.get(s - 1);
continue;
}
}
if (val == -1) break;
// set.remove(new Pair(g[curr].size(),curr));
// for(int a:g[curr]){
// set.remove(new Pair(g[a].size(),a));
// }
g[val].remove(curr);
curr = val;
// set.add(new Pair(g[val].size(),val));
}
System.out.println("! " + (curr + 1));
}
int query(int u, int v, InputReader in) {
System.out.println("? " + (u + 1) + " " + (v + 1));
return in.nextInt() - 1;
}
void pre(InputReader in) {
n = in.nextInt();
m = n - 1;
g = new HashSet[n];
dist = new int[n];
vis = new boolean[n];
for (int i = 0; i < n; i++) g[i] = new HashSet<>();
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1, b = in.nextInt() - 1;
if (a == b) continue;
g[a].add(b);
g[b].add(a);
}
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
}
}
| java |
1307 | A | A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Next 2t2t lines contain a description of test cases — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100) — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day. | [
"greedy",
"implementation"
] | import java.util.Scanner;
import java.util.Arrays;
public class CF1710{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
while(testCases>0){
int arrayLength = scan.nextInt();
int numberOfDays = scan.nextInt();
int[] array = new int[arrayLength];
for(int i=0; i<arrayLength; i++){
array[i] = scan.nextInt();
}
int totalHaysInFirstPile = array[0];
for(int i=1; i<array.length; i++){
if(array[i]>0){
int haysInCurrentArray = array[i];
if(numberOfDays >= i){
int haysToMove = numberOfDays/i;
if(haysToMove >= haysInCurrentArray){
totalHaysInFirstPile += haysInCurrentArray;
numberOfDays -= i*haysInCurrentArray;
}else{
totalHaysInFirstPile+=haysToMove;
break;
}
}
}
}
System.out.println(totalHaysInFirstPile);
testCases--;
}
}
} | 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"
] | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class CodeChef {
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();
long k = sc.nextLong();
int[] A = new int[n];
int[] B = new int[m];
for (int i = 0; i < n; i++) {
A[i] = sc.nextInt();
}
for (int i = 0; i < m; i++) {
B[i] = sc.nextInt();
}
long[] widths = consecutiveOnes(A);
long[] depths = consecutiveOnes(B);
long subRectangles = 0;
for (int i = 1; i < widths.length; i++) {
if (k % i == 0 && k / i <= m) {
subRectangles += widths[i] * depths[(int) k / i];
}
}
out.println(subRectangles);
}
private static long[] consecutiveOnes(int[] arr) {
int n = arr.length;
long[] res = new long[n + 1];
int i = 0;
while (i < n) {
if (arr[i] == 0) {
i++;
continue;
}
int j = i;
while (j < n && arr[j] == 1) {
j++;
}
for (int k = 0; k <= j - i; k++) {
res[k] += (j - i - k + 1);
}
i = j;
}
return res;
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | java |
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"
] | // package c1311;
//
// Codeforces Round #624 (Div. 3) 2020-02-24 06:35
// C. Perform the Combo
// https://codeforces.com/contest/1311/problem/C
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You want to perform the combo on your opponent in one popular fighting game. The combo is the
// string s consisting of n lowercase Latin letters. To perform the combo, you have to press all
// buttons in the order they appear in s. I.e. if s="abca" then you have to press 'a', then 'b', 'c'
// and 'a' again.
//
// You know that you will spend m wrong tries to perform the combo and during the i-th try you will
// make a mistake right after p_i-th button (1 <= p_i < n) (i.e. you will press first p_i buttons
// right and start performing the combo from the beginning). It is guaranteed that during the m+1-th
// try you press all buttons right and finally perform the combo.
//
// I.e. if s="abca", m=2 and p = [1, 3] then the sequence of pressed buttons will be 'a' ( you're
// making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', ( you're
// making a mistake and start performing the combo from the beginning), 'a' (), 'b', 'c', 'a'.
//
// Your task is to calculate for each button (letter) the number of times you'll press it.
//
// You have to answer t independent test cases.
//
// Input
//
// The first line of the input contains one integer t (1 <= t <= 10^4) -- the number of test cases.
//
// Then t test cases follow.
//
// The first line of each test case contains two integers n and m (2 <= n <= 2 * 10^5, 1 <= m <= 2 *
// 10^5) -- the length of s and the number of tries correspondingly.
//
// The second line of each test case contains the string s consisting of n lowercase Latin letters.
//
// The third line of each test case contains m integers p_1, p_2, ..., p_m (1 <= p_i < n) -- the
// number of characters pressed right during the i-th try.
//
// It is guaranteed that the sum of n and the sum of m both does not exceed 2 * 10^5 (\sum n <= 2 *
// 10^5, \sum m <= 2 * 10^5).
//
// It is guaranteed that the answer for each letter does not exceed 2 * 10^9.
//
// Output
//
// For each test case, print the answer -- 26 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'.
//
// Example
/*
input:
3
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
output:
4 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
*/
// Note
//
// The 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 4, 'b' is 2 and 'c' is 2.
//
// 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 9, 'd' is 4, 'e' is 5,
// 'f' is 3, 'o' is 9, 'r' is 3 and 's' is 1.
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1311C {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int[] solve(String s, int[] p) {
int n = s.length();
int m = p.length;
int[] ans = new int[26];
int[][] precnt = new int[n + 1][26];
for (int i = 1; i <= n; i++) {
for (int j = 0; j < 26; j++) {
precnt[i][j] = precnt[i-1][j];
}
int id = s.charAt(i-1) - 'a';
precnt[i][id]++;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < 26; j++) {
ans[j] += precnt[p[i]][j];
}
}
for (int j = 0; j < 26; j++) {
ans[j] += precnt[n][j];
}
return ans;
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int m = in.nextInt();
String s = in.next();
int[] p = new int[m];
for (int i = 0; i < m; i++) {
p[i] = in.nextInt();
}
int[] ans = solve(s, p);
output(ans);
}
}
static void output(int[] a) {
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
}
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 |
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.*;
/*
4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
*/
public class sequenceTransformation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t > 0) {
int n = scan.nextInt();
int sum=0;
int ret=0;
int[] arr = new int[n];
for(int i=0;i<n;i++){
arr[i]=scan.nextInt();
if(arr[i]==0){
ret++;
arr[i]=1;
}
sum+=arr[i];
}
int i=0;
while(sum==0){
if(arr[i]>0){
arr[i]++;
ret++;
sum=1;
}
i++;
}
System.out.println(ret);
t--;
}
}
}
| java |
1288 | A | A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days. | [
"binary search",
"brute force",
"math",
"ternary search"
] |
import java.util.Scanner;
public class A1288 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
while (t > 0) {
int n = scn.nextInt();
int d = scn.nextInt();
if (d <= n || binarySearch(n, d)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
t--;
}
}
public static int func(int x, int d) {
return x + (int) Math.ceil((double) d / (x + 1));
}
public static boolean binarySearch(int n, int days) {
int left = 0;
int right = n;
while (left <= right) {
int mid = (left + right) / 2;
int resDays = func(mid, days);
if (resDays <= n) {
return true;
}
left = mid + 1;
}
return false;
}
} | 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.*;
import java.lang.*;
import java.io.*;
public class CF_018 {
static PrintWriter out;
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}
String next(){
while(st==null || !st.hasMoreElements()){
try{
st= new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str=br.readLine();
}
catch(IOException e){
e.printStackTrace();
}
return str;
}
}
public static ArrayList<Integer> allFactors(int n) {
ArrayList<Integer> list = new ArrayList<>() ;
for(int i = 1; i*i <= n ;i++) {
if( n % i == 0) {
if(i*i == n)
list.add(i) ;
else{
list.add(i) ;
list.add(n/i) ;
}
}
}
return list ;
}
public static void main (String[] args) throws java.lang.Exception
{
FastReader scn = new FastReader() ;
ArrayList<Integer> list = new ArrayList<>() ;
int t = scn.nextInt() ;
while(t-- > 0)
{
String s = scn.next() ;
list.add(0) ;
for(int i =0 ; i < s.length() ; i++ )
{
if(s.charAt(i)=='R')
{
list.add(i+1) ;
}
}
list.add(s.length()+1 ) ;
int max = list.get(1) - list.get(0);
for(int i = 2; i < list.size() ;i++ )
{
if(list.get(i)-list.get(i-1)> max )
{
max = list.get(i)-list.get(i-1) ;
}
}
out.println(max) ;
//out.println(list) ;
list.clear();
}
out.flush() ;
}
} | java |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DCountTheArrays solver = new DCountTheArrays();
solver.solve(1, in, out);
out.close();
}
static class DCountTheArrays {
int n;
int m;
int mod = 998244353;
int N = (int) (2e5 + 5);
long[] fact = new long[N];
long[] infact = new long[N];
public void solve(int testNumber, InputReader in, OutputWriter out) {
fact();
n = in.nextInt();
m = in.nextInt();
long res = 0;
long base = (n - 2) * c(m, n - 1) % mod;
for (int i = 2; i <= n - 1; i++) {
res = (res + base * (c(n - 3, i - 2))) % mod;
}
out.println(res);
}
private long c(int a, int b) {
return fact[a] * infact[b] % mod * infact[a - b] % mod;
}
void fact() {
fact[0] = infact[0] = 1;
for (int i = 1; i < N; i++) {
fact[i] = fact[i - 1] * i % mod;
infact[i] = infact[i - 1] * qmi(i, mod - 2, mod) % mod;
}
}
int qmi(int m, int k, int p) {
long res = 1 % p, t = m;
while (k > 0) {
if ((k & 1) == 1) {
res = res * t % p;
}
t = t * t % p;
k >>= 1;
}
return (int) res % p;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| java |
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 static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import javax.xml.transform.stax.StAXResult;
import java.io.*;
import java.math.*;
public class B_Hyperset {
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 k = f.nextInt();
String s[] = new String[n];
HashSet<String> hs = new HashSet<>();
for(int i = 0; i < n; i++) {
s[i] = f.nextLine();
hs.add(s[i]);
}
char freature[] = {'S', 'E', 'T'};
int ans = 0;
for(int i = 0; i < n; i++) {
String s1 = s[i];
for(int j = i+1; j < n; j++) {
String s2 = s[j];
StringBuilder sb = new StringBuilder();
for(int l = 0; l < k; l++) {
if(s1.charAt(l) == s2.charAt(l)) {
sb.append(s1.charAt(l));
} else {
for(int c = 0; c < 3; c++) {
if(freature[c] != s1.charAt(l) && freature[c] != s2.charAt(l)) {
sb.append(freature[c]);
}
}
}
}
if(hs.contains(sb.toString())) {
ans++;
// out.println(i);
}
}
}
ans /= 3;
out.println(ans);
}
// Sort an array
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
// Find all divisors of n
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
// Check if n is prime or not
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
// Find gcd of a and b
public static long gcd(long a, long b) {
long dividend = a > b ? a : b;
long divisor = a < b ? a : b;
while(divisor > 0) {
long reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
// Find lcm of a and b
public static long lcm(long a, long b) {
long lcm = gcd(a, b);
long hcf = (a * b) / lcm;
return hcf;
}
// Find factorial in O(n) time
public static long fact(int n) {
long res = 1;
for(int i = 2; i <= n; i++) {
res = res * i;
}
return res;
}
// Find power in O(logb) time
public static long power(long a, long b) {
long res = 1;
while(b > 0) {
if((b&1) == 1) {
res = (res * a)%mod;
}
a = (a * a)%mod;
b >>= 1;
}
return res;
}
// Find nCr
public static long nCr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / (fact(r) * fact(n-r));
return ans;
}
// Find nPr
public static long nPr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / fact(r);
return ans;
}
// sort all characters of a string
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// User defined class for fast I/O
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
boolean hasNext() {
if (st != null && st.hasMoreTokens()) {
return true;
}
String tmp;
try {
br.mark(1000);
tmp = br.readLine();
if (tmp == null) {
return false;
}
br.reset();
} catch (IOException e) {
return false;
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
// (a/b)%mod == (a * moduloInverse(b)) % mod;
// moduloInverse(b) = power(b, mod-2);
| java |
1311 | 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 ProblemB {
static int ans = Integer.MAX_VALUE;
static int n,m,x,y,d;
public static void main(String[] args) throws Exception {
Scanner in = new Scanner();
int test = in.readInt();
StringBuilder sb = new StringBuilder();
while(test-->0){
int a = in.readInt();
int b =in.readInt();
int c = in.readInt();
int ans = Integer.MAX_VALUE;
int res[] = new int[3];
for(int i =1;i<=2*a;i++){
for(int j =i;j<=2*b;j+=i){
int t = (c/j)*j;
int cur = Math.abs(a-i)+Math.abs(b-j)+Math.abs(c-t);
if(ans>cur){
ans = cur;
res[0] = i;res[1]=j;res[2]=t;
}
t+=j;
cur = Math.abs(a-i)+Math.abs(b-j)+Math.abs(c-t);
if(ans>cur){
ans = cur;
res[0] = i;res[1]=j;res[2]=t;
}
}
}
sb.append(ans+"\n");
sb.append(res[0]+" "+res[1]+" "+res[2]+"\n");
}
System.out.println(sb);
}
public static ArrayList<Integer> factors(int n){
ArrayList<Integer>l = new ArrayList<>();
for(int i = 1;i*i<=n;i++){
if(n%i == 0){
l.add(i);
if(n/i != i)l.add(n/i);
}
}
return l;
}
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 |
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 Main {
static int[] parent, size;
public static void main(String[] args) throws IOException {
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
char[] temp = sc.next().toCharArray();
int[] arr = new int[n];
Arrays.fill(arr, 1);
if (temp[0] == '<')
arr[0] = -1;
if (temp[n - 2] == '>')
arr[n - 1] = -1;
for (int i = 1; i < temp.length; i++) {
if (temp[i - 1] == '>')
arr[i] = -1;
}
int[] p = new int[n];
for (int i = 0; i < p.length; i++) {
p[i] = i + 1;
}
int ones = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 1)
ones++;
}
int[] max = new int[n];
int l = 0;
int r = ones;
for (int i = 0; i < arr.length;) {
int count = get(arr, i);
int last = i + count;
if (arr[i] < 0) {
for (int j = last; j >= i; j--) {
max[j] = p[l++];
}
} else {
for (int j = i; j <= last; j++) {
max[j] = p[r++];
}
}
i += count + 1;
}
int[] min = new int[n];
ones = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != -1)
ones++;
}
l = n - ones - 1;
r = n - 1;
for (int i = 0; i < arr.length;) {
int count = get(arr, i);
int last = i + count;
if (arr[i] < 0) {
for (int j = i; j <= last; j++) {
min[j] = p[l--];
}
} else {
for (int j = last; j >= i; j--) {
min[j] = p[r--];
}
}
i += count + 1;
}
print(min);
print(max);
}
pw.close();
}
static int get(int[] arr, int idx) {
int res = 0;
for (int i = idx + 1; i < arr.length; i++) {
if (arr[i] == arr[i - 1])
res++;
else
break;
}
return res;
}
static ArrayList<Integer> getDivisors(ArrayList<Pair> list) {
ArrayList<Integer> res = new ArrayList<>();
res.add(1);
for (Pair p : list) {
int num = (int) p.x;
int count = (int) p.y;
int size = res.size();
int mul = num;
while (count > 0) {
for (int i = 0; i < size; i++) {
res.add(mul * res.get(i));
}
count--;
mul *= num;
}
}
return res;
}
static ArrayList<Pair> getPrimeFactors(int[] arr, int num) {
ArrayList<Pair> list = new ArrayList<>();
while (num > 1) {
if (list.isEmpty() || list.get(list.size() - 1).x != arr[num])
list.add(new Pair(arr[num], 0));
list.get(list.size() - 1).y++;
num /= arr[num];
}
return list;
}
static void DSU(int n) {
parent = new int[n + 1];
size = new int[n + 1];
for (int i = 1; i < parent.length; i++) {
parent[i] = i;
size[i] = 1;
}
}
static int find(int a) {
if (a == parent[a])
return a;
return parent[a] = find(parent[a]);
}
static void union(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
if (size[a] < size[b]) {
parent[a] = b;
size[b] += size[a];
} else {
parent[b] = a;
size[a] += size[b];
}
}
static long[] HashStr(char[] arr) {
long[] hash = new long[arr.length];
int p = 31;
int m = 1000000007;
long hashValue = 0;
long power = 1;
for (int i = 0; i < arr.length; i++) {
hashValue = (hashValue + (arr[i] - 'a' + 1) * power) % m;
power = (power * p) % m;
hash[i] = hashValue;
}
return hash;
}
static long compute_hash(char[] s) {
long p = 31;
long m = 1000000007;
long hash_value = 0;
long p_pow = 1;
for (char c : s) {
hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;
p_pow = (p_pow * p) % m;
}
return hash_value;
}
static int toInt(boolean flag) {
return flag ? 1 : 0;
}
static int log2(int n) {
return (int) (Math.log(n) / Math.log(2));
}
static int[] sieve() {
int n = (int) 2e5 + 55;
int[] arr = new int[n];
for (int i = 2; i < arr.length; i++) {
for (int j = i; j < arr.length; j += i) {
if (arr[j] == 0)
arr[j] = i;
}
}
return arr;
}
static void shuffle(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
}
static void sort(int[] arr) {
shuffle(arr);
Arrays.sort(arr);
}
static long getSum(int[] arr) {
long sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
static int getMin(int[] arr) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
min = Math.min(min, arr[i]);
}
return min;
}
static int getMax(int[] arr) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
max = Math.max(max, arr[i]);
}
return max;
}
static boolean isEqual(int[] a, int[] b) {
if (a.length != b.length)
return false;
for (int i = 0; i < b.length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
static void swap(char[] arr, int a, int b) {
char temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
static void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1])
return false;
}
return true;
}
static long gcd(long x, long y) {
if (x == 0)
return y;
return gcd(y % x, x);
}
static long lcm(long a, long b) {
return (1l * a * b) / gcd(a, b);
}
static ArrayList<Integer>[] Graph(int n) {
ArrayList<Integer>[] graph = new ArrayList[n + 1];
for (int i = 1; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
return graph;
}
static HashMap<Integer, Integer> getFrequency(int[] arr) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i : arr) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
return map;
}
static HashMap<Character, Integer> Hash(char[] arr) {
HashMap<Character, Integer> map = new HashMap<>();
for (char i : arr) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
return map;
}
static boolean isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0)
return false;
return true;
}
public static long combination(long n, long r) {
return factorial(n) / (factorial(n - r) * factorial(r));
}
static long factorial(Long n) {
if (n == 0)
return 1;
return (n % mod) * (factorial(n - 1) % mod) % mod;
}
static boolean isPalindrome(char[] str, int i, int j) {
while (i < j) {
if (str[i] != str[j])
return false;
i++;
j--;
}
return true;
}
public static int setBit(int mask, int idx) {
return mask | (1 << idx);
}
public static boolean checkBit(int mask, int idx) {
return (mask & (1 << idx)) != 0;
}
public static long setBit(long mask, int idx) {
return mask | (1l << idx);
}
public static boolean checkBit(long mask, int idx) {
return (mask & (1l << idx)) != 0;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntCharArray() throws IOException {
char[] b = sc.next().toCharArray();
int n = b.length;
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = b[i] - '0';
return a;
}
public int[] NextIntArray(int n) throws IOException {
int[] arr = new int[n + 1];
for (int i = 1; i < arr.length; i++) {
arr[i] = nextInt();
}
return arr;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public ArrayList<Integer>[] directedGraph(int n, int m) throws IOException {
ArrayList<Integer>[] graph = new ArrayList[n + 1];
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
while (m-- > 0) {
int a = nextInt();
int b = nextInt();
graph[a].add(b);
}
return graph;
}
public ArrayList<Integer>[] undirectedGraph(int n, int m) throws IOException {
ArrayList<Integer>[] graph = new ArrayList[n + 1];
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
while (m-- > 0) {
int a = nextInt();
int b = nextInt();
graph[a].add(b);
graph[b].add(a);
}
return graph;
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class Pair implements Comparable<Pair> {
long x;
long y;
public Pair(long x, long y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}
public int compareTo(Pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
public static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
public static void print(int[] arr, String separator) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + separator);
}
pw.println();
}
public static void print(long[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
public static void print(ArrayList arr) {
for (int i = 0; i < arr.size(); i++) {
pw.print(arr.get(i) + " ");
}
pw.println();
}
public static void print(int[][] arr) {
for (int[] i : arr) {
print(i);
}
}
public static void print(boolean[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
public static void print(char[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
}
static int inf = 1000000000;
static long mod = 1000000007;
static Random rn = new Random();
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
} | java |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
String str = sc.next();
System.out.println(ebne(str,n));
}
}
public static String ebne(String str,int n){
int count=0;
String s = new String();
for(int i=0;i<n && count<2;i++){
if((str.charAt(i)-'0') %2 != 0){
s+= str.charAt(i);
count++;
}
}
if(count==2)
return s;
return "-1";
}
} | java |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | import java.util.*;
public class Add{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++){
long a,b,c,d;
a=d=0;
c=0;
a=sc.nextLong();
b=sc.nextLong();
if(a==b){
System.out.println("0");
continue;
}
if(a>b){
d=a-b;
c++;
if(d%2!=0){
c++;
}
}
else if(a<b){
d=b-a;
c++;
if(d%2!=1){
c++;
}
}
System.out.println(c);
}
}
} | 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"
] | // Don't place your source in a package
import javax.swing.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.stream.Stream;
// Please name your class Main
public class Main {
static FastScanner fs=new FastScanner();
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int Int() {
return Integer.parseInt(next());
}
long Long() {
return Long.parseLong(next());
}
String Str(){
return next();
}
}
public static void main (String[] args) throws java.lang.Exception {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//reading /writing file
//Scanner sc=new Scanner(new File("src/text.txt"));
//PrintWriter pr=new PrintWriter("output.txt");
//File file = new File("src/text.txt");
int T=1;
for(int t=0;t<T;t++){
Solution sol1=new Solution(out,fs);
sol1.solution();
}
out.flush();
}
public static int[] Arr(int n){
int A[]=new int[n];
for(int i=0;i<n;i++)A[i]=Int();
return A;
}
public static int Int(){
return fs.Int();
}
public static long Long(){
return fs.Long();
}
public static String Str(){
return fs.Str();
}
}
class Solution {
PrintWriter out;
int INF = 10000000;
int MOD = 998244353;
int mod = 1000000007;
Main.FastScanner fs;
public Solution(PrintWriter out,Main.FastScanner fs) {
this.out = out;
this.fs=fs;
}
public void solution() {
int MAX = 30000 + 10;
TreeSet<Integer>trees[]=new TreeSet[MAX+1];
for(int i = 1; i <= MAX;i++){
trees[i] = new TreeSet<>();
for(int j = i; j <= MAX; j += i){
trees[i].add(j);
}
}
int t = fs.Int();
while(t>0){
t--;
int a = fs.Int();
int b = fs.Int();
int c = fs.Int();
int x = -1, y = -1, z = -1;
int res = Integer.MAX_VALUE;
for(int i = 1; i <= MAX;i++){
int dif1 = Math.abs(i-a);
if(dif1>res)continue;
for(int j = i; j <= MAX; j+=i){
int dif2 = Math.abs(j-b);
if(dif1+dif2>res)continue;
TreeSet<Integer>tree=trees[j];
Integer lo = tree.floor(c);
Integer hi = tree.ceiling(c);
int dif3 = 1000000;
if(lo!=null){
int sum = dif1 + dif2 + Math.abs(lo-c);
if(sum<res){
res = sum;
x = i;
y = j;
z = lo;
}
}
if(hi!=null){
int sum = dif1 + dif2 + Math.abs(hi-c);
if(sum<res){
res = sum;
x = i;
y = j;
z = hi;
}
}
}
}
out.println(res);
out.println(x+" "+y+" "+z);
}
}
}
| java |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | import 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_Array_Sharpening {
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = f.nextInt();
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
int n = f.nextInt();
int arr[] = f.nextArray(n);
if(n == 1) {
out.println("Yes");
return;
}
int ind1 = -1;
for(int i = 0; i < n; i++) {
if(arr[i] < i) {
break;
}
ind1 = i;
}
int ind2 = n;
for(int i = n-1; i >= 0; i--) {
if(arr[i] < n-i-1) {
break;
}
ind2 = i;
}
if(ind1 >= ind2) {
out.println("Yes");
} else {
out.println("No");
}
}
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
public static int gcd(int a, int b) {
int dividend = a > b ? a : b;
int divisor = a < b ? a : b;
while(divisor > 0) {
int reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
public static int lcm(int a, int b) {
int lcm = gcd(a, b);
int hcf = (a * b) / lcm;
return hcf;
}
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
| java |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | import java.io.*;
import java.util.*;
public class cf {
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static boolean isok(long x, long h, long k) {
long sum = 0;
if (h > k) {
long t1 = h - k;
long t = t1 * k;
sum += (k * (k + 1)) / 2;
sum += t - (t1 * (t1 + 1) / 2);
} else {
sum += (h * (h + 1)) / 2;
}
if (sum < x) {
return true;
}
return false;
}
public static boolean binary_search(long[] a, long k) {
long low = 0;
long high = a.length - 1;
long mid = 0;
while (low <= high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == k) {
return true;
} else if (a[(int) mid] < k) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;
}
public static long lowerbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid] == ddp) {
return mid;
}
if (a[(int) mid] < ddp) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
if (low == a.length && low != 0) {
low--;
return low;
}
if (a[(int) low] > ddp && low != 0) {
low--;
}
return low;
}
public static long upperbound(long a[], long ddp) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid] <= ddp) {
low = mid + 1;
} else {
high = mid;
}
}
if (low == a.length) {
return a.length - 1;
}
return low;
}
// public static class pair implements Comparable<pair> {
// long w;
// long h;
// public pair(long w, long h) {
// this.w = w;
// this.h = h;
// }
// public int compareTo(pair b) {
// if (this.w != b.w)
// return (int) (this.w - b.w);
// else
// return (int) (this.h - b.h);
// }
// }
public static class pair {
long w;
long h;
public pair(long w, long h) {
this.w = w;
this.h = h;
}
}
public static class trinary {
long a;
long b;
long c;
public trinary(long a, long b, long c) {
this.a = a;
this.b = b;
this.c = c;
}
}
public static long lowerboundforpairs(pair a[], long pr) {
long low = 0;
long high = a.length;
long mid = 0;
while (low < high) {
mid = low + (high - low) / 2;
if (a[(int) mid].w <= pr) {
low = mid + 1;
} else {
high = mid;
}
}
// if(low + 1 < a.length && a[(int)low + 1] <= ddp){
// low++;
// }
// if(low == a.length && low != 0){
// low--;
// return low;
// }
// if(a[(int)low].w > pr && low != 0){
// low--;
// }
return low;
}
public static pair[] sortpair(pair[] a) {
Arrays.sort(a, new Comparator<pair>() {
public int compare(pair p1, pair p2) {
return (int) p1.w - (int) p2.w;
}
});
return a;
}
public static boolean ispalindrome(String s) {
long i = 0;
long j = s.length() - 1;
boolean is = false;
while (i < j) {
if (s.charAt((int) i) == s.charAt((int) j)) {
is = true;
i++;
j--;
} else {
is = false;
return is;
}
}
return is;
}
public static void sort(long[] arr) {
ArrayList<Long> a = new ArrayList<>();
for (long i : arr) {
a.add(i);
}
Collections.sort(a);
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
public static void sortForObjecttypes(pair[] arr) {
ArrayList<pair> a = new ArrayList<>();
for (pair i : arr) {
a.add(i);
}
Collections.sort(a, new Comparator<pair>() {
@Override
public int compare(pair a, pair b) {
return (int) (a.h - b.h);
}
});
for (int i = 0; i < a.size(); i++) {
arr[i] = a.get(i);
}
}
public static long power(long base, long pow, long mod) {
long result = base;
long temp = 1;
while (pow > 1) {
if (pow % 2 == 0) {
result = ((result % mod) * (result % mod)) % mod;
pow /= 2;
} else {
temp = temp * base;
pow--;
}
}
result = ((result % mod) * (temp % mod));
// System.out.println(result);
return result;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void readArr(int[] ar, int n) {
for (int i = 0; i < n; i++) {
ar[i] = nextInt();
}
}
}
public static void solve(FastReader sc, PrintWriter w) throws Exception {
int n = sc.nextInt();
int m = sc.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int id[] = new int[n];
for (int i = 0; i < m; i++) {
int t = sc.nextInt();
id[t - 1] = 1;
}
boolean is = false;
while (true) {
is = false;
for (int i = 0; i < n - 1; i++) {
if (id[i] == 1 && a[i] > a[i + 1]) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
is = true;
}
}
if (!is) {
break;
}
}
is = true;
for (int i = 0; i < n - 1; i++) {
is &= a[i] <= a[i + 1];
}
if (is) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter w = new PrintWriter(System.out);
long o = sc.nextLong();
while (o > 0) {
solve(sc, w);
o--;
}
w.close();
}
} | java |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
public class UWI {
//#0.00代表保留两位小数
static DecimalFormat df = new DecimalFormat("#0.00000000");
void solve() {
for (int T = 1; T > 0; T--) go();
}
int n, m;
void go() {
n = ni();
m = ni();
int[][] nums = new int[n][];
for (int i = 0; i < n; i++) {
nums[i] = na(m);
}
int l = 0, r = 1000_000_000;
while (l < r) {
int mid = l + r + 1 >> 1;
if (check(mid, nums)) l = mid;
else r = mid - 1;
}
out.println(r1 + " " + r2);
}
int r1 = 1, r2 = 1;
boolean check(int min, int[][] nums) {
var map = new HashMap<Integer, Integer>();//s,row
for (int i = 0; i < n; i++) {
int[] row = nums[i];
int s = 0;
for (int j = 0; j < m; j++) {
s <<= 1;
if (row[j] >= min) s++;
}
map.put(s, i);
}
for (int s1 : map.keySet())
for (int s2 : map.keySet())
if ((s1 | s2) == (1 << m) - 1) {
r1 = map.get(s1)+1;
r2 = map.get(s2)+1;
return true;
}
return false;
}
public static void main(String[] args) throws Exception {
new UWI().run();
}
void run() throws Exception {
if (INPUT.length() > 0)
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
else is = oj ? System.in : new ByteArrayInputStream(new FileInputStream("input/a.test").readAllBytes());
out = new FastWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis() - s + "ms");
}
InputStream is;
FastWriter out;
String INPUT = "";
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 String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(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;
}
//int
private int ni() {
return (int) nl();
}
//long
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 final boolean oj = !local();
boolean local() {
try {
String user = System.getProperty("user.name");
return user.contains("dpz");
} catch (Exception ignored) {
}
return false;
}
//调试的时候打印
private void tr(Object... o) {
if (!oj) System.out.println(Arrays.deepToString(o));
}
}
| java |
1286 | B | B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2
| [
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/*
1
2 3
*/
public class B {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
int n=fs.nextInt();
Node[] nodes=new Node[n];
for (int i=0; i<n; i++) nodes[i]=new Node(i);
Node root=null;
for (int i=0; i<n; i++) {
int par=fs.nextInt()-1;
if (par==-1) root=nodes[i];
else {
nodes[i].par=nodes[par];
nodes[i].par.children.add(nodes[i]);
}
int indeg=fs.nextInt();
nodes[i].indeg=indeg;
}
root.dfs(0);
PriorityQueue<Node> ready=new PriorityQueue<>();
int curLabel=1;
for (Node nn:nodes) {
if (nn.indeg==0) ready.add(nn);
}
while (!ready.isEmpty()) {
Node next=ready.remove();
// System.out.println("Processing "+next.index);
next.process(ready, curLabel++);
}
for (Node nn:nodes) {
if (nn.label==-1) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
for (Node nn:nodes) {
System.out.print(nn.label+" ");
}
System.out.println();
}
static class Node implements Comparable<Node> {
Node par;
int label=-1;
int indeg=0;
int depth;
ArrayList<Node> children=new ArrayList<>();
int index;
public Node(int index) {
this.index=index;
}
public void dfs(int depth) {
this.depth=depth;
for (Node n:children)
n.dfs(depth+1);
}
public void process(PriorityQueue<Node> toAddTo, int curLabel) {
this.label=curLabel;
Node curPar=par;
while (curPar!=null) {
curPar.indeg--;
if (curPar.indeg==0) toAddTo.add(curPar);
curPar=curPar.par;
}
}
public int compareTo(Node o) {
return Integer.compare(depth, o.depth);
}
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
| java |
1299 | A | A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer. | [
"brute force",
"greedy",
"math"
] | import java.util.Scanner;
public class E1299A {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
int n = scn.nextInt();
int[] arr = new int[n];
int[] prefix = new int[n + 1];
int[] suffix = new int[n + 1];
suffix[n] = prefix[0] = -1;
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
prefix[i + 1] = prefix[i] & ~arr[i];
}
for (int i = n - 1; i >= 0; i--) {
suffix[i] = suffix[i + 1] & ~arr[i];
}
int max = 0;
int ind = 0;
for (int i = 0; i < n; i++) {
int f = arr[i] & prefix[i] & suffix[i + 1];
if (max < f) {
ind = i;
max = f;
}
}
sb.append(arr[ind]);
sb.append(" ");
for (int i = 0; i < n; i++) {
if (i == ind) continue;
sb.append(arr[i]);
sb.append(" ");
}
System.out.println(sb);
}
}
| java |
1301 | C | C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement. | [
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] | import java.io.*;
import java.util.*;
public class CF1301C extends PrintWriter {
CF1301C() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1301C o = new CF1301C(); o.main(); o.flush();
}
void main() {
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int q = (n - m) / (m + 1);
int r = (n - m) % (m + 1);
long ans = (long) n * (n + 1) / 2;
long a0 = (long) q * (q + 1) / 2;
long a1 = (long) (q + 1) * (q + 2) / 2;
ans -= (m + 1 - r) * a0 + r * a1;
println(ans);
}
}
} | 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.System.out;
import static java.lang.Math.*;
import static java.lang.System.*;
import java.lang.reflect.Array;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static FastReader sc;
static long mod=((long)1e9)+7;
// static FastWriter out;
static FastWriter out;
public static void main(String hi[]) throws IOException {
// initializeIO();
out=new FastWriter();
sc=new FastReader();
long startTimeProg=System.currentTimeMillis();
long endTimeProg=Long.MAX_VALUE;
int t=sc.nextInt();
// int t=1;
// boolean[] seave=sieveOfEratosthenes((int)(1e5));
// int[] seave2=sieveOfEratosthenesInt((int)(1e5));
while(t--!=0) {
int n=sc.nextInt();
String s=sc.next();
String res_s=s;
int res=1;
for(int i=0;i<n;i++){
int k=i+1;
StringBuilder sb=new StringBuilder();
sb.append(s.substring(i,n));
if(n%2!=0){
if(k%2==0){
sb.append(s.substring(0,i));
}else{
sb.append(reverseString(s.substring(0,i)));
}
}else{
if(k%2==0){
sb.append(reverseString(s.substring(0,i)));
}else{
sb.append(s.substring(0,i));
}
}
boolean done=false;
if(sb.toString().compareTo(res_s)<0){
done=true;
}
if(done){
res_s=sb.toString();
res=k;
}
}
print(res_s+"\n"+res);
// break;
}
endTimeProg=System.currentTimeMillis();
debug("[finished : "+(endTimeProg-startTimeProg)+".ms ]");
// System.out.println(String.format("%.9f", max));
}
private static List<Long> factors2(long n){
List<Long> res=new ArrayList<>();
// res.add(n);
for (long i=2; i*i<(n); i++){
if (n%i==0){
if(i%2!=0)res.add(i);
if (n/i != i){
if((n/i)%2!=0)res.add(n/i);
}
}
}
return res;
}
public static boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
private static boolean isSorted(List<Integer> li){
int n=li.size();
if(n<=1)return true;
for(int i=0;i<n-1;i++){
if(li.get(i)>li.get(i+1))return false;
}
return true;
}
static boolean isPowerOfTwo(long x)
{
return x != 0 && ((x & (x - 1)) == 0);
}
private static boolean ispallindromeList(List<Integer> res){
int l=0,r=res.size()-1;
while(l<r){
if(res.get(l)!=res.get(r))return false;
l++;
r--;
}
return true;
}
private static class Pair{
int first=0;
int sec=0;
int[] arr;
char ch;
String s;
Map<Integer,Integer> map;
Pair(int first,int sec){
this.first=first;
this.sec=sec;
}
Pair(int[] arr){
this.map=new HashMap<>();
for(int x:arr) this.map.put(x,map.getOrDefault(x,0)+1);
this.arr=arr;
}
Pair(char ch,int first){
this.ch=ch;
this.first=first;
}
Pair(String s,int first){
this.s=s;
this.first=first;
}
}
private static int sizeOfSubstring(int st,int e){
int s=e-st+1;
return (s*(s+1))/2;
}
private static Set<Long> factors(long n){
Set<Long> res=new HashSet<>();
// res.add(n);
for (long i=1; i*i<=(n); i++){
if (n%i==0){
res.add(i);
if (n/i != i){
res.add(n/i);
}
}
}
return res;
}
private static long fact(long n){
if(n<=2)return n;
return n*fact(n-1);
}
private static long ncr(long n,long r){
return fact(n)/(fact(r)*fact(n-r));
}
private static int lessThen(long[] nums,long val,boolean work,int l,int r){
int i=-1;
if(work)i=0;
while(l<=r){
int mid=l+((r-l)/2);
if(nums[mid]<=val){
i=mid;
l=mid+1;
}else{
r=mid-1;
}
}
return i;
}
private static int lessThen(List<Long> nums,long val,boolean work,int l,int r){
int i=-1;
if(work)i=0;
while(l<=r){
int mid=l+((r-l)/2);
if(nums.get(mid)<=val){
i=mid;
l=mid+1;
}else{
r=mid-1;
}
}
return i;
}
private static int lessThen(List<Integer> nums,int val,boolean work,int l,int r){
int i=-1;
if(work)i=0;
while(l<=r){
int mid=l+((r-l)/2);
if(nums.get(mid)<=val){
i=mid;
l=mid+1;
}else{
r=mid-1;
}
}
return i;
}
private static int greaterThen(List<Long> nums,long val,boolean work,int l,int r){
int i=-1;
if(work)i=r;
while(l<=r){
int mid=l+((r-l)/2);
if(nums.get(mid)>=val){
i=mid;
r=mid-1;
}else{
l=mid+1;
}
}
return i;
}
private static int greaterThen(List<Integer> nums,int val,boolean work){
int i=-1,l=0,r=nums.size()-1;
if(work)i=r;
while(l<=r){
int mid=l+((r-l)/2);
if(nums.get(mid)>=val){
i=mid;
r=mid-1;
}else{
l=mid+1;
}
}
return i;
}
private static int greaterThen(long[] nums,long val,boolean work,int l,int r){
int i=-1;
if(work)i=r;
while(l<=r){
int mid=l+((r-l)/2);
if(nums[mid]>=val){
i=mid;
r=mid-1;
}else{
l=mid+1;
}
}
return i;
}
private static long gcd(long[] arr){
long ans=0;
for(long x:arr){
ans=gcd(x,ans);
}
return ans;
}
private static int gcd(int[] arr){
int ans=0;
for(int x:arr){
ans=gcd(x,ans);
}
return ans;
}
private static long sumOfAp(long a,long n,long d){
long val=(n*( 2*a+((n-1)*d)));
return val/2;
}
//geometrics
private static double areaOftriangle(double x1,double y1,double x2,double y2,double x3,double y3){
double[] mid_point=midOfaLine(x1,y1,x2,y2);
// debug(Arrays.toString(mid_point)+" "+x1+" "+y1+" "+x2+" "+y2+" "+x3+" "+" "+y3);
double height=distanceBetweenPoints(mid_point[0],mid_point[1],x3,y3);
double wight=distanceBetweenPoints(x1,y1,x2,y2);
// debug(height+" "+wight);
return (height*wight)/2;
}
private static double distanceBetweenPoints(double x1,double y1,double x2,double y2){
double x=x2-x1;
double y=y2-y1;
return (Math.pow(x,2)+Math.pow(y,2));
}
public static boolean isPerfectSquareByUsingSqrt(long n) {
if (n <= 0) {
return false;
}
double squareRoot = Math.sqrt(n);
long tst = (long)(squareRoot + 0.5);
return tst*tst == n;
}
private static double[] midOfaLine(double x1,double y1,double x2,double y2){
double[] mid=new double[2];
mid[0]=(x1+x2)/2;
mid[1]=(y1+y2)/2;
return mid;
}
private static long sumOfN(long n){
return (n*(n+1))/2;
}
private static long power(long x,long y,long p){
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0){
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
/* Function to calculate x raised to the power y in O(logn)*/
static long power(long x, long y){
long temp;
if( y == 0)
return 1l;
temp = power(x, y / 2);
if (y % 2 == 0)
return (temp*temp);
else
return (x*temp*temp);
}
private static StringBuilder reverseString(String s){
StringBuilder sb=new StringBuilder(s);
int l=0,r=sb.length()-1;
while(l<=r){
char ch=sb.charAt(l);
sb.setCharAt(l,sb.charAt(r));
sb.setCharAt(r,ch);
l++;
r--;
}
return sb;
}
private static void swap(List<Integer> li,int i,int j){
int t=li.get(i);
li.set(i,li.get(j));
li.set(j,t);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static long lcm(long a, long b){
return (a / gcd(a, b)) * b;
}
private static String decimalToString(int x){
return Integer.toBinaryString(x);
}
private static String decimalToString(long x){
return Long.toBinaryString(x);
}
private static boolean isPallindrome(String s,int l,int r){
while(l<r){
if(s.charAt(l)!=s.charAt(r))return false;
l++;
r--;
}
return true;
}
private static boolean isSubsequence(String s, String t) {
if (s == null || t == null) return false;
Map<Character, List<Integer>> map = new HashMap<>(); //<character, index>
//preprocess t
for (int i = 0; i < t.length(); i++) {
char curr = t.charAt(i);
if (!map.containsKey(curr)) {
map.put(curr, new ArrayList<Integer>());
}
map.get(curr).add(i);
}
int prev = -1; //index of previous character
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.get(c) == null) {
return false;
} else {
List<Integer> list = map.get(c);
prev = lessThen( list, prev,false,0,list.size()-1);
if (prev == -1) {
return false;
}
prev++;
}
}
return true;
}
private static StringBuilder removeLeadingZero(StringBuilder sb){
int i=0;
while(i<sb.length()&&sb.charAt(i)=='0')i++;
// debug("remove "+i);
if(i==sb.length())return new StringBuilder();
return new StringBuilder(sb.substring(i,sb.length()));
}
private static StringBuilder removeEndingZero(StringBuilder sb){
int i=sb.length()-1;
while(i>=0&&sb.charAt(i)=='0')i--;
// debug("remove "+i);
if(i<0)return new StringBuilder();
return new StringBuilder(sb.substring(0,i+1));
}
private static int stringToDecimal(String binaryString){
// debug(decimalToString(n<<1));
return Integer.parseInt(binaryString,2);
}
private static int stringToInt(String s){
return Integer.parseInt(s);
}
private static String toString(long val){
return String.valueOf(val);
}
private static void debug(int[][] arr){
for(int i=0;i<arr.length;i++){
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(long[][] arr){
for(int i=0;i<arr.length;i++){
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(List<int[]> arr){
for(int[] a:arr){
err.println(Arrays.toString(a));
}
}
private static void debug(float[][] arr){
for(int i=0;i<arr.length;i++){
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(double[][] arr){
for(int i=0;i<arr.length;i++){
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(boolean[][] arr){
for(int i=0;i<arr.length;i++){
err.println(Arrays.toString(arr[i]));
}
}
private static void print(String s)throws IOException {
out.println(s);
}
private static void debug(String s)throws IOException {
err.println(s);
}
private static int charToIntS(char c){
return ((((int)(c-'0'))%48));
}
private static void print(double s)throws IOException {
out.println(s);
}
private static void print(float s)throws IOException {
out.println(s);
}
private static void print(long s)throws IOException {
out.println(s);
}
private static void print(int s)throws IOException {
out.println(s);
}
private static void debug(double s)throws IOException {
err.println(s);
}
private static void debug(float s)throws IOException {
err.println(s);
}
private static void debug(long s){
err.println(s);
}
private static void debug(int s){
err.println(s);
}
private static boolean isPrime(int n){
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
private static List<List<Integer>> readUndirectedGraph(int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<n;i++){
int x=sc.nextInt();
int y=sc.nextInt();
graph.get(x).add(y);
graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readUndirectedGraph(int[][] intervals,int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<intervals.length;i++){
int x=intervals[i][0];
int y=intervals[i][1];
graph.get(x).add(y);
graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readDirectedGraph(int[][] intervals,int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<intervals.length;i++){
int x=intervals[i][0];
int y=intervals[i][1];
graph.get(x).add(y);
// graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readDirectedGraph(int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<n;i++){
int x=sc.nextInt();
int y=sc.nextInt();
graph.get(x).add(y);
// graph.get(y).add(x);
}
return graph;
}
static String[] readStringArray(int n){
String[] arr=new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.next();
}
return arr;
}
private static Map<Character,Integer> freq(String s){
Map<Character,Integer> map=new HashMap<>();
for(char c:s.toCharArray()){
map.put(c,map.getOrDefault(c,0)+1);
}
return map;
}
private static Map<Long,Integer> freq(long[] arr){
Map<Long,Integer> map=new HashMap<>();
for(long x:arr){
map.put(x,map.getOrDefault(x,0)+1);
}
return map;
}
private static Map<Integer,Integer> freq(int[] arr){
Map<Integer,Integer> map=new HashMap<>();
for(int x:arr){
map.put(x,map.getOrDefault(x,0)+1);
}
return map;
}
static boolean[] sieveOfEratosthenes(long n){
boolean prime[] = new boolean[(int)n + 1];
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true){
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
static int[] sieveOfEratosthenesInt(long n){
boolean prime[] = new boolean[(int)n + 1];
Set<Integer> li=new HashSet<>();
for (int i = 1; i <= n; i++){
prime[i] = true;
li.add(i);
}
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true){
for (int i = p * p; i <= n; i += p){
li.remove(i);
prime[i] = false;
}
}
}
int[] arr=new int[li.size()];
int i=0;
for(int x:li){
arr[i++]=x;
}
return arr;
}
public static long Kadens(List<Long> prices) {
long sofar=0;
long max_v=0;
for(int i=0;i<prices.size();i++){
sofar+=prices.get(i);
if (sofar<0) {
sofar=0;
}
max_v=Math.max(max_v,sofar);
}
return max_v;
}
public static int Kadens(int[] prices) {
int sofar=0;
int max_v=0;
for(int i=0;i<prices.length;i++){
sofar+=prices[i];
if (sofar<0) {
sofar=0;
}
max_v=Math.max(max_v,sofar);
}
return max_v;
}
static boolean isMemberAC(int a, int d, int x){
// If difference is 0, then x must
// be same as a.
if (d == 0)
return (x == a);
// Else difference between x and a
// must be divisible by d.
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
static boolean isMemberAC(long a, long d, long x){
// If difference is 0, then x must
// be same as a.
if (d == 0)
return (x == a);
// Else difference between x and a
// must be divisible by d.
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
private static void sort(int[] arr){
int n=arr.length;
List<Integer> li=new ArrayList<>();
for(int x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sortReverse(int[] arr){
int n=arr.length;
List<Integer> li=new ArrayList<>();
for(int x:arr){
li.add(x);
}
Collections.sort(li,Collections.reverseOrder());
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sort(double[] arr){
int n=arr.length;
List<Double> li=new ArrayList<>();
for(double x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sortReverse(double[] arr){
int n=arr.length;
List<Double> li=new ArrayList<>();
for(double x:arr){
li.add(x);
}
Collections.sort(li,Collections.reverseOrder());
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sortReverse(long[] arr){
int n=arr.length;
List<Long> li=new ArrayList<>();
for(long x:arr){
li.add(x);
}
Collections.sort(li,Collections.reverseOrder());
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sort(long[] arr){
int n=arr.length;
List<Long> li=new ArrayList<>();
for(long x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static long sum(int[] arr){
long sum=0;
for(int x:arr){
sum+=x;
}
return sum;
}
private static long sum(long[] arr){
long sum=0;
for(long x:arr){
sum+=x;
}
return sum;
}
private static long evenSumFibo(long n){
long l1=0,l2=2;
long sum=0;
while (l2<n) {
long l3=(4*l2)+l1;
sum+=l2;
if(l3>n)break;
l1=l2;
l2=l3;
}
return sum;
}
private static void initializeIO(){
try {
System.setIn(new FileInputStream("input"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
System.setErr(new PrintStream(new FileOutputStream("error.txt")));
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
private static int maxOfArray(int[] arr){
int max=Integer.MIN_VALUE;
for(int x:arr){
max=Math.max(max,x);
}
return max;
}
private static long maxOfArray(long[] arr){
long max=Long.MIN_VALUE;
for(long x:arr){
max=Math.max(max,x);
}
return max;
}
private static int[][] readIntIntervals(int n,int m){
int[][] arr=new int[n][m];
for(int j=0;j<n;j++){
for(int i=0;i<m;i++){
arr[j][i]=sc.nextInt();
}
}
return arr;
}
private static long gcd(long a,long b){
if(b==0)return a;
return gcd(b,a%b);
}
private static int gcd(int a,int b){
if(b==0)return a;
return gcd(b,a%b);
}
private static int[] readIntArray(int n){
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
return arr;
}
private static double[] readDoubleArray(int n){
double[] arr=new double[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextDouble();
}
return arr;
}
private static long[] readLongArray(int n){
long[] arr=new long[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLong();
}
return arr;
}
private static void print(int[] arr)throws IOException {
out.println(Arrays.toString(arr));
}
private static void print(long[] arr)throws IOException {
out.println(Arrays.toString(arr));
}
private static void print(String[] arr)throws IOException {
out.println(Arrays.toString(arr));
}
private static void print(double[] arr)throws IOException {
out.println(Arrays.toString(arr));
}
private static void debug(String[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(Boolean[][] arr){
for(int i=0;i<arr.length;i++)err.println(Arrays.toString(arr[i]));
}
private static void debug(int[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(long[] arr){
err.println(Arrays.toString(arr));
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str=br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
BufferedWriter bw;
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
FastWriter() {
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
<T> void print(T obj) throws IOException {
bw.write(obj.toString());
bw.flush();
}
void println() throws IOException {
print("\n");
}
<T> void println(T obj) throws IOException {
print(obj.toString() + "\n");
}
void print(int[] arr)throws IOException {
for(int x:arr){
print(x+" ");
}
println();
}
void print(long[] arr)throws IOException {
for(long x:arr){
print(x+" ");
}
println();
}
void print(double[] arr)throws IOException {
for(double x:arr){
print(x+" ");
}
println();
}
void printCharN(char c, int n) throws IOException {
for (int i = 0; i < n; i++) {
print(c);
}
}
}
static class Dsu {
int[] parent, size;
Dsu(int n) {
parent = new int[n + 1];
size = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
private int findParent(int u) {
if (parent[u] == u) return u;
return parent[u] = findParent(parent[u]);
}
private boolean union(int u, int v) {
// System.out.println("uf "+u+" "+v);
int pu = findParent(u);
// System.out.println("uf2 "+pu+" "+v);
int pv = findParent(v);
// System.out.println("uf3 " + u + " " + pv);
if (pu == pv) return false;
if (size[pu] <= size[pv]) {
parent[pu] = pv;
size[pv] += size[pu];
} else {
parent[pv] = pu;
size[pu] += size[pv];
}
return true;
}
}
} | java |
1313 | C1 | C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal. | [
"brute force",
"data structures",
"dp",
"greedy"
] | /*
"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 {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 1; t <= test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
int[] maxHeight = new int[n];
for (int i = 0; i < n; i++) {
maxHeight[i] = sc.nextInt();
}
int[] res = new int[n];
int[] currHeight = new int[n];
long maxSkyscraper = 0;
for (int i = 0; i < n; i++) { // for each peak
long skyscrapers = maxHeight[i];
currHeight[i] = maxHeight[i];
int atMost = maxHeight[i];
for (int j = i - 1; j >= 0; j--) {
atMost = Math.min(atMost, maxHeight[j]);
currHeight[j] = atMost;
skyscrapers += atMost;
}
int atLeast = maxHeight[i];
for (int j = i + 1; j < n; j++) {
atLeast = Math.min(atLeast, maxHeight[j]);
currHeight[j] = atLeast;
skyscrapers += atLeast;
}
if (skyscrapers > maxSkyscraper) {
for (int j = 0; j < n; j++) {
res[j] = currHeight[j];
}
maxSkyscraper = skyscrapers;
}
}
for (int i = 0; i < n; i++) {
out.print(res[i] + " ");
}
out.println();
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
} | java |
1304 | F1 | F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: | [
"data structures",
"dp"
] | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class F {
static int n, m, k;
static int[][] ani; // animals
public static void main(String[] args) {
var scanner = new BufferedScanner();
var writer = new PrintWriter(new BufferedOutputStream(System.out));
n = scanner.nextInt();
m = scanner.nextInt();
k = scanner.nextInt();
ani = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
ani[i][j] = scanner.nextInt();
}
}
writer.println(solve());
scanner.close();
writer.flush();
writer.close();
}
private static int solve() {
dfsCache = new int[n + 1][m + 1];
for (var i = 1; i <= n; i++) {
Arrays.fill(dfsCache[i], -1);
}
leftMaxCache = new int[n + 1][m + 1];
leftMaxAlready = new int[n + 1];
Arrays.fill(leftMaxAlready, 0);
for (int i = 1; i <= n; i++) {
Arrays.fill(leftMaxCache[i], -1);
leftMaxCache[i][0] = 0;
}
rightMaxCache = new int[n + 1][m + 2];
rightMaxAlready = new int[n + 1];
Arrays.fill(rightMaxAlready, m - k + 2);
for (int i = 1; i <= n; i++) {
Arrays.fill(rightMaxCache[i], -1);
rightMaxCache[i][m - k + 2] = 0;
}
var ans = 0;
for (int start = 1; start + k - 1 <= m; start++) {
ans = Math.max(ans, dfs(2, start) + range(1, start, start + k - 1));
}
return ans;
}
static int[][] dfsCache;
private static int dfs(int row, int lastStart) {
if (row > n) {
return 0;
}
if (dfsCache[row][lastStart] >= 0) {
return dfsCache[row][lastStart];
}
var ans = 0;
var lastEnd = lastStart + k - 1;
// no intersection
{
int ans0 = leftMax(row, lastStart - 1);
ans = Math.max(ans, ans0 + range(row, lastStart, lastEnd));
}
{
int ans0 = rightMax(row, lastEnd + 1);
ans = Math.max(ans, ans0 + range(row, lastStart, lastEnd));
}
// intersected
for (int thisStart = Math.max(1, lastStart - k + 1);
thisStart <= lastEnd && thisStart + k - 1 <= m; thisStart++) {
var ans1 = dfs(row + 1, thisStart)
+ watch(row, lastStart, thisStart);
ans = Math.max(ans, ans1);
}
return dfsCache[row][lastStart] = ans;
}
static int[][] rightMaxCache;
static int[] rightMaxAlready;
private static int rightMax(int row, int minStart) {
if (minStart + k - 1 > m) {
return 0;
}
if (rightMaxCache[row][minStart] >= 0) {
return rightMaxCache[row][minStart];
}
var ans0 = rightMaxCache[row][rightMaxAlready[row]];
for (int start = rightMaxAlready[row] - 1; start >= minStart; start--) {
if (rightMaxCache[row][start] >= 0) {
continue;
}
var end = start + k - 1;
var ans1 = dfs(row + 1, start) + range(row, start, end);
rightMaxCache[row][start] = Math.max(rightMaxCache[row][start + 1], ans1);
ans0 = Math.max(ans0, ans1);
}
rightMaxAlready[row] = minStart;
assert ans0 == rightMaxCache[row][minStart];
return ans0;
}
static int[][] leftMaxCache;
static int[] leftMaxAlready;
private static int leftMax(int row, int maxEnd) {
var maxStart = maxEnd - k + 1;
if (maxStart <= 0) {
return 0;
}
if (leftMaxCache[row][maxStart] >= 0) {
return leftMaxCache[row][maxStart];
}
var ans0 = leftMaxCache[row][leftMaxAlready[row]];
// leftMaxCache[row][k - 1] = 0;
for (int start = leftMaxAlready[row] + 1; start <= maxStart; start++) {
var end = start + k - 1;
if (leftMaxCache[row][start] >= 0) {
continue;
}
var ans1 = dfs(row + 1, start) + range(row, start, end);
leftMaxCache[row][start] = Math.max(leftMaxCache[row][start - 1], ans1);
ans0 = Math.max(ans0, ans1);
}
leftMaxAlready[row] = maxStart;
assert ans0 == leftMaxCache[row][maxStart];
return leftMaxCache[row][maxStart];
}
private static int watch(int row, int start1, int start2) {
// System.out.println("row = " + row + ", start1 = " + start1 + ", start2 = " + start2);
if (start1 > start2) {
return watch(row, start2, start1);
}
var end2 = start2 + k - 1;
if (start1 <= 0) {
return range(row, start2, end2);
}
var end1 = start1 + k - 1;
if (end2 < start1 || end1 < start2) {
return range(row, start1, end1) + range(row, start2, end2);
}
return range(row, start1, end1) + range(row, start2, end2)
- range(row, start2, Math.min(end1, end2));
}
static int[][] rangeCache;
private static int range(int row, int start, int end) {
if (start <= 0 || start > end) {
return 0;
}
if (rangeCache == null) {
rangeCache = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
rangeCache[i][0] = 0;
for (int j = 1; j <= m; j++) {
rangeCache[i][j] = rangeCache[i][j - 1] + ani[i][j];
}
}
}
return rangeCache[row][end] - rangeCache[row][start - 1];
}
static final boolean DEBUG = false;
private static void debug(String fmt, Object... args) {
if (DEBUG) {
System.out.println(String.format(fmt, args));
}
}
public static class BufferedScanner {
BufferedReader br;
StringTokenizer st;
public BufferedScanner(Reader reader) {
br = new BufferedReader(reader);
}
public BufferedScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b > 0) {
long tmp = b;
b = a % b;
a = tmp;
}
return a;
}
static long inverse(long a, long m) {
long[] ans = extgcd(a, m);
return ans[0] == 1 ? (ans[1] + m) % m : -1;
}
private static long[] extgcd(long a, long m) {
if (m == 0) {
return new long[]{a, 1, 0};
} else {
long[] ans = extgcd(m, a % m);
long tmp = ans[1];
ans[1] = ans[2];
ans[2] = tmp;
ans[2] -= ans[1] * (a / m);
return ans;
}
}
private static List<Integer> primes(double upperBound) {
var limit = (int) Math.sqrt(upperBound);
var isComposite = new boolean[limit + 1];
var primes = new ArrayList<Integer>();
for (int i = 2; i <= limit; i++) {
if (isComposite[i]) {
continue;
}
primes.add(i);
int j = i + i;
while (j <= limit) {
isComposite[j] = true;
j += i;
}
}
return primes;
}
}
| java |
1315 | A | A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. | [
"implementation"
] | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main{
public static void solve(BufferedReader sc) throws Exception {
StringTokenizer tx = new StringTokenizer(sc.readLine());
int n = Integer.parseInt(tx.nextToken());
int m = Integer.parseInt(tx.nextToken());
int x = Integer.parseInt(tx.nextToken());
int y = Integer.parseInt(tx.nextToken());
int ans = 0;
//
// xy
//
x++;y++;
ans = Math.max(ans, (x-1)*m);
// System.out.println(ans);
ans = Math.max(ans, (y-1)*n);
// System.out.println(ans);
ans = Math.max(ans, (n-x)*m);
// System.out.println(ans);
ans = Math.max(ans, (m-y)*n);
System.out.println(ans);
}
public static void main(String[] args) throws Exception{
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
int tc = 1;
StringTokenizer tx = new StringTokenizer(sc.readLine()); tc = Integer.parseInt(tx.nextToken());
for(int i = 0; i < tc; i++){
solve(sc);
}
}
}
| 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.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class E1294 {
public static void main(String[] args) throws IOException {
Reader scan = new Reader();
int n = scan.nextInt();
int m = scan.nextInt();
int[][] a = new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j] = scan.nextInt();
}
}
long moves = 0;
for(int i=0;i<m;i++) {
moves += solve(a, i, n, m);
}
System.out.println(moves);
}
static int solve(int[][] a, int i, int n, int m) {
int count = 0;
Map<Integer, Integer> posMap = new HashMap<>();
for(int j=0;j<n;j++) {
posMap.put((j*m) + i + 1, j);
}
int[] shifts = new int[n];
for(int j=0;j<n;j++) {
if(posMap.containsKey(a[j][i])) {
shifts[(j - posMap.get(a[j][i]) + n) % n]++;
}
}
count = n - shifts[0];
for(int j=1;j<n;j++) {
count = Math.min(count, n - shifts[j] + j);
}
return count;
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
| java |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | // package c1294;
//
// Codeforces Round #615 (Div. 3) 2020-01-22 06:35
// B. Collecting Packages
// https://codeforces.com/contest/1294/problem/B
// time limit per test 1 second; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There is a robot in a warehouse and n packages he wants to collect. The warehouse can be
// represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th
// package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same
// point. It is also guaranteed that the point (0, 0) doesn't contain a package.
//
// The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move
// the robot can go from the point (x, y) to the point (x + 1, y) or to the point (x, y + 1).
//
// As we say above, the robot wants to collect all n packages (). He wants to do it with the minimum
// possible number of moves. If there are several possible traversals, the robot wants to choose the
// lexicographically smallest path.
//
// The string s of length n is lexicographically less than the string t of length n if there is some
// index 1 <= j <= n that for all i from 1 to j-1 s_i = t_i and s_j < t_j. It is the standard
// comparison of string, like in a dictionary. Most programming languages compare strings in this
// way.
//
// Input
//
// The first line of the input contains an integer t (1 <= t <= 100) -- the number of test cases.
// Then test cases follow.
//
// The first line of a test case contains one integer n (1 <= n <= 1000) -- the number of packages.
//
// The next n lines contain descriptions of packages. The i-th package is given as two integers x_i
// and y_i (0 <= x_i, y_i <= 1000) -- the x-coordinate of the package and the y-coordinate of the
// package.
//
// It is guaranteed that there are no two packages at the same point. It is also guaranteed that the
// point (0, 0) doesn't contain a package.
//
// The sum of all values n over test cases in the test doesn't exceed 1000.
//
// Output
//
// Print the answer for each test case.
//
// If it is impossible to collect all n packages in some order starting from (0,0), print "NO" on
// the first line.
//
// Otherwise, print "YES" in the first line. Then print the path -- a string consisting of
// characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.
//
// .
//
// Example
/*
input:
3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
output:
YES
RUUURRRRUU
NO
YES
RRRRUUU
*/
// Note
//
// For the first test case in the example the optimal path RUUURRRRUU is shown below:
// https://espresso.codeforces.com/8ba8beb3d4798d0c00f093234601e29f45df5fd2.png
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class C1294B {
static final int MOD = 998244353;
static final Random RAND = new Random();
static String solve(int[][] a) {
int n = a.length;
Arrays.sort(a, (x,y)->x[0] != y[0] ? x[0] - y[0] : x[1]-y[1]);
// NO (x1,y1) (x2,y2) such that x1 < x2 and y1 > y2
//
// y1 *
// y2 *
// 0 .
// ^ ^ ^
// 0 x1 x2
//
StringBuilder sb = new StringBuilder();
int x1 = 0;
int y1 = 0;
for (int i = 0; i < n; i++) {
int x2 = a[i][0];
int y2 = a[i][1];
myAssert(x2 >= x1);
if (x2 > x1 && y1 > y2) {
return null;
}
for (int j = x1; j < x2; j++) {
sb.append('R');
}
for (int j = y1; j < y2; j++) {
sb.append('U');
}
x1 = x2;
y1 = y2;
}
return sb.toString();
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int[][] packages = new int[n][2];
for (int i = 0; i < n; i++) {
packages[i][0] = in.nextInt();
packages[i][1] = in.nextInt();
}
String ans = solve(packages);
System.out.println(ans == null ? "NO" : "YES\n" + 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 |
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.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.HashMap;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CInstantNoodles solver = new CInstantNoodles();
int testCount = in.scanInt();
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class CInstantNoodles {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int m = in.scanInt();
long[] values = new long[n];
for (int i = 0; i < n; i++) values[i] = in.scanLong();
int[][] edges = new int[m][2];
long[] random1 = new long[n];
long[] random2 = new long[n];
{
Random rd = new Random();
for (int i = 0; i < n; i++) random1[i] = rd.nextLong();
}
for (int[] edge : edges) {
edge[0] = in.scanInt();
edge[1] = in.scanInt();
random2[edge[1] - 1] ^= random1[(edge[0] - 1)];
}
Map<Long, Long> map = new HashMap<>();
for (int i = 0; i < n; i++) {
if (random2[i] == 0) continue;
map.put(random2[i], map.getOrDefault(random2[i], 0l) + values[i]);
}
long ans = 0;
for (Map.Entry<Long, Long> temp : map.entrySet()) {
ans = CodeHash.gcd(ans, temp.getValue());
}
out.println(ans);
}
}
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 integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
}
static class CodeHash {
public static long gcd(long a, long b) {
while (b != 0) {
long t = b;
b = (a % b);
a = t;
}
return a;
}
}
}
| java |
1303 | C | C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
| [
"dfs and similar",
"greedy",
"implementation"
] | import 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_Perfect_Keyboard {
static long mod = Long.MAX_VALUE;
static OutputStream outputStream = System.out;
static PrintWriter out = new PrintWriter(outputStream);
static FastReader f = new FastReader();
public static void main(String[] args) {
int t = f.nextInt();
while(t-- > 0){
solve();
}
out.close();
}
public static void solve() {
String s = f.nextLine();
int n = s.length();
ArrayList<HashSet<Integer>> adj = new ArrayList<>();
for(int i = 0; i < 26; i++) {
adj.add(new HashSet<>());
}
for(int i = 1; i < n; i++) {
int u = s.charAt(i)-'a';
int v = s.charAt(i-1)-'a';
adj.get(u).add(v);
adj.get(v).add(u);
}
boolean taken[] = new boolean[26];
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 26; i++) {
int sz = adj.get(i).size();
if(sz > 2) {
out.println("NO");
return;
}
if(sz == 0) {
taken[i] = true;
sb.append((char)('a'+i));
} else if(sz == 1 && !taken[i]) {
if(dfs(adj, i, -1, taken, sb)) {
out.println("NO");
return;
}
}
}
if(sb.length() < 26) {
out.println("NO");
return;
}
out.println("YES");
out.println(sb);
}
public static boolean dfs(ArrayList<HashSet<Integer>> adj, int s, int p, boolean taken[], StringBuilder sb) {
taken[s] = true;
sb.append((char)('a'+s));
for(int v: adj.get(s)) {
if(!taken[v]) {
if(dfs(adj, v, s, taken, sb)) {
return true;
}
} else if(v != p) {
return true;
}
}
return false;
}
// Sort an array
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
// Find all divisors of n
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
// Check if n is prime or not
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
// Find gcd of a and b
public static long gcd(long a, long b) {
long dividend = a > b ? a : b;
long divisor = a < b ? a : b;
while(divisor > 0) {
long reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
// Find lcm of a and b
public static long lcm(long a, long b) {
long lcm = gcd(a, b);
long hcf = (a * b) / lcm;
return hcf;
}
// Find factorial in O(n) time
public static long fact(int n) {
long res = 1;
for(int i = 2; i <= n; i++) {
res = res * i;
}
return res;
}
// Find power in O(logb) time
public static long power(long a, long b) {
long res = 1;
while(b > 0) {
if((b&1) == 1) {
res = (res * a)%mod;
}
a = (a * a)%mod;
b >>= 1;
}
return res;
}
// Find nCr
public static long nCr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / (fact(r) * fact(n-r));
return ans;
}
// Find nPr
public static long nPr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / fact(r);
return ans;
}
// sort all characters of a string
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// User defined class for fast I/O
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
boolean hasNext() {
if (st != null && st.hasMoreTokens()) {
return true;
}
String tmp;
try {
br.mark(1000);
tmp = br.readLine();
if (tmp == null) {
return false;
}
br.reset();
} catch (IOException e) {
return false;
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
// (a/b)%mod == (a * moduloInverse(b)) % mod;
// moduloInverse(b) = power(b, mod-2);
| java |
1288 | 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.*;
import java.util.*;
import java.lang.*;
public class Codeforces {
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
int test=input.nextInt();
while(test-->0){
double n=input.nextLong();
double d=input.nextLong();
boolean ok=false;
for(double i=0;i<n;i++)
{
if(i+Math.ceil(d/(i+1))<=n)
{
ok=true;
break;
}
}
if(ok==true)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
}
| java |
1307 | A | A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Next 2t2t lines contain a description of test cases — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100) — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day. | [
"greedy",
"implementation"
] |
/*
_oo0oo_
o8888888o
88" . "88
(| -_- |)
0\ = /0
___/`---'\___
.' \\| |// '.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' |_/ |
\ .-\__ '-' ___/-. /
___'. .' /--.--\ `. .'___
."" '< `.___\_<|>_/___.' >' "".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `_. \_ __\ /__ _/ .-` / /
=====`-.____`.___ \_____/___.-`___.-'=====
`=---='
*/
import java.util.function.Consumer;
import java.util.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.io.*;
import java.lang.Math.*;
public class KickStart2020{
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader(){br = new BufferedReader(
new InputStreamReader(System.in));}
String next(){
while (st == null || !st.hasMoreElements()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) {e.printStackTrace();}}
return st.nextToken();}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next());}
float nextFloat() {return Float.parseFloat(next());}
String nextLine() {
String str = "";
try {str = br.readLine();}
catch (IOException e) { e.printStackTrace();}
return str; }}
static String reverseOfString(String a) {
StringBuilder ssd = new StringBuilder();
for(int i = a.length() - 1; i >= 0; i--) {
ssd.append(a.charAt(i));
}
return ssd.toString();
}
static char[] reverseOfChar(char a[]) {
char b[] = new char[a.length];
int j = 0;
for(int i = a.length - 1; i >= 0; i--) {
b[i] = a[j];
j++;
}
return b;
}
static boolean isPalindrome(char a[]) {
boolean hachu = true;
for(int i = 0; i <= a.length / 2; i++) {
if(a[i] != a[a.length - 1 - i]) {
hachu = false;
break;
}
}
return hachu;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long power(long x, long y, long mod){
long ans = 1;
x = x % mod;
if (x == 0)
return 0;
int i = 1;
while (y > 0){
if ((y & 1) != 0)
ans = (ans * x) % mod;
y = y >> 1;
x = (x * x) % mod;
}
return ans;
}
static boolean check(String a) {
boolean hachu = true;
for(int i = 0; i < a.length(); i++) {
if(a.charAt(0) != a.charAt(i)) {hachu = false; break;}
}
return hachu;
}
static void move(char a[], int i) {
int j = 0;
int temp1 = i;
while(j < i) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
j++;
i--;
}
for(int k = 0; k <= temp1; k++) {
a[k] = (a[k] == '0') ? '1' : '0';
}
}
static boolean mayC(char a[]) {
boolean hachu = false;
for(int i = 2; i < a.length; i++) if(a[i] == 'C') {hachu = true; break;}
return hachu;
}
static boolean pointChecker(int a, int b, int n, int m, int arr[][]) {
boolean hachu = true;
if(b + 1 < m && arr[a][b + 1] != 0) hachu = false;
if(b - 1 > -1 && arr[a][b - 1] != 0) hachu = false;
if(a + 1 < n && arr[a + 1][b] != 0) hachu = false;
if(a - 1 > -1 && arr[a - 1][b] != 0) hachu = false;
return hachu;
}
public static void main(String[] args) throws Exception{
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++) arr[i] = sc.nextInt();
int i = 1, sum = arr[0];
while(i < n) {
while(arr[i] != 0 && k >= i) {arr[i]--; k -= i; sum++;}
i++;
if(k < i) break;
}
out.println(sum);
}
out.close();
}
} | java |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class edu130 {
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 main(String[] args) {
//RSRRSRSSSR
try {
FastReader sc = new FastReader();
FastWriter out = new FastWriter();
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int k=sc.nextInt();
int [] arr=new int[n];
int [] arr2=new int[k];
int [] temp=new int[n];
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
temp[i]=arr[i];
}
for(int i=0;i<k;i++){
int b=sc.nextInt();
arr2[i]=b-1;
map.put(arr2[i],0);
}
Arrays.sort(temp);
boolean tt=false;
for(int i=0;i<n;i++){
if(map.containsKey(i)){
int j=i;
while(j<n && map.containsKey(j)){
j++;
}
Arrays.sort(arr,i,j+1);
i=j;
}
}
for(int i=0;i<n;i++){
if(temp[i]!=arr[i]){
tt=true;
break;
}
}
if(tt){
System.out.println("NO");
}else{
System.out.println("YES");
}
}
}catch(Exception e){
return;
}
}
private static void swap(long[] arr, int i, int ii) {
long 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 |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class LetterA {
static class Point{
int x,y;
Point(int x, int y){
this.x=x;
this.y=y;
}
}
static class Segment{
Point p1,p2;
Segment(Point p1, Point p2){
this.p1=p1;
this.p2=p2;
}
}
static long cross(long x1, long y1, long x2, long y2) {
return x1*y2-x2*y1;
}
static long length(long x, long y){
return x*x+y*y;
}
static boolean acute(Point l, Point m, Point n){
long area= cross(l.x-n.x,l.y-n.y,m.x-n.x,m.y-n.y);
long a=length(l.x-n.x,l.y-n.y);
long b=length(m.x-n.x,m.y-n.y);
long c=length(m.x-l.x,m.y-l.y);
return area!=0 && c<=a+b;
}
static boolean verticalSegment(Segment a, Segment b){
if(a.p1.x==b.p1.x && a.p1.y==b.p1.y){
return acute(a.p2,b.p2,a.p1);
}
if(a.p2.x==b.p2.x && a.p2.y==b.p2.y){
return acute(a.p1,b.p1,a.p2);
}
if(a.p1.x==b.p2.x && a.p1.y==b.p2.y){
return acute(a.p2,b.p1,a.p1);
}
if(a.p2.x==b.p1.x && a.p2.y==b.p1.y){
return acute(a.p1,b.p2,a.p2);
}
return false;
}
static boolean intersecting(Segment s,Point p){
if(p.x<Math.min(s.p1.x,s.p2.x) || p.x>Math.max(s.p1.x,s.p2.x) ||
p.y<Math.min(s.p1.y,s.p2.y)|| p.y>Math.max(s.p1.y,s.p2.y))
return false;
int x=Math.abs(s.p1.x-s.p2.x);
int y=Math.abs(s.p1.y-s.p2.y);
int xm=Math.min(Math.abs(s.p1.x-p.x),Math.abs(s.p2.x-p.x));
int ym=Math.min(Math.abs(s.p1.y-p.y),Math.abs(s.p2.y-p.y));
return x<=5*xm && y<=5*ym &&
(long)(p.x-s.p2.x)*(s.p1.y-s.p2.y)==(long)(p.y-s.p2.y)*(s.p1.x-s.p2.x);
}
static boolean check(Segment a, Segment b, Segment c){
return verticalSegment(a,b)&& (intersecting(a,c.p1)&&intersecting(b,c.p2)
|| intersecting(b,c.p1)&&intersecting(a,c.p2));
}
public static void main(String[] args) throws IOException {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(br.readLine());
Segment[][] segments= new Segment[n][3];
for(int i=0;i<n;i++) {
for(int j=0; j<3;j++){
StringTokenizer st= new StringTokenizer(br.readLine());
int x1 = Integer.parseInt(st.nextToken());
int y1 = Integer.parseInt(st.nextToken());
int x2 = Integer.parseInt(st.nextToken());
int y2 = Integer.parseInt(st.nextToken());
segments[i][j]= new Segment(new Point(x1,y1),new Point(x2,y2));
}
System.out.println(check(segments[i][0],segments[i][1],segments[i][2])
||check(segments[i][1],segments[i][2],segments[i][0])
||check(segments[i][2],segments[i][0],segments[i][1])?"YES":"NO");
}
}
}
| java |
1320 | B | B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3
| [
"dfs and similar",
"graphs",
"shortest paths"
] | import java.io.IOException;
import java.io.InputStream;
import java.util.*;
public class sol {
static long mod=(long)Math.pow(10,9)+7;
static StringBuilder sb = new StringBuilder();
static ArrayList<Integer> adj[];
static boolean vis[];
static int a[], dist[];
static void bfs(int s) {
Queue<Integer> q = new LinkedList<>();
dist[s]=0;
vis[s]=true;
q.add(s);
while(q.size()>0) {
int v=q.poll();
for(Integer i : adj[v]) {
dist[i]=Math.min(dist[i],dist[v]+1);
if(!vis[i]) {
vis[i]=true;
q.add(i);
}
}
}
}
public static void main(String args[])throws Exception {
FastReader in = new FastReader(System.in);
int t=1,i,j;
start:while(t-->0) {
int n = in.nextInt(),m=in.nextInt();
dist =new int[n];
Arrays.fill(dist,Integer.MAX_VALUE);
adj = new ArrayList[n];
vis = new boolean[n];
for(i=0;i<n;i++)
adj[i]=new ArrayList<>();
int x[]=new int[m];
int y[]=new int[m];
int cnt[]=new int[n];
for(i=0;i<m;i++) {
x[i]=in.nextInt()-1;
y[i]=in.nextInt()-1;
adj[y[i]].add(x[i]);
}
int k=in.nextInt();
a = new int[k];
for(i=0;i<k;i++)
a[i]=in.nextInt()-1;
bfs(a[k-1]);
for(i=0;i<m;i++) {
if(dist[y[i]]+1==dist[x[i]])
cnt[x[i]]++;
}
//for(i=0;i<n;i++)
//System.out.println(dist[i]+" "+cnt[i]);
int min=0,max=0;
for(i=0;i<k-1;i++) {
if(dist[a[i+1]]+1>dist[a[i]]) {
min++;
max++;
}
else if(cnt[a[i]]>1)
max++;
}
System.out.println(min+" "+max);
}
//System.out.print(sb);
}
static long power(long a, long b) {
if(b == 0)
return 1L;
long val = power(a, b / 2);
if(b % 2 == 0)
return val * val % mod;
else
return val * val % mod * a % mod;
}
static void prt(int a[]) {
for(int i=0;i<=a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
static void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
static void sort(int arr[], int l, int r) {
if (l < r) {
int m = (l+r)/2;
sort(arr, l, m);
sort(arr , m+1, r);
merge(arr, l, m, r);
}
}
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 x, int y) {
a = x;
b = y;
}
}
}
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();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
return (char) c;
}
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;
}
} | 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.io.*;
import java.util.*;
public class Zx {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
int numberSets = Integer.parseInt(br.readLine());
for (int nos = 0; nos < numberSets; nos++) {
int size = Integer.parseInt(br.readLine());
int [] data = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int counter = 0;
for (int i = 0; i < size; i++) {
if (data[i]%2==0) {
counter++;
}
}
if (counter > 0 && counter < size) {
System.out.println("YES");
continue;
}
if (counter == 0 && size%2 != 0) {
System.out.println("YES");
continue;
}
System.out.println("NO");
}
}
} | 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.io.*;
import java.util.*;
public class new1{
static FastReader s = new FastReader();
public static void main(String[] args) throws IOException{
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int t = s.nextInt();
for(int z = 0; z < t; z++) {
int n = s.nextInt() - 1;
String str = s.next();
ArrayList<Integer> aList = new ArrayList<Integer>();
int count = 1;
for(int i = 1; i < n; i++) {
if(str.charAt(i) == str.charAt(i - 1)) count++;
else {
if(str.charAt(i - 1) == '>') count = -1 * count;
aList.add(count);
count = 1;
//i++;
}
}
if(str.charAt(n - 1) == '>') count = count * -1;
aList.add(count);
if(count < 0) aList.add(0);
ArrayList<Integer> ans = new ArrayList<Integer>();
ans.add(0);
//System.out.println(aList.toString());
int curr = 0;
int ind = 0;
if(aList.get(ind) >= 0) {
for(int i = 1; i <= aList.get(ind); i++) {
ans.add(i);
}
ind++;
}
while(ind < aList.size()) {
for(int i = curr -aList.get(ind + 1) - 1; i >= curr - aList.get(ind + 1) + aList.get(ind); i--) {
ans.add(i);
}
for(int i = curr - aList.get(ind + 1); i < curr; i++) {
ans.add(i);
}
curr = curr - aList.get(ind + 1) + aList.get(ind);
ind = ind + 2;
}
//////////////////////////////////////////////////////////////////
curr = 0; ind = 0;
ArrayList<Integer> ans2= new ArrayList<Integer>();
ans2.add(0);
if(aList.get(aList.size() - 1) == 0) aList.remove(aList.size() - 1);
else aList.add(0);
if(aList.get(ind) <= 0) {
for(int i = -1; i >= aList.get(ind); i--) {
ans2.add(i);
}
ind++;
}
//System.out.println(aList.toString());
while(ind < aList.size()) {
for(int i = curr - aList.get(ind + 1) + 1; i < curr - aList.get(ind + 1) + aList.get(ind) + 1; i++) {
ans2.add(i);
}
for(int i = curr - aList.get(ind + 1); i > curr; i--) {
ans2.add(i);
}
curr = curr - aList.get(ind + 1) + aList.get(ind);
ind = ind + 2;
}
int min1 = 10000000; int min2 = min1;
for(int i = 0; i < ans.size(); i++) {
min1 = Math.min(min1, ans.get(i));
min2 = Math.min(min2, ans2.get(i));
}
for(int i = 0; i < ans.size(); i++) {
ans.set(i, ans.get(i) - min1 + 1);
ans2.set(i, ans2.get(i) - min2 + 1);
}
for(int i = 0; i <= n; i++) output.write(ans.get(i) + " ");
output.write("\n");
for(int i = 0; i <= n; i++) output.write(ans2.get(i) + " ");
output.write("\n");
}
output.flush();
}
}
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();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}} | java |
1141 | F1 | F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"greedy"
] | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
/**
* #
*
* @author pttrung
*/
public class F_Round_547_Div3 {
public static long MOD = 998244353;
static int[] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[] data = new int[n];
int[] sum = new int[n];
for (int i = 0; i < n; i++) {
data[i] = in.nextInt();
sum[i] = data[i] + (i > 0 ? sum[i - 1] : 0);
}
int result = 0;
int val = 0;
int[] pre = new int[n];
HashSet<Integer> set = new HashSet<>();
dp = new int[n];
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int v = sum[j] - (i > 0 ? sum[i - 1] : 0);
if (set.contains(v)) {
continue;
}
set.add(v);
Arrays.fill(dp, -1);
int tmp = cal(0, v, sum);
if (result < tmp) {
val = v;
result = tmp;
pre = Arrays.copyOf(dp, n);
}
}
}
//System.out.println(result);
out.println(result);
int index = 0;
int cur = result;
while (index < n && cur > 0) {
// System.out.println(index + " " + cur + " " + Arrays.toString(pre));
if (index + 1 < n && pre[index + 1] == cur) {
index++;
continue;
}
for (int i = index; i < n; i++) {
int tmp = sum[i] - (index > 0 ? sum[index - 1] : 0);
if (tmp == val) {
out.println((index + 1) + " " + (i + 1));
index = i + 1;
cur--;
break;
}
}
}
out.close();
}
static int cal(int index, int need, int[] sum) {
if (index == sum.length) {
return 0;
}
if (dp[index] != -1) {
return dp[index];
}
int result = cal(index + 1, need, sum);
for (int i = index; i < sum.length; i++) {
int v = sum[i] - (index > 0 ? sum[index - 1] : 0);
if (v == need) {
result = Integer.max(result, 1 + cal(i + 1, need, sum));
break;
}
}
return dp[index] = result;
}
static class P {
int pos, index, open;
P(int pos, int index, int open) {
this.pos = pos;
this.index = index;
this.open = open;
}
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x;
long y;
public Point(int start, long end) {
this.x = start;
this.y = end;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return x == point.x &&
y == point.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return (val * val) % MOD;
} else {
return (val * ((val * a) % MOD)) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
} | 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.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)
// {
long n=sc.nextLong();
double n1=n,ans=0;
while(n1>0)
{
ans=ans+1/(n1);
n1--;
}
out.println(ans);
// }
out.close();
}
}
| java |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
| [
"data structures",
"implementation"
] | import java.io.*;
import java.util.*;
public class cf {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
//st = new StringTokenizer(br.readLine());
int t = Integer.parseInt(br.readLine());
while(t-->0){
int n = Integer.parseInt(br.readLine());
String s = br.readLine();
Map<String,Integer> map = new HashMap<String, Integer>();
int x = 0, y = 0, l = n+1, r = 0;
map.put(x + " " + y, 0);
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
switch (ch){
case 'L': x--; break;
case 'R': x++; break;
case 'U': y++; break;
case 'D': y--; break;
}
String cord = x + " " + y;
if(map.containsKey(cord)){
int cl = i - map.get(cord);
if(cl < l){
l = cl;
r = i+1;
}
map.replace(cord, i+1);
}
else map.put(cord, i+1);
}
if(l == n+1) System.out.println(-1);
else System.out.println(r-l + " " + r);
}
}
} | java |
1295 | E | E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2
| [
"data structures",
"divide and conquer"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author KharYusuf
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
EPermutationSeparation solver = new EPermutationSeparation();
solver.solve(1, in, out);
out.close();
}
static class EPermutationSeparation {
public void solve(int testNumber, FastReader s, PrintWriter w) {
int n = s.nextInt();
int[] pos = new int[n], a = new int[n];
long[] pre = new long[n];
for (int i = 0; i < n; i++) pos[s.nextInt() - 1] = i;
for (int i = 0; i < n; i++) {
pre[i] = a[i] = s.nextInt();
if (i > 0) pre[i] += pre[i - 1];
}
segtreeLazy seg = new segtreeLazy(n);
seg.build(pre);
long ans = seg.query(0, n - 2);
for (int i = 0; i < n; i++) {
int cur = pos[i];
seg.modify(0, cur - 1, a[cur]);
seg.modify(cur, n - 1, -a[cur]);
ans = Math.min(ans, seg.query(0, n - 2));
}
w.println(ans);
}
class segtreeLazy {
int n;
long[] t;
long[] lazy;
segtreeLazy(int n) {
this.n = n;
t = new long[n << 2];
lazy = new long[n << 2];
}
void build(long[] a) {
buildUtil(0, n - 1, a, 1);
}
void modify(int l, int r, long val) {
if (l > r) return;
modifyUtil(0, n - 1, l, r, val, 1);
}
long query(int l, int r) {
if (l > r) throw new RuntimeException("Out of Range");
return queryUtil(0, n - 1, l, r, 1);
}
void buildUtil(int s, int e, long[] a, int n) {
if (s == e) {
t[n] = a[s];
return;
}
int mid = s + e >> 1;
buildUtil(s, mid, a, n << 1);
buildUtil(mid + 1, e, a, n << 1 | 1);
t[n] = Math.min(t[n << 1], t[n << 1 | 1]);
}
void modifyUtil(int s, int e, int qs, int qe, long val, int n) {
if (lazy[n] != 0) {
t[n] += lazy[n];
if (s != e) {
lazy[n << 1] += lazy[n];
lazy[n << 1 | 1] += lazy[n];
}
lazy[n] = 0;
}
if (s > qe || e < qs) return;
if (s >= qs && e <= qe) {
t[n] += val;
if (s != e) {
lazy[n << 1] += val;
lazy[n << 1 | 1] += val;
}
return;
}
int mid = s + e >> 1;
modifyUtil(s, mid, qs, qe, val, n << 1);
modifyUtil(mid + 1, e, qs, qe, val, n << 1 | 1);
t[n] = Math.min(t[n << 1], t[n << 1 | 1]);
}
long queryUtil(int s, int e, int qs, int qe, int n) {
if (lazy[n] != 0) {
t[n] += lazy[n];
if (s != e) {
lazy[n << 1] += lazy[n];
lazy[n << 1 | 1] += lazy[n];
}
lazy[n] = 0;
}
if (s > qe || e < qs) return Long.MAX_VALUE;
if (s >= qs && e <= qe) return t[n];
int mid = s + e >> 1;
return Math.min(queryUtil(s, mid, qs, qe, n << 1), queryUtil(mid + 1, e, qs, qe, n << 1 | 1));
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| java |
1141 | C | C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1
| [
"math"
] |
import java.io.*;
import java.math.*;
import java.util.*;
// @author : Dinosparton
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Sort implements Comparator<Pair>
{
@Override
public int compare(Pair a, Pair b)
{
if(a.x!=b.x)
{
return (int)(a.x - b.x);
}
else
{
return (int)(a.y-b.y);
}
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuilder res = new StringBuilder();
int tc = 1;
while(tc-->0) {
int n = sc.nextInt();
int a[] = new int[n-1];
for(int i=0;i<n-1;i++) {
a[i] = sc.nextInt();
}
int start = 1;
int sum = 0;
for(int i=0;i<n-1;i++) {
sum += a[i];
if(sum<0) {
start = Math.max(start, Math.abs(sum)+1);
}
}
int ans[] = new int[n];
Set<Integer> set = new HashSet<>();
ans[0] = start;
set.add(start);
for(int i=1;i<n;i++) {
ans[i] = ans[i-1] + a[i-1];
set.add(ans[i]);
}
boolean flag = true;
for(int i=1;i<=n;i++) {
if(!set.contains(i)) {
flag = false;
break;
}
}
if(flag) {
for(int i : ans) {
res.append(i+" ");
}
}
else {
res.append(-1);
}
}
System.out.println(res);
}
}
| java |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.Collection;
import java.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.util.Queue;
import java.util.LinkedList;
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);
FThreePathsOnATree solver = new FThreePathsOnATree();
solver.solve(1, in, out);
out.close();
}
static class FThreePathsOnATree {
int n;
int m;
ArrayList<Integer>[] g;
int[] dist;
boolean[] vis;
int[] par;
public void solve(int testNumber, InputReader in, OutputWriter out) {
pre(in);
int[] d1 = bfs(0);
int v1 = 0;
for (int i = 1; i < n; i++) {
if (d1[i] > d1[v1]) {
v1 = i;
}
}
int[] d2 = bfs(v1);
int v2 = 0;
for (int i = 1; i < n; i++) {
if (d2[i] > d2[v2]) {
v2 = i;
}
}
vis = new boolean[n];
path(v1, v2);
for (int i = 0; i < n; i++) {
if (vis[i]) dfs(i, -1, 0);
}
int v3 = 0;
for (int i = 0; i < n; i++) {
if (dist[i] > dist[v3]) {
v3 = i;
}
}
int tot = dist[v3] + d2[v2];
if (v3 == v1 || v3 == v2) {
for (int i = 0; i < n; i++) {
if (i != v1 && i != v2) {
v3 = i;
break;
}
}
}
out.println(tot);
out.println(v1 + 1, v2 + 1, v3 + 1);
}
void dfs(int nn, int pp, int d) {
dist[nn] = d;
for (int a : g[nn]) {
if (a == pp || vis[a]) continue;
dfs(a, nn, d + 1);
}
}
void path(int u, int v) {
vis[v] = true;
if (v == u) {
return;
}
path(u, par[v]);
}
int[] bfs(int u) {
int[] d = new int[n];
par = new int[n];
par[u] = -1;
Arrays.fill(d, Integer.MAX_VALUE);
Queue<Integer> q = new LinkedList<>();
d[u] = 0;
q.add(u);
while (!q.isEmpty()) {
int p = q.poll();
for (int a : g[p]) {
if (d[p] + 1 < d[a]) {
par[a] = p;
d[a] = d[p] + 1;
q.add(a);
}
}
}
return d;
}
void pre(InputReader in) {
n = in.nextInt();
m = n - 1;
g = new ArrayList[n];
dist = new int[n];
vis = new boolean[n];
for (int i = 0; i < n; i++) g[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1, b = in.nextInt() - 1;
g[a].add(b);
g[b].add(a);
}
}
}
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);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| java |
1293 | A | A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor. | [
"binary search",
"brute force",
"implementation"
] | import java.io.*;
import java.util.*;
public class cf {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
while(t-->0){
int n = input.nextInt();
int s = input.nextInt();
int k = input.nextInt();
HashSet<Integer> set = new HashSet<>();
while(k-->0){
set.add(input.nextInt());
}
int distance = 0;
for(int i=0; i<n; i++){
int down = s-i;
int up = s+i;
if(down>0 && !set.contains(down)){
distance=i;
break;
}
if(up<n+1 && !set.contains(up)){
distance=i;
break;
}
}
System.out.println(distance);
}
}
} | java |
1294 | E | E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22. | [
"greedy",
"implementation",
"math"
] | // package c1294;
//
// Codeforces Round #615 (Div. 3) 2020-01-22 06:35
// E. Obtain a Permutation
// https://codeforces.com/contest/1294/problem/E
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You are given a rectangular matrix of size n x m consisting of integers from 1 to 2 * 10^5.
//
// In one move, you can:
// * choose of the matrix and change its value to integer between 1 and n * m, inclusive;
// * take 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 j (1 <= j <= m) and set a_{1, j} :=
// a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} .
// https://espresso.codeforces.com/874a76a681a525102f53f73c046f306bcc2f1b6d.png Example of cyclic
// shift of the first column
//
// You want to perform the minimum number of moves to make this matrix look like this:
// https://espresso.codeforces.com/886b8c37bc9a14c44d2c736abb7a98b18d00de3d.png
//
// In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m}
// = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n * m (i.e. a_{i, j} = (i - 1) * m + j)
// with the performed.
//
// Input
//
// The first line of the input contains two integers n and m (1 <= n, m <= 2 * 10^5, n * m <= 2 *
// 10^5) -- the size of the matrix.
//
// The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1
// <= a_{i, j} <= 2 * 10^5).
//
// Output
//
// Print one integer -- the minimum number of moves required to obtain the matrix, where a_{1, 1} =
// 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n * m
// (a_{i, j} = (i - 1)m + j).
//
// Example
/*
input:
3 3
3 2 1
1 2 3
4 5 6
output:
6
input:
4 3
1 2 3
4 5 6
7 8 9
10 11 12
output:
0
input:
3 4
1 6 3 4
5 10 7 8
9 2 11 12
output:
2
*/
// Note
//
// In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the
// first, the second and the third columns cyclically, so the answer is 6. It can be shown that you
// cannot achieve a better answer.
//
// In the second example, the matrix is already good so the answer is 0.
//
// In the third example, it is enough to shift the second column cyclically twice to obtain a good
// matrix, so the answer is 2.
//
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
public class C1294E {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int solve(int[][] a) {
int n = a.length;
int m = a[0].length;
int ans = 0;
for (int j = 0; j < m; j++) {
Map<Integer, List<Integer>> vcm = new HashMap<>();
int total = 0;
for (int i = 0; i < n; i++) {
int v = a[i][j] - 1;
// target range of the column
int min = j;
int max = j + (n-1) * m;
if (v < min || v > max || v % m != j) {
// v must be replaced regardless shift amount
ans++;
if (test) System.out.format(" j:%d i:%d v:%d replace ans:%d\n", j, i, v + 1, ans);
} else {
total++;
int w = (n + ((j + i * m) - (a[i][j] - 1)) / m) % n;
vcm.computeIfAbsent(w, x -> new ArrayList<>()).add(i);
}
}
int cost = total;
for (Map.Entry<Integer, List<Integer>> e : vcm.entrySet()) {
int v = e.getKey();
List<Integer> idxes = e.getValue();
int k = (n + v) % n;
// If we shift up by k, this group is happy
int z = k + (total - idxes.size());
cost = Math.min(cost, z);
if (test) System.out.format(" j:%d v:%2d k:%d z:%2d cost:%d idxes:%s\n", j, v, k, z, cost, idxes.toString());
}
ans += cost;
}
return ans;
}
static String trace(int[][] a) {
return Arrays.deepToString(a).replace(" ", "").replace('[', '{').replace(']', '}');
}
static String trace(int[] a) {
return Arrays.toString(a).replace(" ", "").replace('[', '{').replace(']', '}');
}
static int solveNaive(int[][] a) {
int n = a.length;
int m = a[0].length;
int ans = 0;
for (int j = 0; j < m; j++) {
int cost = n + 1;
int minh = -1;
for (int h = 0; h < n; h++) {
int cnt = h;
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
int v = a[(i+h)%n][j];
nums[i] = v;
int e = j + i * m + 1;
if (v != e) {
cnt++;
}
}
if (cnt < cost) {
cost = cnt;
minh = h;
}
System.out.format(" j:%d h:%d cnt:%2d %s\n", j, h, cnt, trace(nums));
}
ans += cost;
}
return ans;
}
static void test(int[][] a) {
int ans = solve(a);
int exp = solveNaive(a);
System.out.format("%s => %d %s\n", trace(a), ans, ans == exp ? "":"Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
test(new int[][] {{9,7,8,5},{3,8,2,3},{9,2,9,7}});
for (int t = 0; t < 20; t++) {
int n = 1 + RAND.nextInt(10);
int m = 1 + RAND.nextInt(10);
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = 1 + RAND.nextInt(9);
}
}
test(a);
}
test(new int[][] {{3,2,1},{1,2,3},{4,5,6}});
test(new int[][] {{5},{6},{7},{8},{9},{1},{2},{3},{4}});
test(new int[][] {{5},{6},{7},{8},{9},{2},{2},{3},{4}});
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 m = in.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
}
}
int ans = solve(a);
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.