exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k ⌀ | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k ⌀ | difficulty int64 -1 3.5k ⌀ | prob_desc_output_spec stringlengths 17 1.47k ⌀ | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | eed848b107aea4d4e422c5225adbe875 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes |
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.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
*
* @author pttrung
*/
public class C_Round_728_Div2 {
public static long MOD = 1000000007;
static long[][] 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 T = in.nextInt();
for(int z = 0; z< T; z++){
int n = in.nextInt();
long[]data = new long[n];
for(int i = 0; i < n; i++){
data[i] = in.nextInt();
}
Arrays.sort(data);
long last = 0;
long result = 0;
long cur = 0;
for(int i = 1; i < n; i++){
long w = data[i] - last;
cur += w*i;
result += w - cur;
last = data[i];
}
out.println(result);
}
out.close();
}
static int other(int v, int n) {
return n - v - 1;
}
static long abs(long a) {
return a < 0 ? -a : a;
}
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 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, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * (val * a);
}
}
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 | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | fb541e7d61613854f4d144512f42c555 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | import java.util.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
//import java.util.*;
public class Solution {
static class FastScanner {
BufferedReader br;
StringTokenizer st ;
FastScanner(){
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
FastScanner(String file) {
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
st = new StringTokenizer("");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("file not found");
e.printStackTrace();
}
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
String readLine() throws IOException{
return br.readLine();
}
}
public static void main(String[] args) throws Exception {
FastScanner s = new FastScanner();
int t = s.nextInt();
for(int q=0;q<t;q++){
int n = s.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = s.nextInt();
}
long curr_val = 0;
long prev_sum = 0;
long ans = 0;
Arrays.sort(arr);
for(int i=1;i<n;i++){
curr_val += arr[i] - arr[i-1];
ans += arr[i] - arr[i-1];
ans -= (curr_val * i);
ans += prev_sum;
prev_sum+=arr[i];
}
System.out.println(ans);
}
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | 1455cb138a045769668943aa53b2ff76 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)throws Exception
{
Main ob=new Main();
ob.fun();
}
public void fun()throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(System.out);
int t=Integer.parseInt(br.readLine());
while(t-->0)
{
int n=Integer.parseInt(br.readLine());
String s[]=(br.readLine()).split(" ");
long a[]=new long[n];
Long A[]=new Long[n];
for(int i=0;i<n;i++)
{
a[i]=Long.parseLong(s[i]);
A[i]=new Long(a[i]);
}
Arrays.sort(A);
for(int i=0;i<n;i++)
{
a[i]=(long)(A[i]);
}
long diff[]=new long[n];
long neg=0l;
for(int i=1;i<n;i++)
{
diff[i]=i*(a[i]-a[i-1])+diff[i-1];
neg+=diff[i];
}
long ans=a[n-1];
ans-=neg;
pw.println(ans);
}
pw.flush();
}
public int floorSearch(int arr[], int low,int high, int x)
{
// If low and high cross each other
if (low > high)
return -1;
// If last element is smaller than x
if (x >= arr[high])
return high;
// Find the middle point
int mid = (low + high) / 2;
// If middle point is floor.
if (arr[mid] == x)
return mid;
// If x lies between mid-1 and mid
if (
mid > 0 && arr[mid - 1] <= x && x < arr[mid])
return mid - 1;
// If x is smaller than mid, floor
// must be in left half.
if (x < arr[mid])
return floorSearch(
arr, low,
mid - 1, x);
// If mid-1 is not floor and x is
// greater than arr[mid],
return floorSearch(
arr, mid + 1, high,
x);
}
public int ceilSearch(int arr[], int low, int high, int x)
{
int mid;
/* If x is smaller than or equal to the
first element, then return the first element */
if(x <= arr[low])
return low;
/* If x is greater than the last
element, then return -1 */
if(x > arr[high])
return -1;
/* get the index of middle element
of arr[low..high]*/
mid = (low + high)/2; /* low + (high - low)/2 */
/* If x is same as middle element,
then return mid */
if(arr[mid] == x)
return mid;
/* If x is greater than arr[mid], then
either arr[mid + 1] is ceiling of x or
ceiling lies in arr[mid+1...high] */
else if(arr[mid] < x)
{
if(mid + 1 <= high && x <= arr[mid+1])
return mid + 1;
else
return ceilSearch(arr, mid+1, high, x);
}
/* If x is smaller than arr[mid],
then either arr[mid] is ceiling of x
or ceiling lies in arr[low...mid-1] */
else
{
if(mid - 1 >= low && x > arr[mid-1])
return mid;
else
return ceilSearch(arr, low, mid - 1, x);
}
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | 8bebd9a92ceb6d75646f4b91aa052847 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | import java.util.*;
public class D {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
while(T-->0) {
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
Arrays.sort(a);
long mini=0;long ans=0;
for(int i=1;i<n;i++) {
long diff=a[i]-a[i-1];
mini=(-1)*diff*i+mini;
ans+=mini;
}
System.out.println(ans+a[n-1]);
}
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | 80be7e4567403644419a7402197c7db8 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Problem728C {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out);
int testCases = Integer.parseInt(reader.readLine());
for (int tt = 0; tt < testCases; tt++) {
int n = Integer.parseInt(reader.readLine());
Long[] d = new Long[n];
StringTokenizer info = new StringTokenizer(reader.readLine());
for (int i = 0; i < n; i++) {
d[i] = Long.parseLong(info.nextToken());
}
Arrays.sort(d);
long sum = 0;
long temp = 0;
for (int i = 1; i < n; i++) {
temp += i * (d[i] - d[i - 1]);
sum += temp;
}
writer.println(d[n - 1] - sum);
}
reader.close();
writer.close();
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | 019df33b00e996ae65b4e24580141a5f | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | //package coddeforces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* @author MANJEET JI
*
*/
public class C {
public static void main(String[] args) {
FastReader s = new FastReader();
int t = s.nextInt();
while (t > 0) {
int n = s.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = s.nextInt();
}
long ans = answer(arr);
System.out.println(ans);
t--;
}
}
private static long answer(int[] arr1) {
// TODO Auto-generated method stub
long ans = 0;
Arrays.sort(arr1);
long[] arr = new long[arr1.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = arr1[arr1.length - 1 - i];
}
long sum = arr[0];
long[] prefix = new long[arr.length];
prefix[arr.length - 1] = arr[arr.length - 1];
for (int i = prefix.length - 2; i >= 0; i--) {
prefix[i] = prefix[i + 1] + arr[i];
}
int a = arr.length - 1;
for (int i = 0; i < prefix.length - 1; i++) {
ans += a * arr[i] - prefix[i + 1];
a--;
}
ans = sum - ans;
// System.out.println(sum + " " + ans);
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());
}
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 | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | 2304a3839686a68f7972b2906cf5eff4 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | import java.util.*;
public class abc {
//utilities
static long mod = 1000000007;
static int inf = 1000000009;
static boolean isPerfectSquare(double x) {
if (x >= 0) {
double sr = Math.sqrt(x);
return ((sr * sr) == x);
}
return false;
}
static long max(long a, long b) {
if (a > b) return a;
else
return b;
}
static long min(long a, long b) {
if (a < b) return a;
return b;
}
static long hcf(long a, long b) {
if (b == 0) return a;
return hcf(b, a % b);
}
static void swap(long a[], int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static boolean prime[] = new boolean[10000002];
static void sieve(long n) {
prime[0] = false;
prime[1] = false;
for (int i = 2; i < 10000001; 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;
}
}
}
static long[] inArr(int n, Scanner sc) {
long a[] = new long[n];
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextLong();
}
return a;
}
static void init(int O, Scanner sc) {
O = sc.nextInt();
}
static void inlong(long o, Scanner sc) {
o = sc.nextLong();
}
static void inSt(String s, Scanner sc) {
s = sc.next();
}
//Main
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
long arr[] =new long[n];
for (int i = 0; i <n ; i++) {
arr[i]=sc.nextInt();
}
long ans=0;
Arrays.sort(arr);
long res=0,aux=0;
for(int i=1;i<=n-1;i++) {
res+=((arr[i-1]-arr[i])*i+aux);
aux=(arr[i-1]-arr[i])*i+aux;
}
System.out.println(res+arr[n-1]);
}
}
} | Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | ab936d7d6fcefeacb07bd443e27d0fe2 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.*;
/**
*
* @author xpeng
*/
import java.util.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static StringTokenizer st;
public static void main(String[] args) throws IOException {
int t = readInt();
for (int i = 0; i < t; i++) {
int n = readInt();
long[] arr = new long[n];
for (int j = 0; j < n; j++) {
arr[j]=readInt();
}
Arrays.sort(arr);
long sum1=0,sum2=0;
for (int j = 2; j < n; j++) {
sum1 += arr[j - 2];
sum2 -= (arr[j] * (j - 1));
sum2 += sum1;
}
System.out.println(sum2);
}
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readLine() throws IOException {
return br.readLine().trim();
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | e48289199951f071d53f31c4c849790d | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class C {
static class RealScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
public static void main(String[] args) {
RealScanner sc=new RealScanner();
int t=sc.nextInt();
while (t-->0){
long n=sc.nextLong();
long[] arr=new long[(int) n];
//List<Integer> l=new ArrayList<>();
for (int i=0;i<n;i++){
arr[i]=sc.nextInt();
// l.add(sc.nextLong());
}
Arrays.sort(arr);
// Collections.sort(l);
long val=0,s=0;
for (int i=2;i<n;i++){ //Main
s+=arr[i-2];
val-=arr[i]*(i-1);
val+=s;
}
System.out.println(val);
}
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | a588b6d31c3f2571ce765053a8ea1024 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | import java.util.*;
import java.io.*;
public class GreatGraphs {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int tests = Integer.parseInt(br.readLine());
for(int t=0; t<tests; t++) {
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
PriorityQueue<Long> pq = new PriorityQueue<Long>();
for(int i=0; i<n; i++) {
long next = Long.parseLong(st.nextToken());
pq.add(next);
}
pw.println(solve(pq));
}
pw.close();
br.close();
}
public static long solve(PriorityQueue<Long> pq) {
long ans = 0;
long sum = 0;
long prev = 0;
int numPassed = 0;
while(!pq.isEmpty()) {
sum += prev;
long next = pq.poll();
ans -= ((next)*numPassed - sum);
if(next > 0) {
ans += (next - prev);
}
numPassed++;
prev = next;
}
return ans;
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | 48df7fa71b889b9a3f1f70c68cc48ebf | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | 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 Pranay2516
*/
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);
CGreatGraphs solver = new CGreatGraphs();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class CGreatGraphs {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
long[] d = in.readLongArray(n);
func.sort(d);
long ans = 0;
long count = 0;
for (int i = 2; i < n; i++) {
ans -= d[i] * (i - 1);
count += d[i - 2];
ans += count;
}
out.println(ans);
}
}
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 long nextLong() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String next() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) array[i] = nextLong();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class func {
public static void sort(long[] arr) {
//Taken from @KharYusuf
int n = arr.length, mid, h, s, l, i, j, k;
long[] res = new long[n];
n--;
for (s = 1; s <= n; s <<= 1) {
for (l = 0; l < n; l += (s << 1)) {
h = Math.min(l + (s << 1) - 1, n);
mid = Math.min(l + s - 1, n);
i = l;
j = mid + 1;
k = l;
while (i <= mid && j <= h) res[k++] = (arr[i] <= arr[j] ? arr[i++] : arr[j++]);
while (i <= mid) res[k++] = arr[i++];
while (j <= h) res[k++] = arr[j++];
for (k = l; k <= h; k++) arr[k] = res[k];
}
}
}
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | e7abceeb8a842659912df4e4a2fabed4 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | import java.util.*;
import java.io.*;
public class AiseHi {
static Scanner sc = new Scanner(System.in);
static int mod = (int)(1e9+7);
static int n;
public static void main (String[] args) {
int t = 1;
t = sc.nextInt();
z : while(t-->0) {
int n = sc.nextInt();
ArrayList<long[]> csddsassdcscsdvyncsacsacs = new ArrayList<>();
for(int i=0;i<n;i++) {
long x = sc.nextLong();
csddsassdcscsdvyncsacsacs.add(new long[] {x,i+1});
}
Collections.sort(csddsassdcscsdvyncsacsacs,new Comparator<long[]>() {
@Override
public int compare(long[] o1, long[] o2) {
return (int) (o1[0] - o2[0]);
}
});
long csddsassdcscsdvyn = 0, csddsassdcscsdvyncsa = 0;
for(int i=1;i<csddsassdcscsdvyncsacsacs.size();i++) {
csddsassdcscsdvyn += csddsassdcscsdvyncsacsacs.get(i)[0] - csddsassdcscsdvyncsacsacs.get(i-1)[0];
}
long dif[] = new long[n];
dif[0] = 0;
for(int i=1;i<n;i++) {
dif[i] = csddsassdcscsdvyncsacsacs.get(i-1)[0] - csddsassdcscsdvyncsacsacs.get(i)[0];
}
for(int i=1;i<n;i++) {
csddsassdcscsdvyn += dif[i]*i;
csddsassdcscsdvyn = csddsassdcscsdvyn + (dif[i])*(i)*(n-i-1);
}
System.out.println(csddsassdcscsdvyn);
}
}
private static int[] query(int i) {
System.out.println("? "+i);
int ret[] = new int[n+1];
for(int j=1;j<=n;j++) ret[j] = sc.nextInt();
System.out.flush();
return ret;
}
private static int findn(int[] csddsassdcscsdvyncsacsacs, int l, int h, long m) {
int ret = -1;
while(l<=h) {
int mid = (l+h)/2;
if(csddsassdcscsdvyncsacsacs[mid]>m) {
h = mid-1;
}
else {
ret = mid;
l = mid+1;
}
}
return ret;
}
private static int find(int[] csddsassdcscsdvyncsacsacs, int l, int h, long m) {
int ret = -1;
while(l<=h) {
int mid = (l+h)/2;
if(csddsassdcscsdvyncsacsacs[mid]>=m) {
ret = mid;
h = mid-1;
}
else l = mid+1;
}
return ret;
}
private static boolean find(String ini, String csddsassdcscsdvyncsacsacs) {
return !KMPSearch(ini,csddsassdcscsdvyncsacsacs);
}
static boolean KMPSearch(String pat, String txt)
{
int M = pat.length();
int N = txt.length();
int lps[] = new int[M];
int j = 0;
computeLPSArray(pat, M, lps);
int i = 0;
while (i < N) {
if (pat.charAt(j) == txt.charAt(i)) {
j++;
i++;
}
if (j == M) {
j = lps[j - 1];
return true;
}
else if (i < N && pat.charAt(j) != txt.charAt(i)) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
return false;
}
static void computeLPSArray(String pat, int M, int lps[])
{
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] is always 0
// the loop calculates lps[i] for i = 1 to M-1
while (i < M) {
if (pat.charAt(i) == pat.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
// This is tricky. Consider the example.
// AAACAAAA and i = 7. The idea is similar
// to search step.
if (len != 0) {
len = lps[len - 1];
// Also, note that we do not increment
// i here
}
else // if (len == 0)
{
lps[i] = len;
i++;
}
}
}
}
// private static boolean check(long n,long val) {
// if(n == 0) return true;
//
// while(val<=n) {
//// if(check(n-val,))
// }
// }
private static int find(int[] csddsassdcscsdvyncsacsacs, TreeMap<Integer, Integer> ts, int lp) {
int ret = 1;
int idx = -1;
for(int i=csddsassdcscsdvyncsacsacs.length-1;i>=0;i--) {
if(csddsassdcscsdvyncsacsacs[i] == lp) {
idx = i;
break;
}
}
idx--;
int prev = lp;
while(idx>=0) {
if((prev - csddsassdcscsdvyncsacsacs[idx]) >= lp) {
ret++;
prev = csddsassdcscsdvyncsacsacs[idx];
}
idx--;
}
return ret;
}
private static void reverse(char[] s) {
char csddsassdcscsdvyncsacsacs[] = new char[s.length];
for(int i=0;i<s.length;i++) csddsassdcscsdvyncsacsacs[i] = s[i];
for(int i=0;i<s.length;i++)
s[i] = csddsassdcscsdvyncsacsacs[csddsassdcscsdvyncsacsacs.length-1-i];
}
private static boolean isPalindrome(char[] s) {
int n = s.length;
for(int i=0;i<n/2;i++)
if(s[i]!=s[n-1-i]) return false;
return true;
}
private static boolean is(char[] s) {
for(char c : s) if(c == '0') return false;
return true;
}
// static int ceil(int csddsassdcscsdvyncsacsacs,int b) {
// return csddsassdcscsdvyncsacsacs/b + (csddsassdcscsdvyncsacsacs%b==0?0:1);
// }
static boolean prime[] = new boolean[2000009];
// static int fac[] = new int[2000009];
static void sieve() {
prime[0] = true;
prime[1] = true;
int max = 1000000;
for(int i=2;i*i<=max;i++) {
if(!prime[i]) {
for(int j=i*i;j<=max;j+=i) {
prime[j] = true;
// fac[j] = i;
}
}
}
}
static long gcd(long csddsassdcscsdvyncsacsacs,long b) { if(b==0) return csddsassdcscsdvyncsacsacs; return gcd(b,csddsassdcscsdvyncsacsacs%b); }
}
class DSU {
int par[];
int size[];
DSU(int n) {
par = new int[n];
size = new int[n];
Arrays.fill(size, 1);
for(int i=0;i<n;i++) par[i] = i;
}
int findPar(int x) {
if(x == par[x]) return x;
return par[x] = findPar(par[x]);
}
boolean join(int u,int v) {
int fu = findPar(u);
int fv = findPar(v);
if(fu!=fv) {
if(size[fu]>size[fv]) {
par[fv] = fu;
size[fu] += size[fv];
}
else {
par[fu] = fv;
size[fv] += size[fu];
}
return true;
}
else return false;
}
} | Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | dac6088e6762cbf257f55bf9ae0a2e0b | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
public class codeforcesA{
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 sc=new FastReader();
StringBuilder sb=new StringBuilder();
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int ar[]=new int[n];
for(int i=0;i<n;i++){ar[i]=sc.nextInt();}
Arrays.sort(ar);
long sum[]=new long[n];
for(int i=0;i<n;i++){sum[i]=ar[i];}
for(int i=n-2;i>=0;i--){sum[i]+=sum[i+1];}
long ans=0;
for(int i=0;i<n-2;i++){
ans=ans-(sum[i+2]);
ans+=(long)((long)(n-2-i)*(long)ar[i]);
}
sb.append(ans+"\n");
}
System.out.println(sb.toString());
}
} | Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | 2753457cd62f8486d4832559024b9d27 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.PriorityQueue;
import java.util.Vector;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeMap;
import java.util.Collections;
import java.util.Comparator;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
int t = in.nextInt();
for (int i = 1; i <= t ; i++) {
solver.solve(1, in, out);
}
// solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long[] d = new long[n];
for (int i = 0; i < n; i++)
d[i] = Long.parseLong(in.next());
Arrays.sort(d);
long result = 0, accumulation = 0;
for (int i = 2; i < n; i++) {
accumulation = accumulation + d[i-2];
result = result - (d[i] * (i-1)) + accumulation;
}
out.println(result);
}
public static int gcd(int a, int b, int x, int y) {
if (a == 0) {
x = 0;
y = 1;
return b;
}
int x1 = 1, y1 = 1;
int res = gcd(b % a, a, x1, y1);
x = y1 - (b / a) * x1;
y = x1;
return res;
}
static long mod = (long) (1e9 + 7);
public static long pow(long x, long y) {
long result = 1; // initialize result
x = x % mod; // update x if it is more than or equal to mod
if (x == 0) {
return 0; // incase x is divisible by mod
}
while (y > 0) {
// if y is odd, multiply x with result
if ((y & 1) != 0) {
result = (result * x) % mod;
}
// y must be even now
y = y >> 1;
x = (x * x) % mod;
}
return result;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | 93ecab8ed426dee1f177b1bdde4d37d1 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes |
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.*;
import java.math.*;
public class Contract
{
static StringBuilder sb;
static dsu dsu;
static long fact[];
static long mod=(long)(1e9+7);
static ArrayList<Integer>l;
static int A[];
public static long[] sort(long[] a) {
int n = a.length;
ArrayList<Long> l = new ArrayList<>();
for (long i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a[i] = l.get(i);
return a;
}
static void solve()
{
int n=i();
long A[]=new long[n];
for(int i=0;i<n;i++)
A[i]=l();
sort(A);
long v1=0;long sum=0;
for(int i=2;i<n;i++)
{
sum+=A[i-2];
v1-=(A[i]*(i-1));
v1+=sum;
}
System.out.println(v1);
}
public static void main(String[] args)
{
sb=new StringBuilder();
l=new ArrayList<>();
int test=i();
for(int tt=1;tt<=test;tt++)
{
solve();
}
System.out.println(sb);
}
//*******************************************NCR%P*******************************************************
static long ncr(int n, int r)
{
if(r>n)
return (long)0;
long res=fact[n]%mod;
//System.out.println(res);
res=((long)(res%mod)*(long)(p(fact[r],mod-2)%mod))%mod;
res=((long)(res%mod)*(long)(p(fact[n-r],mod-2)%mod))%mod;
//System.out.println(res);
return res;
}
static long p(long x, long y)//POWER FXN //
{
if(y==0)
return 1;
long res=1;
while(y>0)
{
if(y%2==1)
{
res=(res*x)%mod;
y--;
}
x=(x*x)%mod;
y=y/2;
}
return res;
}
//*******************************************END*******************************************************
//*********************************Disjoint set union*************************//
static class dsu
{
int parent[];
dsu(int n)
{
parent=new int[n];
for(int i=0;i<n;i++)
parent[i]=-1;
}
int find(int a)
{
if(parent[a]<0)
return a;
else
{
int x=find(parent[a]);
parent[a]=x;
return x;
}
}
void merge(int a,int b)
{
a=find(a);
b=find(b);
if(a==b)
return;
parent[b]=a;
}
}
//*******************************************PRIME FACTORIZE *****************************************************************************************************//
static TreeMap<Integer,Integer> prime(long n)
{
TreeMap<Integer,Integer>h=new TreeMap<>();
long num=n;
for(int i=2;i<=Math.sqrt(num);i++)
{
if(n%i==0)
{
int nt=0;
while(n%i==0) {
n=n/i;
nt++;
}
h.put(i, nt);
}
}
if(n!=1)
h.put((int)n, 1);
return h;
}
//*************CLASS PAIR ***********************************************************************************************************************************************
static class pair implements Comparable<pair>
{
int x;
int y;
char c;
pair(int x, int y,char c) {
this.x = x;
this.y = y;
this.c=c;
}
public int compareTo(pair o)
{
return(int) (y-o.y);
}
}
//*************CLASS PAIR *****************************************************************************************************************************************************
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
public static int[] sort(int[] a) {
int n = a.length;
ArrayList<Integer> l = new ArrayList<>();
for (int i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a[i] = l.get(i);
return a;
}
public static long pow(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 != 0) {
res = (res * x);// % modulus;
y--;
}
x = (x * x);// % modulus;
y = y / 2;
}
return res;
}
//GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public static long gcd(long x, long y) {
if (x == 0)
return y;
else
return gcd(y % x, x);
}
//****************LOWEST COMMON MULTIPLE *************************************************************************************************************************************
public static long lcm(long x, long y) {
return (x * (y / gcd(x, y)));
}
//INPUT PATTERN******************************************************************************************************************************************************************
public static int i() {
return in.Int();
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static String s() {
return in.String();
}
public static int[] readArray(int n) {
int A[] = new int[n];
for (int i = 0; i < n; i++) {
A[i] = i();
}
return A;
}
public static long[] readArray(long n) {
long A[] = new long[(int) n];
for (int i = 0; i < n; i++) {
A[i] = l();
}
return A;
}
public int[][] deepCopy(int[][] matrix) {
return java.util.Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone());
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | de64bf9ba3216373ce88f3604134d901 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | /* 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
{//////////////////////////////////////////////////////////////////////////
public static class Pair
{
int x;
int y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
}
public static class EdgeComparator implements Comparator<Pair>{
//ascending order
public int compare(Pair p1,Pair p2) {
if (p1.x < p2.x)
return 1;
else if (p1.x > p2.x)
return -1;
return 0;
}
}
//////////////////////////////////////////////////////////////////////
static boolean prime[] = new boolean[100005];
public static void sieveOfEratosthenes()
{
Arrays.fill(prime,true);
for (int p = 2; p * p <= 100005; p++)
{
if (prime[p] == true)
{
for (int i = p * p; i <= 100005; i += p)
prime[i] = false;
}
}
}
//////////////////////////////////////////////////////////////////////////
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
int n = sc.nextInt();
long a[] = new long[n];
int p[] = new int[4*n+19];
//Arrays.fill(a,0);Arrays.fill(p,0);
long sum=0;
long res=0;
for(int i =0;i<n;i++)
{
a[i] = sc.nextLong();
}
if(n==1)
System.out.println(0);
else
{
Arrays.sort(a);
for(int i=2;i<n;i++){
sum+=a[i-2];
res-=(a[i]*(i-1));
res+=sum;
}
sum*=2;
sum/=4;
sum=0;
System.out.println(res);
}
}
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | 78b5202944f4d2c130b5298cca75cba2 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static long startTime = System.currentTimeMillis();
// for global initializations and methods starts here
// global initialisations and methods end here
static void run() {
boolean tc = true;
IkwinderFastIO r = new IkwinderFastIO();
//FastReader r = new FastReader();
try (OutputStream out = new BufferedOutputStream(System.out)) {
//long startTime = System.currentTimeMillis();
int testcases = tc ? r.ni() : 1;
int tcCounter = 1;
// Hold Here Sparky------------------->>>
// Solution Starts Here
start:
while (testcases-- > 0) {
int n = r.ni();
List<Long> list = new ArrayList<>();
for (int i=0;i<n;i++) list.add(r.nl());
list.sort(Collections.reverseOrder());
long sum = 0;
for (long ele : list) sum+=ele;
long count = list.get(0);
long k = n-1;
for (long ele : list){
count+=sum-ele*(k+1);
k--;
sum-=ele;
}
out.write((count + " ").getBytes());
out.write(("\n").getBytes());
}
// Solution Ends Here
} catch (IOException e) {
e.printStackTrace();
}
}
static class IkwinderFastIO {
final private int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public BufferedReader br;
public StringTokenizer st;
public IkwinderFastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public IkwinderFastIO(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String readLine() throws IOException {
byte[] buf = new byte[100000001]; // 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 ni() 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 nl() 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 nd() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
public static void main(String[] args) throws Exception {
run();
}
static long mod = 998244353;
static long modInv(long base, long e) {
long result = 1;
base %= mod;
while (e > 0) {
if ((e & 1) > 0) result = result * base % mod;
base = base * base % mod;
e >>= 1;
}
return result;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int ni() {
return Integer.parseInt(word());
}
long nl() {
return Long.parseLong(word());
}
double nd() {
return Double.parseDouble(word());
}
}
static int MOD = (int) (1e9 + 7);
static long powerLL(long x, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 1) result = result * x % MOD;
n = n / 2;
x = x * x % MOD;
}
return result;
}
static long powerStrings(int i1, int i2) {
String sa = String.valueOf(i1);
String sb = String.valueOf(i2);
long a = 0, b = 0;
for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD;
for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1);
return powerLL(a, b);
}
static long gcd(long a, long b) {
if (a == 0) return b;
else return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long lower_bound(List<Long> list, long k) {
int s = 0;
int e = list.size();
while (s != e) {
int mid = (s + e) >> 1;
if (list.get(mid) < k) s = mid + 1;
else e = mid;
}
if (s == list.size()) return -1;
return s;
}
static int upper_bound(List<Long> list, long k) {
int s = 0;
int e = list.size();
while (s != e) {
int mid = (s + e) >> 1;
if (list.get(mid) <= k) s = mid + 1;
else e = mid;
}
if (s == list.size()) return -1;
return s;
}
static void addEdge(ArrayList<ArrayList<Integer>> graph, int edge1, int edge2) {
graph.get(edge1).add(edge2);
graph.get(edge2).add(edge1);
}
public static class Pair implements Comparable<Pair> {
int first;
int second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if (this.first != o.first)
return (int) (this.first - o.first);
else return (int) (this.second - o.second);
}
}
public static class PairC<X, Y> implements Comparable<PairC> {
X first;
Y second;
public PairC(X first, Y second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(PairC o) {
// TODO Auto-generated method stub
return o.compareTo((PairC) first);
}
}
static boolean isCollectionsSorted(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false;
return true;
}
static boolean isCollectionsSortedReverseOrder(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false;
return true;
}
} | Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | daa33f0500f7a9ab3b7c53ab56181303 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb = new StringBuffer();
int t = Integer.parseInt(br.readLine());
while(t>0){
t--;
int n = Integer.parseInt(br.readLine());
String str[] = br.readLine().trim().split(" ");
long a[] = new long[n];
for(int i=0;i<n;i++){
a[i] = Long.parseLong(str[i]);
}
Arrays.sort(a);
long sum[] = new long[n];
for(int i=1;i<n;i++){
sum[i] = sum[i-1]+a[i];
}
long ans = 0;
for(int i=2;i<n;i++){
long ss = sum[i-2];
long pos = 0 - ((i-1)*a[i]);
ans += (pos+ss);
}
sb.append(ans+ "\n");
}
System.out.print(sb);
}
}
| Java | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | 04544e6526d4d64da7a074f01096d4f8 | train_107.jsonl | 1624635300 | Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
/**
* @author Naitik
*
*/
public class A
{
static FastReader sc=new FastReader();
static long dp[][];
static int mod=1000000007;
static int max;
static long bit[];
static HashMap<Integer,Integer> map;
public static void main(String[] args)
{
//CHECK FOR N=1
//CHECK FOR N=1
PrintWriter out=new PrintWriter(System.out);
//StringBuffer sb=new StringBuffer("");
int ttt=1;
ttt =i();
outer :while (ttt-- > 0)
{
int n=i();
long B[]=inputL(n);
sort(B);
long A[]=new long[n];
for(int i=1;i<n;i++) {
A[i]=B[i]-B[i-1];
}
long P[]=new long[n];
long res=0;
for(int i=1;i<n;i++) {
P[i]=P[i-1]+A[i]*i;
res+=P[i];
}
System.out.println(-1*(res-sum(A)));
}
out.close();
// System.out.println(sb.toString());
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1 //CHECK FOR M=0
}
static class Pair implements Comparable<Pair>
{
long x;
long y;
Pair(long x,long y){
this.x=x;
this.y=y;
}
@Override
public int compareTo(Pair o) {
if(this.x>o.x)
return 1;
else if(this.x<o.x)
return -1;
else {
if(this.y>o.y)
return 1;
else if(this.y<o.y)
return -1;
else
return 0;
}
}
/* FOR TREE MAP PAIR USE */
// public int compareTo(Pair o) {
// if (x > o.x) {
// return 1;
// }
// if (x < o.x) {
// return -1;
// }
// if (y > o.y) {
// return 1;
// }
// if (y < o.y) {
// return -1;
// }
// return 0;
// }
// public int hashCode()
// {
// final int temp = 14;
// int ans = 1;
// ans =x*31+y*13;
// return ans;
// }
//
// // Equal objects must produce the same
// // hash code as long as they are equal
// @Override
// public boolean equals(Object o)
// {
// if (this == o) {
// return true;
// }
// if (o == null) {
// return false;
// }
// if (this.getClass() != o.getClass()) {
// return false;
// }
// Pair other = (Pair)o;
// if (this.x != other.x || this.y!=other.y) {
// return false;
// }
// return true;
// }
}
//FRENWICK TREE
static void update(int i, int x){
for(; i < bit.length; i += (i&-i))
bit[i] += x;
}
static int sum(int i){
int ans = 0;
for(; i > 0; i -= (i&-i))
ans += bit[i];
return ans;
}
//END
static void add(int v) {
if(!map.containsKey(v)) {
map.put(v, 1);
}
else {
map.put(v, map.get(v)+1);
}
}
static void remove(int v) {
if(map.containsKey(v)) {
map.put(v, map.get(v)-1);
if(map.get(v)==0)
map.remove(v);
}
}
static int[] copy(int A[]) {
int B[]=new int[A.length];
for(int i=0;i<A.length;i++) {
B[i]=A[i];
}
return B;
}
static long[] copy(long A[]) {
long B[]=new long[A.length];
for(int i=0;i<A.length;i++) {
B[i]=A[i];
}
return B;
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static void reverse(long A[]) {
int n=A.length;
long B[]=new long[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void reverse(int A[]) {
int n=A.length;
int B[]=new int[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void input(int A[],int B[]) {
for(int i=0;i<A.length;i++) {
A[i]=sc.nextInt();
B[i]=sc.nextInt();
}
}
static int[][] input(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]=i();
}
}
return A;
}
static char[][] charinput(int n,int m){
char A[][]=new char[n][m];
for(int i=0;i<n;i++) {
String s=s();
for(int j=0;j<m;j++) {
A[i][j]=s.charAt(j);
}
}
return A;
}
static int find(int A[],int a) {
if(A[a]==a)
return a;
return A[a]=find(A, A[a]);
}
static int max(int A[]) {
int max=Integer.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static int min(int A[]) {
int min=Integer.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long max(long A[]) {
long max=Long.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static long min(long A[]) {
long min=Long.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long [] prefix(long A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] prefix(int A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] suffix(long A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static long [] suffix(int A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static void fill(int dp[]) {
Arrays.fill(dp, -1);
}
static void fill(int dp[][]) {
for(int i=0;i<dp.length;i++)
Arrays.fill(dp[i], -1);
}
static void fill(int dp[][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
Arrays.fill(dp[i][j],-1);
}
}
}
static void fill(int dp[][][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
for(int k=0;k<dp[0][0].length;k++) {
Arrays.fill(dp[i][j][k],-1);
}
}
}
}
static void fill(long dp[]) {
Arrays.fill(dp, -1);
}
static void fill(long dp[][]) {
for(int i=0;i<dp.length;i++)
Arrays.fill(dp[i], -1);
}
static void fill(long dp[][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
Arrays.fill(dp[i][j],-1);
}
}
}
static void fill(long dp[][][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
for(int k=0;k<dp[0][0].length;k++) {
Arrays.fill(dp[i][j][k],-1);
}
}
}
}
static int min(int a,int b) {
return Math.min(a, b);
}
static int min(int a,int b,int c) {
return Math.min(a, Math.min(b, c));
}
static int min(int a,int b,int c,int d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static int max(int a,int b) {
return Math.max(a, b);
}
static int max(int a,int b,int c) {
return Math.max(a, Math.max(b, c));
}
static int max(int a,int b,int c,int d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long min(long a,long b) {
return Math.min(a, b);
}
static long min(long a,long b,long c) {
return Math.min(a, Math.min(b, c));
}
static long min(long a,long b,long c,long d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static long max(long a,long b) {
return Math.max(a, b);
}
static long max(long a,long b,long c) {
return Math.max(a, Math.max(b, c));
}
static long max(long a,long b,long c,long d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long power(long x, long y, long p)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static void print(int A[]) {
for(int i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long A[]) {
for(long i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static long mod(long x) {
return ((x%mod + mod)%mod);
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static void sort(int[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static void sort(long[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static String sort(String s) {
Character ch[]=new Character[s.length()];
for(int i=0;i<s.length();i++) {
ch[i]=s.charAt(i);
}
Arrays.sort(ch);
StringBuffer st=new StringBuffer("");
for(int i=0;i<s.length();i++) {
st.append(ch[i]);
}
return st.toString();
}
static HashMap<Integer,Integer> hash(int A[]){
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Integer,Integer> tree(int A[]){
TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static 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 | ["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"] | 2 seconds | ["-3\n0\n0"] | NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$. | Java 8 | standard input | [
"constructive algorithms",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | 7dfe0db5a99e6e4d71eb012fab07685b | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,400 | For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory. | standard output | |
PASSED | 227668d28835cc7f824d026e35ba4339 | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes |
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
public final class D {
private static final int MOD = (int) (1e9 + 7);
static int n;
static int h = 10;
static int time;
static int[][] parents;
static int[][] edges;
static int[][] g;
static int[] d;
static int[] parent;
static int[] in;
static int[] out;
static long[][] dp;
static boolean[][] seen;
static long inv2;
public static void main(String[] args) throws IOException {
final FastReader fs = new FastReader();
n = fs.nextInt();
edges = new int[n - 1][2];
for (int i = 0; i < (n - 1); i++) {
final int u = fs.nextInt() - 1;
final int v = fs.nextInt() - 1;
edges[i] = new int[] { u, v };
}
g = packG();
inv2 = modPow(2, MOD - 2);
long res = 0;
for (int i = 0; i < n; i++) {
time = 0;
in = new int[n];
out = new int[n];
d = new int[n];
parent = new int[n];
dfs(i, i);
initParents();
dp = new long[n][n];
seen = new boolean[n][n];
for (int j = 0; j < n; j++) {
for (int k = j + 1; k < n; k++) {
final int lca = getLca(j, k);
final int u = d[j] - d[lca];
final int v = d[k] - d[lca];
res = (res + dfs2(u, v)) % MOD;
}
}
}
System.out.println((res * modPow(n, MOD - 2)) % MOD);
}
private static long dfs2(int l, int r) {
if (l == 0) {
return 0;
}
if (r == 0) {
return 1;
}
if (seen[l][r]) {
return dp[l][r];
}
long res = (dfs2(l - 1, r) + dfs2(l, r - 1)) % MOD;
res = (res * inv2) % MOD;
seen[l][r] = true;
return dp[l][r] = res;
}
private static void dfs(int u, int p) {
parent[u] = p;
in[u] = time++;
for (int v : g[u]) {
if (v != p) {
d[v] = d[u] + 1;
dfs(v, u);
}
}
out[u] = time;
}
private static long modPow(long a, long n) {
long res = 1;
while (n > 0) {
if (n % 2 == 1) {
res = res * a % MOD;
}
a = a * a % MOD;
n /= 2;
}
return res;
}
private static void initParents() {
parents = new int[h + 1][n];
parents[0] = parent;
for (int i = 1; i <= h; i++) {
for (int u = 0; u < n; u++) {
final int nodeParent = parents[i - 1][u];
parents[i][u] = parents[i - 1][nodeParent];
}
}
}
private static boolean isAncestor(int u, int v) {
return in[u] <= in[v] && out[v] <= out[u];
}
private static int getLca(int u, int v) {
if (isAncestor(u, v)) { return u; }
if (isAncestor(v, u)) { return v; }
for (int i = h; i >= 0; i--) {
if (!isAncestor(parents[i][u], v)) {
u = parents[i][u];
}
}
return parents[0][u];
}
private static int[][] packG() {
final int[][] g = new int[n][];
final int[] size = new int[n];
for (int[] edge : edges) {
++size[edge[0]];
++size[edge[1]];
}
for (int i = 0; i < n; i++) {
g[i] = new int[size[i]];
}
for (int[] edge : edges) {
g[edge[0]][--size[edge[0]]] = edge[1];
g[edge[1]][--size[edge[1]]] = edge[0];
}
return g;
}
static final class Utils {
private static class Shuffler {
private static void shuffle(int[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void shuffle(long[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
private static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
}
public static void shuffleSort(int[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
public static void shuffleSort(long[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
private Utils() {}
}
static class FastReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
FastReader(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 {
final byte[] buf = new byte[1024]; // 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 nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) { return -ret; }
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) { buffer[0] = -1; }
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) { fillBuffer(); }
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | b5e2ddc1adeb394d253f64d5da5289ac | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public final class D {
private static final int MOD = (int) (1e9 + 7);
static int n;
static int h = 10;
static int time;
static int[][] parents;
static int[][] edges;
static int[][] g;
static int[] d;
static int[] parent;
static int[] in;
static int[] out;
static long[][] dp;
static boolean[][] seen;
static long inv2;
public static void main(String[] args) {
final FastScanner fs = new FastScanner();
n = fs.nextInt();
edges = new int[n - 1][2];
for (int i = 0; i < (n - 1); i++) {
final int u = fs.nextInt() - 1;
final int v = fs.nextInt() - 1;
edges[i] = new int[] { u, v };
}
g = packG();
inv2 = modPow(2, MOD - 2);
long res = 0;
for (int i = 0; i < n; i++) {
time = 0;
in = new int[n];
out = new int[n];
d = new int[n];
parent = new int[n];
dfs(i, i);
initParents();
dp = new long[n][n];
seen = new boolean[n][n];
for (int j = 0; j < n; j++) {
for (int k = j + 1; k < n; k++) {
final int lca = getLca(j, k);
final int u = d[j] - d[lca];
final int v = d[k] - d[lca];
res = (res + dfs2(u, v)) % MOD;
}
}
}
System.out.println((res * modPow(n, MOD - 2)) % MOD);
}
private static long dfs2(int l, int r) {
if (l == 0) {
return 0;
}
if (r == 0) {
return 1;
}
if (seen[l][r]) {
return dp[l][r];
}
long res = (dfs2(l - 1, r) + dfs2(l, r - 1)) % MOD;
res = (res * inv2) % MOD;
seen[l][r] = true;
return dp[l][r] = res;
}
private static void dfs(int u, int p) {
parent[u] = p;
in[u] = time++;
for (int v : g[u]) {
if (v != p) {
d[v] = d[u] + 1;
dfs(v, u);
}
}
out[u] = time;
}
private static long modPow(long a, long n) {
long res = 1;
while (n > 0) {
if (n % 2 == 1) {
res = res * a % MOD;
}
a = a * a % MOD;
n /= 2;
}
return res;
}
private static void initParents() {
parents = new int[h + 1][n];
parents[0] = parent;
for (int i = 1; i <= h; i++) {
for (int u = 0; u < n; u++) {
final int nodeParent = parents[i - 1][u];
parents[i][u] = parents[i - 1][nodeParent];
}
}
}
private static boolean isAncestor(int u, int v) {
return in[u] <= in[v] && out[v] <= out[u];
}
private static int getLca(int u, int v) {
if (isAncestor(u, v)) { return u; }
if (isAncestor(v, u)) { return v; }
for (int i = h; i >= 0; i--) {
if (!isAncestor(parents[i][u], v)) {
u = parents[i][u];
}
}
return parents[0][u];
}
private static int[][] packG() {
final int[][] g = new int[n][];
final int[] size = new int[n];
for (int[] edge : edges) {
++size[edge[0]];
++size[edge[1]];
}
for (int i = 0; i < n; i++) {
g[i] = new int[size[i]];
}
for (int[] edge : edges) {
g[edge[0]][--size[edge[0]]] = edge[1];
g[edge[1]][--size[edge[1]]] = edge[0];
}
return g;
}
static final class Utils {
private static class Shuffler {
private static void shuffle(int[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void shuffle(long[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
private static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
}
public static void shuffleSort(int[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
public static void shuffleSort(long[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
private Utils() {}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
private String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int n) {
final int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = nextInt(); }
return a;
}
long[] nextLongArray(int n) {
final long[] a = new long[n];
for (int i = 0; i < n; i++) { a[i] = nextLong(); }
return a;
}
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | b52abeb05ca9e085dca756c3e8ba36a3 | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public final class D {
private static final int MOD = (int) (1e9 + 7);
static int n;
static int h = 10;
static int time;
static int[][] parents;
static int[][] edges;
static int[][] g;
static int[] d;
static int[] parent;
static int[] in;
static int[] out;
static long[][] dp;
static boolean[][] seen;
static long inv2;
public static void main(String[] args) {
final FastScanner fs = new FastScanner();
n = fs.nextInt();
edges = new int[n - 1][2];
for (int i = 0; i < (n - 1); i++) {
final int u = fs.nextInt() - 1;
final int v = fs.nextInt() - 1;
edges[i] = new int[] { u, v };
}
g = packG();
inv2 = modPow(2, MOD - 2);
long res = 0;
for (int i = 0; i < n; i++) {
time = 0;
in = new int[n];
out = new int[n];
d = new int[n];
parent = new int[n];
dfs(i, i);
initParents();
dp = new long[n][n];
seen = new boolean[n][n];
for (int j = 0; j < n; j++) {
for (int k = j + 1; k < n; k++) {
final int lca = getLca(j, k);
final int u = d[j] - d[lca];
final int v = d[k] - d[lca];
if (u < 0 || v < 0) {
System.out.println(
d[j] + " " + d[k] + " " + d[lca] + " " + j + " " + k + " " + lca + " " + i);
throw null;
}
res = (res + dfs2(u, v)) % MOD;
}
}
}
System.out.println((res * modPow(n, MOD - 2)) % MOD);
}
private static long dfs2(int l, int r) {
if (l == 0) {
return 0;
}
if (r == 0) {
return 1;
}
if (seen[l][r]) {
return dp[l][r];
}
long res = (dfs2(l - 1, r) + dfs2(l, r - 1)) % MOD;
res = (res * inv2) % MOD;
seen[l][r] = true;
return dp[l][r] = res;
}
private static void dfs(int u, int p) {
parent[u] = p;
in[u] = time++;
for (int v : g[u]) {
if (v != p) {
d[v] = d[u] + 1;
dfs(v, u);
}
}
out[u] = time;
}
private static long modPow(long a, long n) {
long res = 1;
while (n > 0) {
if (n % 2 == 1) {
res = res * a % MOD;
}
a = a * a % MOD;
n /= 2;
}
return res;
}
private static void initParents() {
parents = new int[h + 1][n];
parents[0] = parent;
for (int i = 1; i <= h; i++) {
for (int u = 0; u < n; u++) {
final int nodeParent = parents[i - 1][u];
parents[i][u] = parents[i - 1][nodeParent];
}
}
}
private static boolean isAncestor(int u, int v) {
return in[u] <= in[v] && out[v] <= out[u];
}
private static int getLca(int u, int v) {
if (isAncestor(u, v)) { return u; }
if (isAncestor(v, u)) { return v; }
for (int i = h; i >= 0; i--) {
if (!isAncestor(parents[i][u], v)) {
u = parents[i][u];
}
}
return parents[0][u];
}
private static int[][] packG() {
final int[][] g = new int[n][];
final int[] size = new int[n];
for (int[] edge : edges) {
++size[edge[0]];
++size[edge[1]];
}
for (int i = 0; i < n; i++) {
g[i] = new int[size[i]];
}
for (int[] edge : edges) {
g[edge[0]][--size[edge[0]]] = edge[1];
g[edge[1]][--size[edge[1]]] = edge[0];
}
return g;
}
static final class Utils {
private static class Shuffler {
private static void shuffle(int[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void shuffle(long[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
private static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
private static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
}
public static void shuffleSort(int[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
public static void shuffleSort(long[] arr) {
Shuffler.shuffle(arr);
Arrays.sort(arr);
}
private Utils() {}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
private String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int n) {
final int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = nextInt(); }
return a;
}
long[] nextLongArray(int n) {
final long[] a = new long[n];
for (int i = 0; i < n; i++) { a[i] = nextLong(); }
return a;
}
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | e54e28c265e37ed95c300647116cd6a9 | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes | import java.math.*;
public class D2 {
public Object solve () {
int N = sc.nextInt();
int [][] E = dec(sc.nextInts(N-1));
long [][] F = new long [N][N]; long H = modInv(2);
for (int j : rep(1, N)) {
F[0][j] = 1;
for (int i : rep(1, N))
F[i][j] = ((F[i-1][j] + F[i][j-1]) * H) % MOD;
}
int [][] G = graph(N, E);
long res = 0;
for (int s : rep(N)) {
LCA lca = new LCA(G, s, true);
for (int i : rep(N))
for (int j : rep(i)) {
int p = lca.query(i, j);
int x = lca.depth(i) - lca.depth(p), y = lca.depth(j) - lca.depth(p);
res = (res + F[x][y]) % MOD;
}
}
res = mod(res * modInv(N));
return res;
}
private static final int CONTEST_TYPE = 1;
private static void init () {
}
private static final int INF = (int) 1e9 + 10;
private static final int MOD = (int) 1e9 + 7;
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) { return wgraph(N, E)[0]; }
private static long mod (long x) { return mod(x, MOD); }
private static long mod (long x, long mod) { return ((x % mod) + mod) % mod; }
private static long modInv (long x) { return modInv(x, MOD); }
private static long modInv (long x, int mod) { return BigInteger.valueOf(x).modInverse(BigInteger.valueOf(mod)).longValue(); }
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
private static class LCA {
final boolean precalc;
private int [][] A;
private int [][] P;
private int [] D;
public LCA (int [][] G, int s, boolean precalc) {
this.precalc = precalc;
int N = G.length;
D = new int [N];
if (precalc) {
P = new int [N][N]; A = new int [N][];
dfs1(G, s, -1);
}
else {
P = new int [N][]; P[s] = new int [0];
dfs2(G, s, -1);
}
}
public int anc (int s, int j) {
assert D[s] >= j;
if (precalc)
return A[s][j];
else {
while (j > 0) {
int i = j & (-j);
s = P[s][Integer.numberOfTrailingZeros(i)];
j -= i;
}
return s;
}
}
public int depth (int i) {
return D[i];
}
public int query (int i, int j) {
if (precalc)
return P[i][j];
else if (D[i] < D[j])
return query(j, i);
else {
i = anc(i, D[i] - D[j]);
if (i == j)
return i;
for (int k = P[j].length - 1; k >= 0; --k)
if (k < P[j].length && P[i][k] != P[j][k]) {
i = P[i][k];
j = P[j][k];
}
assert P[i][0] == P[j][0];
int res = P[i][0];
return res;
}
}
private int [] dfs1 (int [][] G, int s, int p) {
D[s] = p >= 0 ? D[p] + 1 : 0; A[s] = new int [D[s] + 1];
P[s][s] = A[s][0] = s;
int N = G[s].length, M = 0;
int [][] L = new int [N][];
for (int i = 0; i < N; ++i)
if (G[s][i] != p) {
L[i] = dfs1(G, G[s][i], s);
M += L[i].length;
}
else
L[i] = new int [0];
int [] res = new int [M+1]; res[0] = s; int m = 1;
for (int j = 0; j < N; ++j)
for (int y : L[j]) {
A[y][D[y] - D[s]] = P[s][y] = P[y][s] = s;
res[m++] = y;
for (int i = 0; i < j; ++i)
for (int x : L[i])
P[x][y] = P[y][x] = s;
}
return res;
}
private void dfs2 (int [][] G, int s, int p) {
if (p >= 0) {
D[s] = D[p] + 1;
P[s] = new int [1 + Integer.numberOfTrailingZeros(Integer.highestOneBit(D[s]))];
P[s][0] = p;
for (int i = 1; i < P[s].length; ++i)
P[s][i] = P[P[s][i - 1]][i - 1];
}
for (int j : G[s])
if (j != p)
dfs2(G, j, s);
}
}
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int [] nextInts () {
String [] S = nextStrings(); int N = S.length;
int [] res = new int [N];
for (int i = 0; i < N; ++i)
res[i] = Integer.parseInt(S[i]);
return res;
}
public int [][] nextInts (int N) {
int [][] res = new int [N][];
for (int i = 0; i < N; ++i)
res[i] = nextInts();
return res;
}
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
int b;
StringBuilder res = new StringBuilder();
while ((b = System.in.read()) < ' ')
continue;
res.append((char)b);
while ((b = System.in.read()) >= ' ')
res.append((char)b);
return res.toString();
} catch (Exception e) {
throw new Error (e);
}
}
private MyScanner () {
try {
while (System.in.available() == 0)
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
java.util.List<String> str = new java.util.ArrayList<>();
append(str, o);
for (Object p : A)
append(str, p);
return String.join(delim, str.toArray(new String [0]));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (java.util.List<String> str, Object o) {
append(x -> append(str, x), x -> str.add(x.toString()), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void flush () { pw.flush(); System.out.flush(); }
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1)
flush();
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new D2().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
init();
IOUtils.run(N);
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 388a59fa28e6e0babb4651dba97c534f | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes | import java.math.*;
public class D2 {
public Object solve () {
int N = sc.nextInt();
int [][] E = dec(sc.nextInts(N-1));
long [][] F = new long [N][N]; long H = modInv(2);
for (int j : rep(1, N)) {
F[0][j] = 1;
for (int i : rep(1, N))
F[i][j] = ((F[i-1][j] + F[i][j-1]) * H) % MOD;
}
int [][] G = graph(N, E);
long res = 0;
for (int s : rep(N)) {
LCA lca = new LCA(G, s, true);
for (int i : rep(N))
for (int j : rep(i)) {
int p = lca.query(i, j);
int x = lca.depth(i) - lca.depth(p), y = lca.depth(j) - lca.depth(p);
res = (res + F[x][y]) % MOD;
}
}
res = mod(res * modInv(N));
return res;
}
private static final int CONTEST_TYPE = 1;
private static void init () {
}
private static final int INF = (int) 1e9 + 10;
private static final int MOD = (int) 1e9 + 7;
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) { return wgraph(N, E)[0]; }
private static long mod (long x) { return mod(x, MOD); }
private static long mod (long x, long mod) { return ((x % mod) + mod) % mod; }
private static long modInv (long x) { return modInv(x, MOD); }
private static long modInv (long x, int mod) { return BigInteger.valueOf(x).modInverse(BigInteger.valueOf(mod)).longValue(); }
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
private static class LCA {
final boolean precalc;
private int [][] A;
private int [][] P;
private int [] D;
public LCA (int [][] G, int s, boolean precalc) {
this.precalc = precalc;
int N = G.length;
D = new int [N];
if (precalc) {
P = new int [N][N]; A = new int [N][N];
dfs1(G, s, -1);
}
else {
P = new int [N][]; P[s] = new int [0];
dfs2(G, s, -1);
}
}
public int anc (int s, int j) {
assert D[s] >= j;
if (precalc)
return A[s][j];
else {
while (j > 0) {
int i = j & (-j);
s = P[s][Integer.numberOfTrailingZeros(i)];
j -= i;
}
return s;
}
}
public int depth (int i) {
return D[i];
}
public int query (int i, int j) {
if (precalc)
return P[i][j];
else if (D[i] < D[j])
return query(j, i);
else {
i = anc(i, D[i] - D[j]);
if (i == j)
return i;
for (int k = P[j].length - 1; k >= 0; --k)
if (k < P[j].length && P[i][k] != P[j][k]) {
i = P[i][k];
j = P[j][k];
}
assert P[i][0] == P[j][0];
int res = P[i][0];
return res;
}
}
private int [] dfs1 (int [][] G, int s, int p) {
D[s] = p >= 0 ? D[p] + 1 : 0; P[s][s] = s; A[s][0] = s;
int N = G[s].length, M = 0;
int [][] L = new int [N][];
for (int i = 0; i < N; ++i)
if (G[s][i] != p) {
L[i] = dfs1(G, G[s][i], s);
M += L[i].length;
}
else
L[i] = new int [0];
int [] res = new int [M+1]; res[0] = s; int m = 1;
for (int j = 0; j < N; ++j)
for (int y : L[j]) {
A[y][D[y] - D[s]] = P[s][y] = P[y][s] = s;
res[m++] = y;
for (int i = 0; i < j; ++i)
for (int x : L[i])
P[x][y] = P[y][x] = s;
}
return res;
}
private void dfs2 (int [][] G, int s, int p) {
if (p >= 0) {
D[s] = D[p] + 1;
P[s] = new int [1 + Integer.numberOfTrailingZeros(Integer.highestOneBit(D[s]))];
P[s][0] = p;
for (int i = 1; i < P[s].length; ++i)
P[s][i] = P[P[s][i - 1]][i - 1];
}
for (int j : G[s])
if (j != p)
dfs2(G, j, s);
}
}
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int [] nextInts () {
String [] S = nextStrings(); int N = S.length;
int [] res = new int [N];
for (int i = 0; i < N; ++i)
res[i] = Integer.parseInt(S[i]);
return res;
}
public int [][] nextInts (int N) {
int [][] res = new int [N][];
for (int i = 0; i < N; ++i)
res[i] = nextInts();
return res;
}
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
int b;
StringBuilder res = new StringBuilder();
while ((b = System.in.read()) < ' ')
continue;
res.append((char)b);
while ((b = System.in.read()) >= ' ')
res.append((char)b);
return res.toString();
} catch (Exception e) {
throw new Error (e);
}
}
private MyScanner () {
try {
while (System.in.available() == 0)
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
java.util.List<String> str = new java.util.ArrayList<>();
append(str, o);
for (Object p : A)
append(str, p);
return String.join(delim, str.toArray(new String [0]));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (java.util.List<String> str, Object o) {
append(x -> append(str, x), x -> str.add(x.toString()), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void flush () { pw.flush(); System.out.flush(); }
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1)
flush();
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new D2().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
init();
IOUtils.run(N);
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 1f2f9ac330be367b4b081b75dcd2d0fc | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes | import java.math.*;
public class D2 {
public Object solve () {
int N = sc.nextInt();
int [][] E = dec(sc.nextInts(N-1));
long [][] F = new long [N][N];
for (int j : rep(1, N)) {
F[0][j] = 1;
for (int i : rep(1, N))
F[i][j] = mod((F[i-1][j] + F[i][j-1]) * modInv(2));
}
int [][] G = graph(N, E);
long res = 0;
for (int s : rep(N)) {
LCA lca = new LCA(G, s, true);
for (int i : rep(N))
for (int j : rep(i)) {
int p = lca.query(i, j);
int x = lca.depth(i) - lca.depth(p), y = lca.depth(j) - lca.depth(p);
res = mod(res + F[x][y]);
}
}
res = mod(res * modInv(N));
return res;
}
private static final int CONTEST_TYPE = 1;
private static void init () {
}
private static final int INF = (int) 1e9 + 10;
private static final int MOD = (int) 1e9 + 7;
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) { return wgraph(N, E)[0]; }
private static long mod (long x) { return mod(x, MOD); }
private static long mod (long x, long mod) { return ((x % mod) + mod) % mod; }
private static long modInv (long x) { return modInv(x, MOD); }
private static long modInv (long x, int mod) { return BigInteger.valueOf(x).modInverse(BigInteger.valueOf(mod)).longValue(); }
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
private static class LCA {
final boolean precalc;
private int [][] A;
private int [][] P;
private int [] D;
public LCA (int [][] G, int s, boolean precalc) {
this.precalc = precalc;
int N = G.length;
D = new int [N];
if (precalc) {
P = new int [N][N]; A = new int [N][N];
dfs1(G, s, -1);
}
else {
P = new int [N][]; P[s] = new int [0];
dfs2(G, s, -1);
}
}
public int anc (int s, int j) {
assert D[s] >= j;
if (precalc)
return A[s][j];
else {
while (j > 0) {
int i = j & (-j);
s = P[s][Integer.numberOfTrailingZeros(i)];
j -= i;
}
return s;
}
}
public int depth (int i) {
return D[i];
}
public int query (int i, int j) {
if (precalc)
return P[i][j];
else if (D[i] < D[j])
return query(j, i);
else {
i = anc(i, D[i] - D[j]);
if (i == j)
return i;
for (int k = P[j].length - 1; k >= 0; --k)
if (k < P[j].length && P[i][k] != P[j][k]) {
i = P[i][k];
j = P[j][k];
}
assert P[i][0] == P[j][0];
int res = P[i][0];
return res;
}
}
private int [] dfs1 (int [][] G, int s, int p) {
D[s] = p >= 0 ? D[p] + 1 : 0; P[s][s] = s; A[s][0] = s;
int N = G[s].length, M = 0;
int [][] L = new int [N][];
for (int i = 0; i < N; ++i)
if (G[s][i] != p) {
L[i] = dfs1(G, G[s][i], s);
M += L[i].length;
}
else
L[i] = new int [0];
int [] res = new int [M+1]; res[0] = s; int m = 1;
for (int j = 0; j < N; ++j)
for (int y : L[j]) {
A[y][D[y] - D[s]] = P[s][y] = P[y][s] = s;
res[m++] = y;
for (int i = 0; i < j; ++i)
for (int x : L[i])
P[x][y] = P[y][x] = s;
}
return res;
}
private void dfs2 (int [][] G, int s, int p) {
if (p >= 0) {
D[s] = D[p] + 1;
P[s] = new int [1 + Integer.numberOfTrailingZeros(Integer.highestOneBit(D[s]))];
P[s][0] = p;
for (int i = 1; i < P[s].length; ++i)
P[s][i] = P[P[s][i - 1]][i - 1];
}
for (int j : G[s])
if (j != p)
dfs2(G, j, s);
}
}
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int [] nextInts () {
String [] S = nextStrings(); int N = S.length;
int [] res = new int [N];
for (int i = 0; i < N; ++i)
res[i] = Integer.parseInt(S[i]);
return res;
}
public int [][] nextInts (int N) {
int [][] res = new int [N][];
for (int i = 0; i < N; ++i)
res[i] = nextInts();
return res;
}
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
int b;
StringBuilder res = new StringBuilder();
while ((b = System.in.read()) < ' ')
continue;
res.append((char)b);
while ((b = System.in.read()) >= ' ')
res.append((char)b);
return res.toString();
} catch (Exception e) {
throw new Error (e);
}
}
private MyScanner () {
try {
while (System.in.available() == 0)
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
java.util.List<String> str = new java.util.ArrayList<>();
append(str, o);
for (Object p : A)
append(str, p);
return String.join(delim, str.toArray(new String [0]));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (java.util.List<String> str, Object o) {
append(x -> append(str, x), x -> str.add(x.toString()), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void flush () { pw.flush(); System.out.flush(); }
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1)
flush();
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new D2().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
init();
IOUtils.run(N);
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 476bc1f2f75ab58a3ef463efe7186faa | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes | import java.math.*;
public class D2 {
public Object solve () {
int N = sc.nextInt();
int [][] E = dec(sc.nextInts(N-1));
long [][] F = new long [N][N];
for (int j : rep(1, N)) {
F[0][j] = 1;
for (int i : rep(1, N))
F[i][j] = mod((F[i-1][j] + F[i][j-1]) * modInv(2));
}
int [][] G = graph(N, E);
long res = 0;
for (int s : rep(N)) {
LCA lca = new LCA(G, s);
for (int i : rep(N))
for (int j : rep(i)) {
int p = lca.query(i, j);
int x = lca.D[i] - lca.D[p], y = lca.D[j] - lca.D[p];
res = mod(res + F[x][y]);
}
}
res = mod(res * modInv(N));
return res;
}
private static final int CONTEST_TYPE = 1;
private static void init () {
}
private static final int INF = (int) 1e9 + 10;
private static final int MOD = (int) 1e9 + 7;
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) { return wgraph(N, E)[0]; }
private static long mod (long x) { return mod(x, MOD); }
private static long mod (long x, long mod) { return ((x % mod) + mod) % mod; }
private static long modInv (long x) { return modInv(x, MOD); }
private static long modInv (long x, int mod) { return BigInteger.valueOf(x).modInverse(BigInteger.valueOf(mod)).longValue(); }
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
private static class LCA {
private int [][] P;
private int [] D;
public LCA (int [][] G, int s) {
int N = G.length;
D = new int [N]; P = new int [N][]; P[s] = new int [0];
dfs(G, s, -1);
}
public int anc (int s, int j) {
assert D[s] >= j;
while (j > 0) {
int i = j & (-j);
s = P[s][Integer.numberOfTrailingZeros(i)];
j -= i;
}
return s;
}
public int query (int p, int q) {
if (D[p] < D[q])
return query(q, p);
p = anc(p, D[p] - D[q]);
if (p == q)
return p;
for (int i = P[q].length - 1; i >= 0; --i)
if (i < P[q].length && P[p][i] != P[q][i]) {
p = P[p][i];
q = P[q][i];
}
assert P[p][0] == P[q][0];
int res = P[p][0];
return res;
}
private void dfs(int [][] G, int s, int p) {
if (p >= 0) {
D[s] = D[p] + 1;
P[s] = new int [1 + Integer.numberOfTrailingZeros(Integer.highestOneBit(D[s]))];
P[s][0] = p;
for (int i = 1; i < P[s].length; ++i)
P[s][i] = P[P[s][i - 1]][i - 1];
}
for (int j : G[s])
if (j != p)
dfs(G, j, s);
}
}
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int [] nextInts () {
String [] S = nextStrings(); int N = S.length;
int [] res = new int [N];
for (int i = 0; i < N; ++i)
res[i] = Integer.parseInt(S[i]);
return res;
}
public int [][] nextInts (int N) {
int [][] res = new int [N][];
for (int i = 0; i < N; ++i)
res[i] = nextInts();
return res;
}
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
int b;
StringBuilder res = new StringBuilder();
while ((b = System.in.read()) < ' ')
continue;
res.append((char)b);
while ((b = System.in.read()) >= ' ')
res.append((char)b);
return res.toString();
} catch (Exception e) {
throw new Error (e);
}
}
private MyScanner () {
try {
while (System.in.available() == 0)
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
java.util.List<String> str = new java.util.ArrayList<>();
append(str, o);
for (Object p : A)
append(str, p);
return String.join(delim, str.toArray(new String [0]));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (java.util.List<String> str, Object o) {
append(x -> append(str, x), x -> str.add(x.toString()), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void flush () { pw.flush(); System.out.flush(); }
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1)
flush();
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new D2().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
init();
IOUtils.run(N);
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 5d9ffe78e365e4e92aa240315821f79f | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes | import java.math.*;
public class D2 {
public Object solve () {
int N = sc.nextInt();
int [][] E = dec(sc.nextInts(N-1));
G = graph(N, E);
long res = 0, M = modInv(N);
for (int i : rep(N)) {
long c = calc(i);
res = (res + c * M) % MOD;
}
return res;
}
long calc (int s) {
int N = G.length;
LCA lca = new LCA(G, s);
long res = 0;
for (int i : rep(N))
for (int j : rep(i)) {
int p = lca.query(i, j);
int a = lca.D[i] - lca.D[p], b = lca.D[j] - lca.D[p];
res = (res + F[a][b]) % MOD;
}
return res;
}
int [][] G;
private static final int CONTEST_TYPE = 1;
static long [][] F;
private static void init () {
int N = 205;
F = new long [N][N];
long H = modInv(2);
for (int j : rep(1, N)) {
F[0][j] = 1;
for (int i : rep(1, N))
F[i][j] = mod((F[i-1][j] + F[i][j-1]) * H);
}
}
private static final int INF = (int) 1e9 + 10;
private static final int MOD = (int) 1e9 + 7;
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) { return wgraph(N, E)[0]; }
private static long mod (long x) { return mod(x, MOD); }
private static long mod (long x, long mod) { return ((x % mod) + mod) % mod; }
private static long modInv (long x) { return modInv(x, MOD); }
private static long modInv (long x, int mod) { return BigInteger.valueOf(x).modInverse(BigInteger.valueOf(mod)).longValue(); }
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
private static class LCA {
private int [][] P;
private int [] D;
public LCA (int [][] G, int s) {
int N = G.length;
D = new int [N]; P = new int [N][]; P[s] = new int [0];
dfs(G, s, -1);
}
public int anc (int s, int j) {
assert D[s] >= j;
while (j > 0) {
int i = j & (-j);
s = P[s][Integer.numberOfTrailingZeros(i)];
j -= i;
}
return s;
}
public int query (int p, int q) {
if (D[p] < D[q])
return query(q, p);
p = anc(p, D[p] - D[q]);
if (p == q)
return p;
for (int i = P[q].length - 1; i >= 0; --i)
if (i < P[q].length && P[p][i] != P[q][i]) {
p = P[p][i];
q = P[q][i];
}
assert P[p][0] == P[q][0];
int res = P[p][0];
return res;
}
private void dfs(int [][] G, int s, int p) {
if (p >= 0) {
D[s] = D[p] + 1;
P[s] = new int [1 + Integer.numberOfTrailingZeros(Integer.highestOneBit(D[s]))];
P[s][0] = p;
for (int i = 1; i < P[s].length; ++i)
P[s][i] = P[P[s][i - 1]][i - 1];
}
for (int j : G[s])
if (j != p)
dfs(G, j, s);
}
}
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int [] nextInts () {
String [] S = nextStrings(); int N = S.length;
int [] res = new int [N];
for (int i = 0; i < N; ++i)
res[i] = Integer.parseInt(S[i]);
return res;
}
public int [][] nextInts (int N) {
int [][] res = new int [N][];
for (int i = 0; i < N; ++i)
res[i] = nextInts();
return res;
}
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
int b;
StringBuilder res = new StringBuilder();
while ((b = System.in.read()) < ' ')
continue;
res.append((char)b);
while ((b = System.in.read()) >= ' ')
res.append((char)b);
return res.toString();
} catch (Exception e) {
throw new Error (e);
}
}
private MyScanner () {
try {
while (System.in.available() == 0)
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
java.util.List<String> str = new java.util.ArrayList<>();
append(str, o);
for (Object p : A)
append(str, p);
return String.join(delim, str.toArray(new String [0]));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (java.util.List<String> str, Object o) {
append(x -> append(str, x), x -> str.add(x.toString()), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void flush () { pw.flush(); System.out.flush(); }
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1)
flush();
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new D2().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
init();
IOUtils.run(N);
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | d324b61cee5923570a5b1565e15c1765 | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes | import static java.util.Arrays.*;
import java.math.*;
public class D {
public Object solve () {
int N = sc.nextInt();
int [][] E = dec(sc.nextInts(N-1));
G = graph(N, E);
P = new int [N][N];
L = new int [N]; Q = new int [N]; D = new int [N]; T = new int [N];
long res = 0, M = modInv(N);
for (int i : rep(N)) {
long c = calc(i);
res = (res + c * M) % MOD;
}
return res;
}
long calc (int s) {
int N = G.length;
for (int i : rep[N])
fill(P[i], -1);
q = 0; dfs(s, -1, 0);
for (int i : Q)
for (int j : Q)
if (P[i][j] != i && P[i][j] != j)
P[i][j] = P[T[i]][T[j]];
long res = 0;
for (int i : rep[N])
for (int j : rep[i]) {
int p = P[i][j];
int a = D[i] - D[p], b = D[j] - D[p];
res = (res + F[a][b]) % MOD;
}
return res;
}
void dfs (int s, int p, int d) {
L[d] = s; Q[q++] = s; D[s] = d; T[s] = p;
for (int i : rep[d+1])
P[s][L[i]] = P[L[i]][s] = L[i];
for (int j : G[s])
if (j != p)
dfs(j, s, d+1);
}
int [][] G, P;
int [] L, Q, D, T;
int q;
private static final int CONTEST_TYPE = 1;
static long [][] F;
static int [][] rep;
private static void init () {
int N = 205;
F = new long [N][N];
long H = modInv(2);
for (int j : rep(1, N)) {
F[0][j] = 1;
for (int i : rep(1, N))
F[i][j] = mod((F[i-1][j] + F[i][j-1]) * H);
}
rep = new int [N][];
for (int i : rep(N))
rep[i] = rep(i);
}
private static final int INF = (int) 1e9 + 10;
private static final int MOD = (int) 1e9 + 7;
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) { return wgraph(N, E)[0]; }
private static long mod (long x) { return mod(x, MOD); }
private static long mod (long x, long mod) { return ((x % mod) + mod) % mod; }
private static long modInv (long x) { return modInv(x, MOD); }
private static long modInv (long x, int mod) { return BigInteger.valueOf(x).modInverse(BigInteger.valueOf(mod)).longValue(); }
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int [] nextInts () {
String [] S = nextStrings(); int N = S.length;
int [] res = new int [N];
for (int i = 0; i < N; ++i)
res[i] = Integer.parseInt(S[i]);
return res;
}
public int [][] nextInts (int N) {
int [][] res = new int [N][];
for (int i = 0; i < N; ++i)
res[i] = nextInts();
return res;
}
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
int b;
StringBuilder res = new StringBuilder();
while ((b = System.in.read()) < ' ')
continue;
res.append((char)b);
while ((b = System.in.read()) >= ' ')
res.append((char)b);
return res.toString();
} catch (Exception e) {
throw new Error (e);
}
}
private MyScanner () {
try {
while (System.in.available() == 0)
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
java.util.List<String> str = new java.util.ArrayList<>();
append(str, o);
for (Object p : A)
append(str, p);
return String.join(delim, str.toArray(new String [0]));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (java.util.List<String> str, Object o) {
append(x -> append(str, x), x -> str.add(x.toString()), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void flush () { pw.flush(); System.out.flush(); }
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1)
flush();
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new D().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
init();
IOUtils.run(N);
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 35e4642bc6ac11a7de2b9f129be81658 | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Contest1541D
{
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() { // reads in the next string
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() { // reads in the next int
return Integer.parseInt(next());
}
public long nextLong() { // reads in the next long
return Long.parseLong(next());
}
public double nextDouble() { // reads in the next double
return Double.parseDouble(next());
}
}
static InputReader r = new InputReader(System.in);
static PrintWriter pw = new PrintWriter(System.out);
static ArrayList<Integer>[] adj;static long m = 1000000007;
public static void main(String[] args)
{
int n = r.nextInt();
adj = new ArrayList[n];
for (int i = 0; i < n; i ++)
{
adj[i] = new ArrayList<Integer>();
}
for (int i = 0; i < n - 1; i ++)
{
int a = r.nextInt() - 1; int b = r.nextInt() - 1;
adj[a].add(b); adj[b].add(a);
}
long[][] dp = new long[n+2][n+2];
Arrays.fill(dp[0],1);
for (int i = 1; i <= n; i ++)
{
for (int j = 1; j <= n; j ++)
{
dp[i][j] = ((dp[i-1][j]*modInverse(2)%m+dp[i][j-1]*modInverse(2)%m)%m);
dp[i][j]%=m;
}
}
long total = 0;
for (int k = 0; k < n; k ++)
{
int[][] dist = new int[n][n];
for (int i = 0; i < n; i ++)
{
Queue<Integer> q = new LinkedList<Integer>();
boolean[] visit = new boolean[n];
q.add(i);
visit[i] = true;
while (!q.isEmpty())
{
int node = q.poll();
for (int next: adj[node])
{
if (!visit[next])
{
q.add(next);
visit[next] = true;
dist[i][next] = 1 + dist[i][node];
}
}
}
}
for (int i = 0; i < n; i ++)
{
for (int j = i+1; j < n; j ++)
{
int lca = (dist[k][i]+dist[k][j]-dist[i][j])/2;
int di = dist[k][i] - lca;
int dj = dist[k][j] - lca;
total += dp[dj][di]; total%=m;
}
}
}
pw.println(total*modInverse(n)%m);
//dp[i][j] is prob that i is before j
pw.close();
}
public static long binpow(long x, long n) {
assert(n >= 0);
x %= m; // note: m * m must be less than 2^63 to avoid ll overflow
long res = 1;
while (n > 0) {
if (n % 2 == 1) // if n is odd
res = res * x % m;
x = x * x % m;
n /= 2; // divide by two
}
return res;
}
public static long modInverse(long x) {
return binpow(x,m-2);
}
} | Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 63c30753faf872273172b73132d96278 | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes |
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class D {
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
private static int nextInt() {
try {
in.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return (int) in.nval;
}
private static long nextLong() {
try {
in.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return (long) in.nval;
}
private static String next(){
try {
in.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return in.sval;
}
static long mod = (long) (1e9 + 7);
static long inv2 = (mod + 1) / 2;
static List<Integer>[] edges;
public static void main(String[] args) {
n = nextInt();
edges = new List[n+1];
p = new int[n+1][9];
for (int i = 0; i < n + 1; i++) {
edges[i] = new ArrayList<>();
}
depth = new int[n+1];
dp = new long[n+1][n+1];
for (int i = 0; i <= n; i++) {
dp[0][i] = 1;
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
dp[i][j] = (dp[i-1][j] + dp[i][j-1]) * inv2 % mod;
}
}
for (int i = 0; i < n - 1; i++) {
int a = nextInt();
int b = nextInt();
edges[a].add(b);
edges[b].add(a);
}
invn = pow(n, mod-2,mod);
for(int i = 1; i <= n; i++){
solve(i);
}
System.out.println(ans);
}
static int n;
static long invn;
static long[][] dp;
static long ans = 0;
public static void solve(int u){
Arrays.fill(depth,0);
for (int[] ints : p) {
Arrays.fill(ints,0);
}
dfs(u,0);
for(int i = 1; i <= n; i++){
for(int j = 1; j < i; j++){//枚举树上两个不同的点求贡献
int k = lca(i, j);
if(k == i){
ans = (ans + invn) % mod;
} else if(k != j){
ans = (ans + invn * dp[depth[i] - depth[k]][depth[j] - depth[k]] % mod) % mod;
}
}
}
}
public static void dfs(int cur,int parent){
depth[cur] = depth[parent] + 1;
for (Integer next : edges[cur]) {
if(next==parent)continue;
p[next][0] = cur;
for (int i = 1; i <= 8; i++) {
p[next][i] = p[p[next][i-1]][i-1];
}
dfs(next,cur);
}
}
public static int lca(int u,int v) {
if (depth[u] < depth[v]) {
int t = u;
u = v;
v = t;
}
//离线到同一深度
for (int i = depth[u] - depth[v], j = 0; i != 0; i >>= 1, j++) {
if (i % 2 == 1) {
u = p[u][j];
}
}
if (u == v) return u;
for (int i = 8; i >= 0; i--) {
if (p[u][i] == p[v][i]) continue;
u = p[u][i];
v = p[v][i];
}
return p[u][0];
}
static int[] depth;
static int[][] p;
public static long pow(long n,long x,long mod) {
long res = 1;
while (x > 0) {
if ((x & 1) == 1) res = res * n % mod;
n = n * n % mod;
x >>= 1;
}
return res;
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 70cbb91e26078f4194cd94cbfe2ab019 | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes | 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);
DTreeArray solver = new DTreeArray();
solver.solve(1, in, out);
out.close();
}
static class DTreeArray {
int n;
int mod = (int) (1e9 + 7);
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
int[][] dist = new int[n + 1][n + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == j) {
dist[i][j] = 0;
} else {
dist[i][j] = 0x3f3f3f3f;
}
}
}
for (int i = 0; i < n - 1; i++) {
int a = in.nextInt();
int b = in.nextInt();
dist[a][b] = 1;
dist[b][a] = 1;
}
for (int k = 1; k <= n; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
long[][] dp = new long[n][n];
long inv2 = inv(2);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0) {
dp[i][j] = 0;
continue;
}
if (j == 0) {
dp[i][j] = 1;
continue;
}
dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) * inv2 % mod;
}
}
long res = 0;
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
for (int k = 1; k <= n; k++) {
int x = dist[i][k];
int y = dist[j][k];
int d = (x + y - dist[i][j]) / 2;
x -= d;
y -= d;
res = (res + dp[x][y]) % mod;
}
}
}
long invn = inv(n);
out.println(res * invn % mod);
}
long inv(int x) {
return qmi(x, mod - 2, mod);
}
long 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 res % p;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 11 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 32dce3460cce9e354b779d0ea3b27b78 | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public class Main {
static final long MOD = 1000000007L;
//static final long MOD2 = 1000000009L;
//static final long MOD = 998244353L;
//static final long INF = 500000000000L;
static final int INF = 1000000005;
static final int NINF = -1000000005;
//static final long INF = 1000000000000000000L;
static FastScanner sc;
static PrintWriter pw;
static final int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
public static void main(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(System.out);
int N = sc.ni();
ArrayList<Integer>[] tree = new ArrayList[N];
for (int i = 0; i < N; i++) {
tree[i] = new ArrayList<Integer>();
}
for (int i = 0; i < N-1; i++) {
int u = sc.ni()-1;
int v = sc.ni()-1;
tree[u].add(v);
tree[v].add(u);
}
Combo c = new Combo(2*N,MOD);
long[][][] prob = new long[N+1][N+1][2];
for (int d = 0; d <= N; d++) {
prob[0][d] = new long[]{0L,1L};
prob[d][0] = new long[]{1L,1L};
}
for (int d1 = 1; d1 <= N; d1++) {
for (int d2 = 1; d2 <= N; d2++) {
prob[d1][d2] = add(prob[d1-1][d2],prob[d1][d2-1]);
prob[d1][d2][1] = (2*prob[d1][d2][1])%MOD;
}
}
long[] ans = {0L,1L};
for (int r = 0; r < N; r++) {
LCA lca = new LCA(tree,r);
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
//does the inversion "j-i" exist?
int k = lca.lca(i,j);
int d1 = lca.depth[i]-lca.depth[k];
int d2 = lca.depth[j]-lca.depth[k];
ans = add(ans,prob[d1][d2]);
}
}
}
ans[1] = (N*ans[1])%MOD;
long print = c.frac(ans[0],ans[1]);
pw.println(print);
pw.close();
}
public static long[] add(long[] f1, long[] f2) {
long n = (f1[0]*f2[1]+f1[1]*f2[0])%MOD;
long d = (f1[1]*f2[1])%MOD;
return new long[]{n,d};
}
static class Combo {
//cache factorials
long[] facs;
long[] invfacs;
long MOD;
public Combo(int N, long M) {
MOD = M;
facs = new long[N+1];
invfacs = new long[N+1];
facs[0] = 1;
for (int i = 1; i <= N; i++) {
facs[i] = (facs[i-1]*i)%MOD;
}
invfacs[N] = power(facs[N],MOD-2);
for (int i = N-1; i >= 0; i--)
invfacs[i] = ((i+1)*invfacs[i+1])%MOD;
}
public long choose(int n, int k) {
if (n<0||k<0||n<k) return 0;
long denInv = (invfacs[k]*invfacs[n-k])%MOD;
long ans = (facs[n]*denInv)%MOD;
return ans;
}
public long factorial(int n) {
return facs[n];
}
//binary exponentation
public long power(long x, long y) {
long ans = 1;
x %= MOD;
while (y > 0) {
if((y&1)==1)
ans = (ans * x) % MOD;
y /= 2;
x = (x * x) % MOD;
}
return ans;
}
public long frac(long x, long y) {
return (x*power(y,MOD-2))%MOD;
}
}
static class LCA {
public ArrayList<Integer>[] tree;
public int root;
public int N;
public int[][] table;
public int[] depth;
public LCA(ArrayList<Integer>[] tree, int root) {
this.root = root;
this.tree = tree;
N = tree.length;
table = new int[N][8];
depth = new int[N];
depthDFS(root,0,-1);
buildTable();
}
private void buildTable() {
for (int d = 1; d < 8; d++) {
for (int i = 0; i < N; i++) {
int p = table[i][d-1];
if (p >= 0)
table[i][d] = table[p][d-1];
else
table[i][d] = -1;
}
}
}
private void depthDFS(int n, int d, int p) {
depth[n] = d;
table[n][0] = p; //the parent of n
for (int next: tree[n]) {
if (next==p) continue;
depthDFS(next,d+1,n);
}
}
public int lca(int u, int v) {
if (depth[u] < depth[v]) return lca(v,u);
int diff = depth[u]-depth[v];
for (int i = 0; i < 8; i++) {
if ((diff&(1<<i)) > 0)
u = table[u][i];
}
for (int i = 7; i >= 0; i--) {
if (table[u][i] >= 0 && table[v][i] >= 0 && table[u][i]!=table[v][i]) {
u = table[u][i];
v = table[v][i];
}
}
if (u==v)
return u;
else
return table[u][0];
}
}
public static void sort(int[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
public static void sort(long[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr);
}
//Sort an array (immune to quicksort TLE)
public static void sort(int[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
int[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
return a[0]-b[0];
}
});
}
public static void sort(long[][] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int r = rgen.nextInt(arr.length);
long[] temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
}
Arrays.sort(arr, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else
return 0;
//Ascending order.
}
});
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
st = null;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
int[][] graph(int N, int[][] edges) {
int[][] graph = new int[N][];
int[] sz = new int[N];
for (int[] e: edges) {
sz[e[0]] += 1;
sz[e[1]] += 1;
}
for (int i = 0; i < N; i++) {
graph[i] = new int[sz[i]];
}
int[] cur = new int[N];
for (int[] e: edges) {
graph[e[0]][cur[e[0]]] = e[1];
graph[e[1]][cur[e[1]]] = e[0];
cur[e[0]] += 1;
cur[e[1]] += 1;
}
return graph;
}
int[] intArray(int N, int mod) {
int[] ret = new int[N];
for (int i = 0; i < N; i++)
ret[i] = ni()+mod;
return ret;
}
char[] charArray(int N) {
char[] ret = new char[N];
for (int i = 0; i < N; i++)
ret[i] = next().charAt(0);
return ret;
}
long nl() {
return Long.parseLong(next());
}
long[] longArray(int N, long mod) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = nl()+mod;
return ret;
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 8 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 5791d7a699f242566e57d63a8dfd3413 | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static final long MOD = 1000000007;
static int[] readArray(int size, InputReader in) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = in.nextInt();
}
return a;
}
static void sortArray(int[] a) {
Random random = new Random();
for (int i = 0; i < a.length; i++) {
int randomPos = random.nextInt(a.length);
int t = a[i];
a[i] = a[randomPos];
a[randomPos] = t;
}
Arrays.sort(a);
}
private static long inv(long x, long mod, Map<Long, Long> cache) {
if (cache != null) {
if (!cache.containsKey(x)) {
cache.put(x, fastPow(x, mod - 2, mod));
}
return cache.get(x);
} else {
return fastPow(x, mod - 2, mod);
}
}
private static long fastPow(long x, long y, long mod) {
if (x == 1) {
return 1;
}
if (y == 0) {
return 1;
}
long p = fastPow(x, y / 2, mod) % mod;
p = p * p % mod;
if (y % 2 == 1) {
p = p * x % mod;
}
return p;
}
static long HALF = inv(2, MOD, null);
public static void main(String[] args) throws IOException {
long startTime = System.currentTimeMillis();
// InputReader in = new InputReader(new FileInputStream("input.txt"));
// PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("boards.out")));
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = in.nextInt();
long invN = inv(n, MOD, null);
long ans = 0;
List<Integer>[] tree = in.readTree(n);
long[][] ps = new long[202][202];
for (int i = 0; i < 202; i++) {
for (int j = 0; j < 202; j++) {
if (i == 0) {
ps[i][j] = 1;
} else if (j == 0) {
ps[i][j] = 0;
} else {
ps[i][j] = (ps[i - 1][j] + ps[i][j - 1]) * HALF % MOD;
}
}
}
for (int i = 0; i < n; i++) {
ans = (ans + dfs(tree, i, -1, new ArrayList<>(), new HashMap<>(), ps)) % MOD;
}
ans = ans * invN % MOD;
out.println(ans);
out.close();
}
private static long dfs(List<Integer>[] tree, int v, int p, List<Integer> parents, Map<Integer, Integer> children, long[][] ps) {
long ans = 0;
for (int i = 0; i < parents.size(); i++) {
if (parents.get(i) > v) {
ans += 1;
}
}
children.put(v, 1);
parents.add(v);
List<Map<Integer, Integer>> allChildren = new ArrayList<>();
for (int u : tree[v]) {
if (u == p) {
continue;
}
Map<Integer, Integer> uChildren = new HashMap();
ans = (ans + dfs(tree, u, v, parents, uChildren, ps)) % MOD;
allChildren.add(uChildren);
for (Integer uChild : uChildren.keySet()) {
children.put(uChild, uChildren.get(uChild) + 1);
}
}
for (int i = 0; i < allChildren.size(); i++) {
for (Integer u : allChildren.get(i).keySet()) {
for (int j = i + 1; j < allChildren.size(); j++) {
for (Integer w : allChildren.get(j).keySet()) {
int du = allChildren.get(i).get(u);
int dw = allChildren.get(j).get(w);
if (u > w) {
ans = (ans + ps[du][dw]) % MOD;
} else {
ans = (ans + ps[dw][du]) % MOD;
}
}
}
}
}
parents.remove(parents.size() - 1);
return ans;
}
private static long subMod(long x, long y, long mod) {
long res = x - y;
if (res < 0) {
return res + mod;
}
return res;
}
private static int readInt() throws IOException {
int result = 0;
boolean numWasRead = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c >= '0' && c <= '9') {
numWasRead = true;
result = result * 10 + c - '0';
} else if (numWasRead) break;
}
return result;
}
private static void outputArray(List<Integer> ans, PrintWriter out, boolean addOne) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < ans.size(); i++) {
long an = ans.get(i) + (addOne ? 1 : 0);
str.append(an);
if (i < ans.size() - 1) {
str.append(" ");
}
}
out.println(str);
}
private static long fromBinary(int[] binary) {
long res = 0;
long d = 1;
for (int i = 0; i < binary.length; i++) {
if (binary[i] == 1) {
res = res | d;
}
d = d << 1;
}
return res;
}
private static int[] getBinary(long a, int size) {
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = (int) ((a >> i) & 1);
}
return result;
}
private static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextString() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char nextChar() {
return next().charAt(0);
}
public String nextWord() {
return next();
}
private List<Integer>[] readTree(int n) {
return readGraph(n, n - 1);
}
private List<Integer>[] readGraph(int n, int m) {
List<Integer>[] result = new ArrayList[n];
for (int i = 0; i < n; i++) {
result[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = nextInt() - 1;
int v = nextInt() - 1;
result[u].add(v);
result[v].add(u);
}
return result;
}
private Map<Integer, Integer>[] readWeightedGraph(int n, int m, List<int[]> edges) {
Map<Integer, Integer>[] result = new HashMap[n];
for (int i = 0; i < n; i++) {
result[i] = new HashMap<>();
}
for (int i = 0; i < m; i++) {
int u = nextInt() - 1;
int v = nextInt() - 1;
int w = nextInt();
result[u].put(v, w);
result[v].put(u, w);
edges.add(new int[]{w, v, u});
}
return result;
}
}
} | Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 8 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 6090f1e011138dcf9014196e21dd7345 | train_107.jsonl | 1624635300 | You are given a tree consisting of $$$n$$$ nodes. You generate an array from the tree by marking nodes one by one.Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node. It can be shown that the process marks all nodes in the tree. The final array $$$a$$$ is the list of the nodes' labels in order of the time each node was marked.Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.The number of inversions in an array $$$a$$$ is the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i > a_j$$$. For example, the array $$$[4, 1, 3, 2]$$$ contains $$$4$$$ inversions: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class P1541D {
private static final long M = 1000000007L;
private final int n;
private final int[][] D;
private final long[] I;
private final long[][] Q;
private P1541D(int n, int[][] E) {
this.n = n;
this.D = getDarts(E);
this.I = new long[n+1];
for (int i = 1; i <= n; i++) {
I[i] = modinv(i);
}
this.Q = new long[n][n];
for (int b = 1; b < n; b++) {
Q[0][b] = 1;
}
for (int a = 1; a < n; a++) {
for (int b = 1; b < n; b++) {
Q[a][b] = (Q[a-1][b] + Q[a][b-1]) * I[2] % M;
}
}
}
private long get() {
long t = 0;
for (int i = 0; i < n; i++) {
t = (t + get(i)) % M;
}
t = (t * I[n]) % M;
return t;
}
private long get(final int i0) {
final int[] N = new int[n];
final int[] P = new int[n];
final int[] R = new int[n];
N[i0] = 1;
P[i0] = -1;
R[i0] = 0;
final int[] K = new int[n];
int i = i0;
while (true) {
final int k = K[i]++;
if (k < D[i].length) {
final int j = D[i][k];
if (K[j] == 0) {
N[j] = 1;
P[j] = i;
R[j] = R[i] + 1;
i = j;
}
} else {
if (i == i0) {
break;
}
N[P[i]] += N[i];
i = P[i];
}
}
Arrays.fill(K, 0);
i = i0;
long t = 0;
while (true) {
final int k = K[i]++;
if (k < D[i].length) {
final int j = D[i][k];
if (K[j] == 0) {
i = j;
}
} else {
if (i == i0) {
break;
}
if (i < i0) {
// log("A=" + (i0+1) + ", B=" + (i+1));
int a = R[i];
int b = 0;
int h = i;
int g;
do {
g = P[h];
a--;
b++;
final long q = Q[a][b];
final long ng = (N[g] - N[h]);
// log(" a=" + a + ", b=" + b + ", q=" + q
// +", g=" + (g+1) + ", ng=" + ng);
t = (t + (q * ng)) % M;
h = g;
} while (h != i0);
}
i = P[i];
}
}
return t;
}
public static void main(String[] args) throws IOException {
try {
final FastReader fr = new FastReader(
new BufferedInputStream(System.in));
final int n = fr.readInt();
final int[][] E = new int[n-1][2];
for (int i = 0; i < n-1; i++) {
E[i][0] = fr.readInt() - 1;
E[i][1] = fr.readInt() - 1;
}
System.out.println(new P1541D(n, E).get());
} catch (Throwable t) {
t.printStackTrace(System.out);
System.exit(1);
}
}
private static final void log(Object o) {
System.err.println(o);
}
private static class FastReader implements Closeable {
private static final byte B_SP = ' ';
private static final byte B_CR = '\r';
private static final byte B_LF = '\n';
private static final byte B_0 = '0';
private static final byte B_9 = '9';
private static final byte B_DASH = '-';
private final InputStream in;
private byte prev;
public FastReader(InputStream in) {
this.in = in;
}
public byte read() throws IOException {
return (prev = (byte) in.read());
}
public byte readNonWs() throws IOException {
byte b;
do {
b = read();
} while (b <= B_SP);
return b;
}
public int readInt() throws IOException {
byte b = readNonWs();
final boolean neg = (b == B_DASH);
if (neg) {
b = read();
}
int i = (b - B_0);
b = read();
while (b >= B_0 && b <= B_9) {
i = i * 10 + (b - B_0);
b = read();
}
return neg ? -i : i;
}
public long readLong() throws IOException {
byte b = readNonWs();
final boolean neg = (b == B_DASH);
if (neg) {
b = read();
}
long i = (b - B_0);
b = read();
while (b >= B_0 && b <= B_9) {
i = i * 10 + (b - B_0);
b = read();
}
return neg ? -i : i;
}
public int readToken(byte[] tbuf) throws IOException {
byte b = readNonWs();
int i = 0;
do {
tbuf[i++] = b;
b = read();
} while (b >= B_SP);
return i;
}
public int readLine(byte[] lbuf) throws IOException {
byte b;
if (prev == B_CR) {
b = read();
if (b == B_LF) {
b = read();
}
} else {
b = read();
}
int i = 0;
while (b >= B_SP) {
lbuf[i++] = b;
b = read();
}
return i;
}
@Override
public void close() throws IOException {
in.close();
}
}
private int[][] getDarts(int[][] edges) {
final List<List<Integer>> dartsL = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
dartsL.add(new ArrayList<>());
}
for (int j = 0; j < n-1; j++) {
dartsL.get(edges[j][0]).add(edges[j][1]);
dartsL.get(edges[j][1]).add(edges[j][0]);
}
final int[][] darts = new int[n][];
for (int i = 0; i < n; i++) {
darts[i] = toArray(dartsL.get(i));
}
return darts;
}
private static int[] toArray(final List<Integer> lst) {
final int[] arr = new int[lst.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = lst.get(i);
}
return arr;
}
private static long modinv(long a) {
long r0 = a;
long r1 = M;
long s0 = 1;
long s1 = 0;
long t0 = 0;
long t1 = 1;
while (r1 != 0) {
final long q = r0 / r1;
final long r2 = r0 - q * r1;
final long s2 = s0 - q * s1;
final long t2 = t0 - q * t1;
r0 = r1;
r1 = r2;
s0 = s1;
s1 = s2;
t0 = t1;
t1 = t2;
}
if (s0 < M) {
s0 += M;
}
return s0;
}
}
| Java | ["3\n1 2\n1 3", "6\n2 1\n2 3\n6 1\n1 4\n2 5", "5\n1 2\n1 3\n1 4\n2 5"] | 2 seconds | ["166666669", "500000009", "500000007"] | NoteThis is the tree from the first sample: For the first sample, the arrays are almost fixed. If node $$$2$$$ is chosen initially, then the only possible array is $$$[2, 1, 3]$$$ ($$$1$$$ inversion). If node $$$3$$$ is chosen initially, then the only possible array is $$$[3, 1, 2]$$$ ($$$2$$$ inversions). If node $$$1$$$ is chosen initially, the arrays $$$[1, 2, 3]$$$ ($$$0$$$ inversions) and $$$[1, 3, 2]$$$ ($$$1$$$ inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. $$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, so the answer is $$$166666669$$$.This is the tree from the second sample: This is the tree from the third sample: | Java 8 | standard input | [
"combinatorics",
"dp",
"graphs",
"math",
"probabilities",
"trees"
] | 987433ba0b6a115d05f79f512e329f7a | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of nodes in the tree. The next $$$n - 1$$$ lines each contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), denoting an edge between node $$$x$$$ and $$$y$$$. It's guaranteed that the given edges form a tree. | 2,300 | Output the expected number of inversions in the generated array modulo $$$10^9+7$$$. Formally, let $$$M = 10^9+7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | f2c86d4bae5c170c2b21f3b72bca8f2f | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Scanner;
public class Reverse_and_Concatenate {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while (t-- > 0) {
String nums = scan.next() + scan.nextLine();
String word = scan.next() + scan.nextLine();
String[] arrNums = nums.split(" ");
solve(word, Integer.parseInt(arrNums[1]));
}
}
public static void solve(String s, int n) {
String srev = "";
for (int i = s.length()-1; i >= 0; i--) {
srev += s.charAt(i);
}
if (srev.equals(s) || n < 1) {
System.out.println("1");
} else {
System.out.println("2");
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 79d789f496af9a4daee9d56e32ec11e5 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCase = sc.nextInt();
for (int i = 1;i<=testCase;++i){
int n,k;
n = sc.nextInt();
k = sc.nextInt();
String s = sc.next();
String rev = "";
for(int j = n - 1 ; j>=0 ; --j ){
rev+=s.charAt(j);
}
byte ans = 2;
if(s.equals(rev) || k== 0 ){
ans = 1;
}
System.out.println(ans);
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 6c25e88e2f28c9782f73e310c1c6caa8 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | 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();
int op = sc.nextInt();
String s = sc.next();
System.out.println(solve(s, n , op));
}
}
static boolean ispal(String s){
int low = 0 , high = s.length() - 1;
while(low < high){
if(s.charAt(low) != s.charAt(high)){
return false;
}
low++;
high--;
}
return true;
}
static int solve(String s, int n , int op){
if(op == 0){
return 1;
}
if(op == 1){
if(ispal(s)){
return 1;
}
else{
return 2;
}
}
if(op > 1){
if(ispal(s)){
return 1;
}
else{
return 2;
}
}
return 0;
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 3c3f3dde534622460c2cebc7154c1b32 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes |
// Working program with FastReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (this.st == null || !this.st.hasMoreElements()) {
try {
this.st = new StringTokenizer(this.br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return this.st.nextToken();
}
int nextInt() {
return Integer.parseInt(this.next());
}
long nextLong() {
return Long.parseLong(this.next());
}
double nextDouble() {
return Double.parseDouble(this.next());
}
String nextLine() {
String str = "";
try {
str = this.br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static boolean isPalindrome(String str) {
int end = str.length() - 1;
int start = 0;
boolean ans = true;
while (end > start) {
if (str.charAt(end) != str.charAt(start)) {
ans = false;
}
end--;
start++;
}
return ans;
}
public static void main(String[] args) throws IOException {
FastReader s = new FastReader();
int t = s.nextInt();
while (t > 0) {
int n = s.nextInt();
int k = s.nextInt();
String str = s.nextLine();
int ans = 0;
if (k > 0) {
if (isPalindrome(str)) {
ans = 1;
} else {
ans += 2;
}
} else {
ans = 1;
}
System.out.println(ans);
t--;
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 3f4dfdd0f0059d5d5674878925b224d7 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes |
// Working program using Reader Class
import java.util.Scanner;
public class Solution {
public static boolean isPalindrome(String str) {
int end = str.length() - 1;
int start = 0;
boolean ans = true;
while (end > start) {
if (str.charAt(end) != str.charAt(start)) {
ans = false;
}
end--;
start++;
}
return ans;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while (t > 0) {
int n = s.nextInt();
int k = s.nextInt();
s.nextLine();
String str = s.nextLine();
int ans = 0;
if (k > 0) {
if (isPalindrome(str)) {
ans = 1;
} else {
ans += 2;
}
} else {
ans = 1;
}
System.out.println(ans);
t--;
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 1b1443d1cd94701b10a7bb5e87869e76 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static long mod = 1000000007;
static long inv(long a, long b) {return 1 < a ? b - inv(b % a, a) * b / a : 1;}
static long mi(long a) {return inv(a, mod);}
static InputReader sc = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
//setUp();
int t = sc.nextInt();
while(t-- > 0){
int n = sc.nextInt();
int k = sc.nextInt();
String word = sc.next();
boolean result = isPalindrome(word);
if(result || k == 0){
out.println(1);
}else{
out.println(2);
}
}
out.flush();
out.close();
}
private static boolean isPalindrome(String word){
for(int i = 0 ; i < word.length(); i++){
if(word.charAt(i) != word.charAt(word.length() - 1 - i)){
return false;
}
}
return true;
}
public static void solve(){
}
static void setUp() throws IOException {
sc = new InputReader(new FileInputStream("input.txt"));
out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return str;
}
int[] readArray(int N){
int[] arr = new int[N];
for(int i = 0 ; i < N; i++){
arr[i] = sc.nextInt();
}
return arr;
}
}
public static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
public static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static class Pair<K,V> {
K key;
V val;
public Pair(K key, V val){
this.key = key;
this.val = val;
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | f0ff372456dc4dc62af29eb1fc9f9ead | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt(), n, k;
String s;
boolean c;
while(t -- > 0){
c = false;
n = sc.nextInt();
k = sc.nextInt();
s = sc.next();
for(int i = 0; i < n; i ++){
if(s.charAt(i) != s.charAt(n - 1 - i)){
c = true;
break;
}
}
System.out.println(k > 0 && n > 1 && c ? 2 : 1);
}
sc.close();
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 992c278757b72f3906b6eb1e8bc34e7f | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
public class ReverseAndConcatenate {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
for (int i = 0; i < t; i++) {
int n = scan.nextInt();
int k = scan.nextInt();
scan.nextLine();
String s = scan.nextLine();
if(k == 0){
System.out.println(1);
continue;
}
String temp = reverseString(s);
int count = 1;
for(int j = 0; j < k; j++){
if(temp.equals(s)){
break;
}
else{
count++;
s += temp;
temp = s;
}
}
System.out.println(count);
}
}
public static String reverseString(String s) {
String reversed = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed += s.charAt(i);
}
return reversed;
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 91b19d5413718da293246f67401f6713 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.Integer;
public class contests {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
while (n-->0)
{
int t = in.nextInt();
int g = in.nextInt();
String s = in.next();
char a[] = s.toCharArray();
int j = s.length()-1;
int i = 0;
boolean f=false;
while (j>i)
{
if (a[i] != a[j])
{
f=true;
break;
}
j--;
i++;
}
if (f==false || g==0)
{
System.out.println("1");
}
else
{
System.out.println("2");
}
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 1da4569e651ff3ebb9e2075404973a15 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Scanner;
public class ReverseAndConcatenate {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-->0) {
int n = scanner.nextInt();
int k = scanner.nextInt();
String s = scanner.next();
String rev = new StringBuffer(s).reverse().toString();
if(s.length() == n) {
ReverseAndConcatenate obj = new ReverseAndConcatenate();
obj.check(s, k, n);
}
}
}
public void check(String s, int k, int n) {
if (k==0) {
System.out.println("1");
}else if (k>=1) {
boolean result = checkPalin(s, n);
if (result == true) {
System.out.println("1");
} else
System.out.println("2");
}
}
public boolean checkPalin(String s, int n) {
int start = 0, end = n-1;
while (start<end){
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 179e9100ec2c46060aa7ed94810a81b5 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | /*
AUTHOR-> HARSHIT AGGARWAL
CODEFORCES HANDLE-> @harshit_agg
FROM-> MAHARAJA AGRASEN INSTITUE OF TECHNOLOGY
>> YOU CAN DO THIS <<
*/
import java.util.*;
import java.io.*;
public class reverseAndConcatenate {
public static void main(String[] args) throws Exception {
int t = scn.nextInt();
while (t-- > 0) {
solver();
}
}
public static void solver() {
int n = scn.nextInt();
int k = scn.nextInt();
String str= scn.next();
if(k == 0 || pal(str)){
// Debug.dbg("In if"+" "+k+" "+pal(str)+" "+str);
System.out.println(1);
}else{
System.out.println(2);
}
}
public static boolean pal (String str){
char[] arr = str.toCharArray();
int i = 0; int j = str.length()-1;
while( i < j){
if(arr[i] != arr[j])return false;
i++; j--;
}
return true;
}
//-------------------------------- HO JA BHAI ----------------------------------------------------
/* code ends here*/
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx U T I L I T I E S xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
public static class Debug { public static final boolean LOCAL = System.getProperty("LOCAL")==null; private static <T> String ts(T t) { if(t==null) { return "null"; } try { return ts((Iterable) t); }catch(ClassCastException e) { if(t instanceof int[]) { String s = Arrays.toString((int[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof long[]) { String s = Arrays.toString((long[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof char[]) { String s = Arrays.toString((char[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof double[]) { String s = Arrays.toString((double[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof boolean[]) { String s = Arrays.toString((boolean[]) t); return "{"+s.substring(1, s.length()-1)+"}"; } try { return ts((Object[]) t); }catch(ClassCastException e1) { return t.toString(); } } } private static <T> String ts(T[] arr) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: arr) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } private static <T> String ts(Iterable<T> iter) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: iter) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } public static void dbg(Object... o) { if(LOCAL) { System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": ["); for(int i = 0; i<o.length; i++) { if(i!=0) { System.err.print(", "); } System.err.print(ts(o[i])); } System.err.println("]"); } } }
static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { try { br = new BufferedReader(new FileReader("input.txt")); PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out); } catch (Exception e) { 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 int INF = (int) 1e9 + 7; // static int INF = 998244353;
static int MAX = Integer.MAX_VALUE; // static int MAX = 2147483647
static int MIN = Integer.MIN_VALUE; // static int MIN = -2147483647
static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair o) { return this.first- o.first; } }
static class LongPair { long first; long second; LongPair(long a, long b) { this.first = a; this.second = b; } }
public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); }
public static int LowerBound(long a[], long x) { /* x is the key or target value */int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r; }
public static int LowerBound(int a[], int x) { /* x is the key or target value */int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r; }
static int LowerBoundList(ArrayList<Integer> a, int x) { /* x is the key or target value */int l = -1, r = a.size(); while (l + 1 < r) { int m = (l + r) >>> 1; if (a.get(m) >= x) r = m; else l = m; } return r; }
static boolean[] prime; public static void sieveOfEratosthenes(int n) { 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; } } }
public static int UpperBound(long a[], long x) {/* x is the key or target value */int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] <= x) l = m; else r = m; } return l + 1; }
public static int UpperBound(int a[], int x) {/* x is the key or target value */int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] <= x) l = m; else r = m; } return l + 1; }
public static long lcm(long a, long b) { return (a * b) / gcd(a, b); }
public static void swap(int[] arr, int i, int j) { if (i != j) { arr[i] ^= arr[j]; arr[j] ^= arr[i]; arr[i] ^= arr[j]; } }
public static long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = scn.nextLong(); return a; }
public static int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scn.nextInt(); } return a; }
public int[][] nextIntMatrix(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { grid[i] = nextIntArray(m); } return grid; }
public static int smallest_divisor(int n) { int i; for (i = 2; i <= Math.sqrt(n); ++i) { if (n % i == 0) { return i; } } return n; }
public static FastReader scn = new FastReader();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 9e8274efc87e64cf0f2ad71c9715cecb | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | // package practise;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class A {
// static Reader sc;
static PrintWriter w;
public static void main(String[] args) throws IOException {
//sc = new Reader();
Scanner sc= new Scanner(System.in);
w = new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int k=sc.nextInt();
String s=sc.next();
if(s.length()==1) {
w.println(Math.min(1,k+1));
continue;
}
if(s.length()==2) {
w.println(Math.min(2,k+1));
continue;
}
int ct=1;
for(int i=0;i<k;i++) {
if(s.length()>2 && s.charAt(0)==s.charAt(s.length()-1) && isPalindrome(s.substring(1,s.length()-1)) ) {
break;
}
StringBuilder temp= new StringBuilder();
for(int j=s.length()-1;j>=0;j--) {
temp.append(s.charAt(j));
}
String rev=temp.toString();
s=s.concat(rev);
ct++;
}
w.println(ct);
}
w.close();
}
static void solve() throws IOException {
}
static boolean isPalindrome(String str)
{
// Pointers pointing to the beginning
// and the end of the string
int i = 0, j = str.length() - 1;
// While there are characters to compare
while (i < j) {
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;
// Increment first pointer and
// decrement the other
i++;
j--;
}
// Given string is a palindrome
return true;
}
static class FenwickTree{
int tree[];
void contructFenwickTree(int ar[],int n) {
tree= new int[n+1];
for(int i=0;i<ar.length;i++) {
update(i,ar[i],n);
}
}
void update(int i,int delta,int n) { //delta means newValue - preValue.
//i is index of array.
i++;
while(i<=n) {
tree[i]+=delta;
i=i+Integer.lowestOneBit(i);
}
}
int getSum(int i ){
int sum=0;
i++;
while(i>0) {
sum+=tree[i];
i-=Integer.lowestOneBit(i);
}
return sum;
}
int rangeOfSum(int i,int j) {
return getSum(j)-getSum(i-1);
}
}
static ArrayList<Integer> findDiv(int N)
{
//gens all divisors of N
ArrayList<Integer> ls1 = new ArrayList<Integer>();
ArrayList<Integer> ls2 = new ArrayList<Integer>();
for(int i=1; i <= (int)(Math.sqrt(N)+0.00000001); i++)
if(N%i == 0)
{
ls1.add(i);
ls2.add(N/i);
}
Collections.reverse(ls2);
for(int b: ls2)
if(b != ls1.get(ls1.size()-1))
ls1.add(b);
return ls1;
}
static void sort(int[] arr)
{
//because Arrays.sort() uses quicksort which is dumb
//Collections.sort() uses merge sort
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
static long power(long x, long y, long p)
{
//0^0 = 1
long res = 1L;
x = x%p;
while(y > 0)
{
if((y&1)==1)
res = (res*x)%p;
y >>= 1;
x = (x*x)%p;
}
return res;
}
static class Reader // here reader class is defined.
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | a289d73600420ce8fae2f9b3be6a72c1 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes |
//Break in nested for loops creates problem in java
import java.util.*;
import java.io.*;
import java.lang.*;
//import java.util.stream.*;
public class A {
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();
}
}
static int mod=1000000007;
// Power under mod (a ^ b) % mod
// int modpow(int a, int b, int m = mod) {
// int ans = 1;
// while (b) {
// if (b & 1) { ans = (ans * a) % m; }
// b = b >> 1; a = (a * a) % m;
// }
// return ans;
// }
//
// // Inverse Mod (1 / a) % mod
// int modinv(int a, int m = mod) { return modpow(a, m - 2); }
//
// // Modular Arithematic
// int modadd(int a, int b, int m = mod) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; }
// int modsub(int a, int b, int m = mod) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; }
// int modmul(int a, int b, int m = mod) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; }
// int moddiv(int a, int b, int m = mod) { a = a % m; b = b % m; return (modmul(a, modinv(b, m), m) + m) % m; }
static Boolean isSquare(int n)
{
int y= (int)Math.sqrt(n);
return y*y==n;
}
static int highestPowerof2(int x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
static boolean check_pow (int x)
{
return x!=0 && ((x&(x-1)) == 0);
}
static int digits(int n)
{
if(n==0)
return 1;
return (int)(Math.floor(Math.log10(n))+1);
}
static boolean isPalindrome(String str)
{
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j))
return false;
i++;j--;
}
return true;
}
public static boolean IsPrime(long number)
{
if (number < 2) return false;
if (number % 2 == 0) return (number == 2);
int root = (int)Math.sqrt((double)number);
for (int i = 3; i <= root; i += 2)
{
if (number % i == 0) return false;
}
return true;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static int sum(int p)
{
int ans=0;
while(p!=0)
{
ans+=p%10;
p/=10;
}
return ans;
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
FastReader sc= new FastReader();
//FastWriter out = new FastWriter();
StringBuilder sb=new StringBuilder("");
//PrintWriter out= new PrintWriter(System.out);
//Collections.sort(A, (a, b) -> Integer.compare(b[1], a[1]));
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt(),k=sc.nextInt();
String s=sc.nextLine();
if(isPalindrome(s))
System.out.println(1);
else {
if(k==0)
System.out.println(1);
else
System.out.println(2);
}
}
//out.close();
}
}
class Pair {
int x;
int y;
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
}
class Compare {
static void comparey(Pair arr[], int n)
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return p1.y - p2.y;
}
});
}
static void comparex(Pair arr[], int n)
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return p1.x - p2.x;
}
});
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 0ef99c08aa00789ba4defa2e14a0c98c | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class MyClass {
public static boolean check(String s){
if(s.length()%2==0){
for(int i=0;i<s.length()/2;i++){
if(s.charAt(s.length()/2-i-1)!=s.charAt(s.length()/2+i)){
return false;
}
}
}
else
{
for(int i=0;i<s.length()/2;i++){
if(s.charAt(s.length()/2-i-1)!=s.charAt(s.length()/2+i+1)){
return false;
}
}
}
return true;
}
public static void main(String args[]) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
for(int i=0;i<n;i++){
int a=s.nextInt();
int b=s.nextInt();
String str=s.next();
if(a==1){
System.out.println(1);
}
else if(b==0){
System.out.println(1);
}
else
{
if(check(str)){
System.out.println(1);
}else{
System.out.println(2);
}}
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 26a66f3794bfb3af7ca3113b15f4d8c2 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.io.*;
import java.util.*;
public class Codechef {
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine2() throws IOException {
List<Byte> buf = new ArrayList<Byte>();
// byte[] buf = new byte[1000]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf.add((byte) c);
// buf[c] = (byte) c;
cnt++;
}
byte[] buf2 = new byte[buf.size()];
int i = 0;
for (Byte b : buf)
buf2[i++] = b;
return new String(buf2, 0, cnt);
}
public String readLine() throws IOException {
String inp = readLine2().trim();
while (inp.length() == 0)
inp = readLine2().trim();
return inp;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
static PrintWriter out;
static Utility util;
static HashMap<Integer, Long> factMap;
static boolean ONLINE_JUDGE = true;
static int itr;
public static void main(String[] args) {
// Comment this code while running in Online Judge
try {
// System.out.println(System.getProperty("ONLINE_JUDGE"));
if (System.getProperty("ONLINE_JUDGE") == null && !ONLINE_JUDGE) {
FileOutputStream output = new FileOutputStream("output.txt");
PrintStream out = new PrintStream(output);
System.setOut(out);
InputStream input = new FileInputStream("input.txt");
System.setIn(input);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
Reader s = new Reader();
util = new Utility();
out = new PrintWriter(System.out);
int t = s.nextInt();
// System.out.println(t);
while (t > 0) {
int n = s.nextInt();
int k = s.nextInt();
String inp = s.readLine();
if(k == 0 || isPalind(inp))
out.println(1);
else
out.println(2);
t--;
}
out.flush();
}
catch (
Exception e) {
out.flush();
System.out.println(e);
return;
}
}
public static boolean isPalind(String s){
return s.equals((new StringBuilder(s)).reverse().toString());
}
public static int getFirstSetBitPos(int n)
{
int cpy = n;
int x = 0;
while(n>0){
n = n/2;
x++;
}
// out.println(" pow "+(1<<x)+" "+cpy);
return (1l<<x)-cpy > 0 ? x : ((x+1));
}
public static String bsearch(long charH, long charA, long monsH,long monsA, long incA, long incH, int maxCoins){
int l = 0;
int r = maxCoins;
while(l<=r){
if(solve(charH+(l*incH), charA+(maxCoins-l)*incA, monsH, monsA))
return "YES";
l++;
}
return "NO";
}
public static boolean solve(long a, long b, long c, long d){
long p = c<=b ? 0 : ((c)/b)+1;
long q = a<=d ? 0: ((a)/d)+1;
// out.println(a+" "+b+" "+c+" "+d+" mp "+q+" cp "+p+" c "+(a/d)+" m "+(c/b));
if(p<=q)
return true;
return false;
}
public static int getPow(int n){
int cpy = n;
int ans = 0;
while(cpy > 0){
cpy = cpy/2;
ans++;
}
return (1<<ans) <= n ? (1<<ans) : (1<<ans-1);
}
public static int binarySearch(List<Integer> sub, int num) {
int left = 0;
int right = sub.size() - 1;
int mid = (left + right) / 2;
int ans = -1;
while (left <= right) {
mid = (left + right) / 2;
if (sub.get(mid) <= num) {
left = mid + 1;
} else {
ans = mid;
right = mid-1;
}
}
return ans;
}
public static List<Integer> isSpecial(int treeNodes, List<Integer> treeFrom, List<Integer> treeTo) {
int[] res = new int[treeNodes + 1];
for (int i = 0; i < treeFrom.size(); i++) {
res[treeFrom.get(i)]++;
res[treeTo.get(i)]++;
}
List<Integer> ans = new ArrayList<>();
for (int i = 1; i <= treeNodes; i++)
ans.add(res[i] > 1 ? 0 : 1);
return ans;
}
public static int bsearch(int[] inp, int targ) {
int l = 0;
int r = inp.length - 1;
int ans = -1;
while (l <= r) {
int mid = (l + r) / 2;
if (inp[mid] <= targ) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
// out.println(targ + " ind " + ans + " " + (inp.length - (ans + 1)));
return ans;
}
static class Utility {
// Complexity: O(Log min(a, b))
public long ecu_gcd(long a, long b) {
if (a == 0)
return b;
return ecu_gcd(b % a, a);
}
public int[] extended_ecu_gcd(int a, int b) {
if (a == 0) {
return new int[] { b, 0, 1 };
}
int[] temp = extended_ecu_gcd(b % a, a);
return new int[] { temp[0], (temp[2] - (b / a) * temp[1]), temp[1] };
}
static ArrayList<Integer> primesnums;
static boolean hasprimes = false;
// Complexity: O(NLogN)
public boolean[] sieveOfEr_primes(int n) {
hasprimes = true;
boolean[] primes = new boolean[n + 1];
primesnums = new ArrayList<Integer>();
Arrays.fill(primes, true);
int i = 2;
for (i = 2; i * i <= n; i++) {
if (primes[i]) {
for (int p = i * i; p <= n; p += i)
primes[p] = false;
}
}
for (i = 2; i <= n; i++)
if (primes[i])
primesnums.add(i);
return primes;
}
public ArrayList<Integer> prime_Factors(int n) {
ArrayList<Integer> res = new ArrayList<Integer>();
while (n % 2 == 0) {
res.add(2);
n = n / 2;
}
for (int i = 3; i * i <= n; i = i + 2) {
while (n % i == 0) {
res.add(i);
n = n / i;
}
}
if (n > 2)
res.add(n);
return res;
}
public int prime_Factors2(int n) {
HashMap<Integer, Integer> res = new HashMap<Integer, Integer>();
while (n % 2 == 0) {
res.put(2, res.getOrDefault(2, 0) + 1);
n = n / 2;
}
for (int i = 3; i * i <= n; i = i + 2) {
while (n % i == 0) {
res.put(i, res.getOrDefault(i, 0) + 1);
n = n / i;
}
}
if (n > 2)
res.put(n, res.getOrDefault(n, 0) + 1);
int ress = 1;
for (Map.Entry<Integer, Integer> en : res.entrySet()) {
ress *= (en.getValue() + 1);
}
return ress;
}
public long[] fibnocnc(long k) {
if (k == 0)
return new long[] { 0, 1 };
long[] t = fibnocnc(k >> 1);
long a = (t[0] * (2 * t[1] - t[0]));
long b = (t[0] * t[0] + t[1] * t[1]);
if ((k & 1) == 1)
return new long[] { b, (b + a) };
return new long[] { a, b };
}
public long sumofN(long n) {
return n * (n + 1) / 2;
}
public long pos_quadratic_root(long a, long b, long c) {
return (-b + (long) Math.sqrt(b * b - 4 * a * c)) / 2 * a;
}
public long modInverse(long a, long m) {
// out.println(a+" "+m);
long m0 = m;
long y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1) {
// q is quotient
long q = a / m;
long t = m;
// m is remainder now, process
// same as Euclid's algo
m = a % m;
a = t;
t = y;
// Update x and y
y = x - q * y;
x = t;
}
// Make x positive
if (x < 0)
x += m0;
// out.println(x);
return x;
}
public TreeSet<Integer> getallFactors(int n) {
TreeSet<Integer> hst = new TreeSet<Integer>();
hst.add(1);
for (int i = 2; i * 1l * i <= n; i++) {
if (n % i == 0) {
hst.add(i);
if (i != n / i)
hst.add(n / i);
}
}
return hst;
}
static int invertBits(int n) {
// Calculate number of bits of N-1;
int x = (int) (Math.log(n) / Math.log(2));
int m = 1 << x;
m = m | m - 1;
n = n ^ m;
// System.out.println(n);
return n;
}
public static long bnc(int n, int r) {
if (r > n)
return 0;
long m = 1000000007;
long inv[] = new long[r + 1];
inv[1] = 1;
for (int i = 2; i <= r; i++) {
inv[i] = m - (m / i) * inv[(int) (m % i)] % m;
}
int ans = 1;
// for 1/(r!) part
for (int i = 2; i <= r; i++) {
ans = (int) (((ans % m) * (inv[i] % m)) % m);
}
// for (n)*(n-1)*(n-2)*...*(n-r+1) part
for (int i = n; i >= (n - r + 1); i--) {
ans = (int) (((ans % m) * (i % m)) % m);
}
return ans;
}
public static long fact(int n) {
if (n <= 1)
return 1;
if (factMap.containsKey(n))
return factMap.get(n);
factMap.put(n, mod(n * 1l * fact(n - 1)));
return factMap.get(n);
}
public static long mod(long n) {
return n < 0 ? 1000000007 + n : n % 1000000007;
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | e6a1ddb8b49d01028b18f98dd24f0508 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class A2 {
// Private Static Methods Starts Here
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Code Starts Here
int t = sc.nextInt();
while(t-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
String line = sc.next();
if(k == 0 || isPalindrome(line)) {
System.out.println(1);
}else {
System.out.println(2);
}
}
}
private static boolean isPalindrome(String line) {
if(line.length() <= 1) {
return true;
}
for(int i = 0; i < line.length(); i++) {
if(line.charAt(i) != line.charAt(line.length() - i - 1)) {
return false;
}
}
return true;
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 26602d2d679701bdcd235e8dd5ac4cf1 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class a {
public static void main(String[] args) {
int t;
StringBuilder sb = new StringBuilder();
Scanner sc = new Scanner(System.in);
t = sc.nextInt();
while(t-- > 0) {
int n,m;
n = sc.nextInt();
m = sc.nextInt();
String s = sc.next();
int i = 0;
int j = s.length()-1;
boolean pal = true;
while(i<j) {
if(s.charAt(i)!=s.charAt(j)){
pal = false;
}
i++;
j--;
}//
if(m==0 || pal==true){
sb.append(1+"\n");
}
else{
sb.append(2+"\n");
}
}
System.out.print(sb);
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | d716c215ebcc071b46794122f684067d | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class a {
public static void main(String[] args) {
int t;
StringBuilder sb = new StringBuilder();
Scanner sc = new Scanner(System.in);
t = sc.nextInt();
while(t-- > 0) {
int n,m;
n = sc.nextInt();
m = sc.nextInt();
String s = sc.next();
int i = 0;
int j = s.length()-1;
boolean pal = true;
while(i<j) {
if(s.charAt(i)!=s.charAt(j)){
pal = false;
}
i++;
j--;
}
if(m==0 || pal==true){
sb.append(1+"\n");
}
else{
sb.append(2+"\n");
}
}
System.out.print(sb);
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | cadec4f78162d190dc4fabe466bf82f8 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class a {
public static void main(String[] args) {
int t;
StringBuilder sb = new StringBuilder();
Scanner sc = new Scanner(System.in);
t = sc.nextInt();
while(t-- > 0) {
int n,m;
n = sc.nextInt();
m = sc.nextInt();
String s = sc.next();
int i = 0;
int j = s.length()-1;
boolean pal = true;
while(i<j) {
if(s.charAt(i)!=s.charAt(j))
pal = false;
i++;j--;
}
if(m==0 || pal==true)
sb.append(1+"\n");
else
sb.append(2+"\n");
}
System.out.print(sb);
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | c156dde537ca509e76ab4fd951323d9a | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class a {
public static void main(String[] args) {
// TODO Auto-generated method stub
int t;
StringBuilder sb = new StringBuilder();
Scanner sc = new Scanner(System.in);
t = sc.nextInt();
while(t-- > 0) {
int n,m;
n = sc.nextInt();
m = sc.nextInt();
String s = sc.next();
int i = 0;
int j = s.length()-1;
boolean pal = true;
while(i<j) {
if(s.charAt(i)!=s.charAt(j))
pal = false;
i++;j--;
}
if(m==0 || pal==true)
sb.append(1+"\n");
else
sb.append(2+"\n");
}
System.out.print(sb);
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | d1d6ea795229bb10452dcd02191c19d7 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.math.BigInteger;
import java.util.*;
import static java.lang.System.out;
public class Round_780_Div_3 {
static Scanner str = new Scanner(System.in);
static ArrayList<Integer> list;
public static void main(String[] args) {
int t = str.nextInt();
while (t-- > 0) {
solve();
}
}
static void solve() {
int n = str.nextInt();
int k = str.nextInt();
String s = str.next();
if (k == 0) {
out.println(1);
return;
}
out.println(isPalindrome(s) ? 1 : 2);
}
static boolean isPalindrome(String s) {
int l = 0;
int r = s.length() - 1;
while (l < r) {
if (s.charAt(l) != s.charAt(r)) {
return false;
}
l++;
r--;
}
return true;
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 16efdd3e1881e14e81fbcaa6918b930e | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes |
import java.util.*;
public class contest{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long coun = scan.nextLong();
for (int i = 0; i < coun; i++) {
int n = scan.nextInt();
int l = scan.nextInt();
String word = scan.next();
String reversed = "";
for (int k = 0; k < n; k++) {
reversed = word.charAt(k) + reversed;
}
if (reversed.equals(word) || l == 0) {
System.out.println("1");
} else {
System.out.println("2");
}
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | b69df043d4c7e8f36b6d17ef0059d217 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tests = sc.nextInt();
while (tests-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
String s = sc.next();
if (k >= 1)
System.out.println(isPalindrome(s) ? 1 : 2);
else
System.out.println(1);
}
}
public static boolean isPalindrome(String s) {
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length / 2; i++) {
if (chars[i] != chars[chars.length - 1 - i])
return false;
}
return true;
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | f2aad51755a3d4ac06ec7ef56ef7d9ba | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
import java.io.*;
public class Problem1 {
BufferedReader br;
StringTokenizer st;
public boolean isPalindrome(String s){
int n = s.length();
for(int i = 0, j = n-1; i < j; i++, j--){
if(s.charAt(i) != s.charAt(j))
return false;
}
return true;
}
public void run() throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
int t = in();
while(t-- > 0){
int n = in(), k = in();
String s = br.readLine();
if(k < 1){
System.out.println("1");
continue;
}else{
System.out.println(isPalindrome(s) ? "1" : "2");
}
}
}
public static void main(String[] args) throws Exception{
new Problem1().run();
}
Integer in() throws Exception {
return Integer.parseInt(nextToken());
}
String nextToken() throws Exception {
if(st == null || !st.hasMoreTokens()){
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 11b026a4520c3e85ec1f4ba359a6e7d2 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static class Pair<T1, T2> {
T1 first;
T2 second;
public Pair(T1 first, T2 second) {
this.first = first;
this.second = second;
}
}
public static class Edge {
int start, end;
int cost;
public Edge(int a, int b, int c) {
this.start = a;
this.end = b;
this.cost = c;
}
}
public static String reversed(String s) {
StringBuilder s1 = new StringBuilder();
for (int i = s.length() - 1; i >= 0; --i) {
s1.append(s.charAt(i));
}
return s1.toString();
}
public static void main(String[] args) {
MyScanner scanner = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int t = scanner.nextInt();
for (int tt = 0; tt < t; ++tt) {
int n = scanner.nextInt();
int k = scanner.nextInt();
String s = scanner.next();
if (k == 0 || (reversed(s) + s).equals(s + reversed(s))) {
out.println(1);
} else {
out.println(2);
}
}
out.close();
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | dd8b231726d7ef4693936aedaadd9ca6 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class Fgl{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=0;i<t;i++) {
int l = sc.nextInt(),k=sc.nextInt();
String str = sc.next();
String reverse = "";
for(int j=l-1;j>=0;j--) reverse+=str.charAt(j);
if(str.equals(reverse) || k==0) System.out.println(1);
else System.out.println(2);
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 14845ae44233e039b36fc8fcd1811dd0 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int T=Integer.parseInt(br.readLine());
while(T-->0){
String[] s=br.readLine().trim().split("\\s+");
int n=Integer.parseInt(s[0]);
int k=Integer.parseInt(s[1]);
String str=br.readLine();
StringBuilder strb=new StringBuilder(str);
if(strb.reverse().toString().equals(str)||k==0){
System.out.println("1");
} else {
System.out.println("2");
}
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 005ded826c3a2a4335fe0f3befe73dd9 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | 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();
int k=sc.nextInt();
String s=sc.next();
if(n<=1 || k==0){
System.out.println("1");
continue;
}
else{
String s1=new StringBuilder(s).reverse().toString();
if(s.equals(s1)){
System.out.println("1");
}
else System.out.println("2");
}
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 8434c262764f20ba061fd2c8cd6288d9 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.io.*;
import java.util.*;
public class A_Reverse_and_Concatenate {
static final int MOD = (int) 1e9 + 7;
public static boolean isPalindrome(StringBuilder str)
{
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j))
return false;
i++;
j--;
}
return true;
}
public static void main(String args[]) throws IOException {
FastReader scn = new FastReader();
int t = scn.nextInt();
while (t-- > 0) {
// code
int n = scn.nextInt();
int k = scn.nextInt();
StringBuilder str = new StringBuilder(scn.next());
if(isPalindrome(str) || k == 0) System.out.println(1);
else System.out.println(2);
}
}
//highest power of 2 using log (takes logn time)
static int log2(int n)
{
int p = (int)(Math.log(n) /
Math.log(2));
return (int)Math.pow(2, p);
}
// higest power of 2 takes ( O(1)) time fastest
static int highestPowerof2(int x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
static class FastReader {
InputStreamReader ir;
BufferedReader br;
StringTokenizer st;
public FastReader() {
ir = new InputStreamReader(System.in);
br = new BufferedReader(ir);
}
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 | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | a979fbe7217c660145f44b51d39d9438 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.io.*;
import java.util.*;
public class A_Reverse_and_Concatenate {
static final int MOD = (int) 1e9 + 7;
public static boolean isPalindrome(StringBuilder str)
{
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j))
return false;
i++;
j--;
}
return true;
}
public static void main(String args[]) throws IOException {
FastReader scn = new FastReader();
int t = scn.nextInt();
while (t-- > 0) {
// code
int n = scn.nextInt();
int k = scn.nextInt();
StringBuilder str = new StringBuilder(scn.next());
if( k == 0){
System.out.println(1);
}
if( k == 1) {
if(isPalindrome(str)){
System.out.println(1);
}else {
System.out.println(2);
}
}
if(k >1 ){
if( isPalindrome(str) == true) {
System.out.println(1);
}else {
System.out.println(2);
}
}
}
}
//highest power of 2 using log (takes logn time)
static int log2(int n)
{
int p = (int)(Math.log(n) /
Math.log(2));
return (int)Math.pow(2, p);
}
// higest power of 2 takes ( O(1)) time fastest
static int highestPowerof2(int x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
static class FastReader {
InputStreamReader ir;
BufferedReader br;
StringTokenizer st;
public FastReader() {
ir = new InputStreamReader(System.in);
br = new BufferedReader(ir);
}
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 | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | a0d22adf58096949846512bf3e131e5b | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.io.*;
import java.util.*;
public class sol {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
}
static String reverse(String s) {
String rev = "";
for (int i = s.length()-1; i >= 0; i--) {
rev += s.charAt(i);
}
return rev;
}
static void debug(int[] arr) {
for (int e: arr) {
System.out.print(e + " ");
}
System.out.println();
}
/*
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< HELPER FUNCTIONS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
// static void build(int[] tree, int[] arr, int i, int lo, int hi) {
// if (lo == hi) {
// tree[i] = arr[lo];
// return;
// }
// int mid = (lo + hi) >> 1;
// build(tree, arr, 2*i+1, lo, mid);
// build(tree, arr, 2*i+2, mid+1, hi);
// // tree[i] = __gcd(tree[2*i+1], tree[2*i+2]);
// }
public static void main(String[] args) {
FastReader fr = new FastReader();
int t = fr.nextInt();
while (t --> 0) {
int n = fr.nextInt();
long k = fr.nextLong();
String s = fr.next();
String rev = reverse(s);
System.out.println(s.equals(rev) ? 1 : (k > 0) ? 2 : 1);
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 96a1e6f93445a880320801b746e5d64c | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.io.*;
import java.util.*;
public class sol {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
}
static String reverse(String s) {
String rev = "";
for (int i = s.length()-1; i >= 0; i--) {
rev += s.charAt(i);
}
return rev;
}
static void debug(int[] arr) {
for (int e: arr) {
System.out.print(e + " ");
}
System.out.println();
}
/*
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< HELPER FUNCTIONS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*/
// static void build(int[] tree, int[] arr, int i, int lo, int hi) {
// if (lo == hi) {
// tree[i] = arr[lo];
// return;
// }
// int mid = (lo + hi) >> 1;
// build(tree, arr, 2*i+1, lo, mid);
// build(tree, arr, 2*i+2, mid+1, hi);
// // tree[i] = __gcd(tree[2*i+1], tree[2*i+2]);
// }
public static void main(String[] args) {
FastReader fr = new FastReader();
int t = fr.nextInt();
while (t --> 0) {
int n = fr.nextInt();
long k = fr.nextLong();
String s = fr.next();
String rev = reverse(s);
if (s.equals(rev)) {
System.out.println(1);
} else if (k > 0) {
System.out.println(2);
} else {
System.out.println(1);
}
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | af8d5a563f1a39d3fa71642f074b1c52 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class Main
{
public static void main(String[] args) {
// System.out.println("Hello World");
Scanner scn=new Scanner(System.in);
int t=scn.nextInt();
while(t-->0){
int n=scn.nextInt();
int k=scn.nextInt();
scn.nextLine();
String s=scn.nextLine();
// if(k==1 && s.isPalindrme(s)==false{
// System.out.println(1);
// }
// else if(k>=2 && isPalindrome(s)==false){
// System.out.println(2);
// }
// else{
// System.out.println(1);
// }
// }
if(isPalindrome(s)==true){
System.out.println(1);
}
else {
if(k==0){
System.out.println(1);
}
else{
System.out.println(2);
}
}
}
}
public static boolean isPalindrome(String s){
int i=0;
int j=s.length()-1;
while(i<j){
if(s.charAt(i)==s.charAt(j)){
i++;
j--;
}
else{
return false;
}
}
return true;
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 2fa83638da08a030c96cefab0e4f1493 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class Div {
static Scanner scan;
public static void main(String... h) {
int t = scan.nextInt();
while (t-- > 0)
// solve() ;
System.out.println(check());
}
public static int check() {
int n = scan.nextInt();
int rt = scan.nextInt();
String s = scan.next();
if (isPalindrome(s)) return 1;
if (rt < 1) return 1;
return 2;
}
static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j))
return false;
i++;
j--;
}
return true;
}
public static void solve(){
int n = scan.nextInt();
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < (n+"").length(); i++) {
int val = Integer.parseInt(String.valueOf((n+"").charAt(i)));
if(stack.isEmpty()){
stack.push(val);
}else {
int add = stack.pop();
stack.push(add+val);
stack.push(val);
}
}
stack.pop();
StringBuffer res = new StringBuffer();
for(int m:stack)res.append(m);
System.out.println(Integer.parseInt(String.valueOf(res.toString())));
}
public static void A(){
int n = scan.nextInt();
int arr[ ] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
int count = 0;
int index = n-1;
int iter = 0;
int need = arr[index];
for (int i = 0; i < n; i++) {
if(arr[i] == need)count++;
}
int ree = n-count;
while (count<n){
int val = arr[index];
int sal = arr[index-1];
if(val == sal){
count++;
index--;
}else{
index-=count;
count*=2;
}
iter++;
}
System.out.println(ree);
}
static {
scan = new Scanner(System.in);
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 917fc8c035f768a8c8ac54472c439deb | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes |
import java.util.*;
import java.math.*;
import java.io.*;
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void sort(int a[]){ // int -> long
ArrayList<Integer> arr=new ArrayList<>(); // Integer -> Long
for(int i=0;i<a.length;i++)
arr.add(a[i]);
Collections.sort(arr);
for(int i=0;i<a.length;i++)
a[i]=arr.get(i);
}
private static long gcd(long a, long b){
if(b==0)return a;
return gcd(b,a%b);
}
private static long pow(long x,long y){
if(y==0)return 1;
long temp = pow(x, y/2);
if(y%2==1){
return x*temp*temp;
}
else{
return temp*temp;
}
}
static int log(long n){
int res = 0;
while(n>0){
res++;
n/=2;
}
return res;
}
static int mod = (int)1e9+7;
static PrintWriter out;
static FastReader sc ;
public static void main(String[] args) throws IOException {
sc = new FastReader();
out = new PrintWriter(System.out);
// primes();
// ________________________________
// int test = sc.nextInt();
StringBuilder output = new StringBuilder();
int test =sc.nextInt();
while (test-- > 0) {
//System.out.println(mdh+" "+nhc);
int n = sc.nextInt();
int k = sc.nextInt();
String s = sc.next();
solver(s,n,k);
}
// solver(s);
// int n = sc.nextInt();
// out.println(solver());
// ________________________________
out.flush();
}
static class Edge
{
int u, v;
Edge(int u, int v)
{
this.u = u;
this.v = v;
}
}
static class Pair implements Comparable <Pair>{
int l, r;
Pair(int l, int r)
{
this.l = l;
this.r = r;
}
public int compareTo(Pair o)
{
return this.l-o.l;
}
}
//static ArrayList<Long>al =new ArrayList<>();
public static void solver(String s , int n, int k) {
if(k==0)
System.out.println(1);
else
{
boolean flag =true;
for(int i =0;i<n/2;i++)
{
if(s.charAt(i)!=s.charAt(n-1-i))
{
flag = false;
}
}
if(flag)
{
System.out.println(1);
}
else
System.out.println(2);
}
}
public static long log2(long N)
{
// calculate log2 N indirectly
// using log() method
long result = (long)(Math.log(N) / Math.log(2));
return result;
}
static long highestPowerof2(long x)
{
// check for the set bits
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
// Then we remove all but the top bit by xor'ing the
// string of 1's with that string of 1's shifted one to
// the left, and we end up with just the one top bit
// followed by 0's.
return x ^ (x >> 1);
}
public static void DFS(int i,ArrayList<ArrayList<Integer>>adj, boolean [] visited)
{
if(visited[i]==true)
return ;
visited[i] = true;
for(int nbr : adj.get(i))
{
if(!visited[nbr])
{
DFS(nbr,adj,visited);
}
}
}
public
static void rotate(int [] arr, int s, int n)
{
int x = arr[n], i;
for (i = n; i > s; i--)
arr[i] = arr[i-1];
arr[s] = x;
// for(int j=s;j<=n;j++)
// System.out.print(arr[j]+" ");
// System.out.println();
}
static int lower_bound(long[] a , long x)
{
int i = 0;
int j = a.length-1;
//if(arr[i] > key)return -1;
if(a[j] < x)return a.length;
while(i<j)
{
int mid = (i+j)/2;
if(a[mid] == x)
{
j = mid;
}
else if(a[mid] < x)
{
i = mid+1;
}
else
j = mid-1;
}
return i;
}
int upper_bound(int [] arr , int key)
{
int i = 0;
int j = arr.length-1;
if(arr[j] <= key)return j+1;
while(i<j)
{
int mid = (i+j)/2;
if(arr[mid] <= key)
{
i = mid+1;
}
else
j = mid;
}
return i;
}
static void reverseArray(int arr[], int start,
int end)
{
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 2743d5772f01f938ce44c36242b7d0f4 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class A {
static class RealScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
public static void swap(int arr[], int l, int r) {
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
public static void main(String[] args) {
RealScanner sc = new RealScanner();
int t = sc.nextInt();
while (t-- > 0) {
int n, k;
n = sc.nextInt();
k = sc.nextInt();
String s = sc.next();
StringBuffer sb = new StringBuffer(s);
sb.reverse();
String mys = String.valueOf(sb);
if (k == 0) {
System.out.println(1);
continue;
}
if (s.equals(mys)) {
System.out.println("1");
} else {
System.out.println("2");
}
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 81adc351b0829caf63e4d8ade1f099eb | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
import java.lang.*;
public class solution
{
public static void main (String[] args) throws java.lang.Exception {
int in = 0;
// your code goes here'
Scanner sc = new Scanner(System.in);
int y = sc.nextInt();
while (y-- > 0) {
int a = sc.nextInt();
int b = sc.nextInt();
String s = sc.next();
if(palindrome(s) || b==0)System.out.println(1);
else System.out.println(2);
}}
public static boolean palindrome(String s ){
String a="";
for(char c:s.toCharArray()){
a=""+c+a;
}
if(a.equals(s))return true;
return false;
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 9a55abd92142659bb1bb7fd92328451c | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class test2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
//String s = scan.next();
for (int i = 0; i < n; i++) {
int len = scan.nextInt();
int operations = scan.nextInt();
String s = scan.next();
if (palindrome(s) || operations == 0) {
System.out.println(1);
}
else {
System.out.println(2);
}
}
}
public static boolean palindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left <= right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | aa9af8e45cf7dd2ced4284b74ecad871 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | //package learningJava;
import java.util.*;
public class q3 {
public static void main(String args[]){
Scanner s1 = new Scanner(System.in);
int t = s1.nextInt();
while ( t > 0){
int n = s1.nextInt();
int k = s1.nextInt();
String s = s1.next();
// String r = "";
// int m = n-1;
// while(m<=0){
// r = r+s.charAt(m);
// }
// if(k == 0 || k == 1){
// System.out.println("1");
// continue;
// }
// s = s + r;
// String s2 = r + s;
// for(int i = 0; i < k-1; i++){
// s = s + s;
// }
// for(int o = 0; o <k-1; o++){
// s2 = s2 + s2;
// }
// if(s == s2){
// System.out.println("1");
// }
// else{
// System.out.println("2");
// }
int i = 0,j = n-1;
boolean flag = true;
while(i<j){
if(s.charAt(i) != s.charAt(j)){
flag = false;
}
i++;
j--;
}
if(k == 0){
System.out.println("1");
}
else if(flag == false){
System.out.println("2");
}
else{
System.out.println("1");
}
t--;
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 95c0811a53c9cb6f37d76ba00273308f | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int Test_cases=scanner.nextInt();
for(int i=0;i<Test_cases;i++)
{
int n=scanner.nextInt();
int k=scanner.nextInt();
String string=scanner.next();
int ans=k_returner(n,k,string);
System.out.println(ans);
}
}
public static int k_returner(int n,int k,String string)
{
String revString="";
for( int j=n-1;j>=0;j--)
{
revString=revString+string.charAt(j);
}
String x=revString+string;
String y=string+revString;
if(x.compareTo(y)!=0 && k>0)
{
return 2;
}
else
{
return 1;
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | fc1048361a210e8bfdf5e5e28a141e0e | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.*;
import java.util.*;
public class codeforces {
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[]) {
if (System.getProperty("ONLINE_JUDGE") == null) {
// Input is a file
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
} catch (Exception e) {
System.err.println("Error");
}
} else {
// Input is System.in
}
FastReader sc = new FastReader();
// Scanner sc = new Scanner(System.in);
//System.out.println(java.time.LocalTime.now());
StringBuilder sb = new StringBuilder();
int t = sc.nextInt();
while(t>0) {
Set<String> set = new HashSet<>();
int n = sc.nextInt();
int k = sc.nextInt();
String s = sc.next();
boolean bool = true;
for(int i = 0; i<n/2; i++){
if(s.charAt(i) != s.charAt(n-1-i)){
bool = false;
break;
}
}
int ans = 0;
if(!bool && k>0)ans = 2;
else ans = 1;
sb.append(ans+ "\n");
t--;
}
System.out.println(sb);
}
//////////nCr////////////////////////////////////////
///////// SUM OF EACH DIGIT OF A NUMBER ///////////////
public static long digSum(long a) {
long sum = 0;
while(a>0) {
sum += a%10;
a /= 10;
}
return sum;
}
///////// TO CHECK NUMBER IS PRIME OR NOT ///////////////
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+=6) {
if(n%i == 0 || n%(i+2) == 0)return false;
}
return true;
}
///////// NEXT PRIME NUMBER BIGGER THAN GIVEN NUMBER ///////////////
public static int nextPrime(int n) {
while(true) {
n++;
if(isPrime(n)) break;
}
return n;
}
///////// GCD ///////////////
public static int gcd(int a, int b) {
if(b == 0)return a;
return gcd(b, a%b);
}
///////// LCM ///////////////
public static int lcm(int a, int b) {
return (a*b)/gcd(a,b);
}
///////// IS POWER OF 2 ///////////////
public static boolean isPowerOfTwo (int x){
/* First x in the below expression is
for the case when x is 0 */
return x!=0 && ((x&(x-1)) == 0);
}
}
class Pair{
int x;
int y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if(this == o)return true;
if(o == null || this.getClass() != o.getClass())return false;
Pair p = (Pair)o;
return x == p.x && y == p.y;
}
@Override
public int hashCode(){
return Objects.hash(x , y);
}
// @Override
// public int compareTo(Pair o) {
// }
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 1a620092dce6796eb29c293d044d1b0e | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | 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 = fastReader.nextInt();
while (t-- > 0) {
int n = fastReader.nextInt();
int k = fastReader.nextInt();
String s = fastReader.nextLine();
if (isPalindrome(s)){
out.println(1);
}else if (k == 0) {
out.println(1);
} else {
out.println(2);
}
}
out.close();
}
public static boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < n / 2; i++) {
if (s.charAt(i) != s.charAt(n - 1 - i)) {
return false;
}
}
return true;
}
// 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 | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 5160794e3f37f0bab5accceaf3b92a76 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes |
import java.util.*;
public class sol {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n = sc.nextInt();
int k=sc.nextInt();
String s=sc.next();
char ar[] = s.toCharArray();
boolean flag=true;
if(k==0){
System.out.println("1");
}
else{
int i=0;
int j= s.length()-1;
while(i<j){
if(ar[i]!=ar[j]){
flag=false;
break;
}
i++;
j--;
}
if(flag){
System.out.println("1");
}
else{
System.out.println("2");
}
}
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | d1d3e49b1b14d468ded24975a5c571c5 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class Fgl{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=0;i<t;i++) {
int l = sc.nextInt(),k=sc.nextInt();
String str = sc.next();
String reverse = "";
for(int j=l-1;j>=0;j--) reverse+=str.charAt(j);
if(str.equals(reverse) || k==0) System.out.println(1);
else System.out.println(2);
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 603ee41035ccf9d70f4303fcd23b2c56 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
static ArrayList<Integer> []adj;
static boolean visited[];
static char [][] grid;
public static void main(String[] args) throws FileNotFoundException,IOException, InterruptedException {
Scanner s=new Scanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
int t=s.nextInt();
while (t-->0)
{
int n=s.nextInt(),k=s.nextInt();
String x=s.next();
if (k==0)
pw.println(1);
else
{
boolean flag=true;
for (int i=0;i<n/2;i++)
{
if (x.charAt(i)!=x.charAt(n-1-i))
{
flag=false;
break;
}
}
if (!flag)
pw.println(2);
else
pw.println(1);
}
}
pw.flush();
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
//returns INDEX
public static Integer ceiling (int []arr, int x)
{
int lower=0,upper=arr.length-1;
Integer index=null;
while (lower<=upper)
{
int mid=(lower+upper)/2;
if (arr[mid]>=x)
{
upper=mid-1;
index=mid;
}
else
lower=mid+1;
}
return index;
}
public static Integer floor (int []arr,int x)
{
int lower=0,upper=arr.length-1;
Integer index=-1;
while (lower<=upper)
{
int mid=(lower+upper)/2;
if (arr[mid]<=x)
{
lower=mid+1;
index=mid;
}
else
upper=mid-1;
}
return index;
}
// static void takeOrLeave( int i, String x){
//
// if(i == n+1)
// {
// System.out.println(x);
// //list.add(x);
// return;
// }
//
// String y=x;
// y+=i;
// takeOrLeave(i+1,x+i);
// takeOrLeave(i+1,x);
//
//
// }
// static void takeOrLeave( int i, ArrayList<Integer> acc){
//
// if(i == n+1)
// {
// System.out.println(acc);
// //list.add(acc);
// return;
// }
//
// // acc.add(i);
// ArrayList<Integer> temo=(ArrayList<Integer>) acc.clone();
// temo.add(i);
// takeOrLeave(i+1,temo);
// //acc.remove(i);
// takeOrLeave(i+1,acc);
//
//
// }
public static void permute(char []a , int l, int r)
{
if (l == r)
System.out.println(Arrays.toString(a));
else
{
for (int i = l; i <= r; i++)
{
a= swap(a,l,i);
permute(a, l+1, r);
a = swap(a,l,i);
}
}
}
public static char[] swap(char []a, int l, int i) {
char temp=a[l];
a[l]=a[i];
a[i]=temp;
return a;
}
public static double log2(long m)
{
double result = (double)(Math.log(m) / Math.log(2));
return result;
}
public static void shuffle(int []a)
{
for (int i=0; i<a.length;i++)
{
int randIndex=(int)(Math.random()*a.length);
int temp=a[i];
a[i]=a[randIndex];
a[randIndex]=temp;
}
}
public static void shuffle(long []a)
{
for (int i=0; i<a.length;i++)
{
int randIndex=(int)(Math.random()*a.length);
long temp=a[i];
a[i]=a[randIndex];
a[randIndex]=temp;
}
}
}
class Pair implements Comparable{
int x;
int y;
Pair(int x, int y)
{
this.x=x;
this.y=y;
}
@Override
public int compareTo(Object o) {
Pair p=(Pair)o;
return this.x-p.x;
}
public String toString()
{
return "("+x+","+y+")";
}
}
class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public Scanner(String s) throws FileNotFoundException
{
br =new BufferedReader(new FileReader(s));
}
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public long[] nextLongArr(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextInt();
return arr;
}
public boolean ready() throws IOException {return br.ready();}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | d8fe328fc627cc9665a982d61d3150ea | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Scanner;
public class reverse_and_concatenate {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t;
int n;
int k;
String input;
StringBuilder temp;
t = sc.nextInt();
while(t --> 0){
n = sc.nextInt();
k = sc.nextInt();
input = sc.next();
temp = new StringBuilder();
if ( k == 0 || n ==1){
System.out.println(1);
continue;
}
else{
for(int i = input.length()-1; i >=0 ; i--){
temp.append(input.charAt(i));
}
if(input.equalsIgnoreCase(String.valueOf(temp))){
System.out.println(1);
continue;
}
else{
System.out.println(2);
continue;
}
}
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 57fb5b552b0241d259fe631758cfdd20 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Scanner;
public class Solution{
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
int num=scanner.nextInt();
for(int i=1;i<=num;i++){
int n=scanner.nextInt();
int k=scanner.nextInt();
String s=scanner.next();
if(k==0) System.out.println(1);
else if(k>=1){
boolean flag=true;
for(int r=0,t=n-1;r<t;r++,t--){
if(s.charAt(r)!=s.charAt(t)){
flag=false;
break;
}
}
System.out.println(flag?1:2);
}
}
scanner.close();
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 5f6acd11c7bb37349fd84310134ab746 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Scanner;
import java.lang.String;
import java.lang.StringBuilder;
public class Test{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++){
int n = sc.nextInt();
int k = sc.nextInt();
String str = sc.next();
StringBuilder rev = new StringBuilder(str);
rev.reverse();
if (rev.toString().equals(str) || k == 0){
System.out.println(1);
}
else{
System.out.println(2);
}
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | ed94ee47676bee7152176f23ee068f11 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
import java.io.*;
public class ReversAndConcatenate {
public static void main(String [] args)
{
FastScanner fs=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int testCases = fs.nextInt();
for(int i = 0; i < testCases; i++)
{
// System.out.println("Test case : " + (i + 1));
int n = fs.nextInt();
int k = fs.nextInt();
char[] str=fs.next().toCharArray();
if(k == 0)
{
System.out.println("1");
continue;
}
if(isPalindrome(str))
{
System.out.println("1");
continue;
}
System.out.println("2");
}
}
public static boolean isPalindrome(char [] str) {
int n = str.length;
for(int i = 0; i < n; i++) {
if(str[i] != str[n-1-i]) {
return false;
}
}
return true;
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | e81838fe0b5f97ac65d477271b19cf8b | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Practice {
static BufferedReader br;
static PrintWriter out;
public static String[] readLine(){
if(br == null)
br = new BufferedReader(
new InputStreamReader(System.in));
try {
return br.readLine().split(" ");
} catch (IOException e) {
}
return null;
}
public static int[] readIntegers(){
String[] arr = readLine();
int[] res = new int[arr.length];
for(int i=0;i<arr.length;i++)
res[i] = Integer.parseInt(arr[i]);
return res;
}
public static void print(String s){
if(out == null)
out = new PrintWriter(System.out);
out.println(s);
}
public static void flushOutput(){
if(out != null)
out.flush();
}
public static String solve(String s, int k){
if(k == 0)
return "1";
boolean mirror = true;
int id = 0;
while(id < s.length()-id-1){
if(s.charAt(id) != s.charAt(s.length()-id-1)){
mirror = false;
break;
}
id++;
}
return mirror? "1": "2";
}
public static void io(){
int t = readIntegers()[0];
while(t-- > 0){
int k = readIntegers()[1];
String s = readLine()[0];
print(solve(s, k));
}
}
public static void main(String[] args){
io();
flushOutput();
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 3f48f9edd60f3dda02edbbeff20fcaf8 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String args[]){
Scanner inp=new Scanner(System.in);
int t=inp.nextInt();
for(int i=0;i<t;i++){
int n=inp.nextInt();
int k=inp.nextInt();
inp.nextLine();
String rev = "";
String s=inp.nextLine();
for ( int j = n - 1; j >= 0; j-- )
rev = rev + s.charAt(j);
if (s.equals(rev)){
System.out.println(1);
}
else if(k==0){
System.out.println(1);
}
else{
System.out.println(2);
}
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | b2e237e1e65f6d0cb9b2948fde061678 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class ReverseAndConcatenate{
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder result = new StringBuilder();
int testCases = Integer.parseInt(br.readLine());
StringTokenizer str;
while(testCases-- > 0){
str = new StringTokenizer(br.readLine());
int n = Integer.parseInt(str.nextToken());
int k = Integer.parseInt(str.nextToken());
String s = br.readLine();
boolean pallindrome = true;
for(int i = 0; i < n/2; i++){
if(s.charAt(i) != s.charAt(n - i - 1)){
pallindrome = false;
break;
}
}
if(pallindrome){
result.append("1\n");
}else{
if(k == 0){
result.append("1\n");
}else{
result.append("2\n");
}
}
}
System.out.println(result);
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 559d0d2f244bf6f3a61bcb45a7648ed0 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++){
int n=sc.nextInt();
int k=sc.nextInt();
sc.nextLine();
String s=sc.nextLine();
String p="";
for(int j=0;j<n;j++){
p=Character.toString(s.charAt(j))+p;
}
if(k==0){
System.out.println(1);
}
else if(s.equals(p)==true){
System.out.println(1);
}
else if(k==1 && s.equals(p)==false){
System.out.println(2);
}
else
System.out.println(2);
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | de9a62464358c70733ad1dfc9cc83a45 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-- > 0){
int n =scanner.nextInt();
int op = scanner.nextInt();
String s= scanner.next();
if (op == 0){
System.out.println(1);
}
else if (isPalindrome(s)){
System.out.println(1);
}
else {
System.out.println(2);
}
}
}
public static boolean isPalindrome(String s){
StringBuilder sb = new StringBuilder(s);
if (sb.toString().equalsIgnoreCase(sb.reverse().toString())){
return true;
}
return false;
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | aa6446be52918fe0d225520c23520034 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes |
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.Math.PI;
import static java.lang.Math.min;
import static java.lang.System.arraycopy;
import static java.lang.System.exit;
import static java.util.Arrays.copyOf;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.io.FileReader;
import java.io.FileWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Comparator;
import java.lang.StringBuilder;
import java.util.Collections;
import java.util.*;
import java.text.DecimalFormat;
public class Solution {
static class Edge{
int u, v, w;
Edge(int u, int v, int w){
this.u = u;
this.v = v;
this.w = w;
}
}
static class Pair{
int first, second;
Pair(int first, int second){
this.first = first;
this.second = second;
}
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
static int dx[] = {-1,0,1,0};
static int dy[] = {0,-1,0,1};
private static void solve() throws IOException{
int n = scanInt(), k = scanInt();
char[] str = scanString().toCharArray();
boolean flag = true;
for(int l = 0, r = n-1; l<r; l++, r--){
if(str[l] != str[r]){
flag = false;
break;
}
}
if(!flag && k>=1){
out.println(2);
}
else
out.println(1);
}
public static void main(String[] args) {
try {
long startTime = System.currentTimeMillis();
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter(new FileWriter("output.txt"));
int test=scanInt();
for(int t=1; t<=test; t++){
// out.print("Case #"+t+": ");
solve();
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
//out.println(totalTime+"---------- "+System.currentTimeMillis() );
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static double scanDouble() throws IOException {
return parseDouble(scanString());
}
static String scanString() throws IOException {
if (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static String scanLine() throws IOException {
return in.readLine();
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | aef77dd9754021554654b939b68052ac | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Scanner;
public class AReverseAndConcatenation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
while(testCases-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
String s = sc.next();
if(k == 0) {
System.out.println(1);
}
else {
String rev = "";
for(int i = n-1; i >= 0; i--) {
rev+=s.charAt(i);
}
if(rev.equals(s)) {
System.out.println(1);
} else {
System.out.println(2);
}
}
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | d159ee464dd2cdfba6fe0b7a54eb19c9 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.Scanner;
public class CodeForces01 {
public static String revStr(String str) {
String revs = "";
for (int i = 0; i < str.length(); i++) {
revs = str.charAt(i) + revs;
}
return revs;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
// System.out.println(t);
while (t>0) {
int l = sc.nextInt();
int k = sc.nextInt();
sc.nextLine();
String s = sc.nextLine();
if (k == 0) {
System.out.println(1);
} else {
if (s.equals(revStr(s))) {
System.out.println(1);
} else {
System.out.println(2);
}
}
t--;
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 6c92ab63c91080ada2f8e3a5f24d2258 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static boolean isPallindrome(String s) {
String rev = "";
for(int i=s.length()-1; i>=0; i--) {
rev += s.charAt(i);
}
if (s.equals(rev)) return true;
return false;
}
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
int t = Integer.parseInt(br.readLine());
while (t-- != 0) {
String s[] = br.readLine().split(" ");
String ch = br.readLine();
int n = Integer.parseInt(s[0]);
int k = Integer.parseInt(s[1]);
if (k == 0 || isPallindrome(ch)) System.out.println(1);
else System.out.println(2);
}
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 85050e74cd225ff4ce2a3d4fcc929c84 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr = new PrintWriter(new OutputStreamWriter(System.out));
long t = Long.parseLong(br.readLine());
while (t-- != 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
long n = Long.parseLong(st.nextToken());
long k = Long.parseLong(st.nextToken());
// long k = Long.parseLong(st.nextToken());
// long[] arr = new long[(int) n];
// long[] peaks = new long[(int) n];
// ArrayList<Long> list = new ArrayList<>();
// ArrayList<Long> dec = new ArrayList<>();
boolean flag = false;
char[] ch = br.readLine().toCharArray();
for (int i = 0; i < n/2 ; i++) {
if (ch[i] != ch[(int) (n-1-i)]){
flag = true;
}
}
if ((!flag && k>0)||k==0){
pr.println(1);
} else{
pr.println(2);
}
// pr.print(ans);
// StringBuilder str = new StringBuilder(br.readLine());
}
//StringTokenizer st = new StringTokenizer(br.readLine());
pr.close();
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 357e0882ab220c105187b80475435d1e | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | /**
* @Author: Luminous!
* @Date: 2022/02/06/22:27
* @Description: CF1634A
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class CF1634A {
static final int INF = 0x3f3f3f3f;
static final long LNF = 0x3f3f3f3f3f3f3f3fL;
public static void main(String[] args) throws IOException {
initReader();
int T = nextInt();
for (int i = 1; i <= T; i++)
solve();
pw.flush();
}
/***************************************************************************************/
public static void solve() throws IOException {
int n = nextInt();
int k = nextInt();
char[] s = next().toCharArray();
pw.println(k == 0 || fun(s) ? 1 : 2);
}
public static boolean fun(char[] s) {
for (int i = 0, j = s.length - 1; i <= j; i++, j--) {
if (s[i] != s[j]) {
return false;
}
}
return true;
}
/***************************************************************************************/
/***************************************************************************************/
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter pw;
public static void initReader() throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer("");
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
// 从文件读写
// reader = new BufferedReader(new FileReader("test.in"));
// tokenizer = new StringTokenizer("");
// pw = new PrintWriter(new BufferedWriter(new FileWriter("test1.out")));
}
public static boolean hasNext() {
try {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
public static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static char nextChar() throws IOException {
return next().charAt(0);
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | c0ba1e4b13c16ad99df7e73925cd1928 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class A {
static PrintWriter out;
public static void main(String[] args) {
FastReader in = new FastReader();
out = new PrintWriter(System.out);
long t = in.nextLong();
long test = 1;
while (test <= t) {
out.println(solve(in));
// solve(in);
test++;
}
out.close();
}
/*--------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------------*/
// private static void solve(FastReader in) {
// int max = max(1, 2);
// int min = min(6, 2);
//
// }
//
private static long solve(FastReader in) {
int n = in.nextInt();
int k = in.nextInt();
char s[] = in.next().toCharArray();
if (k == 0)
return 1;
String s1=String.valueOf(s)+reverse(s);
String s2=reverse(s)+String.valueOf(s);
if(s1.equals(s2))
return 1;
return 2;
}
private static String reverse(char[] s) {
StringBuilder sb=new StringBuilder(String.valueOf(s));
sb.reverse();
return sb.toString();
}
//
// private static String solve(FastReader in) {
// int max = max(1, 2);
// int min = min(6, 2);
// return "";
//
// }
/*--------------------------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------------------------*/
private static int gcd(int a, int b) {
return b == 0 ? a : (gcd(b, a % b));
}
static boolean[] sieveOfEratosthenes(int n) {
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, true);
prime[0] = prime[1] = false;
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
static void sort(int[] a) {
List<Integer> l = new ArrayList<>();
for (int i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static long modPow(long a, long b, long m) {
long res = 1;
a %= m;
while (b > 0) {
if ((b & 1) != 0) {
res = res * a;
res %= m;
}
b >>= 1;
a *= a;
a %= m;
}
return res;
}
private static class Pair implements Comparable<Pair> {
int ff, ss;
Pair(int x, int y) {
this.ff = x;
this.ss = y;
}
public int compareTo(Pair o) {
return this.ff == o.ff ? this.ss - o.ss : this.ff - o.ff;
}
}
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[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
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 | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | b8e9524998c79c70c586c6556250e366 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
import static java.lang.System.out;
import static java.lang.System.err;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static FastReader sc;
// static FastWriter out;
public static void main(String hi[]){
initializeIO();
sc=new FastReader();
// FastWriter out=new FastWriter();
int t=sc.nextInt();
// boolean[] seave=sieveOfEratosthenes((int)(1e6));
// int t=1;
while(t--!=0){
int n=sc.nextInt();
int k=sc.nextInt();
String s=sc.next();
if(k==0||isPallindrome(s))out.println(1);
else out.println(2);
}
// print(solve(nums,n,m,it,jt));
// System.out.println(String.format("%.10f", max));
}
private static int solve(int[] arr,int n){
// sort(arr);
int c=0;
PriorityQueue<Integer> pq=new PriorityQueue<>();
int ind=1;
TreeSet<Integer> set=new TreeSet<>();
for(int i=1;i<=n;i++)set.add(i);
for(int i=0;i<n;i++){
if(set.contains(arr[i])){
set.remove(arr[i]);
continue;
}
pq.add(arr[i]);
}
// debug(" "+pq+" "+set);
while(!pq.isEmpty()){
int v=pq.poll();
// debug(v+" "+set.first());
if(((v-1)/2)>=set.first()){
set.remove(set.first());
c++;
}else return -1;
}
return c;
}
//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 sqrt(Math.pow(x,2)+Math.pow(y,2));
}
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 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 String decimalToString(int x){
return Integer.toBinaryString(x);
}
private static boolean isPallindrome(String s){
int l=0,r=s.length()-1;
while(l<r){
if(s.charAt(l)!=s.charAt(r))return false;
l++;
r--;
}
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 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(int val){
return String.valueOf(val);
}
private static void print(String s){
out.println(s);
}
private static void debug(String s){
err.println(s);
}
private static int charToInt(char c){
return ((((int)(c-'0'))%48));
}
private static void print(double s){
out.println(s);
}
private static void print(float s){
out.println(s);
}
private static void print(long s){
out.println(s);
}
private static void print(int s){
out.println(s);
}
private static void debug(double s){
err.println(s);
}
private static void debug(float s){
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;
}
//read graph
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;
}
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;
}
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;
}
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);
}
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 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.txt"));
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){
out.println(Arrays.toString(arr));
}
private static void print(long[] arr){
out.println(Arrays.toString(arr));
}
private static void print(String[] arr){
out.println(Arrays.toString(arr));
}
private static void print(double[] arr){
out.println(Arrays.toString(arr));
}
private static void debug(String[] arr){
err.println(Arrays.toString(arr));
}
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 {
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();
}
}
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 | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 9465665503cbd07bb86a3281ddc45e53 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
public static void main(String[]args){
long s = System.currentTimeMillis();
new Solver().run();
System.err.println(System.currentTimeMillis()-s+"ms");
}
}
class Solver{
int N, K;
char arr[];
boolean isPalindrome(){
for(int i = 1; i <= N; i++){
if(arr[i] != arr[N - i + 1]){
return false;
}
}
return true;
}
void process(int testNumber){
N = ni();
K = ni();
arr = (" " + nln()).toCharArray();
int res = 1;
if(isPalindrome() || K == 0){
;
}else{
res = 2;
}
pn(res);
}
final long mod = (long)1e9+7l;
boolean DEBUG = true;
FastReader sc;
PrintWriter out;
void run(){
sc = new FastReader();
out = new PrintWriter(System.out);
int t = 1;
t = ni();
for(int test = 1; test <= t; test++){
process(test);
}
out.flush();
}
void trace(Object... o){ if(!DEBUG) return; System.err.println(Arrays.deepToString(o)); };
void pn(Object o){ out.println(o); }
void p(Object o){ out.print(o); }
int ni(){ return Integer.parseInt(sc.next()); }
long nl(){ return Long.parseLong(sc.next()); }
double nd(){ return Double.parseDouble(sc.next()); }
String nln(){ return sc.nextLine(); }
long gcd(long a, long b){ return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){ return (b==0)?a:gcd(b,a%b); }
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); }
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}
}
}
class pair implements Comparable<pair> {
int first, second;
public pair(int first, int second){
this.first = first;
this.second = second;
}
@Override
public int compareTo(pair ob){
if(this.first != ob.first)
return this.first - ob.first;
return this.second - ob.second;
}
@Override
public String toString(){
return this.first + " " + this.second;
}
static public pair from(int f, int s){
return new pair(f, s);
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 8781f5d59cdebe39f384364c065adb6c | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
FastReader sc = new FastReader();
int t = sc.nextInt();
while (t-- > 0) {
int n=sc.nextInt();
int k=sc.nextInt();
String s=sc.next();
if(k==0 || n==1 || isPalindrome(s)){
System.out.println(1);
}
else{
System.out.println(2);
}
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readArrayLong(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
public static int[] radixSort2(int[] a) {
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for (int v : a) {
c0[(v & 0xff) + 1]++;
c1[(v >>> 8 & 0xff) + 1]++;
c2[(v >>> 16 & 0xff) + 1]++;
c3[(v >>> 24 ^ 0x80) + 1]++;
}
for (int i = 0; i < 0xff; i++) {
c0[i + 1] += c0[i];
c1[i + 1] += c1[i];
c2[i + 1] += c2[i];
c3[i + 1] += c3[i];
}
int[] t = new int[n];
for (int v : a)
t[c0[v & 0xff]++] = v;
for (int v : t)
a[c1[v >>> 8 & 0xff]++] = v;
for (int v : a)
t[c2[v >>> 16 & 0xff]++] = v;
for (int v : t)
a[c3[v >>> 24 ^ 0x80]++] = v;
return a;
}
static boolean isPalindrome(String str) {
// Pointers pointing to the beginning
// and the end of the string
int i = 0, j = str.length() - 1;
// While there are characters to compare
while (i < j) {
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;
// Increment first pointer and
// decrement the other
i++;
j--;
}
// Given string is a palindrome
return true;
}
static boolean palindrome_array(int arr[], int n) {
// Initialise flag to zero.
int flag = 0;
// Loop till array size n/2.
for (int i = 0; i <= n / 2 && n != 0; i++) {
// Check if first and last element are different
// Then set flag to 1.
if (arr[i] != arr[n - i - 1]) {
flag = 1;
break;
}
}
// If flag is set then print Not Palindrome
// else print Palindrome.
if (flag == 1)
return false;
else
return true;
}
static boolean allElementsEqual(int[] arr, int n) {
int z = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i] == arr[i + 1]) {
z++;
}
}
if (z == n - 1) {
return true;
} else {
return false;
}
}
static boolean allElementsDistinct(int[] arr, int n) {
int z = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i] != arr[i + 1]) {
z++;
}
}
if (z == n - 1) {
return true;
} else {
return false;
}
}
public static void reverse(int[] array) {
// Length of the array
int n = array.length;
// Swaping the first half elements with last half
// elements
for (int i = 0; i < n / 2; i++) {
// Storing the first half elements temporarily
int temp = array[i];
// Assigning the first half to the last half
array[i] = array[n - i - 1];
// Assigning the last half to the first half
array[n - i - 1] = temp;
}
}
public static void reverse_Long(long[] array) {
// Length of the array
int n = array.length;
// Swaping the first half elements with last half
// elements
for (int i = 0; i < n / 2; i++) {
// Storing the first half elements temporarily
long temp = array[i];
// Assigning the first half to the last half
array[i] = array[n - i - 1];
// Assigning the last half to the first half
array[n - i - 1] = temp;
}
}
static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
static boolean isReverseSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] < a[i + 1]) {
return false;
}
}
return true;
}
static int[] rearrangeEvenAndOdd(int arr[], int n) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
list.add(arr[i]);
}
}
for (int i = 0; i < n; i++) {
if (arr[i] % 2 != 0) {
list.add(arr[i]);
}
}
int len = list.size();
int[] array = list.stream().mapToInt(i -> i).toArray();
return array;
}
static long[] rearrangeEvenAndOddLong(long arr[], int n) {
ArrayList<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
list.add(arr[i]);
}
}
for (int i = 0; i < n; i++) {
if (arr[i] % 2 != 0) {
list.add(arr[i]);
}
}
int len = list.size();
long[] array = list.stream().mapToLong(i -> i).toArray();
return array;
}
static boolean isPrime(long n) {
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
return true;
}
static int getSum(int n) {
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcdLong(long a, long b) {
if (b == 0)
return a;
return gcdLong(b, a % b);
}
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static int countDigit(long n) {
return (int) Math.floor(Math.log10(n) + 1);
}
static int sumFromString(String s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
if (Character.isDigit(s.charAt(i))) {
sum = sum + Character.getNumericValue(s.charAt(i));
}
}
return sum;
}
static int[] freqCounter(int arr[]) {
int[] fr = new int[arr.length];
int[] fi = new int[arr.length];
int visited = -1;
for (int i = 0; i < arr.length; i++) {
int count = 1;
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
count++;
// To avoid counting same element again
fr[j] = visited;
}
}
if (fr[i] != visited)
fr[i] = count;
}
for (int i = 0; i < fr.length; i++) {
if (fr[i] != visited)
fi[i] = fr[i];
}
return fi;
}
} | Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | d294c977450ecdb4c76911a46d3cc78b | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | //package com.CobCollege;
import java.lang.StringBuilder;
import java.util.Scanner;
public class codeforce1634a {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int t=in.nextInt();
for(int i=0;i<t;i++){
int n=in.nextInt(), k=in.nextInt(), count=0;
String s=in.next();
String[] srev= {s,s};
for(int j=0;j<1;j++){
StringBuilder a=new StringBuilder(srev[0]);
a.reverse();
srev[0]=srev[0]+ a;
a= new StringBuilder(srev[1]);
a.reverse();
srev[1]=a+srev[1];
a.delete(0,a.length());
}
if(srev[0].equals(srev[1]))
System.out.println(1);
else if(k==0)
System.out.println(1);
else
System.out.println(2);
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output | |
PASSED | 513c9d133096048dd49bf7dec35a0432 | train_107.jsonl | 1644158100 | Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. | 256 megabytes | /******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.*;
public class Main
{
public static boolean solve(String str,int n){
int i = 0;
int j = n-1;
while(i<=j){
char ch = str.charAt(i);
char ch1 = str.charAt(j);
if(ch != ch1){
return false;
}
i++;
j--;
}
return true;
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
while(t-->0){
int n = scn.nextInt();
int k = scn.nextInt();
String str = scn.next();
boolean ispalin = solve(str,n);
int diff = 0;
HashSet<Character>set = new HashSet<>();
for(int i = 0;i<n;i++){
char ch = str.charAt(i);
set.add(ch);
}
if(ispalin){
System.out.println(1);
}
else if(set.size()==1){
System.out.println(1);
}
else if(k>=1){
System.out.println(2);
}
else{
System.out.println(1);
}
}
}
}
| Java | ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"] | 1 second | ["2\n2\n1\n1"] | NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab. | Java 11 | standard input | [
"greedy",
"strings"
] | 08cd22b8ee760a9d2dacb0d050dcf37a | The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters. | 800 | For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.