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 | efda553c7f78049201acfe1182b81a0d | train_108.jsonl | 1652020500 | Tokitsukaze has a permutation $$$p$$$ of length $$$n$$$. Recall that a permutation $$$p$$$ of length $$$n$$$ is a sequence $$$p_1, p_2, \ldots, p_n$$$ consisting of $$$n$$$ distinct integers, each of which from $$$1$$$ to $$$n$$$ ($$$1 \leq p_i \leq n$$$).She wants to know how many different indices tuples $$$[a,b,c,d]$$$ ($$$1 \leq a < b < c < d \leq n$$$) in this permutation satisfy the following two inequalities: $$$p_a < p_c$$$ and $$$p_b > p_d$$$. Note that two tuples $$$[a_1,b_1,c_1,d_1]$$$ and $$$[a_2,b_2,c_2,d_2]$$$ are considered to be different if $$$a_1 \ne a_2$$$ or $$$b_1 \ne b_2$$$ or $$$c_1 \ne c_2$$$ or $$$d_1 \ne d_2$$$. | 256 megabytes |
import java.io.*;
import java.util.*;
/**
*
* @author eslam
*/
public class IceCave {
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;
}
}
// Beginning of the solution
static FastReader input = new FastReader();
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
static ArrayList<ArrayList<Long>> powerSet = new ArrayList<>();
static long mod = (long) (Math.pow(10, 9) + 7);
static boolean ca = true;
static int dp[];
public static void main(String[] args) throws IOException {
int t = input.nextInt();
while (t-- > 0) {
int n = input.nextInt();
int a[] = new int[n];
long fans = 0;
for (int i = 0; i < n; i++) {
a[i] = input.nextInt()-1;
}
int ans[][] = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[j] < a[i]) {
ans[a[i]][j] = 1;
}
}
}
for (int i = 0; i < n; i++) {
suffixSum(ans[i]);
}
for (int i = 0; i < n-1; i++) {
int b = 0;
for (int j = 0; j < i; j++) {
long an = ans[a[j]][i+1];
fans += (b) * an;
if (a[j] < a[i]) {
b++;
}
}
}
log.write(fans + "\n");
}
log.flush();
}
public static void graphRepresintionWithCycle(ArrayList<Integer>[] a, int q) {
for (int i = 0; i < a.length; i++) {
a[i] = new ArrayList<>();
}
while (q-- > 0) {
int x = input.nextInt();
int y = input.nextInt();
a[x].add(y);
a[y].add(x);
}
}
public static void dfsRecursive(int n, ArrayList<Integer>[] a, boolean visited[]) {
ArrayList<Integer> nodes = a[n];
visited[n] = true;
for (Integer node : nodes) {
if (!visited[node]) {
dfsRecursive(node, a, visited);
}
}
}
public static int get(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static int primeFactors(int n) {
int sum = 0;
while (n % 2 == 0) {
sum += 2;
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i == 0) {
sum += get(i);
n /= i;
}
if (n < i) {
break;
}
}
if (n > 2) {
sum += get(n);
}
return sum;
}
public static ArrayList<Integer> printPrimeFactoriztion(int n) {
ArrayList<Integer> a = new ArrayList<>();
for (int i = 1; i < Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
if (isPrime(i)) {
a.add(i);
n /= i;
i = 0;
} else if (isPrime(n / i)) {
a.add(n / i);
n = i;
i = 0;
}
}
}
return a;
}
public static void genrate(int ind, long[] a, ArrayList<Long> sub) {
if (ind == a.length) {
powerSet.add(sub);
return;
}
ArrayList<Long> have = new ArrayList<>();
ArrayList<Long> less = new ArrayList<>();
for (int i = 0; i < sub.size(); i++) {
have.add(sub.get(i));
less.add(sub.get(i));
}
have.add(a[ind]);
genrate(ind + 1, a, have);
genrate(ind + 1, a, less);
}
// end of solution
public static long factorial(long n) {
if (n <= 1) {
return 1;
}
long t = n - 1;
while (t > 1) {
n *= t;
t--;
}
return n;
}
public static boolean isPalindrome(int n) {
int t = n;
int ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans == n;
}
static class tri {
int x, y, z;
public tri(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
}
static boolean isPrime(long num) {
if (num == 1) {
return false;
}
if (num == 2) {
return true;
}
if (num % 2 == 0) {
return false;
}
if (num == 3) {
return true;
}
for (int i = 3; i <= Math.sqrt(num) + 1; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void prefixSum(int[] a) {
for (int i = 1; i < a.length; i++) {
a[i] = a[i] + a[i - 1];
}
}
public static void suffixSum(int[] a) {
for (int i = a.length - 2; i > -1; i--) {
a[i] = a[i] + a[i + 1];
}
}
static long mod(long a, long b) {
long r = a % b;
return r < 0 ? r + b : r;
}
public static long binaryToDecimal(String w) {
long r = 0;
long l = 0;
for (int i = w.length() - 1; i > -1; i--) {
long x = (w.charAt(i) - '0') * (long) Math.pow(2, l);
r = r + x;
l++;
}
return r;
}
public static String decimalToBinary(long n) {
String w = "";
while (n > 0) {
w = n % 2 + w;
n /= 2;
}
return w;
}
public static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
public static void print(int a[]) throws IOException {
for (int i = 0; i < a.length; i++) {
log.write(a[i] + " ");
}
log.write("\n");
}
public static void read(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = input.nextInt();
}
}
static class pair {
long x;
int y;
public pair(long x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
public static long LCM(long x, long y) {
return x / GCD(x, y) * y;
}
public static long GCD(long x, long y) {
if (y == 0) {
return x;
}
return GCD(y, x % y);
}
public static void simplifyTheFraction(long a, long b) {
long GCD = GCD(a, b);
System.out.println(a / GCD + " " + b / GCD);
}
/**
*/ // class RedBlackNode
static class RedBlackNode<T extends Comparable<T>> {
/**
* Possible color for this node
*/
public static final int BLACK = 0;
/**
* Possible color for this node
*/
public static final int RED = 1;
// the key of each node
public T key;
/**
* Parent of node
*/
RedBlackNode<T> parent;
/**
* Left child
*/
RedBlackNode<T> left;
/**
* Right child
*/
RedBlackNode<T> right;
// the number of elements to the left of each node
public int numLeft = 0;
// the number of elements to the right of each node
public int numRight = 0;
// the color of a node
public int color;
RedBlackNode() {
color = BLACK;
numLeft = 0;
numRight = 0;
parent = null;
left = null;
right = null;
}
// Constructor which sets key to the argument.
RedBlackNode(T key) {
this();
this.key = key;
}
}// end class RedBlackNode
static class RedBlackTree<T extends Comparable<T>> {
// Root initialized to nil.
private RedBlackNode<T> nil = new RedBlackNode<T>();
private RedBlackNode<T> root = nil;
public RedBlackTree() {
root.left = nil;
root.right = nil;
root.parent = nil;
}
// @param: x, The node which the lefRotate is to be performed on.
// Performs a leftRotate around x.
private void leftRotate(RedBlackNode<T> x) {
// Call leftRotateFixup() which updates the numLeft
// and numRight values.
leftRotateFixup(x);
// Perform the left rotate as described in the algorithm
// in the course text.
RedBlackNode<T> y;
y = x.right;
x.right = y.left;
// Check for existence of y.left and make pointer changes
if (!isNil(y.left)) {
y.left.parent = x;
}
y.parent = x.parent;
// x's parent is nul
if (isNil(x.parent)) {
root = y;
} // x is the left child of it's parent
else if (x.parent.left == x) {
x.parent.left = y;
} // x is the right child of it's parent.
else {
x.parent.right = y;
}
// Finish of the leftRotate
y.left = x;
x.parent = y;
}// end leftRotate(RedBlackNode x)
// @param: x, The node which the leftRotate is to be performed on.
// Updates the numLeft & numRight values affected by leftRotate.
private void leftRotateFixup(RedBlackNode x) {
// Case 1: Only x, x.right and x.right.right always are not nil.
if (isNil(x.left) && isNil(x.right.left)) {
x.numLeft = 0;
x.numRight = 0;
x.right.numLeft = 1;
} // Case 2: x.right.left also exists in addition to Case 1
else if (isNil(x.left) && !isNil(x.right.left)) {
x.numLeft = 0;
x.numRight = 1 + x.right.left.numLeft
+ x.right.left.numRight;
x.right.numLeft = 2 + x.right.left.numLeft
+ x.right.left.numRight;
} // Case 3: x.left also exists in addition to Case 1
else if (!isNil(x.left) && isNil(x.right.left)) {
x.numRight = 0;
x.right.numLeft = 2 + x.left.numLeft + x.left.numRight;
} // Case 4: x.left and x.right.left both exist in addtion to Case 1
else {
x.numRight = 1 + x.right.left.numLeft
+ x.right.left.numRight;
x.right.numLeft = 3 + x.left.numLeft + x.left.numRight
+ x.right.left.numLeft + x.right.left.numRight;
}
}// end leftRotateFixup(RedBlackNode x)
// @param: x, The node which the rightRotate is to be performed on.
// Updates the numLeft and numRight values affected by the Rotate.
private void rightRotate(RedBlackNode<T> y) {
// Call rightRotateFixup to adjust numRight and numLeft values
rightRotateFixup(y);
// Perform the rotate as described in the course text.
RedBlackNode<T> x = y.left;
y.left = x.right;
// Check for existence of x.right
if (!isNil(x.right)) {
x.right.parent = y;
}
x.parent = y.parent;
// y.parent is nil
if (isNil(y.parent)) {
root = x;
} // y is a right child of it's parent.
else if (y.parent.right == y) {
y.parent.right = x;
} // y is a left child of it's parent.
else {
y.parent.left = x;
}
x.right = y;
y.parent = x;
}// end rightRotate(RedBlackNode y)
// @param: y, the node around which the righRotate is to be performed.
// Updates the numLeft and numRight values affected by the rotate
private void rightRotateFixup(RedBlackNode y) {
// Case 1: Only y, y.left and y.left.left exists.
if (isNil(y.right) && isNil(y.left.right)) {
y.numRight = 0;
y.numLeft = 0;
y.left.numRight = 1;
} // Case 2: y.left.right also exists in addition to Case 1
else if (isNil(y.right) && !isNil(y.left.right)) {
y.numRight = 0;
y.numLeft = 1 + y.left.right.numRight
+ y.left.right.numLeft;
y.left.numRight = 2 + y.left.right.numRight
+ y.left.right.numLeft;
} // Case 3: y.right also exists in addition to Case 1
else if (!isNil(y.right) && isNil(y.left.right)) {
y.numLeft = 0;
y.left.numRight = 2 + y.right.numRight + y.right.numLeft;
} // Case 4: y.right & y.left.right exist in addition to Case 1
else {
y.numLeft = 1 + y.left.right.numRight
+ y.left.right.numLeft;
y.left.numRight = 3 + y.right.numRight
+ y.right.numLeft
+ y.left.right.numRight + y.left.right.numLeft;
}
}// end rightRotateFixup(RedBlackNode y)
public void insert(T key) {
insert(new RedBlackNode<T>(key));
}
// @param: z, the node to be inserted into the Tree rooted at root
// Inserts z into the appropriate position in the RedBlackTree while
// updating numLeft and numRight values.
private void insert(RedBlackNode<T> z) {
// Create a reference to root & initialize a node to nil
RedBlackNode<T> y = nil;
RedBlackNode<T> x = root;
// While we haven't reached a the end of the tree keep
// tryint to figure out where z should go
while (!isNil(x)) {
y = x;
// if z.key is < than the current key, go left
if (z.key.compareTo(x.key) < 0) {
// Update x.numLeft as z is < than x
x.numLeft++;
x = x.left;
} // else z.key >= x.key so go right.
else {
// Update x.numGreater as z is => x
x.numRight++;
x = x.right;
}
}
// y will hold z's parent
z.parent = y;
// Depending on the value of y.key, put z as the left or
// right child of y
if (isNil(y)) {
root = z;
} else if (z.key.compareTo(y.key) < 0) {
y.left = z;
} else {
y.right = z;
}
// Initialize z's children to nil and z's color to red
z.left = nil;
z.right = nil;
z.color = RedBlackNode.RED;
// Call insertFixup(z)
insertFixup(z);
}// end insert(RedBlackNode z)
// @param: z, the node which was inserted and may have caused a violation
// of the RedBlackTree properties
// Fixes up the violation of the RedBlackTree properties that may have
// been caused during insert(z)
private void insertFixup(RedBlackNode<T> z) {
RedBlackNode<T> y = nil;
// While there is a violation of the RedBlackTree properties..
while (z.parent.color == RedBlackNode.RED) {
// If z's parent is the the left child of it's parent.
if (z.parent == z.parent.parent.left) {
// Initialize y to z 's cousin
y = z.parent.parent.right;
// Case 1: if y is red...recolor
if (y.color == RedBlackNode.RED) {
z.parent.color = RedBlackNode.BLACK;
y.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
z = z.parent.parent;
} // Case 2: if y is black & z is a right child
else if (z == z.parent.right) {
// leftRotaet around z's parent
z = z.parent;
leftRotate(z);
} // Case 3: else y is black & z is a left child
else {
// recolor and rotate round z's grandpa
z.parent.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
rightRotate(z.parent.parent);
}
} // If z's parent is the right child of it's parent.
else {
// Initialize y to z's cousin
y = z.parent.parent.left;
// Case 1: if y is red...recolor
if (y.color == RedBlackNode.RED) {
z.parent.color = RedBlackNode.BLACK;
y.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
z = z.parent.parent;
} // Case 2: if y is black and z is a left child
else if (z == z.parent.left) {
// rightRotate around z's parent
z = z.parent;
rightRotate(z);
} // Case 3: if y is black and z is a right child
else {
// recolor and rotate around z's grandpa
z.parent.color = RedBlackNode.BLACK;
z.parent.parent.color = RedBlackNode.RED;
leftRotate(z.parent.parent);
}
}
}
// Color root black at all times
root.color = RedBlackNode.BLACK;
}// end insertFixup(RedBlackNode z)
// @param: node, a RedBlackNode
// @param: node, the node with the smallest key rooted at node
public RedBlackNode<T> treeMinimum(RedBlackNode<T> node) {
// while there is a smaller key, keep going left
while (!isNil(node.left)) {
node = node.left;
}
return node;
}// end treeMinimum(RedBlackNode node)
// @param: x, a RedBlackNode whose successor we must find
// @return: return's the node the with the next largest key
// from x.key
public RedBlackNode<T> treeSuccessor(RedBlackNode<T> x) {
// if x.left is not nil, call treeMinimum(x.right) and
// return it's value
if (!isNil(x.left)) {
return treeMinimum(x.right);
}
RedBlackNode<T> y = x.parent;
// while x is it's parent's right child...
while (!isNil(y) && x == y.right) {
// Keep moving up in the tree
x = y;
y = y.parent;
}
// Return successor
return y;
}// end treeMinimum(RedBlackNode x)
// @param: z, the RedBlackNode which is to be removed from the the tree
// Remove's z from the RedBlackTree rooted at root
public void remove(RedBlackNode<T> v) {
RedBlackNode<T> z = search(v.key);
// Declare variables
RedBlackNode<T> x = nil;
RedBlackNode<T> y = nil;
// if either one of z's children is nil, then we must remove z
if (isNil(z.left) || isNil(z.right)) {
y = z;
} // else we must remove the successor of z
else {
y = treeSuccessor(z);
}
// Let x be the left or right child of y (y can only have one child)
if (!isNil(y.left)) {
x = y.left;
} else {
x = y.right;
}
// link x's parent to y's parent
x.parent = y.parent;
// If y's parent is nil, then x is the root
if (isNil(y.parent)) {
root = x;
} // else if y is a left child, set x to be y's left sibling
else if (!isNil(y.parent.left) && y.parent.left == y) {
y.parent.left = x;
} // else if y is a right child, set x to be y's right sibling
else if (!isNil(y.parent.right) && y.parent.right == y) {
y.parent.right = x;
}
// if y != z, trasfer y's satellite data into z.
if (y != z) {
z.key = y.key;
}
// Update the numLeft and numRight numbers which might need
// updating due to the deletion of z.key.
fixNodeData(x, y);
// If y's color is black, it is a violation of the
// RedBlackTree properties so call removeFixup()
if (y.color == RedBlackNode.BLACK) {
removeFixup(x);
}
}// end remove(RedBlackNode z)
// @param: y, the RedBlackNode which was actually deleted from the tree
// @param: key, the value of the key that used to be in y
private void fixNodeData(RedBlackNode<T> x, RedBlackNode<T> y) {
// Initialize two variables which will help us traverse the tree
RedBlackNode<T> current = nil;
RedBlackNode<T> track = nil;
// if x is nil, then we will start updating at y.parent
// Set track to y, y.parent's child
if (isNil(x)) {
current = y.parent;
track = y;
} // if x is not nil, then we start updating at x.parent
// Set track to x, x.parent's child
else {
current = x.parent;
track = x;
}
// while we haven't reached the root
while (!isNil(current)) {
// if the node we deleted has a different key than
// the current node
if (y.key != current.key) {
// if the node we deleted is greater than
// current.key then decrement current.numRight
if (y.key.compareTo(current.key) > 0) {
current.numRight--;
}
// if the node we deleted is less than
// current.key thendecrement current.numLeft
if (y.key.compareTo(current.key) < 0) {
current.numLeft--;
}
} // if the node we deleted has the same key as the
// current node we are checking
else {
// the cases where the current node has any nil
// children and update appropriately
if (isNil(current.left)) {
current.numLeft--;
} else if (isNil(current.right)) {
current.numRight--;
} // the cases where current has two children and
// we must determine whether track is it's left
// or right child and update appropriately
else if (track == current.right) {
current.numRight--;
} else if (track == current.left) {
current.numLeft--;
}
}
// update track and current
track = current;
current = current.parent;
}
}//end fixNodeData()
// @param: x, the child of the deleted node from remove(RedBlackNode v)
// Restores the Red Black properties that may have been violated during
// the removal of a node in remove(RedBlackNode v)
private void removeFixup(RedBlackNode<T> x) {
RedBlackNode<T> w;
// While we haven't fixed the tree completely...
while (x != root && x.color == RedBlackNode.BLACK) {
// if x is it's parent's left child
if (x == x.parent.left) {
// set w = x's sibling
w = x.parent.right;
// Case 1, w's color is red.
if (w.color == RedBlackNode.RED) {
w.color = RedBlackNode.BLACK;
x.parent.color = RedBlackNode.RED;
leftRotate(x.parent);
w = x.parent.right;
}
// Case 2, both of w's children are black
if (w.left.color == RedBlackNode.BLACK
&& w.right.color == RedBlackNode.BLACK) {
w.color = RedBlackNode.RED;
x = x.parent;
} // Case 3 / Case 4
else {
// Case 3, w's right child is black
if (w.right.color == RedBlackNode.BLACK) {
w.left.color = RedBlackNode.BLACK;
w.color = RedBlackNode.RED;
rightRotate(w);
w = x.parent.right;
}
// Case 4, w = black, w.right = red
w.color = x.parent.color;
x.parent.color = RedBlackNode.BLACK;
w.right.color = RedBlackNode.BLACK;
leftRotate(x.parent);
x = root;
}
} // if x is it's parent's right child
else {
// set w to x's sibling
w = x.parent.left;
// Case 1, w's color is red
if (w.color == RedBlackNode.RED) {
w.color = RedBlackNode.BLACK;
x.parent.color = RedBlackNode.RED;
rightRotate(x.parent);
w = x.parent.left;
}
// Case 2, both of w's children are black
if (w.right.color == RedBlackNode.BLACK
&& w.left.color == RedBlackNode.BLACK) {
w.color = RedBlackNode.RED;
x = x.parent;
} // Case 3 / Case 4
else {
// Case 3, w's left child is black
if (w.left.color == RedBlackNode.BLACK) {
w.right.color = RedBlackNode.BLACK;
w.color = RedBlackNode.RED;
leftRotate(w);
w = x.parent.left;
}
// Case 4, w = black, and w.left = red
w.color = x.parent.color;
x.parent.color = RedBlackNode.BLACK;
w.left.color = RedBlackNode.BLACK;
rightRotate(x.parent);
x = root;
}
}
}// end while
// set x to black to ensure there is no violation of
// RedBlack tree Properties
x.color = RedBlackNode.BLACK;
}// end removeFixup(RedBlackNode x)
// @param: key, the key whose node we want to search for
// @return: returns a node with the key, key, if not found, returns null
// Searches for a node with key k and returns the first such node, if no
// such node is found returns null
public RedBlackNode<T> search(T key) {
// Initialize a pointer to the root to traverse the tree
RedBlackNode<T> current = root;
// While we haven't reached the end of the tree
while (!isNil(current)) {
// If we have found a node with a key equal to key
if (current.key.equals(key)) // return that node and exit search(int)
{
return current;
} // go left or right based on value of current and key
else if (current.key.compareTo(key) < 0) {
current = current.right;
} // go left or right based on value of current and key
else {
current = current.left;
}
}
// we have not found a node whose key is "key"
return null;
}// end search(int key)
// @param: key, any Comparable object
// @return: return's the number of elements greater than key
public int numGreater(T key) {
// Call findNumGreater(root, key) which will return the number
// of nodes whose key is greater than key
return findNumGreater(root, key);
}// end numGreater(int key)
// @param: key, any Comparable object
// @return: return's teh number of elements smaller than key
public int numSmaller(T key) {
// Call findNumSmaller(root,key) which will return
// the number of nodes whose key is greater than key
return findNumSmaller(root, key);
}// end numSmaller(int key)
// @param: node, the root of the tree, the key who we must
// compare other node key's to.
// @return: the number of nodes greater than key.
public int findNumGreater(RedBlackNode<T> node, T key) {
// Base Case: if node is nil, return 0
if (isNil(node)) {
return 0;
} // If key is less than node.key, all elements right of node are
// greater than key, add this to our total and look to the left
else if (key.compareTo(node.key) < 0) {
return 1 + node.numRight + findNumGreater(node.left, key);
} // If key is greater than node.key, then look to the right as
// all elements to the left of node are smaller than key
else {
return findNumGreater(node.right, key);
}
}// end findNumGreater(RedBlackNode, int key)
/**
* Returns sorted list of keys greater than key. Size of list will not
* exceed maxReturned
*
* @param key Key to search for
* @param maxReturned Maximum number of results to return
* @return List of keys greater than key. List may not exceed
* maxReturned
*/
public List<T> getGreaterThan(T key, Integer maxReturned) {
List<T> list = new ArrayList<T>();
getGreaterThan(root, key, list);
return list.subList(0, Math.min(maxReturned, list.size()));
}
private void getGreaterThan(RedBlackNode<T> node, T key,
List<T> list) {
if (isNil(node)) {
return;
} else if (node.key.compareTo(key) > 0) {
getGreaterThan(node.left, key, list);
list.add(node.key);
getGreaterThan(node.right, key, list);
} else {
getGreaterThan(node.right, key, list);
}
}
// @param: node, the root of the tree, the key who we must compare other
// node key's to.
// @return: the number of nodes smaller than key.
public int findNumSmaller(RedBlackNode<T> node, T key) {
// Base Case: if node is nil, return 0
if (isNil(node)) {
return 0;
} // If key is less than node.key, look to the left as all
// elements on the right of node are greater than key
else if (key.compareTo(node.key) <= 0) {
return findNumSmaller(node.left, key);
} // If key is larger than node.key, all elements to the left of
// node are smaller than key, add this to our total and look
// to the right.
else {
return 1 + node.numLeft + findNumSmaller(node.right, key);
}
}// end findNumSmaller(RedBlackNode nod, int key)
// @param: node, the RedBlackNode we must check to see whether it's nil
// @return: return's true of node is nil and false otherwise
private boolean isNil(RedBlackNode node) {
// return appropriate value
return node == nil;
}// end isNil(RedBlackNode node)
// @return: return's the size of the tree
// Return's the # of nodes including the root which the RedBlackTree
// rooted at root has.
public int size() {
// Return the number of nodes to the root's left + the number of
// nodes on the root's right + the root itself.
return root.numLeft + root.numRight + 1;
}// end size()
}// end class RedBlackTree
}
| Java | ["3\n\n6\n\n5 3 6 1 4 2\n\n4\n\n1 2 3 4\n\n10\n\n5 1 6 2 8 3 4 10 9 7"] | 1.5 seconds | ["3\n0\n28"] | NoteIn the first test case, there are $$$3$$$ different $$$[a,b,c,d]$$$ tuples.$$$p_1 = 5$$$, $$$p_2 = 3$$$, $$$p_3 = 6$$$, $$$p_4 = 1$$$, where $$$p_1 < p_3$$$ and $$$p_2 > p_4$$$ satisfies the inequality, so one of $$$[a,b,c,d]$$$ tuples is $$$[1,2,3,4]$$$.Similarly, other two tuples are $$$[1,2,3,6]$$$, $$$[2,3,5,6]$$$. | Java 17 | standard input | [
"brute force",
"data structures"
] | d6a123dab1263b0e7b297ca2584fe701 | The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$4 \leq n \leq 5000$$$) — the length of permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$. | 1,600 | For each test case, print a single integer — the number of different $$$[a,b,c,d]$$$ tuples. | standard output | |
PASSED | b0ca54cd295cb677c6d0269b3dc8e146 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class CF789VC {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void sort(int [] a) {
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i:a)
{
arr.add(i);
}
Collections.sort(arr);
int len = arr.size();
for(int i=0;i<len;++i)
a[i] = arr.get(i);
}
static class FenwickTreeExample
{
// Max size of the Fenwick tree in this code
static int MAX_SIZE ;
// the array that represents the fenwick tree
private int fenArr[];
FenwickTreeExample(int n)
{
MAX_SIZE=n;
fenArr = new int [4*MAX_SIZE+15];
for(int i=0;i<4*MAX_SIZE+15;++i)
fenArr[i] = 0;
}
// s --> It is number of element available in the input array.
// fenArr[0 ... s] --> The array that represents the Fenwick Tree
// a[0 ... s - 1] --> It is the input array for which the prefix sum is generated.
// Returns the sum of a[0... idx]. The method assumes
// that the array is already preprocessed and
// the partial sums of the array elements are kept
// in fenArr[].
int getArrSum(int idx)
{
// Initializing the result to 0
int total = 0;
// index in the fenTree[] is one more than the
// index in the array a[]
idx = idx + 1;
// Traversing the ancestors of the fenTree[idx]
while(idx > 0)
{
// Adding the current element of the array fenArr[]
// to the total
total = total + fenArr[idx];
// Moving the index to the parent node in
// getArrSum view
idx -= idx & (-idx);
}
return total;
}
// Updating a node in the Fenwick Tree
// at a given index in the array fenArr[]. The given input value
// 'v' is added to the fenArr[idx] and therefore, it is also added to the
// ancestors of the tree too.
public void updateFenwick(int s, int idx, int v)
{
// index in the array fenArr[] is 1 more than the
// index in the array a[]
idx = idx + 1;
// Traversing all the ancestors and adding 'v'
while(idx <= s)
{
// Add 'val' to current node of BIT Tree
fenArr[idx] = fenArr[idx] + v;
// Updating the idx to that of parent
// in the update View
idx = idx + (idx & (-idx));
}
}
// Method to build the Fenwick tree
// from the given array.
void constructFenTree(int arr[], int s)
{
// Initializing fenArr[] as 0
for(int i = 1; i <= s; i++)
{
fenArr[i] = 0;
}
// Storing the original values in the fenArr[]
// using the mehtod updateFenwick()
for(int j = 0; j < s; j++)
{
updateFenwick(s, j, arr[j]);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PrintWriter out = new PrintWriter(System.out);
FastReader fs = new FastReader();
int t = fs.nextInt();
for(int cs=0;cs<t;++cs)
{
int n= fs.nextInt(),m = fs.nextInt();
char [] s = fs.next().toCharArray();
int len = n*m;
int [][] matA = new int [n][m];
int [][] matB = new int [n][m];
int [][] finmatB = new int [n][m];
int previousOnes = 0;
for(int i=0;i<len;++i)
{
if(i-m>=0)
{
if(s[i-m] == '1' )
{
previousOnes--;
}
}
if(s[i] == '1')
previousOnes++;
matA[i/m][i%m] = ((previousOnes>0)?1:0);
}
for(int j=0;j<m;++j)
{ int flag=0;
for(int i=0;i<n;++i)
{
if(s[i*m+j] == '1')
flag=1;
matB[i][j] = flag;
}
}
for(int i=1;i<n;++i)
{
for(int j=0;j<m;++j)
matA[i][j]+=matA[i-1][j];
}
int previousSum=0;
int removePos;
for(int i=0;i<n;++i)
{
for(int j=0;j<m;++j)
{
removePos = i*m+j-m;
if(removePos>=0)
{
previousSum-=matB[removePos/m][removePos%m];
}
previousSum+=matB[i][j];
finmatB[i][j]=previousSum;
}
}
for(int i=0;i<n*m;++i)
{
out.print( matA[i/m][i%m] + finmatB[i/m][i%m]);
out.print(" ");
}
out.printf("\n");
}
out.close();
}
} | Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | e17be1cb664db9e05c74182efbefc864 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
static double pi = 3.141592653589;
static int mod = (int) 1e9 + 7;
public static void main(String[] args) throws IOException {
int qwe = in.nextInt();
while (qwe-- > 0)
{
solve();
}
out.flush();
out.close();
}
public static void solve() {
int n = in.nextInt();
int m = in.nextInt();
char[] num = in.next().toCharArray();
int[] row = new int[n*m];
int[] col = new int[n*m];
int[] ans = new int[n*m];
int cnt = -1;
for (int i = 0; i < n*m; i++) {
if (num[i]=='1') cnt = i;
if (i < m){
if (cnt != -1) row[i] = 1;
}else {
if (i-cnt<m) row[i] = row[i-m]+1;
else row[i] = row[i-m];
}
ans[i]+=row[i];
}
cnt = 0;
for (int i = 0; i < n*m; i++) {
if (num[i] == '1' && col[i%m]==0){
col[i%m]=1;
cnt++;
}
ans[i]+=cnt;
}
for (int i = 0; i < n*m; i++) {
out.print(ans[i]+" ");
}
out.println();
}
/*
3
3 114514 5
*/
// static int N = 1010;
// static int n,m;
// static int INF = 0x3f3f3f3f;
// static int[][] g = new int[N][N]; // 存储每条边 邻接矩阵
// static int[] dist = new int[N]; // 存储1号点到每个点的最短距离
// static boolean[] st = new boolean[N]; // 存储每个点的最短路是否已经确定
// static void init(){
// Arrays.fill(dist, INF);
// for (int i = 0; i <= n; i++) Arrays.fill(g[i],0x3f3f3f3f);
// }
// // 求x号点到y号点的最短路,如果不存在则返回-1
// static int dijkstra(int x, int y) {
// dist[x] = 0;
// for (int i = 1; i < n; i++) {
// int t = -1; // 在还未确定最短路的点中,寻找距离最小的点
// for (int j = 1; j <= n; j++)
// if (!st[j] && (t == -1 || dist[t] > dist[j]))
// t = j;
//
// st[t] = true;
// // 用t更新其他点的距离
// for (int j = 1; j <= n; j++) dist[j] = Math.min(dist[j], dist[t] + g[t][j]);
// }
// if (dist[y] == INF) return -1;
// return dist[y];
// }
// static int N = 1000 * 26;
// static int[][] trie = new int[N][26];;
// static int[] cnt = new int[N];
// static int idx;
// static void insert_trie(String s) {
// int p = 0;
// for (int i = 0; i < s.length(); i++) {
// int u = s.charAt(i) - 'a'; //如果是大写字母,则需要改成大写A
// if (trie[p][u] == 0) trie[p][u] = ++idx;
// p = trie[p][u];
// }
// cnt[p]++;
// }
// static int search_trie(String s){
// int p = 0;
// for (int i = 0; i < s.length(); i ++ ){
// int u = s.charAt(i) - 'a';
// if (trie[p][u] == 0) return 0;
// p = trie[p][u];
// }
// return cnt[p];
// }
static void kmp(String s1, String s2) { //短字符串、长字符串
int n = s1.length(); //短字符串
int m = s2.length();
char[] p = (" " + s1).toCharArray();//短字符串
char[] s = (" " + s2).toCharArray();
// 构造ne数组
int[] ne = new int[n + 1];
for (int i = 2, j = 0; i <= n; i++) {
while (j != 0 && p[i] != p[j + 1]) j = ne[j];
if (p[i] == p[j + 1]) j++;
ne[i] = j;
}
// kmp匹配
for (int i = 1, j = 0; i <= m; i++) {
while (j != 0 && s[i] != p[j + 1]) j = ne[j];
if (s[i] == p[j + 1]) j++;
if (j == n) { // 匹配了n字符了即代表完全匹配了
out.print(i - n + " "); // 输出在s串中p出现的位置
j = ne[j]; // 完全匹配后继续搜索
}
out.flush();
}
}
// static int N = 100010;
// static int idx = 0; //节点位置
// static char[] str = new char[N];
// static int[] cnt = new int[N];
// static int[][] son = new int[N][26];
// public static void insert(char[] str) {
// int p = 0; //从根节点出发
// for (char i : str) {
// int u = i - 'a';
// if (son[p][u] == 0) son[p][u] = ++idx;
// p = son[p][u];
// }
// cnt[p]++;
// }
// public static int query(char[] str) {
// int p = 0;
// for (char i : str) {
// int u = i - 'a';
// if (son[p][u] == 0) return 0;
// p = son[p][u];
// }
// return cnt[p];
// }
// static int bsearch_l(int l, int r, long target) {
// while (l < r) {
// int mid = l + r >> 1;
// if (num[mid] >= target) r = mid;
// else l = mid + 1;
// }
// return l;
// }
//
// static int bsearch_r(int l, int r, long target) {
// while (l < r) {
// int mid = l + r + 1 >> 1;
// if (num[mid] <= target) l = mid;
// else r = mid - 1;
// }
// return l;
// }
// static double bsearch_d(double l, double r) {
// double eps = 1e-8;
// while (Math.abs(r - l) > eps) {
// double mid = (l + r) / 2;
// if (check(mid)) r = mid;
// else l = mid;
// }
// return l;
// }
// static boolean check(int mid) {
// return true;
// }
public static long ksm(long n, long m) {//本质为n^m
long res = 1, base = n;
while (m != 0) {
if ((m & 1) == 1) { //等价于m%2==1,也就是m为奇数时
res = mul(res, base) % mod;
}
base = mul(base, base) % mod;//m为偶数时,base自乘
m = m >> 1;//等价于m/2
}
return res % mod;
}
static long mul(long a, long b) {//本质为a*b
long ans = 0;
while (b != 0) {
if ((b & 1) == 1) {
ans = (ans + a) % mod;
}
a = (a + a) % mod;
b = b >> 1;
}
return ans % mod;
}
public static long cnm(int a, int b) {
long sum = 1;
int i = a, j = 1;
while (j <= b) {
sum = sum * i / j;
i--;
j++;
}
return sum;
}
public static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static void gbSort(int[] a, int l, int r) {
if (l < r) {
int m = (l + r) >> 1;
gbSort(a, l, m);
gbSort(a, m + 1, r);
int[] t = new int[r - l + 1];
int idx = 0, i = l, j = m + 1;
while (i <= m && j <= r)
if (a[i] <= a[j]) t[idx++] = a[i++];
else t[idx++] = a[j++];
while (i <= m) t[idx++] = a[i++];
while (j <= r) t[idx++] = a[j++];
for (int z = 0; z < t.length; z++) a[l + z] = t[z];
}
}
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
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();
}
boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
return false;
// TODO: handle exception
}
}
return true;
}
public String nextLine() {
String str = null;
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public BigDecimal nextBigDecimal() {
return new BigDecimal(next());
}
}
}
| Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | b86b82a54471a1bf4281646c99ba122e | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 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.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DTokitsukazeAndMeeting solver = new DTokitsukazeAndMeeting();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class DTokitsukazeAndMeeting {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt();
int[] arr = toIntArray(in.next());
int[] rc = new int[m];
int[] cc = new int[m];
int ans = 0;
int point = m;
int last = -2 * m;
for (int i = 0; i < n * m; i++) {
point = (point - 1 + m) % m;
cc[point] += arr[i];
if (cc[point] == 1 && arr[i] == 1) ans++;
if (arr[i] == 1) last = i;
if (i - last < m) rc[i % m]++;
out.print((ans + rc[i % m]) + " ");
}
out.println();
}
int[] toIntArray(String s) {
int[] A = new int[s.length()];
for (int i = 0; i < A.length; i++) {
A[i] = s.charAt(i) - '0';
}
return A;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println() {
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | 5cb446da1ddd930bd948fc3759741b94 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class copy {
static int log=18;
static int[][] ancestor;
static int[] depth;
static void sieveOfEratosthenes(int n, ArrayList<Integer> arr) {
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a
// prime
if (prime[p]) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++) {
if (prime[i]) {
arr.add(i);
}
}
}
public static long fac(long N, long mod) {
if (N == 0)
return 1;
if(N==1)
return 1;
return ((N % mod) * (fac(N - 1, mod) % mod)) % mod;
}
static long power(long x, long y, long p) {
// Initialize result
long res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static long nCrModPFermat(long n, long r,
long p) {
if (n < r)
return 0;
// Base case
if (r == 0)
return 1;
return ((fac(n, p) % p * (modInverse(fac(r, p), p)
% p)) % p * (modInverse(fac(n - r, p), p)
% p)) % p;
}
public static int find(int[] parent, int x) {
if (parent[x] == x)
return x;
return find(parent, parent[x]);
}
public static void merge(int[] parent, int[] rank, int x, int y,int[] child) {
int x1 = find(parent, x);
int y1 = find(parent, y);
if (rank[x1] > rank[y1]) {
parent[y1] = x1;
child[x1]+=child[y1];
} else if (rank[y1] > rank[x1]) {
parent[x1] = y1;
child[y1]+=child[x1];
} else {
parent[y1] = x1;
child[x1]+=child[y1];
rank[x1]++;
}
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static int power(int x, int y, int p)
{
int res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static int nCrModPFermat(int n, int r,
int p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
public static long[][] ncr(int n,int r)
{
long[][] dp=new long[n+1][r+1];
for(int i=0;i<=n;i++)
dp[i][0]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=r;j++)
{
if(j>i)
continue;
dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
}
}
return dp;
}
public static boolean prime(long N)
{
int c=0;
for(int i=2;i*i<=N;i++)
{
if(N%i==0)
++c;
}
return c==0;
}
public static int sparse_ancestor_table(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[] child)
{
int c=0;
for(int i:arr.get(x))
{
if(i!=parent)
{
// System.out.println(i+" hello "+x);
depth[i]=depth[x]+1;
ancestor[i][0]=x;
// if(i==2)
// System.out.println(parent+" hello");
for(int j=1;j<log;j++)
ancestor[i][j]=ancestor[ancestor[i][j-1]][j-1];
c+=sparse_ancestor_table(arr,i,x,child);
}
}
child[x]=1+c;
return child[x];
}
public static int lca(int x,int y)
{
if(depth[x]<depth[y])
{
int temp=x;
x=y;
y=temp;
}
x=get_kth_ancestor(depth[x]-depth[y],x);
if(x==y)
return x;
// System.out.println(x+" "+y);
for(int i=log-1;i>=0;i--)
{
if(ancestor[x][i]!=ancestor[y][i])
{
x=ancestor[x][i];
y=ancestor[y][i];
}
}
return ancestor[x][0];
}
public static int get_kth_ancestor(int K,int x)
{
if(K==0)
return x;
int node=x;
for(int i=0;i<log;i++)
{
if(K%2!=0)
{
node=ancestor[node][i];
}
K/=2;
}
return node;
}
public static ArrayList<Integer> primeFactors(int n)
{
// Print the number of 2s that divide n
ArrayList<Integer> factors=new ArrayList<>();
if(n%2==0)
factors.add(2);
while (n%2==0)
{
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
if(n%i==0)
factors.add(i);
while (n%i == 0)
{
n /= i;
}
}
// This condition is to handle the case when
// n is a prime number greater than 2
if (n > 2)
{
factors.add(n);
}
return factors;
}
static long ans=1,mod=1000000007;
public static void recur(long X,long N,int index,ArrayList<Integer> temp)
{
// System.out.println(X);
if(index==temp.size())
{
System.out.println(X);
ans=((ans%mod)*(X%mod))%mod;
return;
}
for(int i=0;i<=60;i++)
{
if(X*Math.pow(temp.get(index),i)<=N)
recur(X*(long)Math.pow(temp.get(index),i),N,index+1,temp);
else
break;
}
}
public static int upper(ArrayList<Integer> temp,int X)
{
int l=0,r=temp.size()-1;
while(l<=r)
{
int mid=(l+r)/2;
if(temp.get(mid)==X)
return mid;
// System.out.println(mid+" "+temp.get(mid));
if(temp.get(mid)<X)
l=mid+1;
else
{
if(mid-1>=0 && temp.get(mid-1)>=X)
r=mid-1;
else
return mid;
}
}
return -1;
}
public static int lower(ArrayList<Integer> temp,int X)
{
int l=0,r=temp.size()-1;
while(l<=r)
{
int mid=(l+r)/2;
if(temp.get(mid)==X)
return mid;
// System.out.println(mid+" "+temp.get(mid));
if(temp.get(mid)>X)
r=mid-1;
else
{
if(mid+1<temp.size() && temp.get(mid+1)<=X)
l=mid+1;
else
return mid;
}
}
return -1;
}
public static int[] check(String shelf,int[][] queries)
{
int[] arr=new int[queries.length];
ArrayList<Integer> indices=new ArrayList<>();
for(int i=0;i<shelf.length();i++)
{
char ch=shelf.charAt(i);
if(ch=='|')
indices.add(i);
}
for(int i=0;i<queries.length;i++)
{
int x=queries[i][0]-1;
int y=queries[i][1]-1;
int left=upper(indices,x);
int right=lower(indices,y);
if(left<=right && left!=-1 && right!=-1)
{
arr[i]=indices.get(right)-indices.get(left)+1-(right-left+1);
}
else
arr[i]=0;
}
return arr;
}
static boolean check;
public static void check(ArrayList<ArrayList<Integer>> arr,int x,int[] color,boolean[] visited)
{
visited[x]=true;
PriorityQueue<Integer> pq=new PriorityQueue<>();
for(int i:arr.get(x))
{
if(color[i]<color[x])
pq.add(color[i]);
if(color[i]==color[x])
check=false;
if(!visited[i])
check(arr,i,color,visited);
}
int start=1;
while(pq.size()>0)
{
int temp=pq.poll();
if(temp==start)
++start;
else
break;
}
if(start!=color[x])
check=false;
}
static boolean cycle;
public static void cycle(boolean[] stack,boolean[] visited,int x,ArrayList<ArrayList<Integer>> arr)
{
if(stack[x])
{
cycle=true;
return;
}
visited[x]=true;
for(int i:arr.get(x))
{
if(!visited[x])
{
cycle(stack,visited,i,arr);
}
}
stack[x]=false;
}
public static int check(char[][] ch,int x,int y)
{
int cnt=0;
int c=0;
int N=ch.length;
int x1=x,y1=y;
while(c<ch.length)
{
if(ch[x][y]=='1')
++cnt;
// if(x1==0 && y1==3)
// System.out.println(x+" "+y+" "+cnt);
x=(x+1)%N;
y=(y+1)%N;
++c;
}
return cnt;
}
public static void s(char[][] arr,int x)
{
char start=arr[arr.length-1][x];
for(int i=arr.length-1;i>0;i--)
{
arr[i][x]=arr[i-1][x];
}
arr[0][x]=start;
}
public static void shuffle(char[][] arr,int x,int down)
{
int N= arr.length;
down%=N;
char[] store=new char[N-down];
for(int i=0;i<N-down;i++)
store[i]=arr[i][x];
for(int i=0;i<arr.length;i++)
{
if(i<down)
{
// Printing rightmost
// kth elements
arr[i][x]=arr[N + i - down][x];
}
else
{
// Prints array after
// 'k' elements
arr[i][x]=store[i-down];
}
}
}
public static String form(int C1,char ch1,char ch2)
{
char ch=ch1;
String s="";
for(int i=1;i<=C1;i++)
{
s+=ch;
if(ch==ch1)
ch=ch2;
else
ch=ch1;
}
return s;
}
public static void printArray(long[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public static boolean check(long mid,long[] arr,long K)
{
long[] arr1=Arrays.copyOfRange(arr,0,arr.length);
long ans=0;
for(int i=0;i<arr1.length-1;i++)
{
if(arr1[i]+arr1[i+1]>=mid)
{
long check=(arr1[i]+arr1[i+1])/mid;
// if(mid==5)
// System.out.println(check);
long left=check*mid;
left-=arr1[i];
if(left>=0)
arr1[i+1]-=left;
ans+=check;
}
// if(mid==5)
// printArray(arr1);
}
// if(mid==5)
// System.out.println(ans);
ans+=arr1[arr1.length-1]/mid;
return ans>=K;
}
public static long search(long sum,long[] arr,long K)
{
long l=1,r=sum/K;
while(l<=r)
{
long mid=(l+r)/2;
if(check(mid,arr,K))
{
if(mid+1<=sum/K && check(mid+1,arr,K))
l=mid+1;
else
return mid;
}
else
r=mid-1;
}
return -1;
}
public static void primeFactors(int n,HashSet<Integer> hp)
{
// Print the number of 2s that divide n
ArrayList<Integer> factors=new ArrayList<>();
if(n%2==0)
hp.add(2);
while (n%2==0)
{
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
if(n%i==0)
hp.add(i);
while (n%i == 0)
{
n /= i;
}
}
// This condition is to handle the case when
// n is a prime number greater than 2
if (n > 2)
{
hp.add(n);
}
}
public static boolean check(String s)
{
HashSet<Character> hp=new HashSet<>();
char ch=s.charAt(0);
for(int i=1;i<s.length();i++)
{
// System.out.println(hp+" "+s.charAt(i));
if(hp.contains(s.charAt(i)))
{
// System.out.println(i);
// System.out.println(hp);
// System.out.println(s.charAt(i));
return false;
}
if(s.charAt(i)!=ch)
{
hp.add(ch);
ch=s.charAt(i);
}
}
return true;
}
public static int check_end(String[] arr,boolean[] st,char ch)
{
for(int i=0;i<arr.length;i++)
{
if(ch==arr[i].charAt(0) && !st[i] && ch==arr[i].charAt(arr[i].length()-1))
return i;
}
for(int i=0;i<arr.length;i++)
{
if(ch==arr[i].charAt(0) && !st[i])
return i;
}
return -1;
}
public static int check_start(String[] arr,boolean[] st,char ch)
{
for(int i=0;i<arr.length;i++)
{
// if(ch=='B')
// {
// if(!st[i])
// System.out.println(arr[i]+" hello");
// }
if(ch==arr[i].charAt(arr[i].length()-1) && !st[i] && ch==arr[i].charAt(0))
return i;
}
for(int i=0;i<arr.length;i++)
{
// if(ch=='B')
// {
// if(!st[i])
// System.out.println(arr[i]+" hello");
// }
if(ch==arr[i].charAt(arr[i].length()-1) && !st[i])
return i;
}
return -1;
}
public static boolean palin(int N)
{
String s="";
while(N>0)
{
s+=N%10;
N/=10;
}
int l=0,r=s.length()-1;
while(l<=r)
{
if(s.charAt(l)!=s.charAt(r))
return false;
++l;
--r;
}
return true;
}
public static boolean check(long org_s,long org_d,long org_n,long check_ele)
{
if(check_ele<org_s)
return false;
if((check_ele-org_s)%org_d!=0)
return false;
long num=(check_ele-org_s)/org_d;
// if(check_ele==5)
// System.out.println(num+" "+org_n);
return num+1<=org_n;
}
public static long check(long c,long c_diff,long mod,long b_start,long c_start, long c_end,long b_end,long b_diff)
{
// System.out.println(c);
long max=Math.max(c,b_diff);
long min=Math.min(c,b_diff);
long lcm=(max/gcd(max,min))*min;
// System.out.println(lcm);
// System.out.println(c);
// System.out.println(c_diff);
// if(b_diff>c)
// {
long start_point=c_diff/c-c_diff/lcm;
// System.out.println(start_point);
// }
// else
// {
// start_point=c_diff/b_diff-c_diff/c;
// }
// System.out.println(c+" "+start_point);
return (start_point%mod*start_point%mod)%mod;
}
public static boolean check_bounds(int x,int y,int[][] arr,int N,int M)
{
return x>=0 && x<N && y>=0 && y<M && (arr[x][y]==1 || arr[x][y]==9);
}
static boolean found=false;
public static void check(int x,int y,int[][] arr,boolean status[][])
{
if(arr[x][y]==9)
{
found=true;
return;
}
status[x][y]=true;
if(check_bounds(x-1,y,arr,arr.length,arr[0].length)&& !status[x-1][y])
check(x-1,y,arr,status);
if(check_bounds(x+1,y,arr,arr.length,arr[0].length)&& !status[x+1][y])
check(x+1,y,arr,status);
if(check_bounds(x,y-1,arr,arr.length,arr[0].length)&& !status[x][y-1])
check(x,y-1,arr,status);
if(check_bounds(x,y+1,arr,arr.length,arr[0].length)&& !status[x][y+1])
check(x,y+1,arr,status);
}
public static int check(String s1,String s2,int M)
{
int ans=0;
for(int i=0;i<M;i++)
{
ans+=Math.abs(s1.charAt(i)-s2.charAt(i));
}
return ans;
}
public static int check(int[][] arr,int dir1,int dir2,int x1,int y1)
{
int sum=0,N=arr.length,M=arr[0].length;
int x=x1+dir1,y=y1+dir2;
while(x<N && x>=0 && y<M && y>=0)
{
sum+=arr[x][y];
x=x+dir1;
y+=dir2;
}
return sum;
}
public static int check(long[] pref,long X,int N)
{
if(X>pref[N-1])
return -1;
// System.out.println(pref[0]);
if(X<=pref[0])
return 1;
int l=0,r=N-1;
while(l<=r)
{
int mid=(l+r)/2;
if(pref[mid]>=X)
{
if(mid-1>=0 && pref[mid-1]<X)
return mid+1;
else
r=mid-1;
}
else
l=mid+1;
}
return -1;
}
public static div dfs(ArrayList<ArrayList<Integer>> arr,int x,int parent,char[] c)
{
int w=0,b=0;
for(int i:arr.get(x))
{
if(i!=parent)
{
div temp=dfs(arr,i,x,c);
w+=temp.x;
b+=temp.y;
}
}
if(c[x]=='W')
w+=1;
else
b+=1;
if(w==b)
++ans;
return new div(w,b);
}
private static long mergeAndCount(int[] arr, int l,
int m, int r)
{
// Left subarray
int[] left = Arrays.copyOfRange(arr, l, m + 1);
// Right subarray
int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);
int i = 0, j = 0, k = l;long swaps = 0;
while (i < left.length && j < right.length) {
if (left[i] < right[j])
arr[k++] = left[i++];
else {
arr[k++] = right[j++];
swaps += (m + 1) - (l + i);
}
}
while (i < left.length)
arr[k++] = left[i++];
while (j < right.length)
arr[k++] = right[j++];
return swaps;
}
// Merge sort function
private static long mergeSortAndCount(int[] arr, int l,
int r)
{
// Keeps track of the inversion count at a
// particular node of the recursion tree
long count = 0;
if (l < r) {
int m = (l + r) / 2;
// Total inversion count = left subarray count
// + right subarray count + merge count
// Left subarray count
count += mergeSortAndCount(arr, l, m);
// Right subarray count
count += mergeSortAndCount(arr, m + 1, r);
// Merge count
count += mergeAndCount(arr, l, m, r);
}
return count;
}
public static void main(String[] args) throws IOException {
Reader.init(System.in);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int T=Reader.nextInt();
A:for(int m=1;m<=T;m++)
{
int N=Reader.nextInt();
int M=Reader.nextInt();
String s=Reader.next();
ArrayList<Integer> arr=new ArrayList<>();
int[] rem=new int[N*M];
int[] row=new int[N*M+1];
for(int i=0;i<N*M;i++)
{
if(s.charAt(i)=='1')
{
arr.add(i);
rem[i]=i%M;
}
}
for(int i=0;i<arr.size()-1;i++)
{
if(arr.get(i+1)-arr.get(i)>=M)
continue;
int j=arr.get(i+1);
int add=j-arr.get(i);
int fin=M-add%M+j;
// System.out.println(j);
while(j<N*M)
{
// System.out.println(j+" "+fin);
row[j]--;
if(fin<=N*M)
row[fin]++;
j+=M;
fin+=M;
}
}
for(int i=1;i<=N*M;i++)
row[i]+=row[i-1];
// for(int i=0;i<N*M;i++)
// output.write(row[i]+" ");
// output.write("\n");
HashSet<Integer> hp=new HashSet<>();
int cnt=0;
for(int i=0;i<N*M;i++)
{
// if(s.charAt(i)=='0')
// continue;
if(s.charAt(i)=='1')
++cnt;
// if(hp.contains(rem[i]))
// {
// output.write(cnt+row[i]+" ");
//
// }
// else
// {
if(s.charAt(i)=='1')
hp.add(rem[i]);
output.write(cnt+row[i]+hp.size()+" ");
// }
// output.write(cnt);
}
output.write("\n");
}
output.flush();
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
left=null;
right=null;
this.data=data;
}
}
class div {
int x;
int y;
div(int x,int y) {
this.x=x;
this.y=y;
}
}
| Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | 855afa5efdba966117df011d625f8a5d | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import static java.lang.Math.*;
import static java.lang.System.*;
import java.util.*;
public class Main {
static public void main(String[] args){
Read in = new Read(System.in);
int t =in.nextInt();
while(t>0){
t--;
solve(in);
}
}
static void solve(Read in){
int n=in.nextInt(),m=in.nextInt();
String s= in.next();
char[] c = s.toCharArray();
int [] arr = new int [m];
int d = -1;
int cot = 0 ;
boolean [] f = new boolean[m];
int k=0;
StringBuffer an = new StringBuffer();
for(int i=0;i<c.length;i++){
if(d<0){
if(c[i]-'0'!=1){
an.append(0+" ");
continue;
}
d = i;
}
if(c[i]-'0'==1){
cot=0;
if(!f[i%m]){
f[i%m]=true;
k++;
}
}
else{
cot++;
if(cot>=m){
arr[i%m]++;
}
}
//out.println(i+ " "+d);
//out.println((i-d)%m+1 - arr[i%m]+ " "+k);
an.append(((i-d)/m+1 - arr[i%m]+k)+" ");
}
out.println(an.toString());
}
void shuffleArray(long[] arr){
int n = arr.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
static class Read {//自定义快读 Read
public BufferedReader reader;
public StringTokenizer tokenizer;
public Read(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String str = null;
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long gcd(long a, long b) {
return (a % b == 0) ? b : gcd(b, a % b);
}
} | Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | 1a3eacd9b45639cce040f9d5d40b21dc | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
static IOHandler in = new IOHandler();
public static void main(String[] args) {
// TODO Auto-generated method stub
int testCases = in.nextInt();
for (int i = 1; i <= testCases; ++i) {
solve(i);
}
}
private static void solve(int t) {
int m = in.nextInt();
int n = in.nextInt();
String s = in.next();
int [] rowVals = new int [s.length()];
int [] colVals = new int [s.length()];
int [] cols = new int [n];
int r = 0;
int val;
int sum = 0;
int lastOne = -1;
for (int i = 0; i < n; ++i) {
val = s.charAt(i) - '0';
if (val == 1) {
r = 1;
lastOne = i;
}
rowVals[i] = r;
sum += val;
colVals[i] = sum;
cols[i] = val;
}
int idx;
for (int i = n; i < s.length(); ++i) {
val = s.charAt(i) - '0';
if (val == 1) {
r = 1;
lastOne = i;
}
rowVals[i] = rowVals[i - n];
if (i - lastOne < n) {
++rowVals[i];
}
colVals[i] = colVals[i - 1];
idx = i % n;
if (cols[idx] == 0 && val == 1) {
cols[idx] = 1;
++colVals[i];
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ++i) {
val = rowVals[i] + colVals[i];
sb.append(val);
sb.append(' ');
}
System.out.println(sb);
}
private static class IOHandler {
BufferedReader br;
StringTokenizer st;
public IOHandler() {
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\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | a644fe2ba98537e8ceeafecc0305523c | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | //Utilities
import java.io.*;
import java.util.*;
public class b {
static int t;
static int n, m;
static char[] ch;
static int[] add, sub, cnt;
static int pr, pc;
static int colCnt, rowCnt = 0;
static boolean[] bc;
public static void main(String[] args) throws IOException {
t = in.iscan();
while (t-- > 0) {
n = in.iscan(); m = in.iscan();
ch = in.sscan().toCharArray();
bc = new boolean[m]; add = new int[m]; sub = new int[m]; cnt = new int[m];
pr = -1; pc = -1;
rowCnt = 0; colCnt = 0;
for (int d = 0; d < n*m; d++) {
if (pr != -1 && pc != -1) {
pc++;
if (pc == m) {
pc = 0;
pr++;
}
}
char cur = ch[d];
if (cur == '1') {
if (pr == -1 && pc == -1) {
add[d%m]++;
cnt[d%m]++;
}
else {
if (pr >= 1) {
add[d%m]++;
cnt[d%m]++;
}
else {
int leftover = m - pc;
add[(d+leftover)%m]++;
cnt[d%m]++;
}
}
if (!bc[d % m]) {
bc[d % m] = true;
colCnt++;
}
pr = 0; pc = 0;
}
rowCnt += add[d%m]; rowCnt -= sub[d%m];
sub[d%m] += cnt[d%m]; cnt[d%m] = 0;
out.print((rowCnt + colCnt) + " ");
}
out.println();
}
out.close();
}
static INPUT in = new INPUT(System.in);
static PrintWriter out = new PrintWriter(System.out);
private static class INPUT {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public INPUT (InputStream stream) {
this.stream = stream;
}
public INPUT (String file) throws IOException {
this.stream = new FileInputStream (file);
}
public int cscan () throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read (buf);
}
if (numChars == -1)
return numChars;
return buf[curChar++];
}
public int iscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
int res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public String sscan () throws IOException {
int c = cscan ();
while (space (c))
c = cscan ();
StringBuilder res = new StringBuilder ();
do {
res.appendCodePoint (c);
c = cscan ();
}
while (!space (c));
return res.toString ();
}
public double dscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
double res = 0;
while (!space (c) && c != '.') {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
res *= 10;
res += c - '0';
c = cscan ();
}
if (c == '.') {
c = cscan ();
double m = 1;
while (!space (c)) {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
m /= 10;
res += (c - '0') * m;
c = cscan ();
}
}
return res * sgn;
}
public long lscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
long res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public boolean space (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static class UTILITIES {
static final double EPS = 10e-6;
public static void sort(int[] a, boolean increasing) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(long[] a, boolean increasing) {
ArrayList<Long> arr = new ArrayList<Long>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(double[] a, boolean increasing) {
ArrayList<Double> arr = new ArrayList<Double>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static int lower_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static void updateMap(HashMap<Integer, Integer> map, int key, int v) {
if (!map.containsKey(key)) {
map.put(key, v);
}
else {
map.put(key, map.get(key) + v);
}
if (map.get(key) == 0) {
map.remove(key);
}
}
public static long gcd (long a, long b) {
return b == 0 ? a : gcd (b, a % b);
}
public static long lcm (long a, long b) {
return a * b / gcd (a, b);
}
public static long fast_pow_mod (long b, long x, int mod) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;
return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
}
public static int fast_pow (int b, int x) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow (b * b, x / 2);
return b * fast_pow (b * b, x / 2);
}
public static long choose (long n, long k) {
k = Math.min (k, n - k);
long val = 1;
for (int i = 0; i < k; ++i)
val = val * (n - i) / (i + 1);
return val;
}
public static long permute (int n, int k) {
if (n < k) return 0;
long val = 1;
for (int i = 0; i < k; ++i)
val = (val * (n - i));
return val;
}
// start of permutation and lower/upper bound template
public static void nextPermutation(int[] nums) {
//find first decreasing digit
int mark = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
mark = i - 1;
break;
}
}
if (mark == -1) {
reverse(nums, 0, nums.length - 1);
return;
}
int idx = nums.length-1;
for (int i = nums.length-1; i >= mark+1; i--) {
if (nums[i] > nums[mark]) {
idx = i;
break;
}
}
swap(nums, mark, idx);
reverse(nums, mark + 1, nums.length - 1);
}
public static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void reverse(int[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
static int lower_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= cmp) high = mid;
else low = mid + 1;
}
return low;
}
static int upper_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > cmp) high = mid;
else low = mid + 1;
}
return low;
}
// end of permutation and lower/upper bound template
}
}
| Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | 3e09bbbcd37c0fe4cfeb526b9910f89b | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | // JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.*;
import java.lang.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.io.*;
public class CodeForces {
static private final String INPUT = "input.txt";
static private final String OUTPUT = "output.txt";
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(System.out);
static DecimalFormat df = new DecimalFormat("0.00000");
final static int MAX = Integer.MAX_VALUE, MIN = Integer.MIN_VALUE, mod = (int) (1e9 + 7);
final static long LMAX = Long.MAX_VALUE, LMIN = Long.MIN_VALUE;
final static long INF = (long) 1e18, Neg_INF = (long) -1e18;
static Random rand = new Random();
// ======================= MAIN ==================================
public static void main(String[] args) throws IOException {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
// ==== start ====
input();
preprocess();
int t = 1;
t = readInt();
while (t-- > 0) {
solve();
}
out.flush();
// ==== end ====
if (!oj)
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
private static void solve() throws IOException {
int n = readInt(), m = readInt(), prev = -1, count = 0;
char[] s = readCharArray();
int[] rows = new int[m], cols = new int[m];
for (int i = 0; i < n * m; i++) {
if (s[i] == '1') {
prev = i;
if (cols[i % m] == 0) {
cols[i % m]++;
count++;
}
}
if (prev != -1 && i - prev < m)
rows[i % m]++;
out.print((rows[i % m] + count) + " ");
}
out.println();
}
private static void preprocess() throws IOException {
}
// cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces
// javac CodeForces.java
// java CodeForces
// javac CodeForces.java && java CodeForces
// change Stack size -> java -Xss16M CodeForces.java
// ==================== CUSTOM CLASSES ================================
static class Pair implements Comparable<Pair> {
int first, second;
Pair(int f, int s) {
first = f;
second = s;
}
public int compareTo(Pair o) {
if (this.first == o.first)
return this.second - o.second;
return this.first - o.first;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
Pair other = (Pair) (obj);
if (this.first != other.first)
return false;
if (this.second != other.second)
return false;
return true;
}
@Override
public int hashCode() {
return this.first ^ this.second;
}
@Override
public String toString() {
return this.first + " " + this.second;
}
}
static class DequeNode {
DequeNode prev, next;
int val;
DequeNode(int val) {
this.val = val;
}
DequeNode(int val, DequeNode prev, DequeNode next) {
this.val = val;
this.prev = prev;
this.next = next;
}
}
// ======================= FOR INPUT ==================================
private static void input() {
FileInputStream instream = null;
PrintStream outstream = null;
try {
instream = new FileInputStream(INPUT);
outstream = new PrintStream(new FileOutputStream(OUTPUT));
System.setIn(instream);
System.setOut(outstream);
} catch (Exception e) {
System.err.println("Error Occurred.");
}
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(readLine());
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 readString() throws IOException {
return next();
}
static String readLine() throws IOException {
return br.readLine().trim();
}
static int[] readIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = readInt();
return arr;
}
static int[][] read2DIntArray(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
arr[i] = readIntArray(m);
return arr;
}
static List<Integer> readIntList(int n) throws IOException {
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(readInt());
return list;
}
static long[] readLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = readLong();
return arr;
}
static long[][] read2DLongArray(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
arr[i] = readLongArray(m);
return arr;
}
static List<Long> readLongList(int n) throws IOException {
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(readLong());
return list;
}
static char[] readCharArray() throws IOException {
return readString().toCharArray();
}
static char[][] readMatrix(int n, int m) throws IOException {
char[][] mat = new char[n][m];
for (int i = 0; i < n; i++)
mat[i] = readCharArray();
return mat;
}
// ========================= FOR OUTPUT ==================================
private static void printIList(List<Integer> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printLList(List<Long> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printIArray(int[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DIArray(int[][] arr) {
for (int i = 0; i < arr.length; i++)
printIArray(arr[i]);
}
private static void printLArray(long[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DLArray(long[][] arr) {
for (int i = 0; i < arr.length; i++)
printLArray(arr[i]);
}
private static void yes() {
out.println("YES");
}
private static void no() {
out.println("NO");
}
// ====================== TO CHECK IF STRING IS NUMBER ========================
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static boolean isLong(String s) {
try {
Long.parseLong(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
// ==================== FASTER SORT ================================
private static void sort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void sort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
// ==================== MATHEMATICAL FUNCTIONS ===========================
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static int mod_pow(long a, long b, int mod) {
if (b == 0)
return 1;
int temp = mod_pow(a, b >> 1, mod);
temp %= mod;
temp = (int) ((1L * temp * temp) % mod);
if ((b & 1) == 1)
temp = (int) ((1L * temp * a) % mod);
return temp;
}
private static int multiply(int a, int b) {
return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod);
}
private static int divide(int a, int b) {
return multiply(a, mod_pow(b, mod - 2, mod));
}
private static boolean isPrime(long n) {
for (long i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
private static long nCr(long n, long r) {
if (n - r > r)
r = n - r;
long ans = 1L;
for (long i = r + 1; i <= n; i++)
ans *= i;
for (long i = 2; i <= n - r; i++)
ans /= i;
return ans;
}
private static List<Integer> factors(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 1; 1L * i * i <= n; i++)
if (n % i == 0) {
list.add(i);
if (i != n / i)
list.add(n / i);
}
return list;
}
private static List<Long> factors(long n) {
List<Long> list = new ArrayList<>();
for (long i = 1; i * i <= n; i++)
if (n % i == 0) {
list.add(i);
if (i != n / i)
list.add(n / i);
}
return list;
}
// ==================== Primes using Seive =====================
private static List<Integer> getPrimes(int n) {
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, true);
for (int i = 2; 1L * i * i <= n; i++)
if (prime[i])
for (int j = i * i; j <= n; j += i)
prime[j] = false;
// return prime;
List<Integer> list = new ArrayList<>();
for (int i = 2; i <= n; i++)
if (prime[i])
list.add(i);
return list;
}
private static int[] SeivePrime(int n) {
int[] primes = new int[n];
for (int i = 0; i < n; i++)
primes[i] = i;
for (int i = 2; 1L * i * i < n; i++) {
if (primes[i] != i)
continue;
for (int j = i * i; j < n; j += i)
if (primes[j] == j)
primes[j] = i;
}
return primes;
}
// ==================== STRING FUNCTIONS ================================
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
// check if a is subsequence of b
private static boolean isSubsequence(String a, String b) {
int idx = 0;
for (int i = 0; i < b.length() && idx < a.length(); i++)
if (a.charAt(idx) == b.charAt(i))
idx++;
return idx == a.length();
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
private static String sortString(String str) {
int[] arr = new int[256];
for (char ch : str.toCharArray())
arr[ch]++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; i++)
while (arr[i]-- > 0)
sb.append((char) i);
return sb.toString();
}
// ==================== LIS & LNDS ================================
private static int LIS(int arr[], int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find1(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find1(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) >= val) {
ret = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ret;
}
private static int LNDS(int[] arr, int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find2(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find2(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) <= val) {
i = mid + 1;
} else {
ret = mid;
j = mid - 1;
}
}
return ret;
}
// =============== Lower Bound & Upper Bound ===========
// less than or equal
private static int lower_bound(List<Integer> list, int val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(List<Long> list, long val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(int[] arr, int val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(long[] arr, long val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
// greater than or equal
private static int upper_bound(List<Integer> list, int val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(List<Long> list, long val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(int[] arr, int val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(long[] arr, long val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
// ==================== UNION FIND =====================
private static int find(int x, int[] parent) {
if (parent[x] == x)
return x;
return parent[x] = find(parent[x], parent);
}
private static boolean union(int x, int y, int[] parent, int[] rank) {
int lx = find(x, parent), ly = find(y, parent);
if (lx == ly)
return false;
if (rank[lx] > rank[ly])
parent[ly] = lx;
else if (rank[lx] < rank[ly])
parent[lx] = ly;
else {
parent[lx] = ly;
rank[ly]++;
}
return true;
}
// ==================== TRIE ================================
static class Trie {
class Node {
Node[] children;
boolean isEnd;
Node() {
children = new Node[26];
}
}
Node root;
Trie() {
root = new Node();
}
void insert(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
curr.children[ch - 'a'] = new Node();
curr = curr.children[ch - 'a'];
}
curr.isEnd = true;
}
boolean find(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
return false;
curr = curr.children[ch - 'a'];
}
return curr.isEnd;
}
}
// ================== SEGMENT TREE (RANGE SUM & RANGE UPDATE) ==================
public static class SegmentTree {
int n;
long[] arr, tree, lazy;
SegmentTree(long arr[]) {
this.arr = arr;
this.n = arr.length;
this.tree = new long[(n << 2)];
this.lazy = new long[(n << 2)];
build(1, 0, n - 1);
}
void build(int id, int start, int end) {
if (start == end)
tree[id] = arr[start];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
build(left, start, mid);
build(right, mid + 1, end);
tree[id] = tree[left] + tree[right];
}
}
void update(int l, int r, long val) {
update(1, 0, n - 1, l, r, val);
}
void update(int id, int start, int end, int l, int r, long val) {
distribute(id, start, end);
if (end < l || r < start)
return;
if (start == end)
tree[id] += val;
else if (l <= start && end <= r) {
lazy[id] += val;
distribute(id, start, end);
} else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
update(left, start, mid, l, r, val);
update(right, mid + 1, end, l, r, val);
tree[id] = tree[left] + tree[right];
}
}
long query(int l, int r) {
return query(1, 0, n - 1, l, r);
}
long query(int id, int start, int end, int l, int r) {
if (end < l || r < start)
return 0L;
distribute(id, start, end);
if (start == end)
return tree[id];
else if (l <= start && end <= r)
return tree[id];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r);
}
}
void distribute(int id, int start, int end) {
if (start == end)
tree[id] += lazy[id];
else {
tree[id] += lazy[id] * (end - start + 1);
lazy[(id << 1)] += lazy[id];
lazy[(id << 1) + 1] += lazy[id];
}
lazy[id] = 0;
}
}
// ==================== FENWICK TREE ================================
static class FT {
int n;
int[] arr;
int[] tree;
FT(int[] arr, int n) {
this.arr = arr;
this.n = n;
this.tree = new int[n + 1];
for (int i = 1; i <= n; i++) {
update(i, arr[i - 1]);
}
}
FT(int n) {
this.n = n;
this.tree = new int[n + 1];
}
// 1 based indexing
void update(int idx, int val) {
while (idx <= n) {
tree[idx] += val;
idx += idx & -idx;
}
}
// 1 based indexing
long query(int l, int r) {
return getSum(r) - getSum(l - 1);
}
long getSum(int idx) {
long ans = 0L;
while (idx > 0) {
ans += tree[idx];
idx -= idx & -idx;
}
return ans;
}
}
// ==================== BINARY INDEX TREE ================================
static class BIT {
long[][] tree;
int n, m;
BIT(int[][] mat, int n, int m) {
this.n = n;
this.m = m;
tree = new long[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
update(i, j, mat[i - 1][j - 1]);
}
}
}
void update(int x, int y, int val) {
while (x <= n) {
int t = y;
while (t <= m) {
tree[x][t] += val;
t += t & -t;
}
x += x & -x;
}
}
long query(int x1, int y1, int x2, int y2) {
return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1);
}
long getSum(int x, int y) {
long ans = 0L;
while (x > 0) {
int t = y;
while (t > 0) {
ans += tree[x][t];
t -= t & -t;
}
x -= x & -x;
}
return ans;
}
}
} | Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | 0b6bed60cf53e7563519df31519c8e67 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes |
import java.util.*;
import java.io.*;
// you can compare with output.txt and expected out
public class Round789D {
MyPrintWriter out;
MyScanner in;
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void preferFileIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
Round789D sol = new Round789D();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
preferFileIO(isFileIO);
int t = in.nextInt();
for (int i = 1; i <= t; ++i) {
int n = in.nextInt();
int m = in.nextInt();
String s = in.next();
if(isDebug){
out.printf("Test %d\n", i);
}
int[] ans = solve(s, n, m);
out.println(ans);
if(isDebug)
out.flush();
}
in.close();
out.close();
}
private int[] solve(String s, int n, int m) {
int[] ans = new int[n*m];
boolean[] ss = new boolean[n*m];
for(int i=0; i<n*m; i++)
ss[i] = s.charAt(i)=='1';
// firstRow[i] = sum of [0..i]
boolean[] firstRow = new boolean[m];
// rowSum[i] = sum of [i+1..i+m], [i+m+1..i+2m], ... until curr
int[] rowSum = new int[m];
int[] prefix = new int[n*m];
prefix[0] = ss[0]? 1:0;
for(int i=1; i<n*m; i++)
prefix[i] = prefix[i-1] + (ss[i]? 1:0);
boolean[] column = new boolean[m];
// columnSum = sum of column[0], ..., column[m];
int columnSum = 0;
firstRow[0] = ss[0];
column[0] = ss[0];
columnSum = column[0]? 1:0;
ans[0] = firstRow[0]? 1:0;
ans[0] += columnSum;
for(int i=1; i<m; i++) {
firstRow[i] = firstRow[i-1] || ss[i];
column[i] = ss[i];
columnSum += column[i]? 1:0;
ans[i] = firstRow[i]? 1:0;
ans[i] += columnSum;
}
for(int j=1; j<n; j++) {
for(int i=0; i<m; i++) {
int curr=j*m+i;
if(!column[i] && ss[curr]) {
column[i] = true;
columnSum++;
}
ans[curr] = columnSum;
rowSum[i] += prefix[curr]-prefix[curr-m]>0? 1:0;
ans[curr] += rowSum[i];
ans[curr] += firstRow[i]? 1:0;
}
}
return ans;
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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[][] nextGraphEdges(){
return nextGraphEdges(0);
}
int[][] nextGraphEdges(int offset) {
int m = nextInt();
int[][] e = new int[m][2];
for(int i=0; i<m; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
public void print(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void println(long[] arr){
print(arr);
println();
}
public void print(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void println(int[] arr){
print(arr);
println();
}
public <T> void print(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void println(ArrayList<T> arr){
print(arr);
println();
}
public void println(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void println(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
int[] idx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][idx[u]++] = v;
neighbors[v][idx[v]++] = u;
}
return neighbors;
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | 804fc222f7b761d7d4484cbfc5fca1ce | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.cert.X509CRL;
import java.util.*;
import java.lang.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static String OUTPUT = "";
//global
private final static long BASE = 998244353L;
private final static int INF_I = 1001001001;
private final static long INF_L = 1001001001001001001L;
private final static int MAXN = 100100;
private static int decode(int a, int b) {
return a + 2*b;
}
static void solve() {
int ntest = readInt();
for (int test=0;test<ntest;test++) {
int N = readInt(), M = readInt();
char[] S = readString().toCharArray();
int[] row = new int[M];
int[] col = new int[M];
int col1=0,last=-INF_I;
for (int i=0;i<N*M;i++) {
int Si = (int)S[i] - (int)('0');
if (Si==1) {
col1 += (1-col[i%M]);
col[i%M] = 1;
last=i;
}
if (i-last<M) row[i%M]+=1;
out.print((row[i%M]+col1) + " ");
}
out.println();
}
}
public static void main(String[] args) throws Exception
{
long S = System.currentTimeMillis();
if (INPUT=="") {
is = System.in;
} else {
File file = new File(INPUT);
is = new FileInputStream(file);
}
if (OUTPUT == "") out = new PrintWriter(System.out);
else out = new PrintWriter(OUTPUT);
solve();
out.flush();
long G = System.currentTimeMillis();
}
private static class Point<T extends Number & Comparable<T>> implements Comparable<Point<T>> {
private T x;
private T y;
public Point(T x, T y) {
this.x = x;
this.y = y;
}
public T getX() {return x;}
public T getY() {return y;}
@Override
public int compareTo(Point<T> o) {
int cmp = x.compareTo(o.getX());
if (cmp==0) return y.compareTo(o.getY());
return cmp;
}
}
private static class ClassComparator<T extends Comparable<T>> implements Comparator<T> {
public ClassComparator() {}
@Override
public int compare(T a, T b) {
return a.compareTo(b);
}
}
private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> {
public ListComparator() {}
@Override
public int compare(List<T> o1, List<T> o2) {
for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {
int c = o1.get(i).compareTo(o2.get(i));
if (c != 0) {
return c;
}
}
return Integer.compare(o1.size(), o2.size());
}
}
private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
try {
is.mark(1000);
while(true){
int b = is.read();
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
// private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double readDouble() { return Double.parseDouble(readString()); }
private static char readChar() { return (char)skip(); }
private static String readString()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] readChar(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] readTable(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = readChar(m);
return map;
}
private static int[] readIntArray(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = readInt();
return a;
}
private static long[] readLongArray(int n) {
long[] a = new long[n];
for (int i=0;i<n;i++) a[i] = readLong();
return a;
}
private static int readInt()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static long readLong()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | 02d81e62d0dd95e5019203f19beb3c42 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Meeting {
public static void main(String[] args) throws IOException {
// BufferedReader in = new BufferedReader(new FileReader("Meeting.in"));
// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Meeting.out")));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int T = Integer.parseInt(in.readLine());
for (int t = 0; t < T; t++) {
StringTokenizer st = new StringTokenizer(in.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
String s = in.readLine();
int[] numRows = new int[N * M];
boolean[] firstRow = new boolean[M];
boolean[] column = new boolean[M];
int totInFirstRow = 0;
int totColumns = 0;
for (int i = 0; i < N * M; i++) {
boolean one = s.charAt(i) == '1';
if (one) {
totInFirstRow += !firstRow[i % M] ? 1 : 0;
totColumns += !column[i % M] ? 1 : 0;
} else {
totInFirstRow -= firstRow[i % M] ? 1 : 0;
}
column[i % M] |= one;
firstRow[i % M] = one;
numRows[i] = (i >= M ? numRows[i - M] : 0) + (totInFirstRow > 0 ? 1 : 0);
out.print((numRows[i] + totColumns) + " ");
}
out.println();
}
out.close();
in.close();
}
} | Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | e57df20e21711a8fdbe8a6ebccb733b1 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Scanner;
public class D {
static int[] primes = new int[] {2, 3, 7, 11, 13, 17, 19, 23, 29};
static long p = 2 * 3 * 7 * 11 * 13 * 17 * 19 * 23 * 29;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
PrintWriter out = new PrintWriter(System.out);
for(int tt = 0; tt < t; tt++) {
int n = sc.nextInt();
int m = sc.nextInt();
int k = n * m;
char[] studs = new char[k];
String s = sc.next();
for(int i = 0; i <k; i++) {
studs[i] = s.charAt(i);
}
int[] cols = new int[m];
int[] tot = new int[k];
if(studs[0] == '1') {
tot[0] = 1;
cols[0] = 1;
}
for(int i = 1; i < k; i++) {
tot[i] = tot[i - 1];
if(studs[i] == '1') {
if(cols[i%m] == 0) {
cols[i%m] = 1;
tot[i]++;
}
}
}
cols = new int[m];
int run = k-1;
for(int i = 0; i <k; i++) {
if(studs[i] == '0') {
run++;
if(run >= m)
cols[i%m]++;
}
else {
run = 0;
}
tot[i] += (i + m)/m - cols[i%m];
}
for(int i = 0; i < k; i++) {
out.print(tot[i] + " ");
}
out.println();
}
out.flush();
}
static int crt(int p1, int p2, int r1, int r2) {
int out = r1;
while(out % p2 != r2) {
out += p1;
}
return out;
}
}
| Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | fefad67699556fe16db65d6042c727a9 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
void go() {
int m = Reader.nextInt();
int n = Reader.nextInt();
String s = Reader.next();
boolean[] col = new boolean[n];
Queue<Integer> row = new ArrayDeque<>();
int[] dp = new int[m * n];
int cntRow = 0;
int cntCol = 0;
for(int i = 0; i < m * n; i++) {
int c = s.charAt(i) - '0';
if(c == 1 && !col[i % n]) {
col[i % n] = true;
cntCol++;
}
row.offer(c);
if(c == 1) {
cntRow++;
}
if(row.size() > n) {
cntRow -= row.poll();
}
if(i > n - 1) {
dp[i] = dp[i - n] + (cntRow > 0 ? 1 : 0);
} else {
dp[i] = cntRow > 0 ? 1 : 0;
}
if(i == m * n - 1) {
Writer.print(cntCol + dp[i] + "\n");
} else {
Writer.print(cntCol + dp[i] + " ");
}
}
}
void solve() {
for(int T = Reader.nextInt(); T > 0; T--) go();
}
void run() throws Exception {
Reader.init(System.in);
Writer.init(System.out);
solve();
Writer.close();
}
public static void main(String[] args) throws Exception {
new D().run();
}
public static class Reader {
public static StringTokenizer st;
public static BufferedReader br;
public static void init(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public static String next() {
while(!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new InputMismatchException();
}
}
return st.nextToken();
}
public static int nextInt() {
return Integer.parseInt(next());
}
public static long nextLong() {
return Long.parseLong(next());
}
public static double nextDouble() {
return Double.parseDouble(next());
}
}
public static class Writer {
public static PrintWriter pw;
public static void init(OutputStream os) {
pw = new PrintWriter(new BufferedOutputStream(os));
}
public static void print(String s) {
pw.print(s);
}
public static void print(char c) {
pw.print(c);
}
public static void print(int x) {
pw.print(x);
}
public static void print(long x) {
pw.print(x);
}
public static void println(String s) {
pw.println(s);
}
public static void println(char c) {
pw.println(c);
}
public static void println(int x) {
pw.println(x);
}
public static void flush() {
pw.flush();
}
public static void println(long x) {
pw.println(x);
}
public static void close() {
pw.close();
}
}
} | Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | fe7b32602d8fdbe022e21c2a3d4b52c6 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class G {
static FastScanner fs = new FastScanner();
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder("");
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
int t = fs.nextInt();
//int t = 1;
for (int tt = 0; tt < t; tt++) {
int n = fs.nextInt();
int m = fs.nextInt();
char[] s = fs.next().toCharArray();
boolean[] row = new boolean[m];
int[] ans = new int[n*m];
int[] sum = new int[n*m+1];
for (int i = 0; i < n*m; i++) sum[i+1] = sum[i] + s[i]-'0';
for (int i = 0; i < n*m; i++) {
int x = sum[i+1] - sum[Math.max(0, i+1-m)];
if (i >= m) ans[i] = ans[i-m];
ans[i] += (x > 0) ? 1 : 0;
}
int cRow = 0;
for (int i = 0; i < n*m; i++) {
if (s[i] == '1') {
if (!row[i%m]) {
row[i%m] = true;
cRow++;
}
}
ans[i] += cRow;
}
for (int i = 0; i < n*m; i++) sb.append(ans[i] + " ");
sb.append("\n");
}
pw.print(sb.toString());
pw.close();
}
static void sort(int[] a) {
ArrayList<Integer> al = new ArrayList<>();
for (int i : a)
al.add(i);
Collections.sort(al);
for (int i = 0; i < a.length; i++)
a[i] = al.get(i);
}
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) {}return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) {a[i] = nextInt();} return a;}
}
} | Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | 517e1c0ccaf995079a33e35b6e34ed49 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | // package c1678;
//
// Codeforces Round #789 (Div. 2) 2022-05-08 07:35
// D. Tokitsukaze and Meeting
// https://codeforces.com/contest/1678/problem/D
// time limit per test 1 second; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// Tokitsukaze is arranging a meeting. There are n rows and m columns of seats in the meeting hall.
//
// There are exactly n * m students attending the meeting, including several naughty students and
// several serious students. The students are numerated from 1 to n* m. The students will enter the
// meeting hall in order. When the i-th student enters the meeting hall, he will sit in the 1-st
// column of the 1-st row, and the students who are already seated will move back one seat.
// Specifically, the student sitting in the j-th (1<= j <= m-1) column of the i-th row will move to
// the (j+1)-th column of the i-th row, and the student sitting in m-th column of the i-th row will
// move to the 1-st column of the (i+1)-th row.
//
// For example, there is a meeting hall with 2 rows and 2 columns of seats shown as below:
// https://espresso.codeforces.com/71fbef301db6ce11000b1d81b932ef15edcc4d8c.png
//
// There will be 4 students entering the meeting hall in order, represented as a binary string
// "1100", of which '0' represents naughty students and '1' represents serious students. The changes
// of seats in the meeting hall are as follows:
// https://espresso.codeforces.com/6adf53c6760706e7188b39c11a0473a15cb0ae60.png
//
// Denote a row or a column good if and only if there is at least one serious student in this row or
// column. Please predict the number of good rows and columns just after the i-th student enters the
// meeting hall, for all i.
//
// Input
//
// The first contains a single positive integer t (1 <= t <= 10,000)-- the number of test cases.
//
// For each test case, the first line contains two integers n, m (1 <= n,m <= 10^6; 1 <= n * m <=
// 10^6), denoting there are n rows and m columns of seats in the meeting hall.
//
// The second line contains a binary string s of length n * m, consisting only of zeros and ones. If
// s_i equal to '0' represents the i-th student is a naughty student, and s_i equal to '1'
// represents the i-th student is a serious student.
//
// It is guaranteed that the sum of n * m over all test cases does not exceed 10^6.
//
// Output
//
// For each test case, print a single line with n * m integers-- the number of good rows and columns
// just after the i-th student enters the meeting hall.
//
// Example
/*
input:
3
2 2
1100
4 2
11001101
2 4
11001101
output:
2 3 4 3
2 3 4 3 5 4 6 5
2 3 3 3 4 4 4 5
*/
// Note
//
// The first teat case is shown in the statement.
//
// After the 1-st student enters the meeting hall, there are 2 good rows and columns: the 1-st row
// and the 1-st column.
//
// After the 2-nd student enters the meeting hall, there are 3 good rows and columns: the 1-st row,
// the 1-st column and the 2-nd column.
//
// After the 3-rd student enters the meeting hall, the 4 rows and columns are all good.
//
// After the 4-th student enters the meeting hall, there are 3 good rows and columns: the 2-nd row,
// the 1-st column and the 2-nd column.
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1678D {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int[] solve(int n, int m, String s) {
int k = s.length();
myAssert(k == n * m);
int[] ans = new int[k];
// '0' represents a naughty student and '1' represents a serious student
// Denote a row or a column good if and only if there is at least one 1 in this row or column.
// Please predict the number of good rows and columns just after the i-th student enters the meeting hall, for all i.
// 1100 -> 2 3 4 3
// 2 4 11001101
// 1--- 11-- 011- 0011 1001 1100 0110 1011
// ---- ---- ---- ---- 1--- 11-- 011- 0011
// 2 3 3 3 4 4 4 5
// Example of 4x6:
// ........................
// ------______------______
// -----______------______
// ct[r][k] is number of 1 in each row when the front row contains s[0,r]
// * * * * * * cr[2][2]
// * * * * * * cr[2][1]
// * * * . . . cr[2][0]
// . . . . . . cr[2][3]
int[][] ct = new int[m][n];
for (int r = 0; r < m; r++) {
ct[r][0] = (r == 0 ? 0 : ct[r-1][0]) + (s.charAt(r) == '1' ? 1 : 0);
if (r == 0) {
for (int j = 1; j < n; j++) {
int b = r + 1 + (j-1) * m;
for (int h = 0; h < m; h++) {
if (s.charAt(b+h) == '1') {
ct[r][j]++;
}
}
}
} else {
for (int j = 1; j < n; j++) {
// ** ... ****** ****** ******
// *** ... ****** ****** ******
// ^ ^ ^
// r b e
int b = r + (j -1) * m;
int e = b + m;
ct[r][j] = ct[r-1][j] + (s.charAt(e) == '1' ? 1 : 0) - (s.charAt(b) == '1' ? 1 : 0);
}
}
}
int[][] sum = new int[m][n];
for (int r = 0; r < m; r++) {
for (int j = 0; j < n; j++) {
sum[r][j] = (j == 0 ? 0 : sum[r][j-1]) + (ct[r][j] > 0 ? 1 : 0);
}
}
// System.out.println(Utils.trace(ct));
// System.out.println(Utils.trace(sum));
int[] cols = new int[m];
int cur = m - 1;
int colsum = 0;
for (int i = 0; i < k; i++) {
if (s.charAt(i) == '1') {
cols[cur]++;
if (cols[cur] == 1) {
colsum++;
}
}
cur = (cur + m - 1) % m;
int r = i % m;
int j = i / m;
ans[i] = colsum + sum[r][j];
}
return ans;
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int m = in.nextInt();
String s = in.next();
int[] ans = solve(n, m, s);
output(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | 43907de381d390f14e8a791beed6e21c | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF1678D extends PrintWriter {
CF1678D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1678D o = new CF1678D(); o.main(); o.flush();
}
void main() {
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
byte[] cc = sc.next().getBytes();
int[] dp = new int[n * m];
for (int k = 0, h = 0; h < n * m; h++) {
k += cc[h] - '0';
if (h >= m)
k -= cc[h - m] - '0';
dp[h] = (h >= m ? dp[h - m] : 0) + (k > 0 ? 1 : 0);
}
int[] dd = new int[n * m];
for (int j = 0; j < m; j++) {
int i = 0;
while (i < n && cc[i * m + j] == '0')
i++;
if (i < n)
dd[i * m + j]++;
}
for (int k = 0, h = 0; h < n * m; h++) {
k += dd[h];
print(dp[h] + k + " ");
}
println();
}
}
}
| Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 11 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | cc1d731bf5bb7bbab0ffb65c45d0f7e2 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class D {
public static void main(String[]args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int t=sc.nextInt();
a:while(t-->0) {
int n=sc.nextInt(),m=sc.nextInt();
String s=sc.next();
boolean cols[]=new boolean[m];
int[]cnt=new int[m];
int nrows=0,ncols=0,consecZ=0,fone=n*m +1;
for(int i=0;i<s.length();i++) {
if(s.charAt(i)=='1') {
fone=i;break;
}
}
int[] rows=new int[n*m];
for(int i=0;i<s.length();i++) {
if(s.charAt(i)=='1') {
if(!cols[i%m])ncols++;//extra column
consecZ=0;
cols[i%m]=true;
}else {
consecZ++;
}
if(i<m) {
if(consecZ<i+1) {
nrows=1;
}
rows[i]=nrows;
}else {
rows[i]=rows[i-m];
if(consecZ<m)rows[i]++;
}
out.print((rows[i]+ncols)+" ");
}
out.println();
}
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
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 boolean hasNext() {return st.hasMoreTokens();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready(); }
}
}
| Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 8 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | f24755ed72a04ab92d2ac3e08daf998e | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
/*
* Author: Atuer
*/
public class Main
{
// ==== Solve Code ====//
static int INF = 2000000010;
public static void csh()
{
}
public static void main(String[] args) throws IOException
{
// csh();
int t = in.nextInt();
while (t-- > 0)
{
solve();
out.flush();
}
out.close();
}
public static void solve()
{
int n = in.nextInt();
int m = in.nextInt();
char[] s = in.next().toCharArray();
// calculate col
boolean[] vis = new boolean[m];
int[] ans = new int[n * m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
if (i > 0 || j > 0)
ans[i * m + j] = ans[i * m + j - 1];
if (s[i * m + j] == '1')
{
if (!vis[j])
{
vis[j] = true;
ans[i * m + j]++;
}
}
}
// calculate row (滑动窗口查找窗口大小为m的区间是否有1)
boolean[] can = new boolean[n * m];
LinkedList<Integer> q = new LinkedList<>();
for (int i = 0; i < n * m; i++)
{
if (s[i] == '1')
q.add(i);
if (!q.isEmpty() && q.peek() <= i - m)
q.poll();
if (!q.isEmpty())
can[i] = true;
}
// for (int i = 0; i < n * m; i++)
// out.print(ans[i] + " ");
// out.println();
for (int i = 0; i < m; i++)
{
int res = can[i] ? 1 : 0;
ans[i] += res;
for (int j = i + m; j < n * m; j += m)
{
if (can[j])
res++;
ans[j] += res;
}
}
// out.println(Arrays.toString(can));
for (int i = 0; i < n * m; i++)
out.print(ans[i] + " ");
out.println();
}
public static class Node
{
int x, y, k;
public Node(int x, int y, int k)
{
this.x = x;
this.y = y;
this.k = k;
}
}
// ==== Solve Code ====//
// ==== Template ==== //
public static long cnm(int a, int b)
{
long sum = 1;
int i = a, j = 1;
while (j <= b)
{
sum = sum * i / j;
i--;
j++;
}
return sum;
}
public static int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
public static int lcm(int a, int b)
{
return (a * b) / gcd(a, b);
}
public static void gbSort(int[] a, int l, int r)
{
if (l < r)
{
int m = (l + r) >> 1;
gbSort(a, l, m);
gbSort(a, m + 1, r);
int[] t = new int[r - l + 1];
int idx = 0, i = l, j = m + 1;
while (i <= m && j <= r)
if (a[i] <= a[j])
t[idx++] = a[i++];
else
t[idx++] = a[j++];
while (i <= m)
t[idx++] = a[i++];
while (j <= r)
t[idx++] = a[j++];
for (int z = 0; z < t.length; z++)
a[l + z] = t[z];
}
}
// ==== Template ==== //
// ==== IO ==== //
static InputStream inputStream = System.in;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(System.out);
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();
}
boolean hasNext()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e)
{
return false;
// TODO: handle exception
}
}
return true;
}
public String nextLine()
{
String str = null;
try
{
str = reader.readLine();
} catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public Double nextDouble()
{
return Double.parseDouble(next());
}
public BigInteger nextBigInteger()
{
return new BigInteger(next());
}
public BigDecimal nextBigDecimal()
{
return new BigDecimal(next());
}
}
// ==== IO ==== //
} | Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 8 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | b8693af57ad99ddcc692d86dfc2958e7 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.*;
public class Codeforces {
static long mod= 10000_0000_7;
public static void main(String[] args) throws Exception {
PrintWriter out=new PrintWriter(System.out);
FastScanner fs=new FastScanner();
// DecimalFormat formatter= new DecimalFormat("#0.000000");
int t=fs.nextInt();
// int t=1;
// int n=1000000000;
outer:for(int time=1;time<=t;time++) {
int n=fs.nextInt(), m=fs.nextInt();
char arr[]=fs.next().toCharArray();
int col[]=new int[n*m];
boolean c[]=new boolean[m];
for(int i=0;i<n*m;i++) {
if(i>0) col[i]=col[i-1];
if(arr[i]=='1') {
int x= i%m;
if(!c[x]) {
col[i]++;
c[x]=true;
}
}
}
int row[]=new int[n*m];
int last=-m-1;
for(int i=0;i<n*m;i++) {
row[i]=0;
if(i-m>=0) row[i]= row[i-m];
if(arr[i]=='1') {
last=i;
}
if(i-last<m) {
row[i]++;
}
}
for(int i=0;i<n*m;i++) {
out.print((col[i]+row[i])+" ");
}
out.println();
}
out.close();
}
static long pow(long a,long b) {
if(b<0) return 1;
long res=1;
while(b!=0) {
if((b&1)!=0) {
res*=a;
res%=mod;
}
a*=a;
a%=mod;
b=b>>1;
}
return res;
}
static long gcd(long a,long b) {
if(b==0) return a;
return gcd(b,a%b);
}
static long nck(int n,int k) {
if(k>n) return 0;
long res=1;
res*=fact(n);
res%=mod;
res*=modInv(fact(k));
res%=mod;
res*=modInv(fact(n-k));
res%=mod;
return res;
}
static long fact(long n) {
// return fact[(int)n];
long res=1;
for(int i=2;i<=n;i++) {
res*=i;
res%=mod;
}
return res;
}
static long modInv(long n) {
return pow(n,mod-2);
}
static void sort(int[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
static void sort(long[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
long temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String nextLine() {
String str="";
try {
str= (br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long[] readArrayL(int n) {
long a[]=new long[n];
for(int i=0;i<n;i++) a[i]=nextLong();
return a;
}
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 | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 8 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | faf32580843207bc10d72b036095493b | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.io.ByteArrayOutputStream;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.FileNotFoundException;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author tauros
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
RealFastReader in = new RealFastReader(inputStream);
RealFastWriter out = new RealFastWriter(outputStream);
CF1678D solver = new CF1678D();
solver.solve(1, in, out);
out.close();
}
static class CF1678D {
public void solve(int testNumber, RealFastReader in, RealFastWriter out) {
int cases = in.ni();
while (cases-- > 0) {
int n = in.ni(), m = in.ni(), cols = 0, rows = 0;
int[] colNum = new int[m], rowNum = new int[m], rowAns = new int[n * m];
char[] chars = in.ns(n * m);
for (int i = 0, curCol = m; i < n * m; i++) {
if (i > 0) {
out.print(" ");
}
curCol--;
if (curCol < 0) {
curCol += m;
}
char c = chars[i];
if (c == '1') {
if (colNum[curCol] == 0) {
cols++;
}
colNum[curCol]++;
if (rowNum[curCol] == 0) {
rows++;
}
rowNum[curCol] = 1;
} else {
if (rowNum[curCol] == 1) {
rows--;
}
rowNum[curCol] = 0;
}
int preRowAns = i - m < 0 ? 0 : rowAns[i - m];
rowAns[i] = preRowAns + (rows > 0 ? 1 : 0);
out.print(cols + rowAns[i]);
}
out.println();
}
out.flush();
}
}
static class RealFastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
public int lenbuf = 0;
public int ptrbuf = 0;
public RealFastReader(final InputStream is) {
this.is = is;
}
public int readByte() {
if (lenbuf == -1) {
throw new InputMismatchException();
}
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) {
return -1;
}
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
public char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
public int ni() {
return (int) nl();
}
public long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
static class RealFastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private OutputStream out;
private Writer writer;
private int ptr = 0;
private RealFastWriter() {
out = null;
}
public RealFastWriter(Writer writer) {
this.writer = new BufferedWriter(writer);
out = new ByteArrayOutputStream();
}
public RealFastWriter(OutputStream os) {
this.out = os;
}
public RealFastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public RealFastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) {
innerflush();
}
return this;
}
public RealFastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) {
innerflush();
}
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) {
return 10;
}
if (l >= 100000000) {
return 9;
}
if (l >= 10000000) {
return 8;
}
if (l >= 1000000) {
return 7;
}
if (l >= 100000) {
return 6;
}
if (l >= 10000) {
return 5;
}
if (l >= 1000) {
return 4;
}
if (l >= 100) {
return 3;
}
if (l >= 10) {
return 2;
}
return 1;
}
public RealFastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE) {
innerflush();
}
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) {
return 19;
}
if (l >= 100000000000000000L) {
return 18;
}
if (l >= 10000000000000000L) {
return 17;
}
if (l >= 1000000000000000L) {
return 16;
}
if (l >= 100000000000000L) {
return 15;
}
if (l >= 10000000000000L) {
return 14;
}
if (l >= 1000000000000L) {
return 13;
}
if (l >= 100000000000L) {
return 12;
}
if (l >= 10000000000L) {
return 11;
}
if (l >= 1000000000L) {
return 10;
}
if (l >= 100000000L) {
return 9;
}
if (l >= 10000000L) {
return 8;
}
if (l >= 1000000L) {
return 7;
}
if (l >= 100000L) {
return 6;
}
if (l >= 10000L) {
return 5;
}
if (l >= 1000L) {
return 4;
}
if (l >= 100L) {
return 3;
}
if (l >= 10L) {
return 2;
}
return 1;
}
public RealFastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE) {
innerflush();
}
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public RealFastWriter writeln() {
return write((byte) '\n');
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
if (writer != null) {
writer.write(((ByteArrayOutputStream) out).toString());
out = new ByteArrayOutputStream();
writer.flush();
} else {
out.flush();
}
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public RealFastWriter print(String s) {
return write(s);
}
public RealFastWriter print(int x) {
return write(x);
}
public RealFastWriter println() {
return writeln();
}
public void close() {
flush();
try {
out.close();
} catch (Exception e) {
}
}
}
}
| Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 8 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | c81d63bdbff38fb9c5ad2c1a719e818c | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.reflect.Array;
public class tr0 {
static PrintWriter out;
static StringBuilder sb;
static long mod = (long) 1e9 + 7;
static long inf = (long) 1e16;
static int n, m;
static ArrayList<Integer>[] ad, ad1;
static int[][] remove, add;
static long[] inv, f, ncr[];
static HashMap<Integer, Integer> hm;
static int[] pre, suf, Smax[], Smin[];
static int idmax, idmin;
static ArrayList<Integer> av;
static HashMap<Integer, Integer> mm;
static boolean[] msks;
static int[] lazy[], lazyCount;
static int[] c, w;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int ans = 0;
TreeSet<Integer> ts = new TreeSet<>();
char[] s = sc.nextLine().toCharArray();
int col = 0;
int z = 0;
int f = -1;
int[] arr = new int[m];
for (int i = 0; i < n * m; i++) {
if (s[i] == '1') {
ts.add(col);
z = 0;
if (f == -1)
f = i + 1;
} else {
z++;
if (z >= m) {
arr[col]++;
}
}
int rr = (i + 1 + m - 1) / m;
int mod = (i + 1) % m;
if (mod < f && mod!=0)
rr--;
rr -= arr[col];
if (f == -1) {
rr = 0;
}
col++;
if (col == m)
col = 0;
ans = ts.size() + rr;
out.print(ans + " ");
}
out.println();
}
out.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextArrInt(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextArrLong(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextArrIntSorted(int n) throws IOException {
int[] a = new int[n];
Integer[] a1 = new Integer[n];
for (int i = 0; i < n; i++)
a1[i] = nextInt();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[i].intValue();
return a;
}
public long[] nextArrLongSorted(int n) throws IOException {
long[] a = new long[n];
Long[] a1 = new Long[n];
for (int i = 0; i < n; i++)
a1[i] = nextLong();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[i].longValue();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 8 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | 0cba0a52e0234e5fa2625453ceeebb09 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.util.*;
import java.io.*;
// res.append("Case #"+(p+1)+": "+hh+" \n");
////***************************************************************************
/* public class E_Gardener_and_Tree implements Runnable{
public static void main(String[] args) throws Exception {
new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start();
}
public void run(){
WRITE YOUR CODE HERE!!!!
JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!!
}
}
*/
/////**************************************************************************
public class D_Tokitsukaze_and_Meeting{
public static void main(String[] args) {
FastScanner s= new FastScanner();
//PrintWriter out=new PrintWriter(System.out);
//end of program
//out.println(answer);
//out.close();
StringBuilder res = new StringBuilder();
int t=s.nextInt();
int p=0;
while(p<t){
int n=s.nextInt();
int m=s.nextInt();
String str=s.nextToken();
int size=(n*m);
int col[]= new int[size];
//column contri thing
for(int i=0;i<m;i++){
for(int j=i;j<size;j+=m){
char ch=str.charAt(j);
if(ch=='1'){
col[j]=1;
break;
}
}
}
long nice[]= new long[size];
int zeroes=0;
for(int i=0;i<m;i++){
char ch=str.charAt(i);
if(ch=='0'){
zeroes++;
}
}
int start=0;
int end=m-1;
while(end<size){
nice[end]=0;
if(end-m>=0){
nice[end]=nice[(end-m)];
}
if(zeroes==m){
nice[end]++;
}
if(end==size-1){
break;
}
if(str.charAt(start)=='0'){
zeroes--;
}
if(str.charAt(end+1)=='0'){
zeroes++;
}
start++;
end++;
}
long prefix[]= new long[size];
long a1=0;
for(int i=0;i<size;i++){
char ch=str.charAt(i);
if(ch=='1'){
a1++;
}
prefix[i]=a1;
}
long ans[]= new long[size];
long hh=0;
for(int i=0;i<size;i++){
if(col[i]==1){
hh++;
}
long alpha=hh;
long total=(i+1)/m;
long beta=total+alpha-nice[i];
int rem=(i+1)%m;
if(rem>0){
if(prefix[rem-1]>0){
beta++;
}
}
ans[i]=beta;
}
for(int i=0;i<size;i++){
res.append(ans[i]+" ");
}
res.append(" \n");
p++;
}
System.out.println(res);
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
static long modpower(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// SIMPLE POWER FUNCTION=>
static long power(long x, long y)
{
long res = 1; // Initialize result
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = res * x;
// y must be even now
y = y >> 1; // y = y/2
x = x * x; // Change x to x^2
}
return res;
}
} | Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 8 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | 9be258b525bf99b9295634d991788579 | train_108.jsonl | 1652020500 | Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below: There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows: Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
solver.solve(in.nextInt(), in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
for (int i = 0; i < testNumber; i++) {
int n = in.nextInt();
int m = in.nextInt();
int[] solve = new Solution().solve(n, m, in.next());
for (int j = 0; j < solve.length; j++) {
out.print(solve[j] + " ");
}
out.println();
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
class Solution {
public int[] solve(int n, int m, String s) {
char[] chars = s.toCharArray();
int[] ans = new int[m * n];
int[] cntCol = new int[m * n];
boolean[] good = new boolean[m];
int curCol = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '1' && !good[i % m]) {
good[i % m] = true;
curCol++;
}
cntCol[i] = curCol;
}
int[] cntRow = new int[m * n];
int[] sums = new int[m * n + 1];
for (int i = 0; i < sums.length - 1; i++) {
sums[i + 1] = sums[i] + (chars[i] - '0');
}
for (int i = 0; i < m; i++) {
if (sums[i + 1] > 0) {
cntRow[i]++;
}
}
for (int i = m; i < cntRow.length; i++) {
cntRow[i] = cntRow[i - m];
if (sums[i + 1] - sums[i - m + 1] > 0) {
cntRow[i]++;
}
}
for (int i = 0; i < ans.length; i++) {
ans[i] = cntCol[i] + cntRow[i];
}
return ans;
}
} | Java | ["3\n\n2 2\n\n1100\n\n4 2\n\n11001101\n\n2 4\n\n11001101"] | 1 second | ["2 3 4 3\n2 3 4 3 5 4 6 5\n2 3 3 3 4 4 4 5"] | NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column. | Java 8 | standard input | [
"dp",
"implementation"
] | ca835eeb8f24de8860d6f5ac6c0af55d | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. | 1,700 | For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall. | standard output | |
PASSED | d62c719f6ee4b43530076e068456e446 | train_108.jsonl | 1652020500 | Tokitsukaze has a permutation $$$p$$$. She performed the following operation to $$$p$$$ exactly $$$k$$$ times: in one operation, for each $$$i$$$ from $$$1$$$ to $$$n - 1$$$ in order, if $$$p_i$$$ > $$$p_{i+1}$$$, swap $$$p_i$$$, $$$p_{i+1}$$$. After exactly $$$k$$$ times of operations, Tokitsukaze got a new sequence $$$a$$$, obviously the sequence $$$a$$$ is also a permutation.After that, Tokitsukaze wrote down the value sequence $$$v$$$ of $$$a$$$ on paper. Denote the value sequence $$$v$$$ of the permutation $$$a$$$ of length $$$n$$$ as $$$v_i=\sum_{j=1}^{i-1}[a_i < a_j]$$$, where the value of $$$[a_i < a_j]$$$ define as if $$$a_i < a_j$$$, the value is $$$1$$$, otherwise is $$$0$$$ (in other words, $$$v_i$$$ is equal to the number of elements greater than $$$a_i$$$ that are to the left of position $$$i$$$). Then Tokitsukaze went out to work.There are three naughty cats in Tokitsukaze's house. When she came home, she found the paper with the value sequence $$$v$$$ to be bitten out by the cats, leaving several holes, so that the value of some positions could not be seen clearly. She forgot what the original permutation $$$p$$$ was. She wants to know how many different permutations $$$p$$$ there are, so that the value sequence $$$v$$$ of the new permutation $$$a$$$ after exactly $$$k$$$ operations is the same as the $$$v$$$ written on the paper (not taking into account the unclear positions).Since the answer may be too large, print it modulo $$$998\,244\,353$$$. | 256 megabytes | // package c1678;
//
// Codeforces Round #789 (Div. 2) 2022-05-08 07:35
// F. Tokitsukaze and Permutations
// https://codeforces.com/contest/1678/problem/F
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// Tokitsukaze has a permutation p. She performed the following operation to p k times: in one
// operation, for each i from 1 to n - 1 in order, if p_i > p_{i+1}, swap p_i, p_{i+1}. After
// exactly k times of operations, Tokitsukaze got a new sequence a, obviously the sequence a is also
// a permutation.
//
// After that, Tokitsukaze wrote down the value sequence v of a on paper. Denote the value sequence
// v of the permutation a of length n as v_i=\sum_{j=1}^{i-1}[a_i < a_j], where the value of [a_i <
// a_j] define as if a_i < a_j, the value is 1, otherwise is 0 (in other words, v_i is equal to the
// number of elements greater than a_i that are to the left of position i). Then Tokitsukaze went
// out to work.
//
// There are three naughty cats in Tokitsukaze's house. When she came home, she found the paper with
// the value sequence v to be bitten out by the cats, leaving several holes, so that the value of
// some positions could not be seen clearly. She forgot what the original permutation p was. She
// wants to know how many different permutations p there are, so that the value sequence v of the
// new permutation a after k operations is the same as the v written on the paper (not taking into
// account the unclear positions).
//
// Since the answer may be too large, print it modulo 998,244,353.
//
// Input
//
// The first line contains a single integer t (1 <= t <= 1000)-- the number of test cases. Each test
// case consists of two lines.
//
// The first line contains two integers n and k (1 <= n <= 10^6; 0 <= k <= n-1)-- the length of the
// permutation and the exactly number of operations.
//
// The second line contains n integers v_1, v_2, ..., v_n (-1 <= v_i <= i-1)-- the value sequence v.
// v_i = -1 means the i-th position of v can't be seen clearly.
//
// It is guaranteed that the sum of n over all test cases does not exceed 10^6.
//
// Output
//
// For each test case, print a single integer-- the number of different permutations modulo
// 998,244,353.
//
// Example
/*
input:
3
5 0
0 1 2 3 4
5 2
-1 1 2 0 0
5 2
0 1 1 0 0
output:
1
6
6
*/
// Note
//
// In the first test case, only permutation p=[5,4,3,2,1] satisfies the constraint condition.
//
// In the second test case, there are 6 permutations satisfying the constraint condition, which are:
// * [3,4,5,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [3,5,4,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [4,3,5,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [4,5,3,2,1] -> [4,3,2,1,5] -> [3,2,1,4,5]
// * [5,3,4,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [5,4,3,2,1] -> [4,3,2,1,5] -> [3,2,1,4,5]
//
// So after exactly 2 times of swap they will all become a=[3,2,1,4,5], whose value sequence is
// v=[0,1,2,0,0].
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
public class C1678F {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int[] FACT = computeFactArray(1000000);
static int solve(int[] v, int k) {
int n = v.length;
myAssert(v[0] <= 0);
// Sanity check, as the last k element in a is n-k+1,...,n in that order
// last k element in v must be 0 or -1.
for (int i = 1; i <= k; i++) {
if (v[n-i] > 0) {
return 0;
}
}
/* statistics of n = 9, k = 3 as computed by incubate()
0 * * * * * 0 0 0 -> 362880
* 0 * * * * 0 0 0 -> 290304
* 1 * * * * 0 0 0 -> 72576
* * 0 * * * 0 0 0 -> 241920
* * 1 * * * 0 0 0 -> 60480
* * 2 * * * 0 0 0 -> 60480
* * * 0 * * 0 0 0 -> 207360
* * * 1 * * 0 0 0 -> 51840
* * * 2 * * 0 0 0 -> 51840
* * * 3 * * 0 0 0 -> 51840
* * * * 0 * 0 0 0 -> 181440
* * * * 1 * 0 0 0 -> 45360
* * * * 2 * 0 0 0 -> 45360
* * * * 3 * 0 0 0 -> 45360
* * * * 4 * 0 0 0 -> 45360
* * * * * 0 0 0 0 -> 161280 *6,*7,*8,*9 -> *6789 4*8!
* * * * * 1 0 0 0 -> 40320 *5 -> *5789 8!
* * * * * 2 0 0 0 -> 40320 *4 -> *4789 8!
* * * * * 3 0 0 0 -> 40320 *3 -> *3789 8!
* * * * * 4 0 0 0 -> 40320 *2 -> *2789 8!
* * * * * 5 0 0 0 -> 40320 *1 -> *1789 8!
* * * * 0 0 0 0 0 -> 80640 *56 *57 *58 *59 {6,7,8,9}P2 -> *56789 16 * 7!
* * * * 0 1 0 0 0 -> 20160 *65,*75,*85,*95 -> *65789 4*7!
* * * * 0 2 0 0 0 -> 20160 *64,*74,*84,*94 -> *64789 4*7!
* * * * 0 3 0 0 0 -> 20160 *63,*73,*83,*93 -> *64789 4*7!
* * * * 0 4 0 0 0 -> 20160 *62,*72,*82,*92 -> *64789 4*7!
* * * * 0 5 0 0 0 -> 20160 *61,*71,*81,*91 -> *64789 4*7!
* * * * 3 0 0 0 0 -> 20160 *26,*27,*28,*29 -> *26789 4*7!
* * * * 3 1 0 0 0 -> 5040 *25 -> *25789 7!
* * * * 3 2 0 0 0 -> 5040 *34 -> *34789 7!
* * * * 3 3 0 0 0 -> 5040 *23 -> *23789 7!
* * * * 3 4 0 0 0 -> 5040 *32 -> *32789 7!
* * * * 3 5 0 0 0 -> 5040 *31 -> *31789 7!
* * * * 4 0 0 0 0 -> 20160
* * * * 4 1 0 0 0 -> 5040
* * * * 4 2 0 0 0 -> 5040
* * * * 4 3 0 0 0 -> 5040
* * * * 4 4 0 0 0 -> 5040
* * * * 4 5 0 0 0 -> 5040
*/
int e = n - k - 1;
// 0 * * * * 3 0 0 0
// ^
// e
long ans = FACT[k+1];
for (int i = 1; i <= e; i++) {
long mul = 1;
if (v[i] > 0) {
// value [1,i] each has (k+i)!
} else if (v[i] == 0) {
// value 0 has (k+1) * (k+i)!
mul = mul * (k+1) % MOD;
} else {
myAssert(v[i] == -1);
// combine above cases:
// (i + k + 1) * (k+i)!
mul = i + k + 1;
}
ans = ans * mul % MOD;
if (test) {
System.out.format(" i:%d mul:%2d ans:%d\n", i, mul, ans);
}
}
return (int) ans;
}
static int[] computeFactArray(int n) {
int[] fact = new int[n+1];
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (int) (((long) fact[i-1] * i) % MOD);
}
return fact;
}
// Code below were used during incubation and test.
static class Permutation {
int[] perm;
boolean checkedNext = true;
boolean hasNext = true;
// m is used in (n,k) to take the prefix from every m=(n-k)! permutations.
int m = 1;
// all permutations of n unique element
public Permutation(int n) {
this.perm = firstPerm(n);
}
// all permutations of k out of n elements
public Permutation(int n, int k) {
myAssert(n >= 1 && k > 0 && k <= n);
// (n-k)!
this.m = 1;
for (int i = 1; i <= n - k; i++) {
m *= i;
}
this.perm = firstPerm(n);
}
// Flexible permutation (combination) from given state. For example:
// 0,1,2,3,4 --- 120 permutations of 5 elements
// 1,0,0,0,0,0,0,1,1 --- 28 ways to select 3 out of 9 with first element always included
// 0,0,1,1,2,2 --- 90 ways to split 6 element into groups of 2,2,2
public Permutation(int[] state) {
this.perm = state;
}
boolean hasNext() {
if (!checkedNext) {
checkNext();
}
return hasNext;
}
private void checkNext() {
if (!checkedNext) {
for (int i = 0; i < m; i++) {
hasNext = nextPerm(perm);
}
checkedNext = true;
}
}
public int[] next() {
checkNext();
checkedNext = false;
return hasNext ? perm : null;
}
// Get all (remaining) permutations.
public List<int[]> getAll() {
List<int[]> all = new ArrayList<>();
while (hasNext()) {
next();
int[] one = new int[perm.length];
System.arraycopy(perm, 0, one, 0, perm.length);
all.add(one);
}
return all;
}
public static int[] firstPerm(int n) {
int[] perm = new int[n];
for (int i = 0; i < n; i++) {
perm[i] = i;
}
return perm;
}
// Gets next permutation from current one. For example:
// 1 2 2 3 3 3 4 4 4 4 =>
// 1 2 2 3 3 4 3 4 4 4 =>
// 1 2 2 3 3 4 4 3 4 4 =>
// 1 2 2 3 3 4 4 4 3 4 => ...
// 4 4 4 4 3 3 3 2 2 1
public static boolean nextPerm(int[] nums) {
int n = nums.length;
int i = n - 1;
while (i > 0 && nums[i-1] >= nums[i]) {
i--;
}
if (i == 0) {
return false;
}
i--;
int j = n - 1;
while (nums[j] <= nums[i]) {
j--;
}
swap(nums, i ,j);
i++;
j = n - 1;
while (i < j) {
swap(nums, i ,j);
i++;
j--;
}
return true;
}
static void swap(int[] idxes, int i, int j) {
int t = idxes[i];
idxes[i] = idxes[j];
idxes[j] = t;
}
public static List<int[]> getAllPerms(int n, int k) {
return new Permutation(n,k).getAll();
}
}
static void reduce(int[] p) {
int n = p.length;
for (int i = 0; i < n - 1; i++) {
if (p[i] > p[i+1]) {
int t = p[i];
p[i] = p[i+1];
p[i+1] = t;
}
}
}
static void reduce(int[] p, int k) {
for (int i = 0; i < k; i++) {
reduce(p);
}
}
static void getCount(int[] p, int[] ct) {
int n = p.length;
Arrays.fill(ct, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (p[j] > p[i]) {
ct[i]++;
}
}
}
}
static String trace(int[] a) {
StringBuilder sb = new StringBuilder();
sb.append('{');
for (int v : a) {
if (sb.length() > 1) {
sb.append(',');
}
sb.append(v);
}
sb.append('}');
return sb.toString();
}
static void increment(int[] ct, List<int[]> cts, List<Integer> ctv) {
int n = ct.length;
for (int i = 0; i < cts.size(); i++) {
boolean equal = true;
int[] v = cts.get(i);
for (int j = 0; j < n; j++) {
if (v[j] != ct[j]) {
equal = false;
break;
}
}
if (equal) {
ctv.set(i, ctv.get(i) + 1);
return;
}
}
int[] arr = new int[n];
System.arraycopy(ct, 0, arr, 0, n);
cts.add(arr);
ctv.add(1);
}
static void test(int exp, int[] v, int k) {
int ans = solve(v, k);
System.out.format("%s %d => %d%s\n", trace(v), k, ans, ans == exp ? "" : " Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
// incubate();
test(120, new int[] {0,-1,0,0,0}, 4);
test(161280, new int[] {-1,-1,-1,-1,-1,0,0,0,0}, 3);
test(181440, new int[] {-1,-1,-1,-1,0,-1,0,0,0}, 3);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
// Show permutations and statistics of n = 9, k = 3
private static void incubate() {
int n = 9;
int k = 3;
List<int[]> all = Permutation.getAllPerms(n, n);
StringBuilder sb = new StringBuilder();
int index = 0;
int[] ct = new int[n];
List<int[]> cts = new ArrayList<>();
List<Integer> ctv = new ArrayList<>();
for (int[] p : all) {
index++;
sb.append(String.format("%6d ", index));
sb.append(trace(p));
reduce(p, k);
sb.append(" -> ");
sb.append(trace(p));
getCount(p, ct);
sb.append(" -> ");
sb.append(trace(ct));
sb.append('\n');
increment(ct, cts, ctv);
}
System.out.print(sb.toString());
for (int i = 0; i < cts.size(); i++) {
System.out.format(" %4d %s %d\n", i+1, trace(cts.get(i)), ctv.get(i));
}
for (int i = 0; i < n - k; i++) {
char[] ca = new char[2 * n - 1];
Arrays.fill(ca, ' ');
for (int j = 0; j <= i; j++) {
int v = 0;
for (int h = 0; h < n; h++) {
ca[2*h] = h < n - k ? '*' : '0';
}
ca[2*i] = (char)('0' + j);
for (int h = 0; h < cts.size(); h++) {
if (cts.get(h)[i] == j) {
v += ctv.get(h);
}
}
System.out.format(" %s -> %d\n", new String(ca), v);
}
}
// show sub-cases of * * * * 4 ? 0 0 0
int[] ct40 = new int[n];
for (int i = 0; i < cts.size(); i++) {
if (cts.get(i)[4] == 0) {
ct40[cts.get(i)[5]] += ctv.get(i);
}
}
System.out.format(" ct40: %s\n", trace(ct40));
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int k = in.nextInt();
int[] v = new int[n];
for (int i = 0; i < n; i++) {
v[i] = in.nextInt();
}
int ans = solve(v, k);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n\n5 0\n\n0 1 2 3 4\n\n5 2\n\n-1 1 2 0 0\n\n5 2\n\n0 1 1 0 0"] | 2 seconds | ["1\n6\n6"] | NoteIn the first test case, only permutation $$$p=[5,4,3,2,1]$$$ satisfies the constraint condition.In the second test case, there are $$$6$$$ permutations satisfying the constraint condition, which are: $$$[3,4,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[3,5,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,3,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,5,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,3,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,4,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ So after exactly $$$2$$$ times of swap they will all become $$$a=[3,2,1,4,5]$$$, whose value sequence is $$$v=[0,1,2,0,0]$$$. | Java 11 | standard input | [
"dp",
"math"
] | f2b2d12ab1c8a511d2ca550faa9768d4 | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^6$$$; $$$0 \leq k \leq n-1$$$) — the length of the permutation and the exactly number of operations. The second line contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$-1 \leq v_i \leq i-1$$$) — the value sequence $$$v$$$. $$$v_i = -1$$$ means the $$$i$$$-th position of $$$v$$$ can't be seen clearly. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$. | 2,500 | For each test case, print a single integer — the number of different permutations modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 5a2f65af7732e105062f25323e909fd4 | train_108.jsonl | 1652020500 | Tokitsukaze has a permutation $$$p$$$. She performed the following operation to $$$p$$$ exactly $$$k$$$ times: in one operation, for each $$$i$$$ from $$$1$$$ to $$$n - 1$$$ in order, if $$$p_i$$$ > $$$p_{i+1}$$$, swap $$$p_i$$$, $$$p_{i+1}$$$. After exactly $$$k$$$ times of operations, Tokitsukaze got a new sequence $$$a$$$, obviously the sequence $$$a$$$ is also a permutation.After that, Tokitsukaze wrote down the value sequence $$$v$$$ of $$$a$$$ on paper. Denote the value sequence $$$v$$$ of the permutation $$$a$$$ of length $$$n$$$ as $$$v_i=\sum_{j=1}^{i-1}[a_i < a_j]$$$, where the value of $$$[a_i < a_j]$$$ define as if $$$a_i < a_j$$$, the value is $$$1$$$, otherwise is $$$0$$$ (in other words, $$$v_i$$$ is equal to the number of elements greater than $$$a_i$$$ that are to the left of position $$$i$$$). Then Tokitsukaze went out to work.There are three naughty cats in Tokitsukaze's house. When she came home, she found the paper with the value sequence $$$v$$$ to be bitten out by the cats, leaving several holes, so that the value of some positions could not be seen clearly. She forgot what the original permutation $$$p$$$ was. She wants to know how many different permutations $$$p$$$ there are, so that the value sequence $$$v$$$ of the new permutation $$$a$$$ after exactly $$$k$$$ operations is the same as the $$$v$$$ written on the paper (not taking into account the unclear positions).Since the answer may be too large, print it modulo $$$998\,244\,353$$$. | 256 megabytes | // package c1678;
//
// Codeforces Round #789 (Div. 2) 2022-05-08 07:35
// F. Tokitsukaze and Permutations
// https://codeforces.com/contest/1678/problem/F
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// Tokitsukaze has a permutation p. She performed the following operation to p k times: in one
// operation, for each i from 1 to n - 1 in order, if p_i > p_{i+1}, swap p_i, p_{i+1}. After
// exactly k times of operations, Tokitsukaze got a new sequence a, obviously the sequence a is also
// a permutation.
//
// After that, Tokitsukaze wrote down the value sequence v of a on paper. Denote the value sequence
// v of the permutation a of length n as v_i=\sum_{j=1}^{i-1}[a_i < a_j], where the value of [a_i <
// a_j] define as if a_i < a_j, the value is 1, otherwise is 0 (in other words, v_i is equal to the
// number of elements greater than a_i that are to the left of position i). Then Tokitsukaze went
// out to work.
//
// There are three naughty cats in Tokitsukaze's house. When she came home, she found the paper with
// the value sequence v to be bitten out by the cats, leaving several holes, so that the value of
// some positions could not be seen clearly. She forgot what the original permutation p was. She
// wants to know how many different permutations p there are, so that the value sequence v of the
// new permutation a after k operations is the same as the v written on the paper (not taking into
// account the unclear positions).
//
// Since the answer may be too large, print it modulo 998,244,353.
//
// Input
//
// The first line contains a single integer t (1 <= t <= 1000)-- the number of test cases. Each test
// case consists of two lines.
//
// The first line contains two integers n and k (1 <= n <= 10^6; 0 <= k <= n-1)-- the length of the
// permutation and the exactly number of operations.
//
// The second line contains n integers v_1, v_2, ..., v_n (-1 <= v_i <= i-1)-- the value sequence v.
// v_i = -1 means the i-th position of v can't be seen clearly.
//
// It is guaranteed that the sum of n over all test cases does not exceed 10^6.
//
// Output
//
// For each test case, print a single integer-- the number of different permutations modulo
// 998,244,353.
//
// Example
/*
input:
3
5 0
0 1 2 3 4
5 2
-1 1 2 0 0
5 2
0 1 1 0 0
output:
1
6
6
*/
// Note
//
// In the first test case, only permutation p=[5,4,3,2,1] satisfies the constraint condition.
//
// In the second test case, there are 6 permutations satisfying the constraint condition, which are:
// * [3,4,5,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [3,5,4,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [4,3,5,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [4,5,3,2,1] -> [4,3,2,1,5] -> [3,2,1,4,5]
// * [5,3,4,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [5,4,3,2,1] -> [4,3,2,1,5] -> [3,2,1,4,5]
//
// So after exactly 2 times of swap they will all become a=[3,2,1,4,5], whose value sequence is
// v=[0,1,2,0,0].
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
public class C1678F {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int[] FACT = computeFactArray(1000000);
static int solve(int[] v, int k) {
int n = v.length;
myAssert(v[0] <= 0);
/*
if (n == 1) {
return 1;
} else if (n == 2) {
if (k == 0) {
// v is 0 0 or 0 1
return v[1] == -1 ? 2 : 1;
} else {
myAssert(k == 1);
// v must be 0 0
return v[1] > 0 ? 0 : 2;
}
}
*/
// As the last k element in a is n-k+1,...,n in that order
// last k element in v must be 0 or -1.
for (int i = 1; i <= k; i++) {
if (v[n-i] > 0) {
return 0;
}
}
/* n = 9, k = 3
0 * * * * * 0 0 0 -> 362880
* 0 * * * * 0 0 0 -> 290304
* 1 * * * * 0 0 0 -> 72576
* * 0 * * * 0 0 0 -> 241920
* * 1 * * * 0 0 0 -> 60480
* * 2 * * * 0 0 0 -> 60480
* * * 0 * * 0 0 0 -> 207360
* * * 1 * * 0 0 0 -> 51840
* * * 2 * * 0 0 0 -> 51840
* * * 3 * * 0 0 0 -> 51840
* * * * 0 * 0 0 0 -> 181440
* * * * 1 * 0 0 0 -> 45360
* * * * 2 * 0 0 0 -> 45360
* * * * 3 * 0 0 0 -> 45360
* * * * 4 * 0 0 0 -> 45360
* * * * * 0 0 0 0 -> 161280 *6,*7,*8,*9 -> *6789 4*8!
* * * * * 1 0 0 0 -> 40320 *5 -> *5789 8!
* * * * * 2 0 0 0 -> 40320 *4 -> *4789 8!
* * * * * 3 0 0 0 -> 40320 *3 -> *3789 8!
* * * * * 4 0 0 0 -> 40320 *2 -> *2789 8!
* * * * * 5 0 0 0 -> 40320 *1 -> *1789 8!
* * * * 0 0 0 0 0 -> 80640 *56 *57 *58 *59 {6,7,8,9}P2 -> *56789 16 * 7!
* * * * 0 1 0 0 0 -> 20160 *65,*75,*85,*95 -> *65789 4*7!
* * * * 0 2 0 0 0 -> 20160 *64,*74,*84,*94 -> *64789 4*7!
* * * * 0 3 0 0 0 -> 20160 *63,*73,*83,*93 -> *64789 4*7!
* * * * 0 4 0 0 0 -> 20160 *62,*72,*82,*92 -> *64789 4*7!
* * * * 0 5 0 0 0 -> 20160 *61,*71,*81,*91 -> *64789 4*7!
* * * * 3 0 0 0 0 -> 20160 *26,*27,*28,*29 -> *26789 4*7!
* * * * 3 1 0 0 0 -> 5040 *25 -> *25789 7!
* * * * 3 2 0 0 0 -> 5040 *34 -> *34789 7!
* * * * 3 3 0 0 0 -> 5040 *23 -> *23789 7!
* * * * 3 4 0 0 0 -> 5040 *32 -> *32789 7!
* * * * 3 5 0 0 0 -> 5040 *31 -> *31789 7!
* * * * 4 0 0 0 0 -> 20160
* * * * 4 1 0 0 0 -> 5040
* * * * 4 2 0 0 0 -> 5040
* * * * 4 3 0 0 0 -> 5040
* * * * 4 4 0 0 0 -> 5040
* * * * 4 5 0 0 0 -> 5040
*/
int e = n - k - 1;
// 0 * * * * 3 0 0 0
// ^
// e
long ans = FACT[k+1];
for (int i = 1; i <= e; i++) {
long mul = 1;
if (v[i] > 0) {
// value [1,i] each has (k+i)!
} else if (v[i] == 0) {
// value 0 has (k+1) * (k+i)!
mul = mul * (k+1) % MOD;
} else {
myAssert(v[i] == -1);
// combine above cases:
// (i + k + 1) * (k+i)!
mul = i + k + 1;
}
ans = ans * mul % MOD;
if (test) {
System.out.format(" i:%d mul:%2d ans:%d\n", i, mul, ans);
}
}
return (int) ans;
}
static int[] computeFactArray(int n) {
int[] fact = new int[n+1];
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (int) (((long) fact[i-1] * i) % MOD);
}
return fact;
}
static class Permutation {
int[] perm;
boolean checkedNext = true;
boolean hasNext = true;
// m is used in (n,k) to take the prefix from every m=(n-k)! permutations.
int m = 1;
// all permutations of n unique element
public Permutation(int n) {
this.perm = firstPerm(n);
}
// all permutations of k out of n elements
public Permutation(int n, int k) {
myAssert(n >= 1 && k > 0 && k <= n);
// (n-k)!
this.m = 1;
for (int i = 1; i <= n - k; i++) {
m *= i;
}
this.perm = firstPerm(n);
}
// Flexible permutation (combination) from given state. For example:
// 0,1,2,3,4 --- 120 permutations of 5 elements
// 1,0,0,0,0,0,0,1,1 --- 28 ways to select 3 out of 9 with first element always included
// 0,0,1,1,2,2 --- 90 ways to split 6 element into groups of 2,2,2
public Permutation(int[] state) {
this.perm = state;
}
boolean hasNext() {
if (!checkedNext) {
checkNext();
}
return hasNext;
}
private void checkNext() {
if (!checkedNext) {
for (int i = 0; i < m; i++) {
hasNext = nextPerm(perm);
}
checkedNext = true;
}
}
public int[] next() {
checkNext();
checkedNext = false;
return hasNext ? perm : null;
}
// Get all (remaining) permutations.
public List<int[]> getAll() {
List<int[]> all = new ArrayList<>();
while (hasNext()) {
next();
int[] one = new int[perm.length];
System.arraycopy(perm, 0, one, 0, perm.length);
all.add(one);
}
return all;
}
public static int[] firstPerm(int n) {
int[] perm = new int[n];
for (int i = 0; i < n; i++) {
perm[i] = i;
}
return perm;
}
// Gets next permutation from current one. For example:
// 1 2 2 3 3 3 4 4 4 4 =>
// 1 2 2 3 3 4 3 4 4 4 =>
// 1 2 2 3 3 4 4 3 4 4 =>
// 1 2 2 3 3 4 4 4 3 4 => ...
// 4 4 4 4 3 3 3 2 2 1
public static boolean nextPerm(int[] nums) {
int n = nums.length;
int i = n - 1;
while (i > 0 && nums[i-1] >= nums[i]) {
i--;
}
if (i == 0) {
return false;
}
i--;
int j = n - 1;
while (nums[j] <= nums[i]) {
j--;
}
swap(nums, i ,j);
i++;
j = n - 1;
while (i < j) {
swap(nums, i ,j);
i++;
j--;
}
return true;
}
static void swap(int[] idxes, int i, int j) {
int t = idxes[i];
idxes[i] = idxes[j];
idxes[j] = t;
}
public static List<int[]> getAllPerms(int n, int k) {
return new Permutation(n,k).getAll();
}
}
static void reduce(int[] p) {
int n = p.length;
for (int i = 0; i < n - 1; i++) {
if (p[i] > p[i+1]) {
int t = p[i];
p[i] = p[i+1];
p[i+1] = t;
}
}
}
static void reduce(int[] p, int k) {
for (int i = 0; i < k; i++) {
reduce(p);
}
}
static void getCount(int[] p, int[] ct) {
int n = p.length;
Arrays.fill(ct, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (p[j] > p[i]) {
ct[i]++;
}
}
}
}
static String trace(int[] a) {
StringBuilder sb = new StringBuilder();
sb.append('{');
for (int v : a) {
if (sb.length() > 1) {
sb.append(',');
}
sb.append(v);
}
sb.append('}');
return sb.toString();
}
static void increment(int[] ct, List<int[]> cts, List<Integer> ctv) {
int n = ct.length;
for (int i = 0; i < cts.size(); i++) {
boolean equal = true;
int[] v = cts.get(i);
for (int j = 0; j < n; j++) {
if (v[j] != ct[j]) {
equal = false;
break;
}
}
if (equal) {
ctv.set(i, ctv.get(i) + 1);
return;
}
}
int[] arr = new int[n];
System.arraycopy(ct, 0, arr, 0, n);
cts.add(arr);
ctv.add(1);
}
static void test(int exp, int[] v, int k) {
int ans = solve(v, k);
System.out.format("%s %d => %d%s\n", trace(v), k, ans, ans == exp ? "" : " Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
// incubate();
test(120, new int[] {0,-1,0,0,0}, 4);
test(161280, new int[] {-1,-1,-1,-1,-1,0,0,0,0}, 3);
test(181440, new int[] {-1,-1,-1,-1,0,-1,0,0,0}, 3);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
private static void incubate() {
int n = 9;
int k = 3;
List<int[]> all = Permutation.getAllPerms(n, n);
StringBuilder sb = new StringBuilder();
int index = 0;
int[] ct = new int[n];
List<int[]> cts = new ArrayList<>();
List<Integer> ctv = new ArrayList<>();
for (int[] p : all) {
index++;
sb.append(String.format("%6d ", index));
sb.append(trace(p));
reduce(p, k);
sb.append(" -> ");
sb.append(trace(p));
getCount(p, ct);
sb.append(" -> ");
sb.append(trace(ct));
sb.append('\n');
increment(ct, cts, ctv);
}
System.out.print(sb.toString());
for (int i = 0; i < cts.size(); i++) {
System.out.format(" %4d %s %d\n", i+1, trace(cts.get(i)), ctv.get(i));
}
for (int i = 0; i < n - k; i++) {
char[] ca = new char[2 * n - 1];
Arrays.fill(ca, ' ');
for (int j = 0; j <= i; j++) {
int v = 0;
for (int h = 0; h < n; h++) {
ca[2*h] = h < n - k ? '*' : '0';
}
ca[2*i] = (char)('0' + j);
for (int h = 0; h < cts.size(); h++) {
if (cts.get(h)[i] == j) {
v += ctv.get(h);
}
}
System.out.format(" %s -> %d\n", new String(ca), v);
}
}
int[] ct40 = new int[n];
for (int i = 0; i < cts.size(); i++) {
if (cts.get(i)[4] == 0) {
ct40[cts.get(i)[5]] += ctv.get(i);
}
}
System.out.format(" ct40: %s\n", trace(ct40));
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int k = in.nextInt();
int[] v = new int[n];
for (int i = 0; i < n; i++) {
v[i] = in.nextInt();
}
int ans = solve(v, k);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n\n5 0\n\n0 1 2 3 4\n\n5 2\n\n-1 1 2 0 0\n\n5 2\n\n0 1 1 0 0"] | 2 seconds | ["1\n6\n6"] | NoteIn the first test case, only permutation $$$p=[5,4,3,2,1]$$$ satisfies the constraint condition.In the second test case, there are $$$6$$$ permutations satisfying the constraint condition, which are: $$$[3,4,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[3,5,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,3,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,5,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,3,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,4,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ So after exactly $$$2$$$ times of swap they will all become $$$a=[3,2,1,4,5]$$$, whose value sequence is $$$v=[0,1,2,0,0]$$$. | Java 11 | standard input | [
"dp",
"math"
] | f2b2d12ab1c8a511d2ca550faa9768d4 | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^6$$$; $$$0 \leq k \leq n-1$$$) — the length of the permutation and the exactly number of operations. The second line contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$-1 \leq v_i \leq i-1$$$) — the value sequence $$$v$$$. $$$v_i = -1$$$ means the $$$i$$$-th position of $$$v$$$ can't be seen clearly. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$. | 2,500 | For each test case, print a single integer — the number of different permutations modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 027adbd07fc7883faf2ddb580db0025b | train_108.jsonl | 1652020500 | Tokitsukaze has a permutation $$$p$$$. She performed the following operation to $$$p$$$ exactly $$$k$$$ times: in one operation, for each $$$i$$$ from $$$1$$$ to $$$n - 1$$$ in order, if $$$p_i$$$ > $$$p_{i+1}$$$, swap $$$p_i$$$, $$$p_{i+1}$$$. After exactly $$$k$$$ times of operations, Tokitsukaze got a new sequence $$$a$$$, obviously the sequence $$$a$$$ is also a permutation.After that, Tokitsukaze wrote down the value sequence $$$v$$$ of $$$a$$$ on paper. Denote the value sequence $$$v$$$ of the permutation $$$a$$$ of length $$$n$$$ as $$$v_i=\sum_{j=1}^{i-1}[a_i < a_j]$$$, where the value of $$$[a_i < a_j]$$$ define as if $$$a_i < a_j$$$, the value is $$$1$$$, otherwise is $$$0$$$ (in other words, $$$v_i$$$ is equal to the number of elements greater than $$$a_i$$$ that are to the left of position $$$i$$$). Then Tokitsukaze went out to work.There are three naughty cats in Tokitsukaze's house. When she came home, she found the paper with the value sequence $$$v$$$ to be bitten out by the cats, leaving several holes, so that the value of some positions could not be seen clearly. She forgot what the original permutation $$$p$$$ was. She wants to know how many different permutations $$$p$$$ there are, so that the value sequence $$$v$$$ of the new permutation $$$a$$$ after exactly $$$k$$$ operations is the same as the $$$v$$$ written on the paper (not taking into account the unclear positions).Since the answer may be too large, print it modulo $$$998\,244\,353$$$. | 256 megabytes | // package c1678;
//
// Codeforces Round #789 (Div. 2) 2022-05-08 07:35
// F. Tokitsukaze and Permutations
// https://codeforces.com/contest/1678/problem/F
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// Tokitsukaze has a permutation p. She performed the following operation to p k times: in one
// operation, for each i from 1 to n - 1 in order, if p_i > p_{i+1}, swap p_i, p_{i+1}. After
// exactly k times of operations, Tokitsukaze got a new sequence a, obviously the sequence a is also
// a permutation.
//
// After that, Tokitsukaze wrote down the value sequence v of a on paper. Denote the value sequence
// v of the permutation a of length n as v_i=\sum_{j=1}^{i-1}[a_i < a_j], where the value of [a_i <
// a_j] define as if a_i < a_j, the value is 1, otherwise is 0 (in other words, v_i is equal to the
// number of elements greater than a_i that are to the left of position i). Then Tokitsukaze went
// out to work.
//
// There are three naughty cats in Tokitsukaze's house. When she came home, she found the paper with
// the value sequence v to be bitten out by the cats, leaving several holes, so that the value of
// some positions could not be seen clearly. She forgot what the original permutation p was. She
// wants to know how many different permutations p there are, so that the value sequence v of the
// new permutation a after k operations is the same as the v written on the paper (not taking into
// account the unclear positions).
//
// Since the answer may be too large, print it modulo 998,244,353.
//
// Input
//
// The first line contains a single integer t (1 <= t <= 1000)-- the number of test cases. Each test
// case consists of two lines.
//
// The first line contains two integers n and k (1 <= n <= 10^6; 0 <= k <= n-1)-- the length of the
// permutation and the exactly number of operations.
//
// The second line contains n integers v_1, v_2, ..., v_n (-1 <= v_i <= i-1)-- the value sequence v.
// v_i = -1 means the i-th position of v can't be seen clearly.
//
// It is guaranteed that the sum of n over all test cases does not exceed 10^6.
//
// Output
//
// For each test case, print a single integer-- the number of different permutations modulo
// 998,244,353.
//
// Example
/*
input:
3
5 0
0 1 2 3 4
5 2
-1 1 2 0 0
5 2
0 1 1 0 0
output:
1
6
6
*/
// Note
//
// In the first test case, only permutation p=[5,4,3,2,1] satisfies the constraint condition.
//
// In the second test case, there are 6 permutations satisfying the constraint condition, which are:
// * [3,4,5,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [3,5,4,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [4,3,5,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [4,5,3,2,1] -> [4,3,2,1,5] -> [3,2,1,4,5]
// * [5,3,4,2,1] -> [3,4,2,1,5] -> [3,2,1,4,5]
// * [5,4,3,2,1] -> [4,3,2,1,5] -> [3,2,1,4,5]
//
// So after exactly 2 times of swap they will all become a=[3,2,1,4,5], whose value sequence is
// v=[0,1,2,0,0].
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
public class C1678F {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int[] FACT = computeFactArray(1000000);
static int solve(int[] v, int k) {
int n = v.length;
myAssert(v[0] <= 0);
if (n == 1) {
return 1;
} else if (n == 2) {
if (k == 0) {
// v is 0 0 or 0 1
return v[1] == -1 ? 2 : 1;
} else {
myAssert(k == 1);
// v must be 0 0
return v[1] > 0 ? 0 : 2;
}
}
// As the last k element in a is n-k+1,...,n in that order
// last k element in v must be 0 or -1.
for (int i = 1; i <= k; i++) {
if (v[n-i] > 0) {
return 0;
}
}
if (k == n - 1) {
return FACT[n];
}
/* n = 9, k = 3
0 * * * * * 0 0 0 -> 362880
* 0 * * * * 0 0 0 -> 290304
* 1 * * * * 0 0 0 -> 72576
* * 0 * * * 0 0 0 -> 241920
* * 1 * * * 0 0 0 -> 60480
* * 2 * * * 0 0 0 -> 60480
* * * 0 * * 0 0 0 -> 207360
* * * 1 * * 0 0 0 -> 51840
* * * 2 * * 0 0 0 -> 51840
* * * 3 * * 0 0 0 -> 51840
* * * * 0 * 0 0 0 -> 181440
* * * * 1 * 0 0 0 -> 45360
* * * * 2 * 0 0 0 -> 45360
* * * * 3 * 0 0 0 -> 45360
* * * * 4 * 0 0 0 -> 45360
* * * * * 0 0 0 0 -> 161280 *6,*7,*8,*9 -> *6789 4*8!
* * * * * 1 0 0 0 -> 40320 *5 -> *5789 8!
* * * * * 2 0 0 0 -> 40320 *4 -> *4789 8!
* * * * * 3 0 0 0 -> 40320 *3 -> *3789 8!
* * * * * 4 0 0 0 -> 40320 *2 -> *2789 8!
* * * * * 5 0 0 0 -> 40320 *1 -> *1789 8!
* * * * 0 0 0 0 0 -> 80640 *56 *57 *58 *59 {6,7,8,9}P2 -> *56789 16 * 7!
* * * * 0 1 0 0 0 -> 20160 *65,*75,*85,*95 -> *65789 4*7!
* * * * 0 2 0 0 0 -> 20160 *64,*74,*84,*94 -> *64789 4*7!
* * * * 0 3 0 0 0 -> 20160 *63,*73,*83,*93 -> *64789 4*7!
* * * * 0 4 0 0 0 -> 20160 *62,*72,*82,*92 -> *64789 4*7!
* * * * 0 5 0 0 0 -> 20160 *61,*71,*81,*91 -> *64789 4*7!
* * * * 3 0 0 0 0 -> 20160 *26,*27,*28,*29 -> *26789 4*7!
* * * * 3 1 0 0 0 -> 5040 *25 -> *25789 7!
* * * * 3 2 0 0 0 -> 5040 *34 -> *34789 7!
* * * * 3 3 0 0 0 -> 5040 *23 -> *23789 7!
* * * * 3 4 0 0 0 -> 5040 *32 -> *32789 7!
* * * * 3 5 0 0 0 -> 5040 *31 -> *31789 7!
* * * * 4 0 0 0 0 -> 20160
* * * * 4 1 0 0 0 -> 5040
* * * * 4 2 0 0 0 -> 5040
* * * * 4 3 0 0 0 -> 5040
* * * * 4 4 0 0 0 -> 5040
* * * * 4 5 0 0 0 -> 5040
*/
int e = n - k - 1;
// 0 * * * * 3 0 0 0
// ^
// e
long ans = FACT[k+1];
for (int i = 1; i <= e; i++) {
long mul = 1;
if (v[i] > 0) {
// value [1,i] each has (k+i)!
} else if (v[i] == 0) {
// value 0 has (k+1) * (k+i)!
mul = mul * (k+1) % MOD;
} else {
myAssert(v[i] == -1);
// combine above cases:
// (i + k + 1) * (k+i)!
mul = i + k + 1;
}
ans = ans * mul % MOD;
if (test) {
System.out.format(" i:%d mul:%2d ans:%d\n", i, mul, ans);
}
}
return (int) ans;
}
static int[] computeFactArray(int n) {
int[] fact = new int[n+1];
fact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = (int) (((long) fact[i-1] * i) % MOD);
}
return fact;
}
static class Permutation {
int[] perm;
boolean checkedNext = true;
boolean hasNext = true;
// m is used in (n,k) to take the prefix from every m=(n-k)! permutations.
int m = 1;
// all permutations of n unique element
public Permutation(int n) {
this.perm = firstPerm(n);
}
// all permutations of k out of n elements
public Permutation(int n, int k) {
myAssert(n >= 1 && k > 0 && k <= n);
// (n-k)!
this.m = 1;
for (int i = 1; i <= n - k; i++) {
m *= i;
}
this.perm = firstPerm(n);
}
// Flexible permutation (combination) from given state. For example:
// 0,1,2,3,4 --- 120 permutations of 5 elements
// 1,0,0,0,0,0,0,1,1 --- 28 ways to select 3 out of 9 with first element always included
// 0,0,1,1,2,2 --- 90 ways to split 6 element into groups of 2,2,2
public Permutation(int[] state) {
this.perm = state;
}
boolean hasNext() {
if (!checkedNext) {
checkNext();
}
return hasNext;
}
private void checkNext() {
if (!checkedNext) {
for (int i = 0; i < m; i++) {
hasNext = nextPerm(perm);
}
checkedNext = true;
}
}
public int[] next() {
checkNext();
checkedNext = false;
return hasNext ? perm : null;
}
// Get all (remaining) permutations.
public List<int[]> getAll() {
List<int[]> all = new ArrayList<>();
while (hasNext()) {
next();
int[] one = new int[perm.length];
System.arraycopy(perm, 0, one, 0, perm.length);
all.add(one);
}
return all;
}
public static int[] firstPerm(int n) {
int[] perm = new int[n];
for (int i = 0; i < n; i++) {
perm[i] = i;
}
return perm;
}
// Gets next permutation from current one. For example:
// 1 2 2 3 3 3 4 4 4 4 =>
// 1 2 2 3 3 4 3 4 4 4 =>
// 1 2 2 3 3 4 4 3 4 4 =>
// 1 2 2 3 3 4 4 4 3 4 => ...
// 4 4 4 4 3 3 3 2 2 1
public static boolean nextPerm(int[] nums) {
int n = nums.length;
int i = n - 1;
while (i > 0 && nums[i-1] >= nums[i]) {
i--;
}
if (i == 0) {
return false;
}
i--;
int j = n - 1;
while (nums[j] <= nums[i]) {
j--;
}
swap(nums, i ,j);
i++;
j = n - 1;
while (i < j) {
swap(nums, i ,j);
i++;
j--;
}
return true;
}
static void swap(int[] idxes, int i, int j) {
int t = idxes[i];
idxes[i] = idxes[j];
idxes[j] = t;
}
public static List<int[]> getAllPerms(int n, int k) {
return new Permutation(n,k).getAll();
}
}
static void reduce(int[] p) {
int n = p.length;
for (int i = 0; i < n - 1; i++) {
if (p[i] > p[i+1]) {
int t = p[i];
p[i] = p[i+1];
p[i+1] = t;
}
}
}
static void reduce(int[] p, int k) {
for (int i = 0; i < k; i++) {
reduce(p);
}
}
static void getCount(int[] p, int[] ct) {
int n = p.length;
Arrays.fill(ct, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (p[j] > p[i]) {
ct[i]++;
}
}
}
}
static String trace(int[] a) {
StringBuilder sb = new StringBuilder();
sb.append('{');
for (int v : a) {
if (sb.length() > 1) {
sb.append(',');
}
sb.append(v);
}
sb.append('}');
return sb.toString();
}
static void increment(int[] ct, List<int[]> cts, List<Integer> ctv) {
int n = ct.length;
for (int i = 0; i < cts.size(); i++) {
boolean equal = true;
int[] v = cts.get(i);
for (int j = 0; j < n; j++) {
if (v[j] != ct[j]) {
equal = false;
break;
}
}
if (equal) {
ctv.set(i, ctv.get(i) + 1);
return;
}
}
int[] arr = new int[n];
System.arraycopy(ct, 0, arr, 0, n);
cts.add(arr);
ctv.add(1);
}
static void test(int exp, int[] v, int k) {
int ans = solve(v, k);
System.out.format("%s %d => %d%s\n", trace(v), k, ans, ans == exp ? "" : " Expected " + exp);
myAssert(ans == exp);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
// incubate();
test(120, new int[] {0,-1,0,0,0}, 4);
test(161280, new int[] {-1,-1,-1,-1,-1,0,0,0,0}, 3);
test(181440, new int[] {-1,-1,-1,-1,0,-1,0,0,0}, 3);
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
private static void incubate() {
int n = 9;
int k = 3;
List<int[]> all = Permutation.getAllPerms(n, n);
StringBuilder sb = new StringBuilder();
int index = 0;
int[] ct = new int[n];
List<int[]> cts = new ArrayList<>();
List<Integer> ctv = new ArrayList<>();
for (int[] p : all) {
index++;
sb.append(String.format("%6d ", index));
sb.append(trace(p));
reduce(p, k);
sb.append(" -> ");
sb.append(trace(p));
getCount(p, ct);
sb.append(" -> ");
sb.append(trace(ct));
sb.append('\n');
increment(ct, cts, ctv);
}
System.out.print(sb.toString());
for (int i = 0; i < cts.size(); i++) {
System.out.format(" %4d %s %d\n", i+1, trace(cts.get(i)), ctv.get(i));
}
for (int i = 0; i < n - k; i++) {
char[] ca = new char[2 * n - 1];
Arrays.fill(ca, ' ');
for (int j = 0; j <= i; j++) {
int v = 0;
for (int h = 0; h < n; h++) {
ca[2*h] = h < n - k ? '*' : '0';
}
ca[2*i] = (char)('0' + j);
for (int h = 0; h < cts.size(); h++) {
if (cts.get(h)[i] == j) {
v += ctv.get(h);
}
}
System.out.format(" %s -> %d\n", new String(ca), v);
}
}
int[] ct40 = new int[n];
for (int i = 0; i < cts.size(); i++) {
if (cts.get(i)[4] == 0) {
ct40[cts.get(i)[5]] += ctv.get(i);
}
}
System.out.format(" ct40: %s\n", trace(ct40));
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int k = in.nextInt();
int[] v = new int[n];
for (int i = 0; i < n; i++) {
v[i] = in.nextInt();
}
int ans = solve(v, k);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n\n5 0\n\n0 1 2 3 4\n\n5 2\n\n-1 1 2 0 0\n\n5 2\n\n0 1 1 0 0"] | 2 seconds | ["1\n6\n6"] | NoteIn the first test case, only permutation $$$p=[5,4,3,2,1]$$$ satisfies the constraint condition.In the second test case, there are $$$6$$$ permutations satisfying the constraint condition, which are: $$$[3,4,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[3,5,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,3,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,5,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,3,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,4,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ So after exactly $$$2$$$ times of swap they will all become $$$a=[3,2,1,4,5]$$$, whose value sequence is $$$v=[0,1,2,0,0]$$$. | Java 11 | standard input | [
"dp",
"math"
] | f2b2d12ab1c8a511d2ca550faa9768d4 | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^6$$$; $$$0 \leq k \leq n-1$$$) — the length of the permutation and the exactly number of operations. The second line contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$-1 \leq v_i \leq i-1$$$) — the value sequence $$$v$$$. $$$v_i = -1$$$ means the $$$i$$$-th position of $$$v$$$ can't be seen clearly. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$. | 2,500 | For each test case, print a single integer — the number of different permutations modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 3074b98572e7c517c47456c61de600e1 | train_108.jsonl | 1652020500 | Tokitsukaze has a permutation $$$p$$$. She performed the following operation to $$$p$$$ exactly $$$k$$$ times: in one operation, for each $$$i$$$ from $$$1$$$ to $$$n - 1$$$ in order, if $$$p_i$$$ > $$$p_{i+1}$$$, swap $$$p_i$$$, $$$p_{i+1}$$$. After exactly $$$k$$$ times of operations, Tokitsukaze got a new sequence $$$a$$$, obviously the sequence $$$a$$$ is also a permutation.After that, Tokitsukaze wrote down the value sequence $$$v$$$ of $$$a$$$ on paper. Denote the value sequence $$$v$$$ of the permutation $$$a$$$ of length $$$n$$$ as $$$v_i=\sum_{j=1}^{i-1}[a_i < a_j]$$$, where the value of $$$[a_i < a_j]$$$ define as if $$$a_i < a_j$$$, the value is $$$1$$$, otherwise is $$$0$$$ (in other words, $$$v_i$$$ is equal to the number of elements greater than $$$a_i$$$ that are to the left of position $$$i$$$). Then Tokitsukaze went out to work.There are three naughty cats in Tokitsukaze's house. When she came home, she found the paper with the value sequence $$$v$$$ to be bitten out by the cats, leaving several holes, so that the value of some positions could not be seen clearly. She forgot what the original permutation $$$p$$$ was. She wants to know how many different permutations $$$p$$$ there are, so that the value sequence $$$v$$$ of the new permutation $$$a$$$ after exactly $$$k$$$ operations is the same as the $$$v$$$ written on the paper (not taking into account the unclear positions).Since the answer may be too large, print it modulo $$$998\,244\,353$$$. | 256 megabytes |
import java.util.*;
import java.util.function.BiFunction;
import java.io.*;
// you can compare with output.txt and expected out
public class Round789F {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
final static long MOD = 998_244_353;
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
Round789F sol = new Round789F();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = true;
initIO(isFileIO);
//simulate();
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
int n = in.nextInt();
int k = in.nextInt();
int[] v = in.nextIntArray(n);
if(isDebug){
out.printf("Test %d\n", i);
}
long ans = solve(v, k);
out.println(ans);
if(isDebug)
out.flush();
}
in.close();
out.close();
}
private void simulate() {
int N = 5;
int k = 5;
int[] p = new int[N];
for(int i=0; i<N; i++)
p[i] = i;
Random R = new Random();
for(int T = 0; T < 10; T++) {
int m = R.nextInt(N*N*N);
for(int i=0; i<m; i++)
nextPermutation(p);
for(int round=0; round<k; round++) {
out.printAns(p);
int[] v = new int[N];
for(int i=0; i<N; i++) {
int cnt = 0;
for(int j=0; j<i; j++) {
if(p[j] > p[i])
cnt++;
}
v[i] = cnt;
}
out.print(" // ");
out.printlnAns(v);
out.flush();
for(int j=0; j<N-1; j++)
if(p[j] > p[j+1]) {
int temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
out.println("next");
}
}
static void nextPermutation(int[] a) {
int left;
int n = a.length;
for (left = n-2; left >= 0 && a[left] >= a[left+1]; left--);
// left == -1 or nums[left] < nums[left+1]
if (left == -1)
reverse(a, 0, n-1);
else {
for (int i = n-1; i>=0; i--)
if (a[i] > a[left]) {
int temp = a[i];
a[i] = a[left];
a[left] = temp;
break;
}
reverse(a, left+1, n-1);
}
}
static void reverse(int[] a, int left, int right) {
int i = left;
int j = right;
while(i < j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
private long solve(int[] v, int k) {
int n = v.length;
// vi = # of j < i s.t. aj > ai
// vi = -1 -> torn apart
// in one operation
// p0 p1 ... pi -> p1 p2 ... p0 pi
// when nli(0) = i, i.e., next larger element of p0 is pi.
// then this repeats for pi, and so on
// this is one step of the bubble sort!
// what happens for k operations?
// k extra largest elements are placed at the end
// so if the original permutation had m largest elements at the end
// we would have m+k largest elements after k operations
// 1 2 3 4 5
// k = 2
// 3 2 1 // 4 5
// 2 3 1 // 4 5
// 4 1 3 2 // 5
//
// [3,4,5,2,1] �� [3,4,2,1,5] �� [3,2,1,4,5]
// [0 0 0 3 4] -> [0 0 2 3 0] -> [0 1 2 0 0]
// so on average, n!/(n-k)! permutations should become v
// what's important is change of v
// run simulate then notice that v(i) = x -> v(i-1) = max(x-1, 0) after the operation
// for each 0, we have a choice at which operation to make it 1
//
long ans = 1;
for(int i=n-1; i>=0; i--) {
if(i >= n-k) {
// problem statement is bad... how can a cat make v bad?
assert(v[i] <= 0);
if(v[i] > 0)
return 0;
ans *= (n-1-i)+1;
ans %= MOD;
}
else if(v[i] == 0) {
ans *= k+1;
ans %= MOD;
}
else if(v[i] == -1) {
ans *= (k+1)+i; // could be v[i] = 1 to i as well
ans %= MOD;
}
}
return ans;
// long[] fac = new long[n+1];
// fac[0] = 0;
// for(int i=1; i<=n; i++)
// fac[i] = fac[i-1]*i % MOD;
//
// long ans = 0;
// for(int i=n-k-1; i>=0; i--) {
// if(v[i] == 0)
// continue;
// ans += fac[i]*inverse(fac[i-k]);
// ans = ans >= MOD? ans-MOD: ans;
// if(v[i] > 0)
// break;
// }
// int[] p = new int[n];
//
// int[] a = new int[n];
// Arrays.fill(a, 1);
//
// SegmentTree remaining = new SegmentTree((x, y) -> x+y, a, 0);
//
// for(int i=n-1; i>=0; i--) {
// // need to find an index k s.t. sum[k+1..n-1] = key and a[k] = 1
// // i.e., a largest index k s.t. sum[k..n-1] = key+1
// int left = 0;
// int right = n-1;
// int key = v[i]+1;
// while(left < right) {
// int mid = (left+right+1)/2;
// int val = remaining.getRange(mid, n-1);
// if(val >= key) {
// left = mid;
// }
// else { // val < key
// right = mid-1;
// }
// }
// p[i] = left;
// remaining.update(left, 0);
// }
// out.printlnAns(p);
}
class SegmentTree {
BiFunction<Integer, Integer, Integer> function;
int identity;
int n;
int[] tree;
public SegmentTree(BiFunction<Integer, Integer, Integer> function, int[] arr, int identity){
this.function = function;
this.identity = identity;
this.n = arr.length;
int m = 1;
while(m < n+1){
m <<= 1;
}
m <<= 1;
tree = new int[m];
Arrays.fill(tree, identity);
for(int i=0; i<n; i++){
update(i, arr[i]);
}
}
public void update(int idx, int val){
update(idx+1, val, 1, 1, n);
}
private int update(int idx, int val, int treeIdx, int left, int right) {
// no need to update, not containing idx
if(left > idx || idx > right)
return tree[treeIdx];
// base case
if(left == right){
tree[treeIdx] = val;
return val;
}
// update [left, right] containing idx
int mid = (left+right)/2;
int val1 = update(idx, val, treeIdx*2, left, mid);
int val2 = update(idx, val, treeIdx*2+1, mid+1, right);
val = function.apply(val1, val2);
tree[treeIdx] = val;
return val;
}
public int getRange(int start, int end){
return getRange(start+1, end+1, 1, 1, n);
}
private int getRange(int start, int end, int treeIdx, int left, int right) {
// guaranteed: left <= start <= end <= right
// alternative: just return identity for the case of out of range
if(start == left && end == right)
return tree[treeIdx];
int mid = (left+right)/2;
if(end <= mid)
return getRange(start, end, treeIdx*2, left, mid);
else if(start <= mid){
int val1 = getRange(start, mid, treeIdx*2, left, mid);
int val2 = getRange(mid+1, end, treeIdx*2+1, mid+1, right);
return function.apply(val1, val2);
}
else
return getRange(start, end, treeIdx*2+1, mid+1, right);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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[][] nextTreeEdges(int n, int offset){
int[][] e = new int[n-1][2];
for(int i=0; i<n-1; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
int[][] nextGraphEdges(){
return nextGraphEdges(0);
}
int[][] nextGraphEdges(int offset) {
int m = nextInt();
int[][] e = new int[m][2];
for(int i=0; i<m; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
public void printAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
print(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
print(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
int[] inIdx = new int[n];
int[] outIdx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][outIdx[u]++] = v;
inNeighbors[v][inIdx[v]++] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
int[] idx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][idx[u]++] = v;
neighbors[v][idx[v]++] = u;
}
return neighbors;
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["3\n\n5 0\n\n0 1 2 3 4\n\n5 2\n\n-1 1 2 0 0\n\n5 2\n\n0 1 1 0 0"] | 2 seconds | ["1\n6\n6"] | NoteIn the first test case, only permutation $$$p=[5,4,3,2,1]$$$ satisfies the constraint condition.In the second test case, there are $$$6$$$ permutations satisfying the constraint condition, which are: $$$[3,4,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[3,5,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,3,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,5,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,3,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,4,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ So after exactly $$$2$$$ times of swap they will all become $$$a=[3,2,1,4,5]$$$, whose value sequence is $$$v=[0,1,2,0,0]$$$. | Java 11 | standard input | [
"dp",
"math"
] | f2b2d12ab1c8a511d2ca550faa9768d4 | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^6$$$; $$$0 \leq k \leq n-1$$$) — the length of the permutation and the exactly number of operations. The second line contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$-1 \leq v_i \leq i-1$$$) — the value sequence $$$v$$$. $$$v_i = -1$$$ means the $$$i$$$-th position of $$$v$$$ can't be seen clearly. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$. | 2,500 | For each test case, print a single integer — the number of different permutations modulo $$$998\,244\,353$$$. | standard output | |
PASSED | 1cccc94ee2d132b0fd05e832e175d5ff | train_108.jsonl | 1652020500 | Tokitsukaze has a permutation $$$p$$$. She performed the following operation to $$$p$$$ exactly $$$k$$$ times: in one operation, for each $$$i$$$ from $$$1$$$ to $$$n - 1$$$ in order, if $$$p_i$$$ > $$$p_{i+1}$$$, swap $$$p_i$$$, $$$p_{i+1}$$$. After exactly $$$k$$$ times of operations, Tokitsukaze got a new sequence $$$a$$$, obviously the sequence $$$a$$$ is also a permutation.After that, Tokitsukaze wrote down the value sequence $$$v$$$ of $$$a$$$ on paper. Denote the value sequence $$$v$$$ of the permutation $$$a$$$ of length $$$n$$$ as $$$v_i=\sum_{j=1}^{i-1}[a_i < a_j]$$$, where the value of $$$[a_i < a_j]$$$ define as if $$$a_i < a_j$$$, the value is $$$1$$$, otherwise is $$$0$$$ (in other words, $$$v_i$$$ is equal to the number of elements greater than $$$a_i$$$ that are to the left of position $$$i$$$). Then Tokitsukaze went out to work.There are three naughty cats in Tokitsukaze's house. When she came home, she found the paper with the value sequence $$$v$$$ to be bitten out by the cats, leaving several holes, so that the value of some positions could not be seen clearly. She forgot what the original permutation $$$p$$$ was. She wants to know how many different permutations $$$p$$$ there are, so that the value sequence $$$v$$$ of the new permutation $$$a$$$ after exactly $$$k$$$ operations is the same as the $$$v$$$ written on the paper (not taking into account the unclear positions).Since the answer may be too large, print it modulo $$$998\,244\,353$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class G {
static FastScanner fs = new FastScanner();
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder("");
static Scanner scn = new Scanner(System.in);
static int md = 998244353;
public static void main(String[] args) {
int t = fs.nextInt();
//int t = 1;
for (int tt = 0; tt < t; tt++) {
int n = fs.nextInt();
int m = fs.nextInt();
int[] a = new int[n+1];
for (int i = 1; i <= n; i++) a[i] = fs.nextInt();
boolean ok = false;
for (int i = n-m+1; i <= n; i++) {
if (a[i] == -1) a[i] = 0;
if (a[i] != 0) {
ok = true;
sb.append("0\n");
break;
}
}
if (ok) continue;
long ans = 1;
for (int i = n; i > m; i--) {
a[i] = a[i-m];
if (a[i] > 0) a[i] += m;
else if (a[i] == 0) ans = ans * (m+1)%md;
}
for (int i = 1; i <= m; i++) a[i] = -1;
for (int i = 1; i <= n; i++) if (a[i] == -1) ans = ans * i%md;
sb.append(ans + "\n");
}
pw.print(sb.toString());
pw.close();
}
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) {}return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) {a[i] = nextInt();} return a;}
}
} | Java | ["3\n\n5 0\n\n0 1 2 3 4\n\n5 2\n\n-1 1 2 0 0\n\n5 2\n\n0 1 1 0 0"] | 2 seconds | ["1\n6\n6"] | NoteIn the first test case, only permutation $$$p=[5,4,3,2,1]$$$ satisfies the constraint condition.In the second test case, there are $$$6$$$ permutations satisfying the constraint condition, which are: $$$[3,4,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[3,5,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,3,5,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[4,5,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,3,4,2,1]$$$ $$$\rightarrow$$$ $$$[3,4,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ $$$[5,4,3,2,1]$$$ $$$\rightarrow$$$ $$$[4,3,2,1,5]$$$ $$$\rightarrow$$$ $$$[3,2,1,4,5]$$$ So after exactly $$$2$$$ times of swap they will all become $$$a=[3,2,1,4,5]$$$, whose value sequence is $$$v=[0,1,2,0,0]$$$. | Java 11 | standard input | [
"dp",
"math"
] | f2b2d12ab1c8a511d2ca550faa9768d4 | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^6$$$; $$$0 \leq k \leq n-1$$$) — the length of the permutation and the exactly number of operations. The second line contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$-1 \leq v_i \leq i-1$$$) — the value sequence $$$v$$$. $$$v_i = -1$$$ means the $$$i$$$-th position of $$$v$$$ can't be seen clearly. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$. | 2,500 | For each test case, print a single integer — the number of different permutations modulo $$$998\,244\,353$$$. | standard output | |
PASSED | a93e93de5d8538ec7e0017c034a90ac9 | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static long INF = 2000000000000000010l;
static int fx[][] = {{-1,0},{0,1},{1,0},{0,-1},{-1,-1},{1,1},{1,-1},{-1,1}};
public static void main(String[] args) throws IOException {
int t=1;
t = cin.nextInt();
while (t-- > 0)
{
// csh();
solve();
out.flush();
}
out.close();
}
static boolean vis[];
static int[]val,b,a,gx=new int[100010];
public static void solve() {
int n=cin.nextInt();
a=new int[n+1];
b=new int[n+1];
for(int i=1;i<=n;i++){
gx[i]=i;
a[i]=cin.nextInt();
}
for(int i=1;i<=n;i++){
b[i]=cin.nextInt();
}
for(int i=1;i<=n;i++){
if(find(a[i])!=find(b[i])){
gx[find(a[i])]=find(b[i]);
}
}
val=new int[n+1];
for(int i=1;i<=n;i++){
val[find(i)]++;
}
//dfs(0,0,a[1],0);
// out.println(Arrays.toString(val));
Arrays.sort(val);
ArrayList<Integer>w=new ArrayList<Integer>();
for(int i=n;i>=1;i--){
if(val[i]!=0){
w.add(val[i]);
}else{
break;
}
}
long as=0,x=0;
for(int i=w.size()-1;i>=0;i--){
// out.println(w.get(i));
int z=w.get(i);
z=z/2;
z=z*2;
// out.println(z);
as+=(n-z/2-x)*(z);
x+=z;
}
out.println(as);
}
static int find(int x){
if(gx[x]!=x) gx[x]=find(gx[x]);
return gx[x];
}
static class Node {
int x, y, k;
Node(){}
public Node(int x, int y, int k) {
this.x = x;
this.y = y;
this.k = k;
}
}
static void csh() {
}
static long cnm(int a, int b) {
long sum = 1;
int i = a, j = 1;
while (j <= b) {
sum = sum * i / j;
i--;
j++;
}
return sum;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
static void gbSort(int[] a, int l, int r) {
if (l < r) {
int m = (l + r) >> 1;
gbSort(a, l, m);
gbSort(a, m + 1, r);
int[] t = new int[r - l + 1];
int idx = 0, i = l, j = m + 1;
while (i <= m && j <= r){
//cnt++;
if (a[i] <= a[j])
t[idx++] = a[i++];
else{
t[idx++] = a[j++];
// cnt += m -i +1;//nx
}
}
while (i <= m)
t[idx++] = a[i++];
while (j <= r)
t[idx++] = a[j++];
for (int z = 0; z < t.length; z++)
a[l + z] = t[z];
}
}
static FastScanner cin = new FastScanner(System.in);
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in), 16384);
eat("");
}
public void eat(String s) {
st = new StringTokenizer(s);
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
public boolean hasNext() {
while (!st.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
eat(s);
}
return true;
}
public String next() {
hasNext();
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public BigDecimal nextBigDecimal() {
return new BigDecimal(next());
}
}
} | Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 775ff0efa04198aafea318472e7394d4 | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
/*
* Author: Atuer
*/
public class Main
{
// ==== Solve Code ====//
static int INF = 2000000010;
public static void csh()
{
}
public static void main(String[] args) throws IOException
{
// csh();
int t = in.nextInt();
while (t-- > 0)
{
solve();
out.flush();
}
out.close();
}
public static void solve()
{
int n = in.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
for (int i = 0; i < n; i++)
b[i] = in.nextInt();
f = new int[n + 1];
for (int i = 1; i <= n; i++)
f[i] = i;
for (int i = 0; i < n; i++)
{
int fa = find(a[i]);
int fb = find(b[i]);
if (fa != fb)
f[fa] = fb;
}
int[] cot = new int[n + 1];
for (int i = 1; i <= n; i++)
cot[find(f[i])]++;
long ans = 0;
long res = n - 1;
for (int i = 1; i <= n; i++)
{
int t = cot[i] / 2;
while (t-- > 0)
{
ans += res;
res -= 2;
}
}
out.println(ans * 2);
}
static int[] f;
private static int find(int x)
{
if (f[x] != x)
f[x] = find(f[x]);
return f[x];
}
public static class Node
{
int x, y, k;
public Node(int x, int y, int k)
{
this.x = x;
this.y = y;
this.k = k;
}
}
// ==== Solve Code ====//
// ==== Template ==== //
public static long cnm(int a, int b)
{
long sum = 1;
int i = a, j = 1;
while (j <= b)
{
sum = sum * i / j;
i--;
j++;
}
return sum;
}
public static int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
public static int lcm(int a, int b)
{
return (a * b) / gcd(a, b);
}
public static void gbSort(int[] a, int l, int r)
{
if (l < r)
{
int m = (l + r) >> 1;
gbSort(a, l, m);
gbSort(a, m + 1, r);
int[] t = new int[r - l + 1];
int idx = 0, i = l, j = m + 1;
while (i <= m && j <= r)
if (a[i] <= a[j])
t[idx++] = a[i++];
else
t[idx++] = a[j++];
while (i <= m)
t[idx++] = a[i++];
while (j <= r)
t[idx++] = a[j++];
for (int z = 0; z < t.length; z++)
a[l + z] = t[z];
}
}
// ==== Template ==== //
// ==== IO ==== //
static InputStream inputStream = System.in;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(System.out);
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();
}
boolean hasNext()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e)
{
return false;
// TODO: handle exception
}
}
return true;
}
public String nextLine()
{
String str = null;
try
{
str = reader.readLine();
} catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public Double nextDouble()
{
return Double.parseDouble(next());
}
public BigInteger nextBigInteger()
{
return new BigInteger(next());
}
public BigDecimal nextBigDecimal()
{
return new BigDecimal(next());
}
}
// ==== IO ==== //
} | Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 29f60aaed3d3642857a82ceb55a9bc7e | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes |
import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
public static long dfs(int[] b, int[] index, boolean[] visited, int i){
if(visited[i]){
return 0;
}
visited[i] = true;
return 1 + dfs(b, index, visited, index[b[i]]);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0){
int n = sc.nextInt();
int[] index = new int[n + 1];
int[] b = new int[n];
IntStream.range(0, n).forEach(i -> {
index[sc.nextInt()] = i;
});
IntStream.range(0, n).forEach(i ->{
b[i] = sc.nextInt();
});
boolean[] visited = new boolean[n];
long nPeaksValleys = 0;
for(int i = 0; i < n; i++){
nPeaksValleys += dfs(b, index, visited, i) / 2l;
}
System.out.println(2l * nPeaksValleys * ((long)n - nPeaksValleys));
}
}
}
| Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | c8190ea3271e908b13c55b9083a09c6e | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.stream.IntStream;
import java.io.ByteArrayOutputStream;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.FileNotFoundException;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author tauros
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
RealFastReader in = new RealFastReader(inputStream);
RealFastWriter out = new RealFastWriter(outputStream);
CF1678E solver = new CF1678E();
solver.solve(1, in, out);
out.close();
}
static class CF1678E {
public void solve(int testNumber, RealFastReader in, RealFastWriter out) {
int cases = in.ni();
while (cases-- > 0) {
int n = in.ni();
int[][] pos = new int[2][n + 1], nums = new int[2][n + 1];
for (int i = 0; i < 2; i++) {
for (int j = 1; j <= n; j++) {
nums[i][j] = in.ni();
}
}
int[] next = new int[n + 1], size = new int[n], head = new int[n];
for (int i = 1; i <= n; i++) {
pos[0][nums[0][i]] = i;
pos[1][nums[1][i]] = i;
}
boolean[] vis = new boolean[n + 1];
int idx = 0;
for (int i = 1; i <= n; i++) {
if (!vis[nums[0][i]]) {
int cur = 0, iter = nums[0][i];
head[idx] = iter;
while (!vis[iter]) {
vis[iter] = true;
size[idx]++;
next[iter] = nums[cur ^ 1][pos[cur][iter]];
iter = nums[cur][pos[cur][next[iter]]];
}
idx++;
}
}
int min = 1, max = n, oddNum = 0;
long ans = 0;
for (int i = 0; i < idx; i++) {
if (size[i] == 1) {
continue;
}
if ((size[i] & 1) == 0) {
int val = max--;
int cur = val;
for (int cnt = 1; cnt < size[i]; cnt++) {
int pre = cur;
cur = (cnt & 1) == 1 ? min++ : max--;
ans += Math.abs(pre - cur);
}
ans += Math.abs(cur - val);
} else {
int val = max--;
int cur = val;
for (int cnt = 1; cnt < size[i] - 1; cnt++) {
int pre = cur;
cur = (cnt & 1) == 1 ? min++ : max--;
ans += Math.abs(pre - cur);
}
ans += val - cur;
}
}
out.println(ans);
}
out.flush();
}
}
static class RealFastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private OutputStream out;
private Writer writer;
private int ptr = 0;
private RealFastWriter() {
out = null;
}
public RealFastWriter(Writer writer) {
this.writer = new BufferedWriter(writer);
out = new ByteArrayOutputStream();
}
public RealFastWriter(OutputStream os) {
this.out = os;
}
public RealFastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public RealFastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) {
innerflush();
}
return this;
}
public RealFastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) {
innerflush();
}
});
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) {
return 19;
}
if (l >= 100000000000000000L) {
return 18;
}
if (l >= 10000000000000000L) {
return 17;
}
if (l >= 1000000000000000L) {
return 16;
}
if (l >= 100000000000000L) {
return 15;
}
if (l >= 10000000000000L) {
return 14;
}
if (l >= 1000000000000L) {
return 13;
}
if (l >= 100000000000L) {
return 12;
}
if (l >= 10000000000L) {
return 11;
}
if (l >= 1000000000L) {
return 10;
}
if (l >= 100000000L) {
return 9;
}
if (l >= 10000000L) {
return 8;
}
if (l >= 1000000L) {
return 7;
}
if (l >= 100000L) {
return 6;
}
if (l >= 10000L) {
return 5;
}
if (l >= 1000L) {
return 4;
}
if (l >= 100L) {
return 3;
}
if (l >= 10L) {
return 2;
}
return 1;
}
public RealFastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE) {
innerflush();
}
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public RealFastWriter writeln(long x) {
return write(x).writeln();
}
public RealFastWriter writeln() {
return write((byte) '\n');
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
if (writer != null) {
writer.write(((ByteArrayOutputStream) out).toString());
out = new ByteArrayOutputStream();
writer.flush();
} else {
out.flush();
}
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public RealFastWriter println(long x) {
return writeln(x);
}
public void close() {
flush();
try {
out.close();
} catch (Exception e) {
}
}
}
static class RealFastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
public int lenbuf = 0;
public int ptrbuf = 0;
public RealFastReader(final InputStream is) {
this.is = is;
}
public int readByte() {
if (lenbuf == -1) {
throw new InputMismatchException();
}
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) {
return -1;
}
}
return inbuf[ptrbuf++];
}
public int ni() {
return (int) nl();
}
public long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
}
| Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 72b2788c3c3e1992aa699b0fe0dffdb3 | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class E {
public static void main(String[]args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int t=sc.nextInt();
a:while(t-->0) {
int n=sc.nextInt();
int[]a=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
int[]b=new int[n];
for(int i=0;i<n;i++)b[i]=sc.nextInt();
UnionFind uf=new UnionFind(n);
for(int i=0;i<n;i++)uf.unionSet(a[i]-1, b[i]-1);
int cnt=0;
boolean[]vis=new boolean[n];
for(int i=0;i<n;i++) {
int p=uf.findSet(i);
if(!vis[p]) {
cnt+=uf.sizeOfSet(p)/2;
vis[p]=true;
}
}
long ans=0l;
for(int mrg=2*n-2;cnt>0;cnt--,mrg-=4) {
ans+=mrg;
}
out.println(ans);
}
out.close();
}
static class UnionFind {
int[] p, rank, setSize;
int numSets;
public UnionFind(int N)
{
p = new int[numSets = N];
rank = new int[N];
setSize = new int[N];
for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; }
}
public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); }
public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); }
public void unionSet(int i, int j)
{
if (isSameSet(i, j))
return;
numSets--;
//if(numSets==1)total=0;
int x = findSet(i), y = findSet(j);
if(rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; }
else
{ p[x] = y; setSize[y] += setSize[x];
if(rank[x] == rank[y]) rank[y]++;
}
}
public int numDisjointSets() { return numSets; }
public int sizeOfSet(int i) { return setSize[findSet(i)]; }
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
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 boolean hasNext() {return st.hasMoreTokens();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready(); }
}
}
| Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 22e07f747078243d1efb8dc904ba15ea | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution
{
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static int sum(int idx , int bit[])
{
int sum = 0;
while(idx > 0)
{
sum += bit[idx];
idx -= idx&(-idx);
}
return sum;
}
static void update(int n , int idx , int val , int bit[])
{
while(idx <= n)
{
bit[idx] += val;
idx += idx&(-idx);
}
}
static long mod = 1000000007;
static long pow(long a , long b)
{
if(b == 0)
return 1;
long ans = pow(a,b/2);
if(b%2 == 0)
return ans*ans%mod;
return ans*ans%mod*a%mod;
}
static long f(long v)
{
if(v <= 0)
return 0;
return (v*(v+1)/2);
}
static int parent(int a , int p[])
{
if(a == p[a])
return a;
return p[a] = parent(p[a],p);
}
static void union(int a , int b , int p[] , int sz[])
{
a = parent(a,p);
b = parent(b,p);
if(a == b)
return;
if(sz[a] < sz[b])
{
int tmp = a;
a = b;
b = tmp;
}
sz[a] += sz[b];
p[b] = a;
}
public static void main(String []args) throws IOException
{
Reader sc = new Reader();
int t = sc.nextInt();
while(t-- > 0)
{
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
int pos1[] = new int[n+1];
int pos2[] = new int[n+1];
for(int i = 0 ; i < n ; i++)
{
a[i] = sc.nextInt();
pos1[a[i]] = i;
}
for(int i = 0 ; i < n ; i++)
{
b[i] = sc.nextInt();
pos2[b[i]] = i;
}
int p[] = new int[n];
int sz[] = new int[n];
for(int i = 0 ; i < n ; i++)
{
p[i] = i;
sz[i] = 1;
}
for(int i = 0 ; i < n ; i++)
{
union(i,pos1[b[i]],p,sz);
union(i,pos2[a[i]],p,sz);
}
ArrayList<Integer> arr = new ArrayList<Integer>();
int cnt[] = new int[n+1];
for(int i = 0 ; i < n ; i++)
{
int x = parent(i,p);
if(cnt[x] == 0)
{
arr.add(sz[x]);
cnt[x] = 1;
}
}
long c = 0;
for(Integer cc : arr)
{
c += cc/2;
}
long ans = 2*(long)c*(long)(n-c);
System.out.println(ans);
}
}
} | Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | b8eee2e533dd9b319e9c05f3fb6abfef | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
//--------------------------INPUT READER---------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(long nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os);
}
public void p(int i) {w.println(i);}
public void p(long l) {w.println(l);}
public void p(double d) {w.println(d);}
public void p(String s) { w.println(s);}
public void pr(int i) {w.print(i);}
public void pr(long l) {w.print(l);}
public void pr(double d) {w.print(d);}
public void pr(String s) { w.print(s);}
public void pl() {w.println();}
public void close() {w.close();}
}
//-----------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static long mod = 1000000007;
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
ADMIN_MODE();
int t = sc.ni();while(t-->0)
solve();
w.close();
}
static long[] sum(long l, long r, long size) {
long a = r-l;
long n = size-1;
if(size%2==1)n--;
long sum = (n * ((2*a + ((n-1)*-1))))/2;
r-=size/2;
sum+=(r+1)-l;
l+=size/2;
return new long[] {sum, l, r};
}
static void solve() throws IOException {
int n = sc.ni();
int[] a = sc.na(n), b = sc.na(n);
uf uf = new uf(n);
for(int i = 0; i < n; i++) {
uf.unify(a[i], b[i]);
}
TreeMap<Integer, Integer> hm = new TreeMap<>();
for(int i = 0; i < n; i++) {
int pt = uf.find(i+1);
hm.put(pt, hm.getOrDefault(pt, 0)+1);
}
int l = 1, r = n;
long ans = 0;
while(hm.size() > 0) {
int key = hm.firstKey();
int cSize = hm.get(key);
hm.remove(key);
if(cSize == 1) continue;
long aa = r-l;
long nn = cSize-1;
if(cSize%2==1)nn--;
long sum = (nn * ((2*aa + ((nn-1)*-1))))/2;
r-=cSize/2;
sum+=(r+1)-l;
l+=cSize/2;
ans += sum;
}
w.p(ans);
}
static class uf {
int[] id, sz; int comps;
// 0 to n
public uf(int n) {
id = new int[n+1]; sz = new int[n+1];
comps = n+1;
for (int i = 0; i < n + 1; i++) {
id[i] = i;
}
Arrays.fill(sz, 1);
}
public int find(int a) {
return id[a]=(id[a]==a?a:find(id[a]));
}
public boolean con(int a, int b) {return find(a)==find(b);}
public int size(int a) {return sz[find(a)];}
public int comps() {return comps;}
public void unify(int a, int b) {
a = find(a); b = find(b);
if(a==b)return;
if(sz[a] >= sz[b]) {
id[b] = a;
sz[a] += sz[b];
} else {
id[a] = b;
sz[b] += sz[a];
}
comps--;
}
}
} | Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | f66a0a70c8f4e2ab3b248d64708d735f | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.util.*;
import java.io.*;
// res.append("Case #"+(p+1)+": "+hh+" \n");
////***************************************************************************
/* public class E_Gardener_and_Tree implements Runnable{
public static void main(String[] args) throws Exception {
new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start();
}
public void run(){
WRITE YOUR CODE HERE!!!!
JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!!
}
}
*/
/////**************************************************************************
public class C_Tokitsukaze_and_Two_Colorful_Tapes{
public static void main(String[] args) {
FastScanner s= new FastScanner();
//PrintWriter out=new PrintWriter(System.out);
//end of program
//out.println(answer);
//out.close();
StringBuilder res = new StringBuilder();
// System.out.println("here1");
int t=s.nextInt();
int p=0;
while(p<t){
int n=s.nextInt();
long array1[]= new long[n];
long array2[]= new long[n];
int pos[]= new int[n+1];
for(int i=0;i<n;i++){
array1[i]=s.nextLong();
pos[(int)array1[i]]=i;
}
//stores the pos of a number in array1
for(int i=0;i<n;i++){
array2[i]=s.nextLong();
}
ArrayList<Long> list = new ArrayList<Long>();
int visited[]= new int[n];
for(int i=0;i<n;i++){
if(visited[i]==1){
continue;
}
int start=i;
int index=i;
long count=0;
while(true){
visited[index]=1;
count++;
long num=array2[index];
int yoyo=pos[(int)num];
index=yoyo;
if(index==start){
break;
}
}
list.add(count);
}
long hh=0;
ArrayList<Long> odd = new ArrayList<Long>();
for(int i=0;i<list.size();i++){
long num=list.get(i);
if(num%2==0){
hh+=num;
}
else{
odd.add(num);
}
}
long half=hh/2;
long ans=0;
long start=1;
long end=n;
while(start<=half){
long kk=end-start;
ans+=kk;
ans+=kk;
start++;
end--;
}
Collections.sort(odd,Collections.reverseOrder());
ArrayList<ArrayList<Long>> well = new ArrayList<ArrayList<Long>>();
for(int i=0;i<odd.size();i++){
long num=odd.get(i);
long alpha=num/2;
ArrayList<Long> nice = new ArrayList<Long>();
while(alpha>0){
nice.add(start);
nice.add(end);
start++;
end--;
alpha--;
}
well.add(nice);
}
int kk=0;
for(long i=start;i<=end;i++){
well.get(kk).add(i);
kk++;
}
for(int i=0;i<well.size();i++){
ArrayList<Long> nice = well.get(i);
if(nice.size()<2){
continue;
}
Collections.sort(nice,Collections.reverseOrder());
int count=nice.size();
// int beg=0;
int use[]= new int[count];
int beg=count-1;
int count2=count;
for(int j=0;j<nice.size();j++){
if(count2==0){
break;
}
long num=nice.get(j);
long ll=num-nice.get(beg);
ans+=ll;
count2--;
use[beg]++;
if(count2==0){
break;
}
long ll2=num-nice.get(beg-1);
ans+=ll2;
count2--;
use[beg-1]++;
if(use[beg-1]==2){
beg=beg-2;
}
if(count2==0){
break;
}
}
}
res.append(ans+" \n");
p++;
}
System.out.println(res);
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
static long modpower(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// SIMPLE POWER FUNCTION=>
static long power(long x, long y)
{
long res = 1; // Initialize result
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = res * x;
// y must be even now
y = y >> 1; // y = y/2
x = x * x; // Change x to x^2
}
return res;
}
} | Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 4f596a0b9105db51339a34c1d85e267a | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main {
public static int inf = (int)1e9+7;
public static int mod = (int)1e9+7;
public static void main(String[] args) throws IOException, InterruptedException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
MyScanner sc = new MyScanner();
//code part
int t = sc.nextInt();
while (t-- > 0){
int n = sc.nextInt();
int[] a = new int[n + 1];
int[] b = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = sc.nextInt();
}
for (int i = 1; i <= n; i++) {
b[i] = sc.nextInt();
}
UnionFindSet ufs = new UnionFindSet(n + 1);
for (int i = 1; i <= n; i++) {
ufs.union(a[i], b[i]);
}
long ans = 0;
int l = 1;
int r = n;
for (int i = 1; i <= n; i++) {
int root = ufs.find(i);
if(i == root){
int x = ufs.size[root];
if(x % 2 == 1){
x--;
}
int mid = x / 2;
long temp = calc(r - mid + 1, r) - calc(l, l + mid - 1);
l += mid;
r -= mid;
ans += 2 * temp;
}
}
writer.write(ans + "\n");
}
//code part
writer.flush();
writer.close();
}
public static long calc(int l, int r){
long res = 1L;
res *= (l + r);
res *= (r - l + 1);
res /= 2;
return res;
}
//快读模板
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;
}
}
}
class UnionFindSet{
public int n;
public int[] p;
public int[] size;
public UnionFindSet(int n){
this.n = n;
this.p = new int[n];
this.size = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
size[i] = 1;
}
}
public int find(int x){
if(x != p[x]){
p[x] = find(p[x]);
}
return p[x];
}
public void union(int x, int y){
int rootX = find(x);
int rootY = find(y);
if(rootX != rootY){
p[rootX] = rootY;
size[rootY] += size[rootX];
}
}
}
| Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | f215d19251836c898ed079f18636c1d7 | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
solver.solve(in.nextInt(), in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
for (int i = 0; i < testNumber; i++) {
int n = in.nextInt();
int[] ca = new int[n];
for (int j = 0; j < n; j++) {
ca[j] = in.nextInt();
}
int[] cb = new int[n];
for (int j = 0; j < n; j++) {
cb[j] = in.nextInt();
}
out.println(new Solution().solve(ca, cb));
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
class Solution {
public long solve(int[] ca, int[] cb) {
int n = ca.length;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(ca[i], i);
}
List<Integer> list = new ArrayList<>();
boolean[] vis = new boolean[n];
int cnt = 0;
for (int i = 0; i < n; i++) {
if (vis[i]) {
continue;
}
int t = i;
while (!vis[t]) {
vis[t] = true;
cnt++;
t = map.get(cb[t]);
}
if (cnt > 1) {
if (cnt % 2 == 1) {
cnt--;
}
list.add(cnt);
}
cnt = 0;
}
long sum = 0;
long l = 1;
long r = n;
for (Integer t : list) {
long f = l;
for (int i = 0; i < t - 1; i++) {
sum += r - l;
if (i % 2 == 0) {
l++;
} else {
r--;
}
}
sum += r - f;
r--;
}
return sum;
}
} | Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | cdcc14dbc231440c710dac7c66e29460 | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes |
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public final class E {
private static final class UnionFind {
private final int[] parent;
private final int[] size;
private int count;
private UnionFind(int n) {
parent = new int[n];
size = new int[n];
count = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public int find(int p) {
// path compression
while (p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
public void union(int p, int q) {
final int rootP = find(p);
final int rootQ = find(q);
if (rootP == rootQ) {
return;
}
// union by size
if (size[rootP] > size[rootQ]) {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
size[rootQ] = 0;
} else {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
size[rootP] = 0;
}
count--;
}
public int count() { return count; }
public int[] size() { return size; }
}
public static void main(String[] args) throws IOException {
final FastReader fs = new FastReader();
final int t = fs.nextInt();
for (int test = 0; test < t; test++) {
final int n = fs.nextInt();
final int[] top = new int[n];
final int[] bot = new int[n];
final int[] map = new int[n];
final UnionFind uf = new UnionFind(n);
final List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) {
top[i] = fs.nextInt() - 1;
map[top[i]] = i;
}
for (int i = 0; i < n; i++) {
bot[i] = fs.nextInt() - 1;
}
for (int i = 0; i < n; i++) {
uf.union(top[i], bot[i]);
}
int max = n;
int min = 1;
long res = 0;
final int[] vals = new int[n];
for (int i = 0; i < n; i++) {
if (uf.find(i) == i) {
final List<Integer> cycle = getCycle(top, bot, map, map[i]);
final int m = cycle.size() - cycle.size() % 2;
for (int j = 0; j < m; j++) {
if (j % 2 == 0) {
vals[cycle.get(j)] = max--;
} else {
vals[cycle.get(j)] = min++;
}
}
for (int j = 0; j < m; j++) {
final int v = (j + 1) % m;
res += Math.abs(vals[cycle.get(j)] - vals[cycle.get(v)]);
}
}
}
System.out.println(res);
}
}
private static List<Integer> getCycle(int[] top, int[] bot, int[] map, int root) {
final List<Integer> cycle = new ArrayList<>();
cycle.add(top[root]);
int u = map[bot[root]];
while (u != root) {
cycle.add(top[u]);
u = map[bot[u]];
}
return cycle;
}
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 int[] nextIntArray(int n) throws IOException {
final int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
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 long[] nextLongArray(int n) throws IOException {
final long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
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\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 3477093c438f9fff010a3df967e9ddd4 | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes |
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public final class E {
private static final class UnionFind {
private final int[] parent;
private final int[] size;
private int count;
private UnionFind(int n) {
parent = new int[n];
size = new int[n];
count = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public int find(int p) {
// path compression
while (p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
public void union(int p, int q) {
final int rootP = find(p);
final int rootQ = find(q);
if (rootP == rootQ) {
return;
}
// union by size
if (size[rootP] > size[rootQ]) {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
size[rootQ] = 0;
} else {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
size[rootP] = 0;
}
count--;
}
public int count() { return count; }
public int[] size() { return size; }
}
public static void main(String[] args) throws IOException {
final FastReader fs = new FastReader();
final int t = fs.nextInt();
for (int test = 0; test < t; test++) {
final int n = fs.nextInt();
final int[] top = new int[n];
final int[] bot = new int[n];
final int[] map = new int[n];
final UnionFind uf = new UnionFind(n);
final List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) {
top[i] = fs.nextInt() - 1;
map[top[i]] = i;
}
for (int i = 0; i < n; i++) {
bot[i] = fs.nextInt() - 1;
}
for (int i = 0; i < n; i++) {
uf.union(top[i], bot[i]);
}
for (int i = 0; i < n; i++) {
if (uf.find(i) == i) {
final int root = map[i];
final List<Integer> cycle = new ArrayList<>();
cycle.add(top[root]);
int u = map[bot[root]];
while (u != root) {
cycle.add(top[u]);
u = map[bot[u]];
}
g.add(cycle);
}
}
int max = n;
int min = 1;
long res = 0;
final int[] vals = new int[n];
for (List<Integer> list : g) {
final int m = list.size() - list.size() % 2;
for (int i = 0; i < m; i++) {
if (i % 2 == 0) {
vals[list.get(i)] = max--;
} else {
vals[list.get(i)] = min++;
}
}
for (int i = 0; i < m; i++) {
final int u = (i + 1) % m;
res += Math.abs(vals[list.get(i)] - vals[list.get(u)]);
}
}
System.out.println(res);
}
}
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 int[] nextIntArray(int n) throws IOException {
final int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
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 long[] nextLongArray(int n) throws IOException {
final long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
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\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | d26a84620b693e467fdf334d3b2f8848 | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes |
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public final class E {
private static final class UnionFind {
private final int[] parent;
private final int[] size;
private int count;
private UnionFind(int n) {
parent = new int[n];
size = new int[n];
count = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public int find(int p) {
// path compression
while (p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
public void union(int p, int q) {
final int rootP = find(p);
final int rootQ = find(q);
if (rootP == rootQ) {
return;
}
// union by size
if (size[rootP] > size[rootQ]) {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
size[rootQ] = 0;
} else {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
size[rootP] = 0;
}
count--;
}
public int count() { return count; }
public int[] size() { return size; }
}
public static void main(String[] args) throws IOException {
final FastReader fs = new FastReader();
final int t = fs.nextInt();
for (int test = 0; test < t; test++) {
final int n = fs.nextInt();
final int[] top = new int[n];
final int[] bot = new int[n];
for (int i = 0; i < n; i++) {
top[i] = fs.nextInt() - 1;
}
for (int i = 0; i < n; i++) {
bot[i] = fs.nextInt() - 1;
}
final UnionFind uf = new UnionFind(n);
for (int i = 0; i < n; i++) {
uf.union(top[i], bot[i]);
}
final List<int[]> size = new ArrayList<>();
final boolean[] seen = new boolean[n];
for (int i = 0; i < n; i++) {
final int r = uf.find(i);
if (!seen[r]) {
seen[r] = true;
size.add(new int[] { r, uf.size()[r] });
}
}
size.sort((a, b) -> a[1] % 2 == b[1] % 2
? Integer.compare(b[1], a[1])
: Integer.compare(a[1] % 2, b[1] % 2));
final Map<Integer, Set<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.computeIfAbsent(uf.find(top[i]), val -> new HashSet<>()).add(top[i]);
g.computeIfAbsent(uf.find(top[i]), val -> new HashSet<>()).add(bot[i]);
}
int max = n;
int min = 1;
long res = 0;
final int[] vals = new int[n];
for (int[] cc : size) {
final List<Integer> list = new ArrayList<>(g.get(cc[0]));
final int m = list.size() - list.size() % 2;
for (int i = 0; i < m; i++) {
if (i % 2 == 0) {
vals[list.get(i)] = max--;
} else {
vals[list.get(i)] = min++;
}
}
for (int i = 0; i < m; i++) {
final int u = (i + 1) % m;
res += Math.abs(vals[list.get(i)] - vals[list.get(u)]);
}
}
System.out.println(res);
}
}
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 int[] nextIntArray(int n) throws IOException {
final int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
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 long[] nextLongArray(int n) throws IOException {
final long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
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\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 72587002a0054aa79edab029be561fb0 | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes |
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public final class E {
private static final class UnionFind {
private final int[] parent;
private final int[] size;
private int count;
private UnionFind(int n) {
parent = new int[n];
size = new int[n];
count = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public int find(int p) {
// path compression
while (p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
public void union(int p, int q) {
final int rootP = find(p);
final int rootQ = find(q);
if (rootP == rootQ) {
return;
}
// union by size
if (size[rootP] > size[rootQ]) {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
size[rootQ] = 0;
} else {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
size[rootP] = 0;
}
count--;
}
public int count() { return count; }
public int[] size() { return size; }
}
public static void main(String[] args) throws IOException {
final FastReader fs = new FastReader();
final int t = fs.nextInt();
for (int test = 0; test < t; test++) {
final int n = fs.nextInt();
final int[] top = new int[n];
final int[] bot = new int[n];
for (int i = 0; i < n; i++) {
top[i] = fs.nextInt() - 1;
}
for (int i = 0; i < n; i++) {
bot[i] = fs.nextInt() - 1;
}
final UnionFind uf = new UnionFind(n);
for (int i = 0; i < n; i++) {
uf.union(top[i], bot[i]);
}
final List<int[]> size = new ArrayList<>();
final boolean[] seen = new boolean[n];
for (int i = 0; i < n; i++) {
final int r = uf.find(i);
if (!seen[r]) {
seen[r] = true;
size.add(new int[] { r, uf.size()[r] });
}
}
size.sort((a, b) -> a[1] % 2 == b[1] % 2
? Integer.compare(b[1], a[1])
: Integer.compare(a[1] % 2, b[1] % 2));
final Map<Integer, Set<Integer>> g = new HashMap<>();
for (int i = 0; i < n; i++) {
g.computeIfAbsent(uf.find(top[i]), val -> new LinkedHashSet<>()).add(top[i]);
g.computeIfAbsent(uf.find(top[i]), val -> new LinkedHashSet<>()).add(bot[i]);
}
int max = n;
int min = 1;
long res = 0;
final int[] vals = new int[n];
for (int[] cc : size) {
final List<Integer> list = new ArrayList<>(g.get(cc[0]));
final int m = list.size() - list.size() % 2;
for (int i = 0; i < m; i++) {
if (i % 2 == 0) {
vals[list.get(i)] = max--;
} else {
vals[list.get(i)] = min++;
}
}
for (int i = 0; i < m; i++) {
final int u = (i + 1) % m;
res += Math.abs(vals[list.get(i)] - vals[list.get(u)]);
}
}
System.out.println(res);
}
}
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 int[] nextIntArray(int n) throws IOException {
final int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
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 long[] nextLongArray(int n) throws IOException {
final long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
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\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 80b58eab3938e38f861b67e9dc5bd3fe | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.util.*;
import java.io.*;
// you can compare with output.txt and expected out
public class Round789E {
MyPrintWriter out;
MyScanner in;
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void preferFileIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
Round789E sol = new Round789E();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
preferFileIO(isFileIO);
int t = in.nextInt();
for (int i = 1; i <= t; ++i) {
int n = in.nextInt();
int[] a = in.nextIntArray(n, -1);
int[] b = in.nextIntArray(n, -1);
if(isDebug){
out.printf("Test %d\n", i);
}
long ans = solve(a, b);
out.println(ans);
if(isDebug)
out.flush();
}
in.close();
out.close();
}
private long solve(int[] a, int[] b) {
int n = a.length;
// a[i] = color of type a at pos i
// b[i] = color of type b at pos i
// for each color j, map j |-> x_j
// minimize sum |x_ai - x_bi|
// inverted[i] = pos of color i in type a
int[] inverted = new int[n];
for(int i=0; i<n; i++)
inverted[a[i]] = i;
// a[i1] -> b[i1] = a[i2] -> b[i2] = a[i3] -> .... -> b[ik] = a[i1]
// to maximize cost: pair max with min, min with max-1, max-1 with min+1, .....
// to minimize cost: |max x value - min x value|*2
boolean[] visited = new boolean[n];
ArrayList<Integer> chainLengths = new ArrayList<Integer>();
for(int i=0; i<n; i++) {
if(!visited[i]) {
visited[i] = true;
int len = 1;
int curr = inverted[b[i]];
while(curr != i) {
visited[curr] = true;
len++;
curr = inverted[b[curr]];
}
chainLengths.add(len);
}
}
// given a cycle, middle part can be freely chosen
long ans = 0;
int left = 0;
int right = n-1;
for(int len: chainLengths) {
if( (len&1) > 0)
len--;
for(int i=0; i<len; i+=2) {
ans -= left;
ans += right;
left++;
right--;
}
}
return ans*2;
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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[][] nextGraphEdges(){
return nextGraphEdges(0);
}
int[][] nextGraphEdges(int offset) {
int m = nextInt();
int[][] e = new int[m][2];
for(int i=0; i<m; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
public void print(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void println(long[] arr){
print(arr);
println();
}
public void print(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void println(int[] arr){
print(arr);
println();
}
public <T> void print(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void println(ArrayList<T> arr){
print(arr);
println();
}
public void println(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void println(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
int[] inIdx = new int[n];
int[] outIdx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][outIdx[u]++] = v;
inNeighbors[v][inIdx[v]++] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
int[] idx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][idx[u]++] = v;
neighbors[v][idx[v]++] = u;
}
return neighbors;
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 171ae406ba44e3e3e5ddce7bc1073bb7 | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.io.*;
import java.util.*;
public class E {
void go() {
int n = Reader.nextInt();
int[] A = new int[n];
int[] B = new int[n];
int[] p1 = new int[n + 1];
int[] p2 = new int[n + 1];
long ans = 0;
long r = n;
long l = 1;
for(int i = 0; i < n; i++) {
A[i] = Reader.nextInt();
p1[A[i]] = i;
}
for(int i = 0; i < n; i++) {
B[i] = Reader.nextInt();
p2[B[i]] = i;
}
// int cnt = 0;
// for(int i = 0; i < n; i++) {
// if(A[i] == B[i]) {
// cnt++;
// }
// }
//
// int left = n - cnt;
// left = left % 2 == 0 ? left : left - 1;
// for(int i = 0; i < left; i += 2) {
// upper += r * 2;
// lower += l * 2;
// r--;
// l++;
// }
//
// ans += upper - lower;
boolean[] visited = new boolean[n];
for(int i = 0; i < n; i++) {
if(visited[i]) {
continue;
}
int cycle = 0;
int cur = i;
long upper = 0;
long lower = 0;
do{
visited[cur] = true;
cycle++;
cur = p2[A[cur]];
} while(!visited[cur]);
cycle = cycle % 2 == 0 ? cycle : cycle - 1;
while(cycle != 0) {
upper += r * 2;
lower += l * 2;
r--;
l++;
cycle -= 2;
}
ans += upper - lower;
}
Writer.println(ans);
}
void solve() {
for(int T = Reader.nextInt(); T > 0; T--) go();
}
void run() throws Exception {
Reader.init(System.in);
Writer.init(System.out);
solve();
Writer.close();
}
public static void main(String[] args) throws Exception {
new E().run();
}
public static class Reader {
public static StringTokenizer st;
public static BufferedReader br;
public static void init(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public static String next() {
while(!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new InputMismatchException();
}
}
return st.nextToken();
}
public static int nextInt() {
return Integer.parseInt(next());
}
public static long nextLong() {
return Long.parseLong(next());
}
public static double nextDouble() {
return Double.parseDouble(next());
}
}
public static class Writer {
public static PrintWriter pw;
public static void init(OutputStream os) {
pw = new PrintWriter(new BufferedOutputStream(os));
}
public static void print(String s) {
pw.print(s);
}
public static void print(char c) {
pw.print(c);
}
public static void print(int x) {
pw.print(x);
}
public static void print(long x) {
pw.print(x);
}
public static void println(String s) {
pw.println(s);
}
public static void println(char c) {
pw.println(c);
}
public static void println(int x) {
pw.println(x);
}
public static void flush() {
pw.flush();
}
public static void println(long x) {
pw.println(x);
}
public static void close() {
pw.close();
}
}
} | Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | e9bf9ebca378061c565ce6b2a924cfca | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class CF789VC {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void sort(int [] a) {
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i:a)
{
arr.add(i);
}
Collections.sort(arr);
int len = arr.size();
for(int i=0;i<len;++i)
a[i] = arr.get(i);
}
static class FenwickTreeExample
{
// Max size of the Fenwick tree in this code
static int MAX_SIZE ;
// the array that represents the fenwick tree
private int fenArr[];
FenwickTreeExample(int n)
{
MAX_SIZE=n;
fenArr = new int [4*MAX_SIZE+15];
for(int i=0;i<4*MAX_SIZE+15;++i)
fenArr[i] = 0;
}
// s --> It is number of element available in the input array.
// fenArr[0 ... s] --> The array that represents the Fenwick Tree
// a[0 ... s - 1] --> It is the input array for which the prefix sum is generated.
// Returns the sum of a[0... idx]. The method assumes
// that the array is already preprocessed and
// the partial sums of the array elements are kept
// in fenArr[].
int getArrSum(int idx)
{
// Initializing the result to 0
int total = 0;
// index in the fenTree[] is one more than the
// index in the array a[]
idx = idx + 1;
// Traversing the ancestors of the fenTree[idx]
while(idx > 0)
{
// Adding the current element of the array fenArr[]
// to the total
total = total + fenArr[idx];
// Moving the index to the parent node in
// getArrSum view
idx -= idx & (-idx);
}
return total;
}
// Updating a node in the Fenwick Tree
// at a given index in the array fenArr[]. The given input value
// 'v' is added to the fenArr[idx] and therefore, it is also added to the
// ancestors of the tree too.
public void updateFenwick(int s, int idx, int v)
{
// index in the array fenArr[] is 1 more than the
// index in the array a[]
idx = idx + 1;
// Traversing all the ancestors and adding 'v'
while(idx <= s)
{
// Add 'val' to current node of BIT Tree
fenArr[idx] = fenArr[idx] + v;
// Updating the idx to that of parent
// in the update View
idx = idx + (idx & (-idx));
}
}
// Method to build the Fenwick tree
// from the given array.
void constructFenTree(int arr[], int s)
{
// Initializing fenArr[] as 0
for(int i = 1; i <= s; i++)
{
fenArr[i] = 0;
}
// Storing the original values in the fenArr[]
// using the mehtod updateFenwick()
for(int j = 0; j < s; j++)
{
updateFenwick(s, j, arr[j]);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PrintWriter out = new PrintWriter(System.out);
FastReader fs = new FastReader();
int t = fs.nextInt();
for(int cs=0;cs<t;++cs)
{
int n= fs.nextInt();
int [] a = new int [n+1];
int [] b = new int [n+1];
int [] tracker = new int [n+1];
for(int i=1;i<=n;++i)
{
a[i] = fs.nextInt();
tracker[a[i]] = i;
}
for(int i=1;i<=n;++i)
{
b[i] = fs.nextInt();
}
int [] visited = new int [n+1];
for(int i=0;i<=n;++i)
visited[i] = 0;
int numpos=0;
for(int i=1;i<=n;++i)
{
if(a[i] == b[i])
continue;
if(visited[i] == 1)
continue;
int j=i;
int hopc=0;
while(visited[j] == 0) {
visited[j] = 1;
j=tracker[b[j]];
hopc++;
}
numpos+=(hopc)/2;
}
long sumbeg=0;
long finish = n;
long start=1;
while(numpos>0)
{
sumbeg+=(finish-start);
finish--;
start++;
numpos--;
}
sumbeg=2*sumbeg;
out.print(sumbeg);
out.println();
}
out.close();
}
} | Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 4dfec11bbac72e791d292245395159ff | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import static java.lang.Math.*;
import static java.lang.System.*;
import java.util.*;
public class Main {
static public void main(String[] args){
Read in = new Read(System.in);
int t =in.nextInt();
while(t>0){
t--;
solve(in);
}
}
static void solve(Read in){
int n=in.nextInt();
int a[][]= new int[n][2];
for(int i=0;i<n;i++){
a[i][0]=in.nextInt();
}
for(int i=0;i<n;i++){
a[i][1]=in.nextInt();
}
int[][] id = new int[n+1][2];
for(int i=0;i<n;i++){
id[a[i][0]][0]=i;
id[a[i][1]][1]=i;
}
int sum = n;
boolean[] f = new boolean[n];
for(int i = 0; i < n; i++){
if(f[i]) continue;
f[i]=true;
int cot = 1;
int A = a[i][0];
int B = a[i][1];
while(A != B){
int j = id[B][0];
B = a[j][1];
f[j]=true;
cot++;
}
if(cot%2==1){
sum--;
}
}
sum = sum/2;
long ans = 1l*(2 * n - 2*sum)*sum;
out.println(ans);
}
void shuffleArray(long[] arr){
int n = arr.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
static class Read {//自定义快读 Read
public BufferedReader reader;
public StringTokenizer tokenizer;
public Read(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
String str = null;
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long gcd(long a, long b) {
return (a % b == 0) ? b : gcd(b, a % b);
}
} | Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 929b909be1875718aa756e1fc354ee55 | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.util.*;
import java.io.*;
public class G {
static FastScanner fs = new FastScanner();
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder("");
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
int t = fs.nextInt();
//int t = 1;
for (int tt = 0; tt < t; tt++) {
int n = fs.nextInt();
int[] a = new int[n];
int[] b = new int[n];
int[] p = new int[n];
for (int i = 0; i < n; i++) a[i] = fs.nextInt()-1;
for (int i = 0; i < n; i++) {
b[i] = fs.nextInt()-1;
p[a[i]] = b[i];
}
long ans = 0;
int x = 0;
boolean[] vis = new boolean[n];
for (int i = 0; i < n; i++) {
if (vis[i]) continue;
int len = 0;
for (int j = i; !vis[j]; j = p[j]) {
vis[j] = true;
len++;
}
x += len/2;
}
for (int i = 0; i < x; i++) ans += n-1-i-i;
ans *= 2;
sb.append(ans + "\n");
}
pw.print(sb.toString());
pw.close();
}
static void sort(int[] a) {
ArrayList<Integer> al = new ArrayList<>();
for (int i : a)
al.add(i);
Collections.sort(al);
for (int i = 0; i < a.length; i++)
a[i] = al.get(i);
}
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) {}return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) {a[i] = nextInt();} return a;}
}
} | Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | d2a5542f014da4c4553a081f562e164b | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | // package c1678;
//
// Codeforces Round #789 (Div. 2) 2022-05-08 07:35
// E. Tokitsukaze and Two Colorful Tapes
// https://codeforces.com/contest/1678/problem/E
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// Tokitsukaze has two colorful tapes. There are n distinct colors, numbered 1 through n, and each
// color appears exactly once on each of the two tapes. Denote the color of the i-th position of the
// first tape as ca_i, and the color of the i-th position of the second tape as cb_i.
//
// Now Tokitsukaze wants to select each color an integer value from 1 to n, distinct for all the
// colors. After that she will put down the color values in each colored position on the tapes.
// Denote the number of the i-th position of the first tape as numa_i, and the number of the i-th
// position of the second tape as numb_i.
// https://espresso.codeforces.com/c43e6f42a4cd7b8a218983155bef73e1fb7807c9.png
//
// For example, for the above picture, assuming that the color red has value x (1 <= x <= n), it
// appears at the 1-st position of the first tape and the 3-rd position of the second tape, so
// numa_1=numb_3=x.
//
// Note that each color i from 1 to n should have a value, and the same color which appears in both
// tapes has the same value.
//
// After labeling each color, the beauty of the two tapes is calculated as <div
// class="MathJax_Display" style="text-align: center;"></div>\sum_{i=1}^{n}|numa_i-numb_i|.
//
// Please help Tokitsukaze to find the highest possible beauty.
//
// Input
//
// The first contains a single positive integer t (1 <= t <= 10^4)-- the number of test cases.
//
// For each test case, the first line contains a single integer n (1<= n <= 10^5)-- the number of
// colors.
//
// The second line contains n integers ca_1, ca_2, ..., ca_n (1 <= ca_i <= n)-- the color of each
// position of the first tape. It is guaranteed that ca is a permutation.
//
// The third line contains n integers cb_1, cb_2, ..., cb_n (1 <= cb_i <= n)-- the color of each
// position of the second tape. It is guaranteed that cb is a permutation.
//
// It is guaranteed that the sum of n over all test cases does not exceed 2 * 10^{5}.
//
// Output
//
// For each test case, print a single integer-- the highest possible beauty.
//
// Example
/*
input:
3
6
1 5 4 3 2 6
5 3 1 4 6 2
6
3 5 4 6 2 1
3 6 4 5 2 1
1
1
1
output:
18
10
0
*/
// Note
//
// An optimal solution for the first test case is shown in the following figure:
// https://espresso.codeforces.com/33efd0f1d29332f2920727cec796463f3416ab5a.png
//
// The beauty is <=ft|4-3 \right|+<=ft|3-5 \right|+<=ft|2-4 \right|+<=ft|5-2 \right|+<=ft|1-6
// \right|+<=ft|6-1 \right|=18.
//
// An optimal solution for the second test case is shown in the following figure:
// https://espresso.codeforces.com/be704f7644a30ed1c595245dc0cc4754a2fa91cd.png
//
// The beauty is <=ft|2-2 \right|+<=ft|1-6 \right|+<=ft|3-3 \right|+<=ft|6-1 \right|+<=ft|4-4
// \right|+<=ft|5-5 \right|=10.
//
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.StringTokenizer;
public class C1678E {
static final int MOD = 998244353;
static final Random RAND = new Random();
static long solve(int[] a, int[] b) {
int n = a.length;
int[] ia = new int[n];
for (int i = 0; i < n; i++) {
ia[a[i]] = i;
}
int[] ib = new int[n];
for (int i = 0; i < n; i++) {
ib[b[i]] = i;
}
boolean[] done = new boolean[n];
for (int i = 0; i < n; i++) {
if (a[i] == b[i]) {
done[i] = true;
}
}
int k = 0;
for (int i = 0; i < n; i++) {
if (done[i]) {
continue;
}
int j = i;
int len = 0;
while (true) {
myAssert(!done[j]);
len++;
done[j] = true;
j = ib[a[j]];
if (j == i) {
break;
}
}
// System.out.format(" len: %s\n", len);
k += len / 2;
}
// System.out.format(" k:%d\n", k);
return (long)(n-k) * k * 2;
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int T = in.nextInt();
for (int t = 1; t <= T; t++) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt()-1;
}
int[] b = new int[n];
for (int i = 0; i < n; i++) {
b[i] = in.nextInt()-1;
}
long ans = solve(a, b);
System.out.println(ans);
}
}
static void output(int[] a) {
if (a == null) {
System.out.println("-1");
return;
}
StringBuilder sb = new StringBuilder();
for (int v : a) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | a3ad39267929b45c535c4ca54c5e7120 | train_108.jsonl | 1652020500 | Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$. For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF1678E extends PrintWriter {
CF1678E() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1678E o = new CF1678E(); o.main(); o.flush();
}
void main() {
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] aa = new int[n];
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
aa[i] = a;
}
int[] pp = new int[n + 1];
for (int i = 0; i < n; i++) {
int a = aa[i];
int b = sc.nextInt();
pp[a] = b;
}
int[] cnt = new int[n + 1];
for (int a = 1; a <= n; a++) {
if (pp[a] == 0)
continue;
int k = 0;
for (int b = a; pp[b] != 0; ) {
int c = pp[b];
pp[b] = 0;
b = c;
k++;
}
cnt[k / 2]++;
}
long ans = 0;
for (int k = n / 2; k > 0; k--)
while (cnt[k]-- > 0) {
// 1 3 5 ... 6 4 2
for (int b = 2; b <= k * 2; b += 2) {
int a = b - 1;
int c = b == k * 2 ? 1 : b + 1;
int xb = n - (b / 2 - 1);
int xa = (a + 1) / 2;
int xc = (c + 1) / 2;
ans += xb - xa + xb - xc;
}
n -= k * 2;
}
println(ans);
}
}
}
| Java | ["3\n\n6\n\n1 5 4 3 2 6\n\n5 3 1 4 6 2\n\n6\n\n3 5 4 6 2 1\n\n3 6 4 5 2 1\n\n1\n\n1\n\n1"] | 2 seconds | ["18\n10\n0"] | NoteAn optimal solution for the first test case is shown in the following figure: The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure: The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dsu",
"greedy",
"math"
] | 4bcaa910cce687f0881a36231aa1a2c8 | The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$. | 1,900 | For each test case, print a single integer — the highest possible beauty. | standard output | |
PASSED | 17fe3c3a0c35d978f5e6756125dda400 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | /*
stream Butter!
eggyHide eggyVengeance
I need U
xiao rerun when
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1607E
{
public static final int INF = Integer.MAX_VALUE/2;
public static void main(String hi[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
while(T-->0)
{
st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
char[] arr = infile.readLine().toCharArray();
int minX = 0, maxX = 0;
int minY = 0, maxY = 0;
int currX = 0, currY = 0;
int resX = 0;
int resY = 0;
for(int i=0; i < arr.length; i++)
{
char c = arr[i];
if(c == 'U')
currY++;
else if(c == 'D')
currY--;
else if(c == 'L')
currX--;
else
currX++;
minX = min(minX, currX);
maxX = max(maxX, currX);
minY = min(minY, currY);
maxY = max(maxY, currY);
if(maxX-minX+1 <= M && maxY-minY+1 <= N)
{
resX = -1*minX;
resY = -1*minY;
}
else
break;
//System.out.println(minX+" "+maxX+" "+minY+" "+maxY);
}
resY = N-resY;
resX++;
sb.append(resY+" "+resX+"\n");
}
System.out.print(sb);
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
/*
1
3 3
RRDLUU
*/ | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | a15f154e4ad8b8712e7056e0ac5a9d0d | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
int t = nextInt();
while (t-- != 0) {
long n = nextLong();
long m = nextLong();
String s = nextToken();
long maxx = 0;
long maxy = 0;
long minx = 0;
long miny = 0;
long x = 0;
long y = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'U') y++;
else if (s.charAt(i) == 'D') y--;
else if (s.charAt(i) == 'R') x++;
else x--;
maxx = Math.max(maxx, x);
maxy = Math.max(maxy, y);
minx = Math.min(minx, x);
miny = Math.min(miny, y);
if (Math.abs(maxx) + Math.abs(minx) >= m || Math.abs(maxy) + Math.abs(miny) >= n) {
if (s.charAt(i) == 'U') maxy--;
else if (s.charAt(i) == 'D') miny=Math.min(0,miny+1);
else if (s.charAt(i) == 'R') maxx=Math.max(0,maxx-1);
else minx++;
break;
}
}
out.println(Math.min(n,Math.abs(maxy)+1)+" "+Math.min(m,Math.abs(minx)+1));
}
out.close();
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(System.out);
static StringTokenizer in = new StringTokenizer("");
public static boolean hasNext() throws IOException {
if (in.hasMoreTokens()) return true;
String s;
while ((s = br.readLine()) != null) {
in = new StringTokenizer(s);
if (in.hasMoreTokens()) return true;
}
return false;
}
public static String nextToken() throws IOException {
while (!in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 4511c73048eb2ee72602e9316779b350 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
public class robotonboard{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0){
int n = sc.nextInt();
int m = sc.nextInt();
sc.nextLine();
String s = sc.nextLine();
int ansX =1; int ansY=1;
int mindx=0; int mindy=0;
int maxdx=0; int maxdy=0;
int dx=0; int dy=0;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
// x is row and y is col
if(c=='L'){
dy--;
}
if(c=='R'){
dy++;
}
if(c=='U'){
dx--;
}
if(c=='D'){
dx++;
}
mindx = Math.min(mindx,dx);
mindy = Math.min(mindy,dy);
maxdx = Math.max(maxdx,dx);
maxdy= Math.max(maxdy,dy);
//x+maxdx <= n && x+mindx>=1
int maxX = n - maxdx;
int minX = 1 - mindx;
int maxY = m - maxdy;
int minY = 1 - mindy;
if (minX <= maxX && minY <= maxY){
ansX = minX;
ansY = minY;
}
else break;
}
System.out.println(ansX + " "+ ansY);
}
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | e8d8fdb87c5694375c2ec8d040a1e296 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | /*
* In_The_Name_Of_Allah_The_Merciful */
import java.util.*;
import java.io.*;
public class Solution
{
class Pair implements Comparable<Pair>{
int f,s;
Pair(int x,int y){
f=x;
s=y;
}
@Override
public int compareTo(Pair a) {
if(a.f!=this.f)return Integer.compare(f,a.f);
else return Integer.compare(s,a.s);
}
}
PrintWriter out;
FastReader sc;
long[] m1= {(long)(1e9+7),998244353};
long mod=m1[1];
long maxlong=Long.MAX_VALUE;
StringBuilder sb;
/******************************************************************************************
*****************************************************************************************/
public void sol() {
int n=ni(),m=ni();
char[] s=rl();
int slen=s.length;
int maxdx=0,mindx=Integer.MAX_VALUE,maxdy=0,mindy=Integer.MAX_VALUE,dx=0,dy=0,ansx=1,ansy=1;
for(int i=0;i<slen;i++) {
if(s[i]=='U') {
dy--;
}
else if (s[i]=='D') {
dy++;
}else if (s[i]=='L') {
dx--;
}else {
dx++;
}
maxdx=max(maxdx,dx);
mindx=min(mindx,dx);
maxdy=max(maxdy,dy);
mindy=min(mindy,dy);
int x=m-maxdx;
if(x+mindx<1||x<1)break;
int y=n-maxdy;
if(y+mindy<1||y<1)break;
ansx=x;
ansy=y;
// pl(x+" "+y);
}pl(ansy+" "+ansx);
}
public static void main(String[] args)
{
Solution g=new Solution();
g.out=new PrintWriter(System.out);
g.sc=new FastReader();
int t=1;
t=g.ni();
while(t-->0) {
g.sol();
}
g.out.flush();
}
/****************************************************************************************
*****************************************************************************************/
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 int ni(){
return sc.nextInt();
}public long nl(){
return sc.nextLong();
}public double nd(){
return sc.nextDouble();
}public char[] rl(){
return sc.nextLine().toCharArray();
}public String rl1(){
return sc.nextLine();
}
public void pl(Object s){
out.println(s);
}
public void pr(Object s){
out.print(s);
}public String next(){
return sc.next();
}public long abs(long x){
return Math.abs(x);
}
public int abs(int x){
return Math.abs(x);
}
public double abs(double x){
return Math.abs(x);
}public long min(long x,long y){
return (long)Math.min(x,y);
}
public int min(int x,int y){
return (int)Math.min(x,y);
}
public double min(double x,double y){
return Math.min(x,y);
}public long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}public long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
void sort1(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) {
l.add(i);
}
Collections.sort(l,Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}void sort(char[] a) {
ArrayList<Character> l = new ArrayList<>();
for (char i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}void sort1(char[] a) {
ArrayList<Character> l = new ArrayList<>();
for (char i : a) {
l.add(i);
}
Collections.sort(l,Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}void sort1(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) {
l.add(i);
}
Collections.sort(l,Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
void sort(double[] a) {
ArrayList<Double> l = new ArrayList<>();
for (double i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}long pow(long a,long b){
if(b==0){
return 1;
}long p=pow(a,b/2);
if(b%2==0) return mMultiplication(p,p)%mod;
else return (mMultiplication(mMultiplication(p,p),a))%mod;
}
int swap(int a,int b){
return a;
}long swap(long a,long b){
return a;
}double swap(double a,double b){
return a;
}
boolean isPowerOfTwo (int x)
{
return x!=0 && ((x&(x-1)) == 0);
}boolean isPowerOfTwo (long x)
{
return x!=0 && ((x&(x-1)) == 0);
}public long max(long x,long y){
return (long)Math.max(x,y);
}
public int max(int x,int y){
return (int)Math.max(x,y);
}
public double max(double x,double y){
return Math.max(x,y);
}long sqrt(long x){
return (long)Math.sqrt(x);
}int sqrt(int x){
return (int)Math.sqrt(x);
}void input(int[] ar,int n){
for(int i=0;i<n;i++)ar[i]=ni();
}void input(long[] ar,int n){
for(int i=0;i<n;i++)ar[i]=nl();
}void fill(int[] ar,int k){
Arrays.fill(ar,k);
}void yes(){
pl("YES");
}void no(){
pl("NO");
}
long c2(long n) {
return (n*(n-1))/2;
}
long[] sieve(int n)
{
long[] k=new long[n+1];
boolean[] pr=new boolean[n+1];
for(int i=1;i<=n;i++){
k[i]=i;
pr[i]=true;
}for(int i=2;i<=n;i++){
if(pr[i]){
for(int j=i+i;j<=n;j+=i){
pr[j]=false;
if(k[j]==j){
k[j]=i;
}
}
}
}return k;
}
int strSmall(int[] arr, int target)
{
int start = 0, end = arr.length-1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] >= target) {
end = mid - 1;
}
else {
ans = mid;
start = mid + 1;
}
}
return ans;
} int strSmall(ArrayList<Integer> arr, int target)
{
int start = 0, end = arr.size()-1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr.get(mid) > target) {
start = mid + 1;
ans=start;
}
else {
end = mid - 1;
}
}
return ans;
}long mMultiplication(long a,long b)
{
long res = 0;
a %= mod;
while (b > 0)
{
if ((b & 1) > 0)
{
res = (res + a) % mod;
}
a = (2 * a) % mod;
b >>= 1;
}
return res;
}long nCr(int n, int r ,long p)
{
if (n<r)
return 0;
if (r == 0)
return 1;
long[] fac = new long[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i %p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}long power(long x, long y, long p)
{
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}long modInverse(long n, long p)
{
return power(n, p - 2, p);
}
int[][] floydWarshall(int graph[][],int INF,int V)
{
int dist[][] = new int[V][V];
int i, j, k;
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];
for (k = 0; k < V; k++)
{
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}return dist;
}
class minque {
Deque<Long> q;
minque(){
q=new ArrayDeque<Long>();
}public void add(long p){
while(!q.isEmpty()&&q.peekLast()>p)q.pollLast();
q.addLast(p);
}public void remove(long p) {
if(!q.isEmpty()&&q.getFirst()==p)q.removeFirst();
}public long min() {
return q.getFirst();
}
}
int find(subset[] subsets, int i)
{
if (subsets[i].parent != i)
subsets[i].parent
= find(subsets, subsets[i].parent);
return subsets[i].parent;
}void Union(subset[] subsets, int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank) {
subsets[xroot].parent = yroot;
}
else if (subsets[yroot].rank < subsets[xroot].rank) {
subsets[yroot].parent = xroot;
}
else {
subsets[xroot].parent = yroot;
subsets[yroot].rank++;
}
}class subset
{
int parent;
int rank;
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 2007655a003d357cac33187a72a3710e | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.Scanner;
public class RobotOnBoard {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tests = sc.nextInt();
sc.nextLine();
for(int i = 0;i<tests;i++) {
String[] rowsAndCols = sc.nextLine().split(" ");
int rows = Integer.parseInt(rowsAndCols[0]);
int cols = Integer.parseInt(rowsAndCols[1]);
String moves = sc.nextLine();
System.out.println(calculateMoves(rows, cols, moves));
}
}
public static String calculateMoves(int rows, int cols, String moves) {
int lc = 0;
int rc = 0;
int uc = 0;
int dc = 0;
int initialX = 1;
int initialY = 1;
int curX = initialX;
int curY = initialY;
outer:
for(int i = 0;i<moves.length();i++) {
char c = moves.charAt(i);
switch (c) {
case 'L':
lc++;
rc = rc == 0 ? 0 : rc - 1;
if(Math.abs(lc) == cols) {
return initialX + " " + initialY;
}
curY--;
if(curY < 1) {
initialY++;
curY++;
}
break;
case 'R':
lc = lc == 0 ? 0 : lc - 1;
rc++;
if(Math.abs(rc) == cols) {
return initialX + " " + initialY;
}
curY++;
if(curY > cols) {
if(initialY == 1) {
return initialX + " " + initialY;
}
initialY--;
curY--;
}
break;
case 'U':
uc++;
dc = dc == 0 ? 0 : dc - 1;
if(Math.abs(uc) == rows) {
return initialX + " " + initialY;
}
curX--;
if(curX < 1) {
if(initialX == rows) {
return initialX + " " + initialY;
}
initialX++;
curX++;
}
break ;
case 'D':
uc = uc == 0 ? 0 : uc - 1;
dc++;
if(Math.abs(dc) == rows) {
return initialX + " " + initialY;
}
curX++;
if(curX > rows) {
if(initialX == 1) {
return initialX + " " + initialY;
}
initialX--;
curX--;
}
break;
}
}
return new StringBuilder().append(initialX).append(" ").append(initialY).toString();
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 2cd490aca80c1f470c479dc2a78050d1 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
import java.io.*;
public class E1607{
static FastScanner fs = null;
public static void main(String[] args) {
fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = fs.nextInt();
while (t-->0) {
int n = fs.nextInt();
int m = fs.nextInt();
String s = fs.next();
char ch1[] = s.toCharArray();
int ni = s.length();
int r = 1;
int c = 1;
int x = 0;
int y = 0;
int lx = 0;
int ly = 0;
int hx = 0;
int hy = 0;
for(int i=0;i<ni;i++){
if(ch1[i]=='L'){
x-=1;
}
if(ch1[i]=='R'){
x+=1;
}
if(ch1[i]=='U'){
y-=1;
}
if(ch1[i]=='D'){
y+=1;
}
lx = Math.min(lx,x);
hx = Math.max(hx,x);
ly = Math.min(ly,y);
hy = Math.max(hy,y);
if(hy-ly<n &&hx-lx<m){
c = 1-lx;
r = 1-ly;
}
}
out.println(r+" "+c);
}
out.println();
out.close();
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static 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\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 5373df1a025217d26523420fb4f72dbc | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for (int t = in.nextInt(); t > 0; t--) {
int rows = in.nextInt();
int cols = in.nextInt();
char[] commands = in.next().toCharArray();
List<Integer> horizontal = new ArrayList<>();
List<Integer> vertical = new ArrayList<>();
for (char com: commands) {
if (com == 'L') horizontal.add(-1);
else if (com == 'R') horizontal.add(1);
else if (com == 'U') vertical.add(-1);
else vertical.add(1);
}
int row = getPos(vertical, rows);
int col = getPos(horizontal, cols);
System.out.println(buildString(row, col));
}
}
private static int getPos(List<Integer> commands, int size) {
int pos = 0, min = 0, max = 0;
for (int com: commands) {
pos += com;
min = Math.min(min, pos);
max = Math.max(max, pos);
if (max - min == size) {
if (com > 0) return size - max + 1;
else return size - max;
}
}
return size - max;
}
private static String buildString(int... args) {
StringBuilder line = new StringBuilder();
for (int arg: args) line.append(arg).append(" ");
return line.toString();
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | abee49d83abf03bd9513671e70ea3931 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for (int t = in.nextInt(); t > 0; t--) {
int rows = in.nextInt();
int cols = in.nextInt();
char[] commands = in.next().toCharArray();
List<Integer> horizontal = new ArrayList<>();
List<Integer> vertical = new ArrayList<>();
for (char com: commands) {
if (com == 'L') horizontal.add(-1);
else if (com == 'R') horizontal.add(1);
else if (com == 'U') vertical.add(-1);
else vertical.add(1);
}
int row = getPos(vertical, rows);
int col = getPos(horizontal, cols);
StringBuilder line = new StringBuilder()
.append(row).append(" ").append(col);
System.out.println(line);
}
}
private static int getPos(List<Integer> commands, int size) {
int pos = 0, min = 0, max = 0;
for (int com: commands) {
pos += com;
min = Math.min(min, pos);
max = Math.max(max, pos);
if (max - min == size) {
if (com > 0) return size - max + 1;
else return size - max;
}
}
return size - max;
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 31c0d55a325582b6916f322f5c32d7fc | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.LinkedList;
import java.util.*;
import java.util.StringTokenizer;
public class C {
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 int find(String D,int m){
// char d[]=D.toCharArray();
// int id=0;
// int min=0;
// int max=0;
// int sum=0;
// for(int i=0;i<d.length;i++){
// if(d[i]=='L'||d[i]=='U'){
// sum--;
// if(max-sum>=m) break;
// if(min>sum) min=sum;
// }
// else{
// sum++;
// if(sum-min>=m) break;
// if(max<sum) max=sum;
// }
// }
// return m-max;
// }
public static void main(String[] args) {
FastReader s=new FastReader();
int t=s.nextInt();
while(t-->0){
int n=s.nextInt();
int m=s.nextInt();
String command=s.next();
int i=0;
char d[]=command.toCharArray();
int maxH=0;
int minH=0;
int maxV=0;
int minV=0;
int sumH=0;
int sumV=0;
boolean a=true,b=true;
for(i=0;i<d.length;i++){
if(a && d[i]=='L'){
sumH--;
if(maxH-sumH>=m) a=false;
if(a && minH>sumH) minH=sumH;
}
else if(a && d[i]=='R'){
sumH++;
if(sumH-minH>=m) a=false;
if(a&& maxH<sumH) maxH=sumH;
}
if(b && d[i]=='U'){
sumV--;
if(maxV-sumV>=n) b=false;
if(b&&minV>sumV) minV=sumV;
}
else if(b && d[i]=='D'){
sumV++;
if(sumV-minV>=n) b=false;
if(b&&maxV<sumV) maxV=sumV;
}
}
int x=m-maxH;
int y=n-maxV;
System.out.println(y+" "+x);
}
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | d81a08a25a6339df949117a196427f33 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st;
int t = Integer.parseInt(br.readLine());
while (t --> 0) {
st = new StringTokenizer(br.readLine());
int row = Integer.parseInt(st.nextToken());
int col = Integer.parseInt(st.nextToken());
String dir = br.readLine();
int left = 0;
int right = 0;
int top = 0;
int bottom = 0;
int currRow = 0;
int currCol = 0;
for (int i = 0; i < dir.length(); i++) {
char next = dir.charAt(i);
if (next == 'L') {
currCol -= 1;
} else if (next == 'R') {
currCol += 1;
} else if (next == 'U') {
currRow -= 1;
} else if (next == 'D') {
currRow += 1;
}
bottom = Math.min(bottom, currRow);
top = Math.max(top, currRow);
left = Math.min(left, currCol);
right = Math.max(right, currCol);
if (top - bottom >= row) {
if (currRow == bottom) bottom++;
break;
}
if (right - left >= col) {
if (currCol == left) left++;
break;
}
}
pw.println((1 - bottom) + " " + (1 - left));
}
pw.close();
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | f67ecc92743d2d0db196a5f8f143e94e | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.Scanner;
public class CodeForces_1607E {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numTestcases = sc.nextInt();
while(numTestcases-->0){
int n = sc.nextInt();
int m = sc.nextInt();
char[] dir = sc.next().toCharArray();
int R_Count = 0;
int R_Count_max = 0;
int L_Count_max = 0;
int ans_m = 0;
int ans_n = 0;
int D_Count = 0;
int U_Count_max = 0;
int D_Count_max = 0;
for(int i = 0; i <dir.length ; i++){
if(dir[i] == 'R'){
R_Count+=1;
}
if(dir[i] == 'L'){
R_Count-=1;
}
if(dir[i] == 'D'){
D_Count+=1;
}
if(dir[i] == 'U'){
D_Count-=1;
}
if(R_Count > R_Count_max){
R_Count_max = R_Count;
}
if(R_Count < L_Count_max){
L_Count_max = R_Count;
}
if(D_Count > D_Count_max){
D_Count_max = D_Count;
}
if(D_Count < U_Count_max){
U_Count_max = D_Count;
}
if((R_Count_max - L_Count_max) == m ) {
if(dir[i] == 'R'){
R_Count_max-=1;
}
break;
}
if((D_Count_max - U_Count_max) == n ){
if(dir[i] == 'D'){
D_Count_max-=1;
}
break;
}
}
System.out.println((n-D_Count_max)+" "+(m-R_Count_max ));
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 1c2d03ce13acd825f7eac5dad14dc3d8 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
/*
Goal: Become better in CP!
Key: Consistency!
*/
public class Coder {
static StringBuffer str=new StringBuffer();
static int n,m;
static char c[];
static void solve(){
int dx, dy, mndx, mxdx, mndy, mxdy;
dx=dy=mndx=mxdx=mndy=mxdy=0;
int x=1,y=1;
for(int i=0;i<c.length;i++){
if(c[i]=='L') dy--;
if(c[i]=='R') dy++;
if(c[i]=='U') dx--;
if(c[i]=='D') dx++;
// -ve value gives |val| to be moved away from left and up resp.
// +ve value gives |val| to be moved away from right and down resp.
mndx=Math.min(mndx, dx);
mndy=Math.min(mndy, dy);
mxdx=Math.max(mxdx, dx);
mxdy=Math.max(mxdy, dy);
int mxx = n-mxdx;
int mnx = 1-mndx;
int mxy = m-mxdy;
int mny = 1-mndy;
if(mnx>mxx || mny>mxy) break;
x=mxx;
y=mny;
}
str.append(x).append(" ").append(y).append("\n");
}
public static void main(String[] args) throws java.lang.Exception {
BufferedReader bf;
PrintWriter pw;
boolean lenv=false;
if(lenv){
bf = new BufferedReader(
new FileReader("input.txt"));
pw=new PrintWriter(new
BufferedWriter(new FileWriter("output.txt")));
}else{
bf = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
}
int q = Integer.parseInt(bf.readLine().trim());
while (q-- > 0) {
String s[]=bf.readLine().trim().split("\\s+");
n=Integer.parseInt(s[0]);
m=Integer.parseInt(s[1]);
c=bf.readLine().trim().toCharArray();
solve();
}
pw.print(str);
pw.flush();
// System.out.print(str);
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 377c5da26320e50af53a7d24cbe159fc | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
/*
Goal: Become better in CP!
Key: Consistency!
*/
public class Coder {
static StringBuffer str=new StringBuffer();
static int n,m;
static char c[];
static void solve(){
int dx, dy, mndx, mxdx, mndy, mxdy;
dx=dy=mndx=mxdx=mndy=mxdy=0;
int x=1,y=1;
for(int i=0;i<c.length;i++){
if(c[i]=='L') dy--;
if(c[i]=='R') dy++;
if(c[i]=='U') dx--;
if(c[i]=='D') dx++;
mndx=Math.min(mndx, dx);
mndy=Math.min(mndy, dy);
mxdx=Math.max(mxdx, dx);
mxdy=Math.max(mxdy, dy);
int mxx = n-mxdx;
int mnx = 1-mndx;
int mxy = m-mxdy;
int mny = 1-mndy;
if(mnx>mxx || mny>mxy) break;
x=mnx;
y=mny;
}
str.append(x).append(" ").append(y).append("\n");
}
public static void main(String[] args) throws java.lang.Exception {
BufferedReader bf;
PrintWriter pw;
boolean lenv=false;
if(lenv){
bf = new BufferedReader(
new FileReader("input.txt"));
pw=new PrintWriter(new
BufferedWriter(new FileWriter("output.txt")));
}else{
bf = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
}
int q = Integer.parseInt(bf.readLine().trim());
while (q-- > 0) {
String s[]=bf.readLine().trim().split("\\s+");
n=Integer.parseInt(s[0]);
m=Integer.parseInt(s[1]);
c=bf.readLine().trim().toCharArray();
solve();
}
pw.print(str);
pw.flush();
// System.out.print(str);
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 8fc6deeba2f3e532ba3a443a29ecb3e0 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
import java.io.*;
public class codeforces1607E {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numCases = Integer.parseInt(br.readLine());
StringBuilder ans = new StringBuilder();
while (numCases-->0)
{
StringTokenizer st = new StringTokenizer(br.readLine());
int width = Integer.parseInt(st.nextToken());
int length = Integer.parseInt(st.nextToken());
String str = br.readLine();
int netChangeW = 0;
int netChangeL = 0;
int answerX = 0;
int answerY = 0;
int [] x = new int[str.length()];
int [] y = new int[str.length()];
for (int i = 0; i<str.length();i++)
{
if (str.charAt(i)=='L')
{
netChangeL--;
}
else if (str.charAt(i)=='R')
{
netChangeL++;
}
else if (str.charAt(i)=='U')
{
netChangeW--;
}
else
{
netChangeW++;
}
x[i] = netChangeL;
y[i] = netChangeW;
}
int lX = 0;
int lY = 0;
int gX = 0;
int gY = 0;
//boolean bo = true;
for (int i = 0; i<str.length();i++)
{
if (x[i]>gX)
{
gX = x[i];
if (gX-lX>=length)
{
gX--;
//ans.append((width-gY)+" "+(length-gX));
break;
}
}
else if (x[i]<lX)
{
lX = x[i];
if (gX-lX>=length)
{
//bo = false;
lX++;
break;
}
}
if (y[i]>gY)
{
gY = y[i];
if (gY-lY>=width)
{
gY--;
break;
}
}
else if (y[i]<lY)
{
lY = y[i];
if (gY-lY>=width)
{
//bo = false;
lY++;
break;
}
}
//System.out.println("HIT");
}
ans.append((Math.max(width-gY,-lY+1))+" "+(Math.max(length-gX,-lX+1))+"\n");
}
System.out.println(ans);
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 9ea04bdac2132f19df5fef7f3e4b2d1f | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.CompletableFuture.AsynchronousCompletionTask;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.DataInputStream;
public class Solution {
//TEMPLATE -------------------------------------------------------------------------------------
public static boolean Local(){
try{
return System.getenv("LOCAL_SYS")!=null;
}catch(Exception e){
return false;
}
}
public static boolean LOCAL;
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();
}
}
static class Pair<T,X> {
T first;
X second;
Pair(T first,X second){
this.first = first;
this.second = second;
}
@Override
public int hashCode(){
return Objects.hash(first,second);
}
@Override
public boolean equals(Object obj){
return obj.hashCode() == this.hashCode();
}
}
static PrintStream debug = null;
static long mod = (long)(Math.pow(10,9) + 7);
//TEMPLATE -------------------------------------------------------------------------------------END//
public static void main(String[] args) throws Exception {
FastScanner s = new FastScanner();
LOCAL = Local();
//PrintWriter pw = new PrintWriter(System.out);
if(LOCAL){
s = new FastScanner("src/input.txt");
PrintStream o = new PrintStream("src/sampleout.txt");
debug = new PrintStream("src/debug.txt");
System.setOut(o);
// pw = new PrintWriter(o);
} long mod = 1000000007;
int tcr = s.nextInt();
StringBuilder sb = new StringBuilder();
for(int tc=0;tc<tcr;tc++){
int n = s.nextInt();
int m = s.nextInt();
String str = s.next();
int dx = 0;
int dy = 0;
int max_dx = 0;
int min_dx = 0;
int max_dy = 0;
int min_dy = 0;
int ans_x = 1;
int ans_y = 1;
int range_x[] = new int[]{1,m};
int range_y[] = new int[]{1,n};
for(char c : str.toCharArray()){
if(c == 'L'){dx--;}
else if(c == 'R'){dx++;}
else if(c == 'U'){dy--;}
else{dy++;}
min_dx = Math.min(min_dx,dx);
max_dx = Math.max(max_dx,dx);
min_dy = Math.min(min_dy,dy);
max_dy = Math.max(max_dy,dy);
range_x[0] = Math.max(range_x[0],1 - min_dx);
range_x[1] = Math.min(range_x[1],m - max_dx);
range_y[0] = Math.max(range_y[0],1 - min_dy);
range_y[1] = Math.min(range_y[1],n - max_dy);
// dbg(debug,range_x);
// dbg(debug,range_y);
if((range_x[0] > range_x[1]) || (range_y[0] > range_y[1]) || (!inRange(1,m,range_x[0])) || (!inRange(1,m,range_x[1])) || (!inRange(1, n,range_y[0])) || (!inRange(1,n,range_y[1]))){
break;
}
ans_x = range_x[0];
ans_y = range_y[0];
}
sb.append(ans_y+" "+ans_x+"\n");
}
print(sb.toString());
}
public static List<int[]> print_prime_factors(int n){
List<int[]> list = new ArrayList<>();
for(int i=2;i<=(int)(Math.sqrt(n));i++){
if(n % i == 0){
int cnt = 0;
while( (n % i) == 0){
n = n/i;
cnt++;
}
list.add(new int[]{i,cnt});
}
}
if(n!=1){
list.add(new int[]{n,1});
}
return list;
}
public static List<int[]> prime_factors(int n,List<Integer> sieve){
List<int[]> list = new ArrayList<>();
int index = 0;
while(n > 1 && sieve.get(index) <= Math.sqrt(n)){
int curr = sieve.get(index);
int cnt = 0;
while((n % curr) == 0){
n = n/curr;
cnt++;
}
if(cnt >= 1){
list.add(new int[]{curr,cnt});
}
index++;
}
if(n > 1){
list.add(new int[]{n,1});
}
return list;
}
public static boolean inRange(int r1,int r2,int val){
return ((val >= r1) && (val <= r2));
}
static int len(long num){
return Long.toString(num).length();
}
static long mulmod(long a, long b,long mod)
{
long ans = 0l;
while(b > 0){
long curr = (b & 1l);
if(curr == 1l){
ans = ((ans % mod) + a) % mod;
}
a = (a + a) % mod;
b = b >> 1;
}
return ans;
}
public static void dbg(PrintStream ps,Object... o) throws Exception{
if(ps == null){
return;
}
Debug.dbg(ps,o);
}
public static long modpow(long num,long pow,long mod){
long val = num;
long ans = 1l;
while(pow > 0l){
long bit = pow & 1l;
if(bit == 1){
ans = (ans * (val%mod))%mod;
}
val = (val * val) % mod;
pow = pow >> 1;
}
return ans;
}
public static char get(int n){
return (char)('a' + n);
}
public static long[] sort(long arr[]){
List<Long> list = new ArrayList<>();
for(long n : arr){list.add(n);}
Collections.sort(list);
for(int i=0;i<arr.length;i++){
arr[i] = list.get(i);
}
return arr;
}
public static int[] sort(int arr[]){
List<Integer> list = new ArrayList<>();
for(int n : arr){list.add(n);}
Collections.sort(list);
for(int i=0;i<arr.length;i++){
arr[i] = list.get(i);
}
return arr;
}
// return the (index + 1)
// where index is the pos of just smaller element
// i.e count of elemets strictly less than num
public static int justSmaller(long arr[],long num){
// System.out.println(num+"@");
int st = 0;
int e = arr.length - 1;
int ans = -1;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] >= num){
e = mid - 1;
}else{
ans = mid;
st = mid + 1;
}
}
return ans + 1;
}
public static int justSmaller(int arr[],int num){
// System.out.println(num+"@");
int st = 0;
int e = arr.length - 1;
int ans = -1;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] >= num){
e = mid - 1;
}else{
ans = mid;
st = mid + 1;
}
}
return ans + 1;
}
//return (index of just greater element)
//count of elements smaller than or equal to num
public static int justGreater(long arr[],long num){
int st = 0;
int e = arr.length - 1;
int ans = arr.length;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] <= num){
st = mid + 1;
}else{
ans = mid;
e = mid - 1;
}
}
return ans;
}
public static int justGreater(int arr[],int num){
int st = 0;
int e = arr.length - 1;
int ans = arr.length;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] <= num){
st = mid + 1;
}else{
ans = mid;
e = mid - 1;
}
}
return ans;
}
public static void println(Object obj){
System.out.println(obj.toString());
}
public static void print(Object obj){
System.out.print(obj.toString());
}
public static int gcd(int a,int b){
if(b == 0){return a;}
return gcd(b,a%b);
}
public static long gcd(long a,long b){
if(b == 0l){
return a;
}
return gcd(b,a%b);
}
public static int find(int parent[],int v){
if(parent[v] == v){
return v;
}
return parent[v] = find(parent, parent[v]);
}
public static List<Integer> sieve(){
List<Integer> prime = new ArrayList<>();
int arr[] = new int[100001];
Arrays.fill(arr,1);
arr[1] = 0;
arr[2] = 1;
for(int i=2;i<=100000;i++){
if(arr[i] == 1){
prime.add(i);
for(long j = (i*1l*i);j<100001;j+=i){
arr[(int)j] = 0;
}
}
}
return prime;
}
static boolean isPower(long n,long a){
long log = (long)(Math.log(n)/Math.log(a));
long power = (long)Math.pow(a,log);
if(power == n){return true;}
return false;
}
private static int mergeAndCount(int[] arr, int l,int m, int r)
{
// Left subarray
int[] left = Arrays.copyOfRange(arr, l, m + 1);
// Right subarray
int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);
int i = 0, j = 0, k = l, swaps = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j])
arr[k++] = left[i++];
else {
arr[k++] = right[j++];
swaps += (m + 1) - (l + i);
}
}
while (i < left.length)
arr[k++] = left[i++];
while (j < right.length)
arr[k++] = right[j++];
return swaps;
}
// Merge sort function
private static int mergeSortAndCount(int[] arr, int l,int r)
{
// Keeps track of the inversion count at a
// particular node of the recursion tree
int count = 0;
if (l < r) {
int m = (l + r) / 2;
// Total inversion count = left subarray count
// + right subarray count + merge count
// Left subarray count
count += mergeSortAndCount(arr, l, m);
// Right subarray count
count += mergeSortAndCount(arr, m + 1, r);
// Merge count
count += mergeAndCount(arr, l, m, r);
}
return count;
}
static class Debug{
//change to System.getProperty("ONLINE_JUDGE")==null; for CodeForces
public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==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)+"}\n";
}else if(t instanceof long[]) {
String s = Arrays.toString((long[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof char[]) {
String s = Arrays.toString((char[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof double[]) {
String s = Arrays.toString((double[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof boolean[]) {
String s = Arrays.toString((boolean[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}
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("}\n");
return ret.toString();
}
public static void dbg(PrintStream ps,Object... o) throws Exception {
if(LOCAL) {
System.setErr(ps);
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [\n");
for(int i = 0; i<o.length; i++) {
if(i!=0) {
System.err.print(", ");
}
System.err.print(ts(o[i]));
}
System.err.println("]");
}
}
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | a31cddb1d30101c60b5206174f4c7ec6 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
static Scanner scanner=new Scanner (System.in);
public static void main(String[] args) throws IOException {
int t=scanner.nextInt();
l:while(t-->0) {
int x=scanner.nextInt();
int y=scanner.nextInt();
int xx=0,yy=0;
char a[]=scanner.next().toCharArray();
int maxx=0,maxy=0,minx=0,miny=0;
for(int i=0;i<a.length;i++) {
int mxx=maxx,mnx=minx,mxy=maxy,mny=miny;
if(a[i]=='L') {
xx++;
maxx=Math.max(maxx, xx);
minx=Math.min(minx, xx);
if(maxx-minx>=y) {
xx--;
maxx=mxx;
minx=mnx;
break;
}
}else if(a[i]=='R') {
xx--;
maxx=Math.max(maxx, xx);
minx=Math.min(minx, xx);
if(maxx-minx>=y) {
xx++;
maxx=mxx;
minx=mnx;
break;
}
}else if(a[i]=='U'){
yy++;
maxy=Math.max(maxy,yy);
miny=Math.min(miny, yy);
if(maxy-miny>=x) {
yy--;
maxy=mxy;
miny=mny;
break;
}
}else {
yy--;
maxy=Math.max(maxy,yy);
miny=Math.min(miny, yy);
if(maxy-miny>=x) {
yy--;
maxy=mxy;
miny=mny;
break;
}
}
}
//System.out.println(maxx+" "+minx+" "+maxy+" "+miny);
System.out.println((maxy+1)+" "+(maxx+1));
}
}
static class Node {
int a;
char c;
public Node(int a, char c) {
this.a = a;
this.c = c;
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 1ccb6e6be180f48dc1b5a369648b993c | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | //package codeforces.round753div3;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
//Think through the entire logic before jump into coding!
//If you are out of ideas, take a guess! It is better than doing nothing!
//Read both C and D, it is possible that D is easier than C for you!
//Be aware of integer overflow!
//If you find an answer and want to return immediately, don't forget to flush before return!
public class E {
static InputReader in;
static PrintWriter out;
public static void main(String[] args) {
//initReaderPrinter(true);
initReaderPrinter(false);
solve(in.nextInt());
//solve(1);
}
static void solve(int testCnt) {
for (int testNumber = 0; testNumber < testCnt; testNumber++) {
int n = in.nextInt(), m = in.nextInt();
char[] s = in.next().toCharArray();
int ansX = 1, ansY = 1;
int minX = 1, maxX = 1;
int minY = 1, maxY = 1;
int currX = 1, currY = 1;
for(int i = 0; i < s.length; i++) {
//u, d for x; l, r for y
if(s[i] == 'U') {
currX--;
if(currX < 1) {
if(maxX < n) {
ansX++;
currX = 1;
maxX++;
}
else break;
}
minX = min(minX, currX);
}
else if(s[i] == 'D') {
currX++;
if(currX > n) {
if(minX > 1) {
ansX--;
currX = n;
minX--;
}
else break;
}
maxX = max(maxX, currX);
}
else if(s[i] == 'L') {
currY--;
if(currY < 1) {
if(maxY < m) {
ansY++;
currY = 1;
maxY++;
}
else break;
}
minY = min(minY, currY);
}
else {
currY++;
if(currY > m) {
if(minY > 1) {
ansY--;
currY = m;
minY--;
}
else break;
}
maxY = max(maxY, currY);
}
}
out.println(ansX + " " + ansY);
}
out.close();
}
static void initReaderPrinter(boolean test) {
if (test) {
try {
in = new InputReader(new FileInputStream("src/input.in"));
out = new PrintWriter(new FileOutputStream("src/output.out"));
} catch (IOException e) {
e.printStackTrace();
}
} else {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream), 32768);
} catch (Exception e) {
e.printStackTrace();
}
}
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();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
Integer[] nextIntArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[] nextIntArrayPrimitive(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[] nextIntArrayPrimitiveOneIndexed(int n) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) a[i] = nextInt();
return a;
}
Long[] nextLongArray(int n) {
Long[] a = new Long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long[] nextLongArrayPrimitive(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long[] nextLongArrayPrimitiveOneIndexed(int n) {
long[] a = new long[n + 1];
for (int i = 1; i <= n; i++) a[i] = nextLong();
return a;
}
String[] nextStringArray(int n) {
String[] g = new String[n];
for (int i = 0; i < n; i++) g[i] = next();
return g;
}
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | cc9038d751d082f5449786403f7665d9 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
static Scanner sc = new Scanner(new BufferedInputStream(System.in));
static int sc(){return sc.nextInt();}
static double scd(){return sc.nextDouble();}
static char[] carr(){return sc.next().toCharArray();}
static long scl(){return sc.nextLong();}
static String scs(){return sc.next();}
static char scf(){return sc.next().charAt(0);}
static char[] chars(){String s = sc.next();char[] c = new char[s.length()+1];for(int i = 1;i<=s.length();i++){c[i] = s.charAt(i-1);}return c;}
// static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// static int toi(String s){return Integer.parseInt(s);}
// static double tod(String s) {return Double.parseDouble(s);}
// static long tol(String s) {return Long.parseLong(s);}
// static int[] geti() throws Exception{String[] s = sarr();int[] a = new int[s.length];for(int i = 0;i<s.length;i++) {a[i] = Integer.parseInt(s[i]);}return a;}
// static long[] getl() throws Exception{String[] s = sarr();long[] a = new long[s.length];for(int i = 0;i<s.length;i++) {a[i] = Long.parseLong(s[i]);}return a;}
// static double[] getd() throws Exception{String[] s = sarr();double[] a = new double[s.length];for(int i = 0;i<s.length;i++) {a[i] = Double.parseDouble(s[i]);}return a;}
// static char[] carr() throws Exception{return br.readLine().toCharArray();}
// static char[] chars() throws Exception{char[] c = carr();char[] res = new char[c.length+1];System.arraycopy(c, 0, res, 1, c.length);return res;}
// static String[] sarr() throws Exception{return br.readLine().split(" ");}
// static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
// static int sc() throws Exception{in.nextToken();return (int)in.nval;}
// static double scd() throws Exception{in.nextToken();return in.nval;}
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static void print(Object o){out.print(o);}
static void println(Object o){out.println(o);}
static void println(){out.println();}
static void Y(){println("YES");}
static void N(){println("NO");}
static final int N = (int)2e6+10,M = 2010,P = 131,MOD = (int)1e9+7;
static int n;
static int[] dx = new int[]{0,-1,0,1},dy = new int[]{-1,0,1,0};
static int INF= 0x3f3f3f3f;
// static int[] h = new int[N],e = new int[N],ne = new int[N],w = new int[N];
// static int idx;
// static int[] a = new int[N];
public static void main(String[] args) throws Exception{
int t = sc();
while(t-->0){
n = sc();
int m = sc();
char[] c = carr();
int x = 1,y = 1;
int minx = 1,maxx = n;
int miny = 1,maxy = m;
int lenl = 0,lendown = 0;
boolean f = false;
for(int i = 0;i<c.length;i++){
if(f) break;
if(minx == maxx&&miny == maxy){
break;
}
if(c[i] == 'R'){
lenl++;
maxy = Math.min(maxy,m - lenl);
if(maxy<miny){
f = true;
println(minx+" "+miny);
}
}else if(c[i] == 'D'){
lendown++;
maxx = Math.min(maxx,n-lendown);
if(maxx<minx){
f = true;
println(minx+" "+miny);
}
}else if(c[i] == 'U'){
lendown--;
minx = Math.max(minx,-lendown+1);
if(maxx<minx){
f = true;
println(maxx+" "+miny);
}
}else {
lenl--;
miny = Math.max(miny,-lenl+1);
if(maxy<miny){
f = true;
println(minx+" "+maxy);
}
}
}
if(!f) println(maxx+" "+maxy);
}
out.close();
}
static class D{int x,y;D(int x,int y){this.x = x;this.y = y;}}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | eedb311bded22b187de3318c27a4a5cd | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | /********
* @author Brennan Cox
*
********/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.StringTokenizer;
public class Main {
public Main() {
FastScanner input = new FastScanner(System.in);
StringBuilder output = new StringBuilder();
int t = input.nextInt();
for (int i = 0; i < t; i++) {
int rows = input.nextInt();
int columns = input.nextInt();
Point start = new Point(1, 1);
Point at = new Point(1, 1);
Number row = new Number(rows - 1);
Number column = new Number(columns - 1);
for(char direction : input.next().toCharArray()) {
Point moveTo = null;
switch (direction) {
case 'R':
column.increase();
if (column.withinDiff()) {
moveTo = new Point(0, 1);
}
break;
case 'L':
column.decrease();
if (column.withinDiff()) {
moveTo = new Point(0, -1);
}
break;
case 'U':
row.decrease();
if (row.withinDiff()) {
moveTo = new Point(-1, 0);
}
break;
case 'D':
row.increase();
if (row.withinDiff()) {
moveTo = new Point(1, 0);
}
break;
}
if (moveTo == null) {
break;
}
if (at.canGo(moveTo, rows, columns)) {
at.go(moveTo);
} else {
moveTo.opposite();
if (start.canGo(moveTo, rows, columns)) {
start.go(moveTo);
} else {
break;
}
}
}
output.append(start.toString() + "\n");
}
System.out.println(output);
}
/**
* This class is intended to allow for storage of multiple different elements
* and allows us to know if our starting point can move in specified directions
*
* it helps us understand if we are still on the table
* Ex: in the grid [][][]
* we put the arbitrary starting location on the first index
* [*][][]
* now if we wanted to move left then move the starting point right
* [][*][]
* now if we were to move right twice then technically if we were to mark where we are at
* [a][*][] now we could move right twice
* [][a*][]
* [][*][a] but from the before mentioned knowledge if we wanted to move another right
* then why not move the start back again?
* [*][][a]
* this is because then we would not have been able to previously move left
* so to preserve this idea we keep a minimum and a maximum of the directions
* we travel to the left or right and if the difference of those is larger than
* row - 1 then we couldn't possible shift the start location again
* @author Brennan
*
*/
class Number {
int max;
int min;
int num;
int maxDiff;
public Number(int maxDiff) {
max = min = num = 0;
this.maxDiff = maxDiff;
}
public void increase() {
num++;
update();
}
public void decrease() {
num--;
update();
}
public void update() {
max = Math.max(max, num);
min = Math.min(min, num);
}
public boolean withinDiff() {
return max - min <= maxDiff;
}
@Override
public String toString() {
return max +" "+ min +": "+ maxDiff;
}
}
class Point {
int row;
int column;
public Point(int row, int column) {
this.row = row;
this.column = column;
}
public boolean canGo(Point point, int limitRow, int limitColumn) {
int row = this.row + point.row;
int column = this.column + point.column;
return row > 0 && row <= limitRow && column > 0 && column <= limitColumn;
}
public void go(Point point) {
this.row+= point.row;
this.column+= point.column;
}
public void opposite() {
this.column*= -1;
this.row*= -1;
}
public boolean equals(Point point) {
return this.row == point.row && this.column == point.column;
}
@Override
public String toString() {
return row + " " + column;
}
}
public static void main(String[] args) {
new Main();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner(InputStream in) {
this(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() { return Double.parseDouble(next());}
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 52440997a036a0736e0c07fd9435f3c6 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
public class RobotOnBoard {
public static void main(String[] args) throws IOException {
FastReader fr = new FastReader();
PrintWriter pr = new PrintWriter(new OutputStreamWriter(System.out));
int t = fr.nextInt();
while (t-- > 0) {
int n = fr.nextInt();
int m = fr.nextInt();
String s = fr.nextLine();
int minX = 0, minY = 0;
int maxX = 0, maxY = 0;
int cx = 0;
int cy = 0;
int temp;
boolean possible = true;
for (int i = 0; i < s.length() && possible; i++) {
switch (s.charAt(i)) {
case 'L':
cy--;
temp = minY;
minY = Math.min(minY, cy);
if (maxY + Math.abs(minY) >= m) {
minY = temp;
possible = false;
break;
}
break;
case 'R':
cy++;
temp = maxY;
maxY = Math.max(maxY, cy);
if (maxY + Math.abs(minY) >= m) {
maxY = temp;
possible = false;
break;
}
break;
case 'D':
cx++;
temp = maxX;
maxX = Math.max(maxX, cx);
if (Math.abs(minX) + maxX >= n) {
maxX = temp;
possible = false;
break;
}
break;
case 'U':
cx--;
temp = minX;
minX = Math.min(minX, cx);
if (Math.abs(minX) + maxX >= n) {
minX = temp;
possible = false;
cx++;
break;
}
break;
default:
break;
}
}
pr.println((Math.abs(minX) + 1) + " " + (Math.abs(minY) + 1));
}
pr.close();
}
static class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
static int toInt(String s) {
return Integer.parseInt(s);
}
// MERGE SORT IMPLEMENTATION
void sort(int[] arr, int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
sort(arr, l, m);
sort(arr, m + 1, r);
// call merge
merge(arr, l, m, r);
}
}
void merge(int[] arr, int l, int m, int r) {
// find sizes
int len1 = m - l + 1;
int len2 = r - m;
int[] L = new int[len1];
int[] R = new int[len2];
// push to copies
for (int i = 0; i < L.length; i++)
L[i] = arr[l + i];
for (int i = 0; i < R.length; i++) {
R[i] = arr[m + 1 + i];
}
// fill in new array
int i = 0, j = 0;
int k = l;
while (i < len1 && j < len2) {
if (L[i] < R[i]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[i];
j++;
}
k++;
}
// add remaining elements
while (i < len1) {
arr[k] = L[i];
i++;
k++;
}
while (j < len2) {
arr[k] = R[j];
j++;
k++;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() throws FileNotFoundException {
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\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 49c51555fc8c5e5b3a2b77b95c4ac05c | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class E {
public static void main(String args[]) {
Scanner fs = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int T = fs.nextInt();
for(int loop=1; loop<=T; loop++) {
int n = fs.nextInt(), m = fs.nextInt();
String d = fs.next();
int dx = 0, dy = 0;
int maxDeltaX = 0, minDeltaX = 0, maxDeltaY = 0, minDeltaY = 0;
int ans_x = 1;
int ans_y = 1;
for(int i = 0; i < d.length(); i++) {
char x = d.charAt(i);
if (x == 'L') minDeltaY = Math.min(minDeltaY, --dy);
if (x == 'R') maxDeltaY = Math.max(maxDeltaY, ++dy);
if (x == 'U') minDeltaX = Math.min(minDeltaX, --dx);
if (x == 'D') maxDeltaX = Math.max(maxDeltaX, ++dx);
int maxX = n - maxDeltaX;
int minX = 1 - minDeltaX;
int maxY = m - maxDeltaY;
int minY = 1 - minDeltaY;
if(minX <= maxX && minY <= maxY) {
ans_x = minX;
ans_y = minY;
} else {
break;
}
}
System.out.println(ans_x + " " + ans_y);
}
}
// public static void main(String args[]) {
// Scanner fs = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
// int T = fs.nextInt();
// for(int loop=1; loop<=T; loop++) {
// int n = fs.nextInt(), m = fs.nextInt();
// String d = fs.next();
// int leftRight = 0, upDown = 0;
// int maxX = 0, minX = 0, maxY = 0, minY = 0;
// int ans_x = 1;
// int ans_y = 1;
// for(int i = 0; i < d.length(); i++) {
// char dir = d.charAt(i);
// if(dir == 'U') maxY = Math.max(maxY, ++upDown);
// else if(dir == 'D') minY = Math.min(minY, --upDown);
// else if(dir == 'R') maxX = Math.max(maxX, ++leftRight);
// else minX = Math.min(minX, --leftRight);
// if(maxX - minX >= m || maxY - minY >= n) {
// break;
// } else {
// ans_x = Math.abs(maxY) + 1;
// ans_y = Math.abs(minX) + 1;
// }
// }
// System.out.println(ans_x + " " + ans_y);
// }
// }
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 024f86388bb13e3a329ba428656d55f2 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class E {
public static void main(String args[]) {
Scanner fs = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int T = fs.nextInt();
for(int loop=1; loop<=T; loop++) {
int n = fs.nextInt(), m = fs.nextInt();
String d = fs.next();
int leftRight = 0, upDown = 0;
int maxX = 0, minX = 0, maxY = 0, minY = 0;
int ans_x = 1;
int ans_y = 1;
for(int i = 0; i < d.length(); i++) {
char dir = d.charAt(i);
if(dir == 'U') maxY = Math.max(maxY, ++upDown);
else if(dir == 'D') minY = Math.min(minY, --upDown);
else if(dir == 'R') maxX = Math.max(maxX, ++leftRight);
else minX = Math.min(minX, --leftRight);
if(maxX - minX >= m || maxY - minY >= n) {
break;
} else {
ans_x = Math.abs(maxY) + 1;
ans_y = Math.abs(minX) + 1;
}
}
System.out.println(ans_x + " " + ans_y);
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | f6ddfc16bdda6c9f990cda751f576717 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class E {
public static void main(String args[]) {
Scanner fs = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int T = fs.nextInt();
for(int loop=1; loop<=T; loop++) {
int n = fs.nextInt(), m = fs.nextInt();
String d = fs.next();
int leftRight = 0, upDown = 0;
int maxX = 0, minX = 0, maxY = 0, minY = 0;
int ans_x = 1;
int ans_y = 1;
for(int i = 0; i < d.length(); i++) {
char dir = d.charAt(i);
if(dir == 'U') maxY = Math.max(maxY, ++upDown);
else if(dir == 'D') minY = Math.min(minY, --upDown);
else if(dir == 'R') maxX = Math.max(maxX, ++leftRight);
else minX = Math.min(minX, --leftRight);
// Assuming x is the answer
// Assuming y is the answer
// At any point
// x + maxDx <= n | x + minDx >= 1;
// x = n - maxDx | x = 1 - minDx
// x <= n | x >= 1
// y + maxDy <= n | y + minDy >= 1;
if(maxX - minX + 1 > m || maxY - minY + 1 > n) {
break;
} else {
ans_x = Math.abs(maxY) + 1;
ans_y = Math.abs(minX) + 1;
}
// int dR = m - maxX;
// int dL = 1 - minX;
// int dU = n - maxY;
// int dD = 1 - minY;
// if(dL <= dR && dD <= dU) {
// ans_x = dL;
// ans_y = dD;
// } else {
// break;
// }
}
System.out.println(ans_x + " " + ans_y);
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | cacdb820285e13aed9fd94c8c84a5b96 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes |
import java.awt.Container;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
FastScanner input = new FastScanner();
int tc = input.nextInt();
while (tc-- > 0) {
int n = input.nextInt();
int m = input.nextInt();
char a[] = input.next().toCharArray();
int x = 0;
int y = 0;
int ansx = 1;
int ansy = 1;
int mindx = 0;
int mindy = 0;
int maxdx = 0;
int maxdy = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == 'L') {
y--;
} else if (a[i] == 'R') {
y++;
} else if (a[i] == 'U') {
x--;
} else {
x++;
}
mindx = Math.min(mindx, x);
maxdx = Math.max(maxdx, x);
mindy = Math.min(mindy, y);
maxdy = Math.max(maxdy, y);
if(maxdx-mindx<n&&maxdy-mindy<m)
{
ansx =1-mindx;
ansy = 1-mindy;
}
else
break;
}
System.out.println(ansx+" "+ansy);
}
}
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) {
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine() throws IOException
{
return br.readLine();
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | bfc2c3ba2dd6530d45884d2f97734977 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes |
import java.awt.Container;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
FastScanner input = new FastScanner();
int tc = input.nextInt();
while (tc-- > 0) {
int n = input.nextInt();
int m = input.nextInt();
char a[] = input.next().toCharArray();
int x = 0;
int y = 0;
int ansx = 1;
int ansy = 1;
int mindx = 0;
int mindy = 0;
int maxdx = 0;
int maxdy = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == 'L') {
y--;
} else if (a[i] == 'R') {
y++;
} else if (a[i] == 'U') {
x--;
} else {
x++;
}
mindx = Math.min(mindx, x);
maxdx = Math.max(maxdx, x);
mindy = Math.min(mindy, y);
maxdy = Math.max(maxdy, y);
if(maxdx-mindx>=n||maxdy-mindy>=m)
break;
ansx =n-maxdx;
ansy = m-maxdy;
}
System.out.println(ansx+" "+ansy);
}
}
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) {
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine() throws IOException
{
return br.readLine();
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | ba5307d42947bf02681d7b7e112b49ea | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes |
import java.awt.Container;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
FastScanner input = new FastScanner();
int tc = input.nextInt();
while (tc-- > 0) {
int n = input.nextInt();
int m = input.nextInt();
char a[] = input.next().toCharArray();
int x = 0;
int y = 0;
int ansx = 1;
int ansy = 1;
int mindx = 0;
int mindy = 0;
int maxdx = 0;
int maxdy = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == 'L') {
y--;
} else if (a[i] == 'R') {
y++;
} else if (a[i] == 'U') {
x--;
} else {
x++;
}
mindx = Math.min(mindx, x);
maxdx = Math.max(maxdx, x);
mindy = Math.min(mindy, y);
maxdy = Math.max(maxdy, y);
if(maxdx-mindx>=n||maxdy-mindy>=m)
break;
ansx =1-mindx;
ansy = 1-mindy;
}
System.out.println(ansx+" "+ansy);
}
}
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) {
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine() throws IOException
{
return br.readLine();
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 34a53ac29a6c14a89919058899a2d60c | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class Main{
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static long MOD = (long) (1e9 + 7);
// static long MOD = 998244353;
static long MOD2 = MOD * MOD;
static FastReader sc = new FastReader();
static int pInf = Integer.MAX_VALUE;
static int nInf = Integer.MIN_VALUE;
static long ded = (long)(1e17)+9;
public static void main(String[] args) throws Exception {
int test = 1;
test = sc.nextInt();
for (int i = 1; i <= test; i++){
// out.print("Case #"+i+": ");
solve();
}
out.flush();
out.close();
}
static void solve(){
int n = sc.nextInt();
int m = sc.nextInt();
char[] c = sc.next().toCharArray();
int minX = 0;
int maxX = 0;
int minY = 0;
int maxY = 0;
int X = 0;
int Y = 0;
for(char g: c){
if(g=='L'){
X -= 1;
minX = Math.min(minX,X);
}else if(g=='R'){
X += 1;
maxX = Math.max(maxX,X);
}else if(g=='U'){
Y -= 1;
minY = Math.min(minY,Y);
}else{
Y += 1;
maxY = Math.max(maxY,Y);
}
if(maxX-minX>=m){
if(X==minX){
minX++;
}
break;
}
if(maxY-minY>=n){
if(Y==minY){
minY++;
}
break;
}
}
out.println((1-minY)+" "+(1-minX));
}
static long lcm(long a, long b){
return (a*b)/gcd(a,b);
}
public static long mul(long a, long b) {
return ((a % MOD) * (b % MOD)) % MOD;
}
public static long sub(long a, long b) {
return ((a%MOD)-(b%MOD)+MOD)%MOD;
}
public static long add(long a, long b) {
if((a+b)>MOD){
return a+b-MOD;
}else{
return a+b;
}
// return ((a % MOD) + (b % MOD)) % MOD;
}
static class Pair implements Comparable<Pair> {
int x;
int y;
int idx;
public Pair(int x, int y,int idx) {
this.x = x;
this.y = y;
this.idx = idx;
}
@Override
public int compareTo(Pair o){
if(this.y==o.y){
return Integer.compare(this.x,o.x);
}
return Integer.compare(this.y,o.y);
}
@Override
public String toString() {
return "Pair{" + "x=" + x + ", y=" + y + '}';
// return x+" "+y;
}
// public boolean equals(Pair o){
// return this.x==o.x&&this.y==o.y;
// }
}
public static long c2(long n) {
if ((n & 1) == 0) {
return mul(n / 2, n - 1);
} else {
return mul(n, (n - 1) / 2);
}
}
//Shuffle Sort
static final Random random = new Random();
static void ruffleSort(long[] a) {
int n = a.length;//shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n); long temp= a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
//Brian Kernighans Algorithm
static long countSetBits(long n) {
if (n == 0) return 0;
return 1 + countSetBits(n & (n - 1));
}
//Euclidean Algorithm
static long gcd(long A, long B) {
if (B == 0) return A;
return gcd(B, A % B);
}
//Modular Exponentiation
static long fastExpo(long x, long n) {
if (n == 0) return 1;
if ((n & 1) == 0) return fastExpo((x * x) % MOD, n / 2) % MOD;
return ((x % MOD) * fastExpo((x * x) % MOD, (n - 1) / 2)) % MOD;
}
//AKS Algorithm
static boolean isPrime(long n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i <= Math.sqrt(n); i += 6)
if (n % i == 0 || n % (i + 2) == 0) return false;
return true;
}
public static long modinv(long x) {
return modpow(x, MOD - 2);
}
public static long modpow(long a, long b) {
if (b == 0) {
return 1;
}
long x = modpow(a, b / 2);
x = (x * x) % MOD;
if (b % 2 == 1) {
return (x * a) % MOD;
}
return x;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 4c8b42bee2500d1ebbf2d88071dfe689 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef {
public static void main(String[] args) throws java.lang.Exception {
FastReader in = new FastReader(System.in);
StringBuilder sb = new StringBuilder();
int t = 1;
t = in.nextInt();
while (t > 0) {
--t;
int n = in.nextInt();
int m = in.nextInt();
String s = in.next();
int ansx = 1;
int ansy = 1;
int dx = 0;
int dy = 0;
int minx = 0;
int maxx = 0;
int miny = 0;
int maxy = 0;
for(int i = 0;i<s.length();i++)
{
if(s.charAt(i) == 'D')
++dx;
if(s.charAt(i) == 'U')
--dx;
if(s.charAt(i) == 'L')
--dy;
if(s.charAt(i) == 'R')
++dy;
minx = Math.min(minx, dx);
maxx = Math.max(maxx, dx);
miny = Math.min(miny, dy);
maxy = Math.max(maxy, dy);
int x = n - maxx;
int y = m - maxy;
if(x>=1 && x<=n && y>=1 && y<=m && x+minx>=1 && x+maxx<=n && y+miny>=1 && y+maxy<=m)
{
ansx = x;
ansy = y;
}
else
break;
}
sb.append(ansx+" "+ansy+"\n");
}
System.out.print(sb);
}
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 / gcd(a, b)) * b;
}
static void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
}
}
class FastReader {
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan())
;
return (char) c;
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan())
;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | c3068c51c2a17636cd068b4183b12bdf | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
public class E {
public static void main(String[] args)throws IOException {
FastScanner scan = new FastScanner();
PrintWriter output = new PrintWriter(System.out);
int t = scan.nextInt();
for(int tt = 0;tt<t;tt++) {
int n = scan.nextInt(), m = scan.nextInt();
char arr[] = scan.next().toCharArray();
int len = arr.length;
int hori = 0, vert = 0;
int lmax = 0, rmax = 0, umax = 0, dmax = 0;
for(int i = 0;i<len;i++) {
if(arr[i] == 'R') hori++;
else if(arr[i] == 'L') hori--;
else if(arr[i] == 'U') vert++;
else if(arr[i] == 'D') vert--;
int tlmax = Math.max(lmax, -hori);
int trmax = Math.max(rmax, hori);
int tdmax = Math.max(dmax, -vert);
int tumax = Math.max(umax, vert);
if((tlmax+trmax) >= m || (tumax+tdmax) >= n) break;
lmax = tlmax;
rmax = trmax;
umax = tumax;
dmax = tdmax;
}
// System.out.println("l r u d " + lmax + " " + rmax + " " + umax + " " + dmax);
int x, y;
if(lmax >= rmax) y = lmax+1;
else y = m-rmax;
if(umax >= dmax) x = umax+1;
else x = n-dmax;
output.println(x + " " + y);
}
output.flush();
}
public static int[] sort(int arr[]) {
List<Integer> list = new ArrayList<>();
for(int i:arr) list.add(i);
Collections.sort(list);
for(int i = 0;i<list.size();i++) arr[i] = list.get(i);
return arr;
}
public static int gcd(int a, int b) {
if(a == 0) return b;
return gcd(b%a, a);
}
static boolean isPrime(int n) {
if (n <= 1) return false;
else if (n == 2) return true;
else if (n % 2 == 0) return false;
for (int i = 3; i <= Math.sqrt(n); i += 2) if (n % i == 0) return false;
return true;
}
public static void printArray(int arr[]) {
for(int i:arr) System.out.print(i+" ");
System.out.println();
}
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());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 80501fe506b98eb17d09b8f332274430 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
static int M = 998244353;
static Random rng = new Random();
private static int[] testCase(int n, int m, String s) {
int startX = 0, startY = 0;
int currX = startX, currY = startY, minX = startX, minY = startY, maxX = startX, maxY = startY;
int xMoves = 0, yMoves = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'L') {
currX--;
minX = Math.min(minX, currX);
if (maxX - minX >= m) {
break;
}
} else if (s.charAt(i) == 'R') {
currX++;
maxX = Math.max(maxX, currX);
if (maxX - minX >= m) {
break;
}
}
xMoves++;
}
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'U') {
currY--;
minY = Math.min(minY, currY);
if (maxY - minY >= n) {
break;
}
} else if (s.charAt(i) == 'D') {
currY++;
maxY = Math.max(maxY, currY);
if (maxY - minY >= n) {
break;
}
}
yMoves++;
}
currX = startX;
currY = startY;
minX = startX;
minY = startY;
maxX = startX;
maxY = startY;
for (int i = 0; i < Math.min(xMoves, yMoves); i++) {
if (s.charAt(i) == 'L') {
currX--;
minX = Math.min(minX, currX);
} else if (s.charAt(i) == 'R') {
currX++;
maxX = Math.max(maxX, currX);
} else if (s.charAt(i) == 'U') {
currY--;
minY = Math.min(minY, currY);
} else if (s.charAt(i) == 'D') {
currY++;
maxY = Math.max(maxY, currY);
}
}
return new int[] {-minX + 1, -minY + 1};
}
public static void main(String[] args) {
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = in.nextInt(); // Scanner has functions to read ints, longs, strings, chars, etc.
//in.nextLine();
for (int tt = 1; tt <= t; ++tt) {
int n = in.nextInt(), m = in.nextInt();
String s = in.next();
int[] ans = testCase(n, m, s);
out.println(ans[1] + " " + ans[0]);
}
out.close();
}
private 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();
}
boolean hasNext() {
return st.hasMoreTokens();
}
char[] readCharArray(int n) {
char[] arr = new char[n];
try {
br.read(arr);
br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return arr;
}
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[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
private static void sort(int[] arr) {
int temp, idx;
for (int i = arr.length - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr);
}
private static void sort(long[] arr) {
long temp;
int idx;
for (int i = arr.length - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr);
}
private static <T> void sort(T[] arr) {
T temp;
int idx;
for (int i = arr.length - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr);
}
private static <T> void sort(T[] arr, Comparator<? super T> cmp) {
T temp;
int idx;
for (int i = arr.length - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
Arrays.sort(arr, cmp);
}
private static <T extends Comparable<? super T>> void sort(List<T> list) {
T temp;
int idx;
for (int i = list.size() - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = list.get(i);
list.set(i, list.get(idx));
list.set(idx, temp);
}
Collections.sort(list);
}
private static <T> void sort(List<T> list, Comparator<? super T> cmp) {
T temp;
int idx;
for (int i = list.size() - 1; i > 0; i--) {
idx = rng.nextInt(i + 1);
temp = list.get(i);
list.set(i, list.get(idx));
list.set(idx, temp);
}
Collections.sort(list, cmp);
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | eac864fb515ed4164e9d9eea5d043104 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.math.BigInteger;
public final class A
{
static PrintWriter out = new PrintWriter(System.out);
static StringBuilder ans=new StringBuilder();
static FastReader in=new FastReader();
static ArrayList<Integer> g[];
static long mod=(long)998244353,INF=Long.MAX_VALUE;
static boolean set[];
static int par[],partial[];
static int Days[],P[][];
static int dp[][],sum=0,size[],D[];
static int seg[],col[];
static ArrayList<Long> A;
// static HashSet<Integer> visited,imposters;
// static HashSet<Integer> set;
// static node1 seg[];
//static pair moves[]= {new pair(-1,0),new pair(1,0), new pair(0,-1), new pair(0,1)};
public static void main(String args[])throws IOException
{
/*
* star,rope
*/
int T=i();
outer:while(T-->0)
{
int N=i(),M=i();
char X[]=in.next().toCharArray();
int size=X.length;
int A[][]=new int[size][4];
//R
//L
//U
//D
int answer_x=1,answer_y=1;
int x=0,y=0;
for(int i=0; i<size; i++)
{
if(X[i]=='R')x++;
else if(X[i]=='L')x--;
else if(X[i]=='U')y--;
else y++;
A[i][0]=Math.max(0, x);
A[i][1]=Math.max(0,0-x);
A[i][2]=Math.max(0,0-y);
A[i][3]=Math.max(0,y);
if(i>0)
{
for(int j=0; j<4; j++)
{
A[i][j]=Math.max(A[i][j], A[i-1][j]);
}
}
if(A[i][0]+A[i][1]<M && A[i][2]+A[i][3]<N)
{
//System.out.println("RUN--> ");
answer_x=A[i][1]+1;
answer_y=A[i][2]+1;
}
//System.out.println(y+" "+x);
}
ans.append(answer_y+" "+answer_x+"\n");
}
out.println(ans);
out.close();
}
static int f2(ArrayList<Long> A,long x)
{
int l=-1,r=A.size();
while(r-l>1)
{
int m=(l+r)/2;
long a=A.get(m);
if(a<=x)l=m;
else r=m;
}
return l+1;
}
static int f1(ArrayList<Long> A,long x)
{
int l=-1,r=A.size();
while(r-l>1)
{
int m=(l+r)/2;
long a=A.get(m);
if(a>=x)r=m;
else l=m;
}
return A.size()-r;
}
static long f(long a,long A[])
{
int l=-1,r=A.length;
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]<=a)l=m;
else r=m;
}
return A[l];
}
static void build(int v,int tl,int tr,int A[])
{
if(tl==tr)
{
seg[v]=A[tl];
return;
}
int tm=(tl+tr)/2;
build(v*2,tl,tm,A);
build(v*2+1,tm+1,tr,A);
seg[v]=Math.min(seg[v*2], seg[v*2+1]);
}
static void update(int v,int tl,int tr,int index,int x)
{
if(tl==tr && tl==index)
{
seg[v]=x;
return;
}
int tm=(tl+tr)/2;
if(index<=tm)update(v*2,tl,tm,index,x);
else update(v*2+1,tm+1,tr,index,x);
seg[v]=Math.min(seg[v*2], seg[v*2+1]);
}
static int ask(int v,int tl,int tr,int l,int r)
{
// System.out.println(v);
// if(v>100)return 0;
if(l>r)return Integer.MAX_VALUE;
if(tl==l && tr==r)return seg[v];
int tm=(tl+tr)/2;
int a=ask(v*2,tl,tm,l,Math.min(tm, r));
// System.out.println("for--> "+(v)+" tm--> "+(tm+1)+" tr--> "+tr+" l--> "+Math.max(l, tm+1)+" r--> "+r);
int b=ask(v*2+1,tm+1,tr,Math.max(l, tm+1),r);
return Math.min(a, b);
}
static int find(int a)
{
if(par[a]<0)return a;
return par[a]=find(par[a]);
}
static void union(int a,int b)
{
a=find(a);
b=find(b);
if(a!=b)
{
par[a]+=par[b];
par[b]=a;
}
}
static int ask(int a,int b)
{
System.out.println("? "+a+" "+b);
return i();
}
static long and(int i,int j)
{
System.out.println("and "+i+" "+j);
return l();
}
static long or(int i,int j)
{
System.out.println("or "+i+" "+j);
return l();
}
static boolean is_Sorted(int A[])
{
int N=A.length;
for(int i=1; i<=N; i++)if(A[i-1]!=i)return false;
return true;
}
static boolean f(StringBuilder sb,String Y,String order)
{
StringBuilder res=new StringBuilder(sb.toString());
HashSet<Character> set=new HashSet<>();
for(char ch:order.toCharArray())
{
set.add(ch);
for(int i=0; i<sb.length(); i++)
{
char x=sb.charAt(i);
if(set.contains(x))continue;
res.append(x);
}
}
String str=res.toString();
return str.equals(Y);
}
static boolean all_Zero(int f[])
{
for(int a:f)if(a!=0)return false;
return true;
}
static long form(int a,int l)
{
long x=0;
while(l-->0)
{
x*=10;
x+=a;
}
return x;
}
static int count(String X)
{
HashSet<Integer> set=new HashSet<>();
for(char x:X.toCharArray())set.add(x-'0');
return set.size();
}
// static void build(int v,int tl,int tr,long A[])
// {
// if(tl==tr)
// {
// seg[v]=A[tl];
// }
// else
// {
// int tm=(tl+tr)/2;
// build(v*2,tl,tm,A);
// build(v*2+1,tm+1,tr,A);
// seg[v]=Math.min(seg[v*2], seg[v*2+1]);
// }
// }
static int [] sub(int A[],int B[])
{
int N=A.length;
int f[]=new int[N];
for(int i=N-1; i>=0; i--)
{
if(B[i]<A[i])
{
B[i]+=26;
B[i-1]-=1;
}
f[i]=B[i]-A[i];
}
for(int i=0; i<N; i++)
{
if(f[i]%2!=0)f[i+1]+=26;
f[i]/=2;
}
return f;
}
static int max(int a ,int b,int c,int d)
{
a=Math.max(a, b);
c=Math.max(c,d);
return Math.max(a, c);
}
static int min(int a ,int b,int c,int d)
{
a=Math.min(a, b);
c=Math.min(c,d);
return Math.min(a, c);
}
static HashMap<Integer,Integer> Hash(int A[])
{
HashMap<Integer,Integer> mp=new HashMap<>();
for(int a:A)
{
int f=mp.getOrDefault(a,0)+1;
mp.put(a, f);
}
return mp;
}
static long mul(long a, long b)
{
return ( a %mod * 1L * b%mod )%mod;
}
static void swap(int A[],int a,int b)
{
int t=A[a];
A[a]=A[b];
A[b]=t;
}
static boolean isSorted(int A[])
{
for(int i=1; i<A.length; i++)
{
if(A[i]<A[i-1])return false;
}
return true;
}
static boolean isDivisible(StringBuilder X,int i,long num)
{
long r=0;
for(; i<X.length(); i++)
{
r=r*10+(X.charAt(i)-'0');
r=r%num;
}
return r==0;
}
static int lower_Bound(int A[],int low,int high, int x)
{
if (low > high)
if (x >= A[high])
return A[high];
int mid = (low + high) / 2;
if (A[mid] == x)
return A[mid];
if (mid > 0 && A[mid - 1] <= x && x < A[mid])
return A[mid - 1];
if (x < A[mid])
return lower_Bound( A, low, mid - 1, x);
return lower_Bound(A, mid + 1, high, x);
}
static String f(String A)
{
String X="";
for(int i=A.length()-1; i>=0; i--)
{
int c=A.charAt(i)-'0';
X+=(c+1)%2;
}
return X;
}
static void sort(long[] a) //check for long
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static String swap(String X,int i,int j)
{
char ch[]=X.toCharArray();
char a=ch[i];
ch[i]=ch[j];
ch[j]=a;
return new String(ch);
}
static int sD(long n)
{
if (n % 2 == 0 )
return 2;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0 )
return i;
}
return (int)n;
}
static void setGraph(int N)
{
// tot=new int[N+1];
partial=new int[N+1];
Days=new int[N+1];
P=new int[N+1][(int)(Math.log(N)+10)];
set=new boolean[N+1];
g=new ArrayList[N+1];
D=new int[N+1];
for(int i=0; i<=N; i++)
{
g[i]=new ArrayList<>();
Days[i]=-1;
D[i]=Integer.MAX_VALUE;
//D2[i]=INF;
}
}
static long pow(long a,long b)
{
//long mod=1000000007;
long pow=1;
long x=a;
while(b!=0)
{
if((b&1)!=0)pow=(pow*x)%mod;
x=(x*x)%mod;
b/=2;
}
return pow;
}
static long toggleBits(long x)//one's complement || Toggle bits
{
int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1;
return ((1<<n)-1)^x;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
static int kadane(int A[])
{
int lsum=A[0],gsum=A[0];
for(int i=1; i<A.length; i++)
{
lsum=Math.max(lsum+A[i],A[i]);
gsum=Math.max(gsum,lsum);
}
return gsum;
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static void print(char A[])
{
for(char c:A)System.out.print(c+" ");
System.out.println();
}
static void print(boolean A[])
{
for(boolean c:A)System.out.print(c+" ");
System.out.println();
}
static void print(int A[])
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static void print(long A[])
{
for(long i:A)System.out.print(i+ " ");
System.out.println();
}
static void print(boolean A[][])
{
for(boolean a[]:A)print(a);
}
static void print(long A[][])
{
for(long a[]:A)print(a);
}
static void print(int A[][])
{
for(int a[]:A)print(a);
}
static void print(ArrayList<Integer> A)
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static int i()
{
return in.nextInt();
}
static long l()
{
return in.nextLong();
}
static int[] input(int N){
int A[]=new int[N];
for(int i=0; i<N; i++)
{
A[i]=in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[]=new long[N];
for(int i=0; i<A.length; i++)A[i]=in.nextLong();
return A;
}
static long GCD(long a,long b)
{
if(b==0)
{
return a;
}
else return GCD(b,a%b );
}
}
class Edge
{
int a,cnt;
// boolean said;
Edge(int a,int cnt)
{
this.a=a;
// this.said=said;
this.cnt=cnt;
}
}
//Code For FastReader
//Code For FastReader
//Code For FastReader
//Code For FastReader
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 | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | b3da5c6dc4f5eab25d61c604cd867398 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception {
int tc = io.nextInt();
for (int i = 0; i < tc; i++) {
solve();
}
io.close();
}
private static void solve() throws Exception {
int n = io.nextInt();
int m = io.nextInt();
String s = io.next();
int currX = 0;
int minX = 0;
int maxX = 0;
for (char c : s.toCharArray()) {
if (maxX - minX + 1 == m) break;
if (c == 'L') {
currX--;
} else if (c == 'R') {
currX++;
}
minX = Math.min(minX, currX);
maxX = Math.max(maxX, currX);
if (maxX - minX + 1 == m) break;
}
int currY = 0;
int minY = 0;
int maxY = 0;
for (char c : s.toCharArray()) {
if (maxY - minY + 1 == n) break;
if (c == 'U') {
currY--;
} else if (c == 'D') {
currY++;
}
minY = Math.min(minY, currY);
maxY = Math.max(maxY, currY);
if (maxY - minY + 1 == n) break;
}
io.println((-minY + 1) + " " + (-minX + 1));
}
static void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>(a.length);
for (long i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
//-----------PrintWriter for faster output---------------------------------
public static FastIO io = new FastIO();
//-----------MyScanner class for faster input----------
static class FastIO extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar, numChars;
// standard input
public FastIO() {
this(System.in, System.out);
}
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c;
do {
c = nextByte();
} while (c <= ' ');
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nextByte();
} while (c > ' ');
return res.toString();
}
public String nextLine() {
int c;
do {
c = nextByte();
} while (c < '\n');
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nextByte();
} while (c > '\n');
return res.toString();
}
public int nextInt() {
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() {
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
int[] nextInts(int n) {
int[] data = new int[n];
for (int i = 0; i < n; i++) {
data[i] = io.nextInt();
}
return data;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
//--------------------------------------------------------
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 05e992bd5008f17e67b2a1ddca5f288c | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
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;
t = in.nextInt();
//t = 1;
while (t > 0) {
solver.call(in,out);
t--;
}
out.close();
}
static class TaskA {
public void call(InputReader in, PrintWriter out) {
int n, m, x = 0, y = 0, maxXl = 0, maxXR = 0, maxYU = 0, maxYD = 0;
n = in.nextInt();
m = in.nextInt();
char[] arr = in.next().toCharArray();
for (int i = 0; i < arr.length; i++) {
if(arr[i]=='L' || arr[i]=='R'){
if(arr[i]=='L'){
x--;
}
else{
x++;
}
if(x < 0){
if(maxXR - x > m - 1){
break;
}
maxXl = Math.max(maxXl, -1*x);
}
else{
if(maxXl + x > m - 1){
break;
}
maxXR = Math.max(maxXR, x);
}
}
else{
if(arr[i]=='D'){
y--;
}
else{
y++;
}
if(y < 0){
if(maxYU - y > n - 1){
break;
}
maxYD = Math.max(maxYD, Math.abs(y));
}
else{
if(maxYD + y > n - 1){
break;
}
maxYU = Math.max(maxYU, y);
}
}
}
x = maxXl + 1;
y = maxYU + 1;
out.println(y+" "+x);
}
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int a, b;
public answer(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer o) {
return o.b - this.b;
}
}
static class arrayListClass {
ArrayList<Integer> arrayList2 ;
public arrayListClass(ArrayList<Integer> arrayList) {
this.arrayList2 = arrayList;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n = a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | e12dd8fc7ff6f3de3f57ad9552852fad | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collections;
public class E {
static FastScanner sc = new FastScanner();
public static void main(String[] args) {
int t = sc.nextInt();
while(t-->0) {
solve();
}
}
public static void solve() {
int n = sc.nextInt();
int m = sc.nextInt();
String movement = sc.next();
int deltaX=0, deltaY=0, minX = 0,maxX = 0, minY = 0, maxY = 0;
int ansX = 1, ansY = 1;
for(int i=0;i<movement.length();i++) {
char ch = movement.charAt(i);
if(ch == 'L')
deltaY--;
else if(ch == 'R')
deltaY++;
else if(ch == 'D')
deltaX++;
else
deltaX--;
minX = min(minX, deltaX);
maxX = max(maxX, deltaX);
minY = min(minY, deltaY);
maxY = max(maxY, deltaY);
int x = n - maxX;
int y = m - maxY;
if( x>=1 && x<=n && y>=1 && y<=m && x + maxX <=n && x + minX>=1 && y + minY>=1 && y+maxY<=m) {
ansX = x;
ansY = y;
}
else
break;
}
System.out.println(ansX+" "+ansY);
}
public static void sort(int arr[]) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0;i<arr.length;i++)
arr[i] = ls.get(i);
}
public static int max(int a, int b) {
return Math.max(a, b);
}
public static int min(int a, int b) {
return Math.min(a, b);
}
public static void print(int a[]) {
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
public static void inputArray(int a[]) {
for(int i=0;i<a.length;i++)
a[i] = sc.nextInt();
}
static class FastScanner
{
//I don't understand how this works lmao
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 675515933197bd17bf965760eee1c1e7 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class RobotOnTheBoard1 {
public static void main(String[] args){
int t;
Scanner scanner = new Scanner(System.in);
t = scanner.nextInt();
while(t>0){
t--;
int n,m;
n = scanner.nextInt();
m = scanner.nextInt();
List<List<Integer>> board= new ArrayList<>();
scanner.nextLine();
String s = scanner.nextLine();
int max_val = 0;
int x = 0;
int y = 0;
int maxUp = 0;
int maxDown = 0;
int maxLeft = 0;
int maxRight = 0;
for(int i = 0;i<s.length();i++){
char c = s.charAt(i);
if (c == 'U'){
x++;
if (x > maxUp) maxUp = x;
if ((maxUp - maxDown + 1) > n){
maxUp--;
break;
}
}
if (c =='D'){
x--;
if (x< maxDown) maxDown = x;
if ((maxUp - maxDown + 1) > n){
maxDown++;
break;
}
}
if (c == 'R'){
y++;
if (y> maxRight) maxRight = y;
if ((maxRight - maxLeft + 1) > m){
maxRight--;
break;
}
}
if (c == 'L'){
y--;
if (y < maxLeft) maxLeft = y;
if ((maxRight - maxLeft + 1) > m){
maxLeft++;
break;
}
}
}
int xloc = 0;
for(int i = 1;i<n+1;i++){
if (i-maxUp -1 >= 0 && (i - maxDown -1) >=0){
xloc = i;
break;
}
}
int yloc = 0;
for(int i = 1;i<m+1;i++){
if (i+maxLeft >= 1 && (i + maxRight) <=m){
yloc = i;
break;
}
}
System.out.println(xloc + " " + yloc);
// int max_x = 0;
// int max_y = 0;
// int max_val = Integer.MIN_VALUE;
// for(int i = 0;i<n;i++){
// board.add(new ArrayList<>());
// for (int j = 0;j<m;j++){
// int val = 0;
// int x = i;
// int y = j;
// int pos = 0;
// while(x>=0 && x<n && y>=0 && y<m && pos<s.length()){
// Character c = s.charAt(pos);
// if (c.equals('L')) y--;
// if (c.equals('R')) y++;
// if (c.equals('U')) x--;
// if (c.equals('D')) x++;
// if (x>=0 && x<n && y>=0 && y<m){
// val++;
// }
// pos++;
// }
// board.get(i).add(val);
// if (val > max_val){
// max_x = i;
// max_y = j;
// max_val = val;
// }
// }
// }
// for(int i = 0;i<n;i++){
// for(int j = 0;j<m;j++){
// System.out.printf("%d ",board.get(i).get(j));
// }
// System.out.println();
// }
// max_x++;
// max_y++;
// System.out.println(max_x + " " + max_y);
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 334b63749fc6e3de01260c5a792a85df | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class Main{
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static long MOD = (long) (1e9 + 7);
// static long MOD = 998244353;
static long MOD2 = MOD * MOD;
static FastReader sc = new FastReader();
static int pInf = Integer.MAX_VALUE;
static int nInf = Integer.MIN_VALUE;
static long ded = (long)(1e17)+9;
public static void main(String[] args) throws Exception {
int test = 1;
test = sc.nextInt();
for (int i = 1; i <= test; i++){
// out.print("Case #"+i+": ");
solve();
}
out.flush();
out.close();
}
static void solve(){
int n = sc.nextInt();
int m = sc.nextInt();
char[] c = sc.next().toCharArray();
int minX = 0;
int maxX = 0;
int minY = 0;
int maxY = 0;
int X = 0;
int Y = 0;
for(char g: c){
if(g=='L'){
X -= 1;
minX = Math.min(minX,X);
}else if(g=='R'){
X += 1;
maxX = Math.max(maxX,X);
}else if(g=='U'){
Y -= 1;
minY = Math.min(minY,Y);
}else{
Y += 1;
maxY = Math.max(maxY,Y);
}
if(maxX-minX>=m){
if(X==minX){
minX++;
}
break;
}
if(maxY-minY>=n){
if(Y==minY){
minY++;
}
break;
}
}
out.println((1-minY)+" "+(1-minX));
}
static long lcm(long a, long b){
return (a*b)/gcd(a,b);
}
public static long mul(long a, long b) {
return ((a % MOD) * (b % MOD)) % MOD;
}
public static long sub(long a, long b) {
return ((a%MOD)-(b%MOD)+MOD)%MOD;
}
public static long add(long a, long b) {
if((a+b)>MOD){
return a+b-MOD;
}else{
return a+b;
}
// return ((a % MOD) + (b % MOD)) % MOD;
}
static class Pair implements Comparable<Pair> {
int x;
int y;
int idx;
public Pair(int x, int y,int idx) {
this.x = x;
this.y = y;
this.idx = idx;
}
@Override
public int compareTo(Pair o){
if(this.y==o.y){
return Integer.compare(this.x,o.x);
}
return Integer.compare(this.y,o.y);
}
@Override
public String toString() {
return "Pair{" + "x=" + x + ", y=" + y + '}';
// return x+" "+y;
}
// public boolean equals(Pair o){
// return this.x==o.x&&this.y==o.y;
// }
}
public static long c2(long n) {
if ((n & 1) == 0) {
return mul(n / 2, n - 1);
} else {
return mul(n, (n - 1) / 2);
}
}
//Shuffle Sort
static final Random random = new Random();
static void ruffleSort(long[] a) {
int n = a.length;//shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n); long temp= a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
//Brian Kernighans Algorithm
static long countSetBits(long n) {
if (n == 0) return 0;
return 1 + countSetBits(n & (n - 1));
}
//Euclidean Algorithm
static long gcd(long A, long B) {
if (B == 0) return A;
return gcd(B, A % B);
}
//Modular Exponentiation
static long fastExpo(long x, long n) {
if (n == 0) return 1;
if ((n & 1) == 0) return fastExpo((x * x) % MOD, n / 2) % MOD;
return ((x % MOD) * fastExpo((x * x) % MOD, (n - 1) / 2)) % MOD;
}
//AKS Algorithm
static boolean isPrime(long n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i <= Math.sqrt(n); i += 6)
if (n % i == 0 || n % (i + 2) == 0) return false;
return true;
}
public static long modinv(long x) {
return modpow(x, MOD - 2);
}
public static long modpow(long a, long b) {
if (b == 0) {
return 1;
}
long x = modpow(a, b / 2);
x = (x * x) % MOD;
if (b % 2 == 1) {
return (x * a) % MOD;
}
return x;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 47cf2cd9b3beb3cb0496b1bc96f79539 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
public class Templ {
static StreamTokenizer in;
static int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
public static void main(String[] args) throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n = sc.nextInt();
int m = sc.nextInt();
String s = sc.next();
int x_min = 0;
int x_max = 0;
int y_min = 0;
int y_max = 0;
int x = 0, y = 0;
int fx = 1, fy = 1;
for (int j = 0; j < s.length(); j++) {
char c = s.charAt(j);
if (c == 'R') {
x++;
} else if (c == 'L') {
x--;
} else if (c == 'U') {
y--;
} else if (c == 'D') {
y++;
}
x_max = Math.max(x_max, x);
x_min = Math.min(x_min, x);
y_max = Math.max(y_max, y);
y_min = Math.min(y_min, y);
int dx = x_max - x_min;
int dy = y_max - y_min;
if (dx < m && dy < n) {
if (x_max > -x_min) fx = m - x_max;
else fx = 1 - x_min;
if (y_max > -y_min) fy = n - y_max;
else fy = 1 - y_min;
} else {
break;
}
}
System.out.println(fy + " " + fx);
}
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 441b4939c4e19761aff78a1abd86c8e4 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 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
*/
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);
ERobotOnTheBoard1 solver = new ERobotOnTheBoard1();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class ERobotOnTheBoard1 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
char c[] = in.next().toCharArray();
int currentColumn = 0;
int currentRow = 0;
int minColumn = 0;
int minRow = 0;
int maxColumn = 0;
int maxRow = 0;
int prevmaxColumn = 0;
int prevmaxRow = 0;
for (char ch : c) {
if (ch == 'L') {
currentColumn--;
} else if (ch == 'R') {
currentColumn++;
} else if (ch == 'U') {
currentRow--;
} else {
currentRow++;
}
minColumn = Math.min(minColumn, currentColumn);
maxColumn = Math.max(maxColumn, currentColumn);
minRow = Math.min(minRow, currentRow);
maxRow = Math.max(maxRow, currentRow);
if (Math.abs(maxColumn - minColumn) >= m || Math.abs(maxRow - minRow) >= n) {
break;
}
prevmaxColumn = maxColumn;
prevmaxRow = maxRow;
}
out.println((n - prevmaxRow) + " " + (m - prevmaxColumn));
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
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 readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | cd1d7fe8877427d507fd39789a23b0bd | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
public class E {
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 FastReader s = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
private static int[] rai(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
return arr;
}
private static int[][] rai(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = s.nextInt();
}
}
return arr;
}
private static long[] ral(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextLong();
}
return arr;
}
private static long[][] ral(int n, int m) {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = s.nextLong();
}
}
return arr;
}
private static int ri() {
return s.nextInt();
}
private static long rl() {
return s.nextLong();
}
private static String rs() {
return s.next();
}
static long gcd(long a,long b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
static int gcd(int a,int b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
static boolean isPrime(int n) {
//check if n is a multiple of 2
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;
}
static int MOD=1000000007;
static long mpow(long base,long pow)
{
long res=1;
while(pow>0)
{
if(pow%2==1)
{
res=(res*base)%MOD;
}
pow>>=1;
base=(base*base)%MOD;
}
return res;
}
static enum Type
{
T1, T2,T3, T4
}
static class Node
{
String start,end;
long count;
long len ;
public Node(String start, String end, long count, long len) {
this.start = start;
this.end = end;
this.count = count;
this.len = len;
}
@Override
public String toString() {
return "("+start+" "+end+" "+count+")";
}
}
public static void main(String[] args) {
StringBuilder ans = new StringBuilder();
int t = ri();
// int t = 1;
// int tc = 0;
while (t-- > 0)
{
int n=ri();
int m=ri();
char[] arr=rs().toCharArray();
int row = 0, col = 0;
int min = 0, max=0;
int curr = 0;
for(char c:arr)
{
if(c=='L')
{
curr--;
if(curr<min)
{
if(max-curr+1>m)
{
break;
}
min=curr;
}
}
else if(c=='R')
{
curr++;
if(curr>max)
{
if(curr-min+1>m)
{
break;
}
max=curr;
}
}
}
for(int i=min;i<=0;i++)
{
col++;
}
min = 0; max=0;
curr = 0;
for(char c:arr)
{
if(c=='U')
{
curr--;
if(curr<min)
{
if(max-curr+1>n)
{
break;
}
min=curr;
}
// System.out.println("U = "+min+" "+max);
}
else if(c=='D')
{
curr++;
if(curr>max)
{
if(curr-min+1>n)
{
break;
}
max=curr;
}
// System.out.println("D = "+min+" "+max);
}
}
for(int i=min;i<=0;i++)
{
row++;
}
ans.append(row).append(" ").append(col).append("\n");
}
out.print(ans.toString());
out.flush();
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 19552933dbcf6b5b9a1b8d2135278501 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
public class E {
public static void main(String... args) {
try {
Scanner sc = new Scanner(System.in);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
int t = sc.nextInt();
for (; t > 0; t--) {
int n = sc.nextInt(); int m = sc.nextInt();
String s = sc.next();
int[][] step = new int[s.length()+1][4]; //0-L; 1-R; 2-D; 3-U;
int[][] maxStep = new int[s.length()+1][4];
for (int i = 1; i <= s.length(); i++) {
char c = s.charAt(i-1);
for (int j = 0; j < 4; j++)
step[i][j] = step[i-1][j];
if (c == 'L') {
step[i][0]++; step[i][1]--;
} if (c == 'R') {
step[i][1]++; step[i][0]--;
} if (c == 'D') {
step[i][2]++; step[i][3]--;
} if (c == 'U') {
step[i][3]++; step[i][2]--;
}
for (int j = 0; j < 4; j++)
maxStep[i][j] = Math.max(maxStep[i-1][j], step[i][j]);
}
for (int i = s.length(); i >= 0; i--) {
int vertCeils = maxStep[i][2] + maxStep[i][3] + 1;
int horCeils = maxStep[i][0] + maxStep[i][1] + 1;
if (vertCeils > n || horCeils > m)
continue;
System.out.printf("%s %s\n", 1 + maxStep[i][3], 1 + maxStep[i][0]);
break;
}
}
sc.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 7864b4ad4cc6ba5855f8b24019256695 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
public class aaa {
//--------------------------INPUT READER--------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(long nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os);
}
public void p(int i) {w.println(i);};
public void p(long l) {w.println(l);};
public void p(double d) {w.println(d);};
public void p(String s) { w.println(s);};
public void pr(int i) {w.print(i);};
public void pr(long l) {w.print(l);};
public void pr(double d) {w.print(d);};
public void pr(String s) { w.print(s);};
public void pl() {w.println();};
public void close() {w.close();};
}
//------------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static long ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
ADMIN_MODE();
int t = sc.ni();while(t-->0)
solve();
w.close();
}
static long mod = 1000000007;
static void solve() throws IOException {
int n = sc.ni(), m = sc.ni();
String str = sc.ns();
char[] strr = str.toCharArray();
List<Character> ver = new ArrayList<>(), hor = new ArrayList<>();
for(int i = 0; i < strr.length; i++) {
char curr = strr[i];
if(curr == 'R' || curr == 'L') {
hor.add(curr);
} else ver.add(curr);
}
// HORIZONTAL
int max = 0;
int sum = 1;
int hst = 1;
for(int i = 0; i < hor.size(); i++) {
char curr = hor.get(i);
if(curr == 'R') {
sum++;
max = Math.max(max, sum);
}
else sum--;
if(sum == m) break;
if(sum == 0) {
if(hst+1 == m+1) break;
if(max+1 >= m+1) break;
max++;
hst++;
sum = 1;
}
}
// VERTICAL
max = 0;
int vst = 1;
sum = 1;
for(int i = 0; i < ver.size(); i++) {
char curr = ver.get(i);
if(curr == 'D') {
sum++;
max = Math.max(max, sum);
}
else sum--;
if(sum == n) break;
if(sum == 0) {
if(vst+1 == n+1) break;
if(max+1 >= n+1) break;
max++;
vst++;
sum = 1;
}
}
w.p(vst+" "+hst);
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 230d214a396ede6756f6819e139cfb45 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution {
public static void solve(InputReader in, PrintWriter out) {
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
int m = in.nextInt();
String st = in.next();
int x = 1, y = 1, mx = 1, my = 1, cx = 1, cy = 1;
int len = st.length();
for (int i = 0; i < len; i++) {
if (st.charAt(i) == 'R') {
cy++;
if (cy > m) {
break;
}
my = Math.max(my, cy);
} else if (st.charAt(i) == 'L') {
cy--;
if (cy < 1) {
if (my + 1 <= m) {
y++;
cy = 1;
my++;
} else {
break;
}
}
} else if (st.charAt(i) == 'U') {
cx--;
if (cx < 1) {
if (mx + 1 <= n) {
x++;
cx = 1;
mx++;
} else {
break;
}
}
} else {
cx++;
if (cx > n) {
break;
}
mx = Math.max(mx, cx);
}
}
out.println(x + " " + y);
}
}
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
String nextLine() throws Exception{
String str = "";
try{
str = reader.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 28fbcbecba921624282317971f89b18b | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes |
import java.io.*;
import java.util.*;
public class E {
public static void main(String[] args) {
FastIO io = new FastIO();
int t = io.nextInt();
while (t --> 0) {
int r = io.nextInt(), c = io.nextInt();
String s = io.next();
int hor = 0, ver = 0;
int hormax = 0, hormin = 0, vermax = 0, vermin = 0;
for (int i=0; i<s.length(); i++) {
//System.out.println(hor + " " + ver);
//System.out.println(hormin + " " + hormax + " " + vermin + " " + vermax);
if (s.charAt(i) == 'R') {
hor++;
if (hor > hormax) {
hormax = hor;
if (!check(hormax, hormin, c)) {
hor--;
hormax--;
break;
}
}
}
else if (s.charAt(i) == 'L') {
hor--;
if (hor < hormin) {
hormin = hor;
if (!check(hormax, hormin, c)) {
hor++;
hormin++;
break;
}
}
}
else if (s.charAt(i) == 'U') {
ver++;
if (ver > vermax) {
vermax = ver;
if (!check(vermax, vermin, r)) {
ver--;
vermax--;
break;
}
}
}
else if (s.charAt(i) == 'D') {
ver--;
if (ver < vermin) {
vermin = ver;
if (!check(vermax, vermin, r)) {
ver++;
vermin++;
break;
}
}
}
}
c = 1+Math.abs(hormin);
r = 1+Math.abs(vermax);
io.println(r + " " + c);
}
io.close();
}
static boolean check(int a, int b, int d) {
if (Math.abs(a-b)+1 > d) {
return false;
}
return true;
}
static class FastIO extends PrintWriter {
BufferedReader br;
StringTokenizer st;
public FastIO() {
super(System.out);
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
catch (Exception e) {
return null;
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public void close() {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
super.close();
}
}
}
class command {
int steps;
char dir;
public command(int x, char y) {
steps = x;
dir = y;
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | b50c2d8ee54c09aa3261c8e8d5283359 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 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;
//AdityaFastIO r = new AdityaFastIO();
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();
int m = r.ni();
char[] s = r.word().toCharArray();
int x = 0;
int y = 0;
int left = 0;
int right = 0;
int up = 0;
int down = 0;
int X = 0, Y = 0;
for (char c : s) {
if (c == 'L') x--;
else if (c == 'R') x++;
else if (c == 'U') y++;
else y--;
left = Math.min(left, x);
right = Math.max(right, x);
up = Math.max(up, y);
down = Math.min(down, y);
if (up - down < n && -left + right < m) {
X = -left;
Y = up;
}
}
out.write((++Y + " " + (++X) + " ").getBytes());
out.write(("\n").getBytes());
}
// Solution Ends Here
} catch (IOException e) {
e.printStackTrace();
}
}
static class AdityaFastIO {
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 AdityaFastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public AdityaFastIO(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(int[] arr, int x) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (arr[m] >= x) r = m;
else l = m;
}
return r;
}
static int upper_bound(int[] arr, int x) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (arr[m] <= x) l = m;
else r = m;
}
return l + 1;
}
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 | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 505553b68c77ccbef389ad6cddba7e5d | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static PrintWriter pw;
static Scanner sc;
static long ceildiv(long x, long y) { return (x+y-1) / y; }
static int mod(long x, int m) { return (int) ((x%m + m) % m); }
static void put(Map<Integer, Integer> map, Integer p){if(map.containsKey(p)) map.replace(p, map.get(p)+1); else map.put(p, 1); }
static void rem(Map<Integer, Integer> map, Integer p){ if(map.get(p)==1) map.remove(p); else map.replace(p, map.get(p)-1); }
static int Int(boolean x){ return x ? 1 : 0; }
static final int inf=(int)1e9, mod= inf + 7;
static final long infL=inf*1l*inf;
static final double eps=1e-9;
public static long gcd(long x, long y) { return y==0? x: gcd(y, x%y); }
public static void main(String[] args) throws Exception {
sc = new Scanner(System.in);
pw = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0)
testCase();
pw.close();
}
static void testCase() throws Exception{
int n = sc.nextInt(), m = sc.nextInt();
String s = sc.next();
Pair curr = new Pair(0, 0), max = new Pair(0, 0), min = new Pair(0, 0);
for (int i = 0; i < s.length(); i++) {
curr = change(curr, s.charAt(i));
if(Math.abs(curr.x) == m || Math.abs(curr.y) == n){
print(combine(max, min), n, m);
return;
}
Pair prevMax = max.clone();
Pair prevMin = min.clone();
max.x = Math.max(max.x, curr.x);
max.y = Math.max(max.y, curr.y);
min.x = Math.min(min.x, curr.x);
min.y = Math.min(min.y, curr.y);
if(max.x - min.x >= m || max.y - min.y >= n){
print(combine(prevMax, prevMin), n, m);
return;
}
}
print(combine(max, min), n, m);
}
static Pair combine(Pair max, Pair min){
int x = Math.abs(max.x) > Math.abs(min.x) ? max.x : min.x;
int y = Math.abs(max.y) > Math.abs(min.y) ? max.y : min.y;
return new Pair(x, y);
}
static Pair change(Pair p, char change){
if(change == 'L')
return new Pair(p.x-1, p.y);
if(change == 'R')
return new Pair(p.x+1, p.y);
if(change == 'D')
return new Pair(p.x, p.y-1);
return new Pair(p.x, p.y+1);
}
static void print(Pair ans, int n, int m){
int x = ans.x < 0 ? -ans.x : m - ans.x - 1;
int y = ans.y < 0 ? -ans.y : n - ans.y - 1;
pw.println((n-y) + " " + (x+1));
}
static void printArr(int[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(long[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(double[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printArr(Integer[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
}
static void printIter(Iterable list) {
for (Object o : list)
pw.print(o + " ");
pw.println();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextDigits() throws IOException {
String s = nextLine();
int[] arr = new int[s.length()];
for (int i = 0; i < arr.length; i++)
arr[i] = s.charAt(i) - '0';
return arr;
}
public int[] nextArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextInt();
return arr;
}
public Integer[] nextsort(int n) throws IOException {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public Pair nextPair() throws IOException {
return new Pair(nextInt(), nextInt());
}
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 Pair[] nextPairArr(int n) throws IOException {
Pair[] arr = new Pair[n];
for (int i = 0; i < n; i++)
arr[i] = nextPair();
return arr;
}
public boolean hasNext() throws IOException {
return (st != null && st.hasMoreTokens()) || br.ready();
}
}
static class Pair implements Comparable<Pair> {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public Pair(Map.Entry<Integer, Integer> a) {
x = a.getKey();
y = a.getValue();
}
public int hashCode() {
return (int) ((this.x*1l*100003 + this.y) % mod);
}
public int compareTo(Pair p) {
if(x != p.x)
return x - p.x;
return y - p.y;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Pair p = (Pair) obj;
return this.x == p.x && this.y == p.y;
}
public Pair clone() {
return new Pair(x, y);
}
public String toString() {
return this.x + " " + this.y;
}
public void subtract(Pair p) {
x -= p.x;
y -= p.y;
}
public void add(Pair p) {
x += p.x;
y += p.y;
}
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | ae2ed0830398dc1b4b15372cd4817e3e | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class E_Robot_on_the_Board_1
{
static int M = 1_000_000_007;
static final PrintWriter out =new PrintWriter(System.out);
static final FastReader fs = new FastReader();
static boolean prime[];
public static void main (String[] args) throws java.lang.Exception
{
int t= fs.nextInt();
for(int i=0;i<t;i++)
{
int n=fs.nextInt();
int m=fs.nextInt();
char c[]=fs.nextLine().toCharArray();
ArrayList<Character> h=new ArrayList<Character>();
ArrayList<Character> v=new ArrayList<Character>();
for(int j=0;j<c.length;j++){
if(c[j]=='U'||c[j]=='D'){
v.add(c[j]);
}else{
h.add(c[j]);
}
}
int x=(m+1)/2;
int y=(n+1)/2;
int hr=(m+1)/2;
int hl=(m+1)/2;
int vu=(n+1)/2;
int vd=(n+1)/2;
int currh=(m+1)/2;
int currv=(n+1)/2;
for(int j=0;j<h.size();j++){
if(h.get(j)=='R'){
currh++;
}else{
currh--;
}
if(currh>m){
if(hl>1){
hl--;
currh--;
x--;
}else{
break;
}
}else if(currh<1){
if(hr<m){
hr++;
currh++;
x++;
}
}
hr=Math.max(hr,currh);
hl=Math.min(hl,currh);
}
for(int j=0;j<v.size();j++){
if(v.get(j)=='U'){
currv--;
}else{
currv++;
}
if(currv<1){
if(vd<n){
vd++;
currv++;
y++;
}else{
break;
}
}else if(currv>n){
if(vu>1){
vu--;
currv--;
y--;
}
}
vu=Math.min(vu,currv);
vd=Math.max(vd,currv);
}
out.println(y+" "+x);
}
out.flush();
}
public static long power(long x, long y)
{
long temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return modMult(temp,temp);
else {
if (y > 0)
return modMult(x,modMult(temp,temp));
else
return (modMult(temp,temp)) / x;
}
}
static void sieveOfEratosthenes(int n)
{
prime = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
prime[0]=false;
if(1<=n)
prime[1]=false;
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 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 [] arrayIn(int n) throws IOException
{
int arr[] = new int[n];
for(int i=0; i<n; i++)
{
arr[i] = nextInt();
}
return arr;
}
}
public static class Pairs implements Comparable<Pairs>
{
int value,index;
Pairs(int value, int index)
{
this.value = value;
this.index = index;
}
public int compareTo(Pairs p)
{
return Integer.compare(this.value, p.value);
}
}
static final Random random = new Random();
static void ruffleSort(int arr[])
{
int n = arr.length;
for(int i=0; i<n; i++)
{
int j = random.nextInt(n),temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static long nCk(int n, int k) {
return (modMult(fact(n),fastexp(modMult(fact(n-k),fact(k)),M-2)));
}
static long fact (long n) {
long fact =1;
for(int i=1; i<=n; i++) {
fact = modMult(fact,i);
}
return fact%M;
}
static long modMult(long a,long b) {
return a*b%M;
}
static long fastexp(long x, int y){
if(y==1) return x;
long ans = fastexp(x,y/2);
if(y%2 == 0) return modMult(ans,ans);
else return modMult(ans,modMult(ans,x));
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 14794b97f32039002cedc938e5232dbb | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | //created by Whiplash99
import java.io.*;
import java.util.*;
public class E
{
private static int calcCost(int start, int lim, ArrayDeque<Integer> DQ)
{
int cost=0;
for(int x:DQ)
{
start+=x;
if(start<1||start>lim) cost++;
start=Math.max(1,start);
start=Math.min(lim,start);
}
return cost;
}
private static int ternarySearch(int l, int r, ArrayDeque<Integer> DQ)
{
int ans=l, lim=r;
while(l<=r-5)
{
int m1=l+(r-l)/3;
int m2=r-(r-l)/3;
int val1=calcCost(m1,lim,DQ);
int val2=calcCost(m2,lim,DQ);
if(val1<=val2) r=m2-1;
else l=m1+1;
}
int cost=Integer.MAX_VALUE;
for(int i=l;i<=r;i++)
{
int tmp=calcCost(i,lim,DQ);
if(tmp<cost)
{
cost=tmp;
ans=i;
}
}
return ans;
}
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
int T=Integer.parseInt(br.readLine().trim());
StringBuilder sb=new StringBuilder();
while (T-->0)
{
String[] s=br.readLine().trim().split(" ");
N=Integer.parseInt(s[0]);
int M=Integer.parseInt(s[1]);
char[] str=br.readLine().trim().toCharArray();
ArrayDeque<Integer> hori=new ArrayDeque<>();
ArrayDeque<Integer> vert=new ArrayDeque<>();
for(char ch:str)
{
switch (ch)
{
case 'L': hori.add(-1); break;
case 'R': hori.add(1); break;
case 'U': vert.add(-1); break;
case 'D': vert.add(1); break;
}
}
int x=ternarySearch(1,N,vert);
int y=ternarySearch(1,M,hori);
sb.append(x).append(" ").append(y).append("\n");
}
System.out.println(sb);
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | a3aaba14cf76f78926f0331898ff0fe7 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.util.Scanner;
public class E1607 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder out = new StringBuilder();
int T = in.nextInt();
for (int t=0; t<T; t++) {
int R = in.nextInt();
int C = in.nextInt();
char[] S = in.next().toCharArray();
int r = 0;
int c = 0;
int minR = 0;
int maxR = 0;
int minC = 0;
int maxC = 0;
int answer = -1;
for (char ch : S) {
switch (ch) {
case 'L': c--; break;
case 'R': c++; break;
case 'U': r--; break;
case 'D': r++; break;
}
if (r < minR) {
if (maxR-r+1 <= R) {
minR = r;
} else {
break;
}
}
if (maxR < r) {
if (r-minR+1 <= R) {
maxR = r;
} else {
break;
}
}
if (c < minC) {
if (maxC-c+1 <= C) {
minC = c;
} else {
break;
}
}
if (maxC < c) {
if (c-minC+1 <= C) {
maxC = c;
} else {
break;
}
}
}
out.append(1-minR).append(' ').append(1-minC).append('\n');
}
System.out.print(out);
}
}
| Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | 91b1fb3bbcbe73a01e0ca7491a367957 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
public class RobotOnTheBoard1 {
private static final int START_TEST_CASE = 1;
private static final int[] DR = {-1, 0, 1, 0};
private static final int[] DC = {0, 1, 0, -1};
private static final int[] DIR = new int[256];
static {
DIR['U'] = 0;
DIR['R'] = 1;
DIR['D'] = 2;
DIR['L'] = 3;
}
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
final int M = io.nextInt();
final char[] S = io.nextLine().toCharArray();
int r = 0;
int c = 0;
int rMin = 0;
int rMax = 0;
int cMin = 0;
int cMax = 0;
int bestR = 0;
int bestC = 0;
for (char op : S) {
int d = DIR[op];
r += DR[d];
c += DC[d];
rMin = Math.min(rMin, r);
rMax = Math.max(rMax, r);
cMin = Math.min(cMin, c);
cMax = Math.max(cMax, c);
if (rMax - rMin < N && cMax - cMin < M) {
bestR = -rMin;
bestC = -cMin;
}
}
io.println(1 + bestR, 1 + bestC);
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
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 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 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;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output | |
PASSED | d0ec3f23c7a33a73f1141418b367f8a6 | train_108.jsonl | 1635863700 | The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column). The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static BufferedReader bf;
static PrintWriter out;
static Scanner sc;
static StringTokenizer st;
static long mod = (long)(1e9+7);
static long mod2 = 998244353;
static long fact[] = new long[1000001];
static long inverse[] = new long[1000001];
public static void main (String[] args)throws IOException {
bf = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new Scanner(System.in);
// fact[0] = 1;
// inverse[0] = 1;
// for(int i = 1;i<fact.length;i++){
// fact[i] = (fact[i-1] * i)%mod;
// // inverse[i] = binaryExpo(fact[i], mod-2);
// }
int t = nextInt();
while(t-->0){
solve();
}
}
public static void solve() throws IOException{
int n = nextInt();
int m = nextInt();
String s = bf.readLine();
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for(int i = 0;i<s.length();i++){
if(s.charAt(i) == 'L' || s.charAt(i) == 'R'){
a.append(s.charAt(i));
}
else{
b.append(s.charAt(i));
}
}
int max = 0;
int l = 1;
int r = n;
int ans = 1;
while(l <= r){
int mid = (l + r)/2;
int start = mid;
int count = 0;
for(int i = 0;i<b.length();i++){
if(b.charAt(i) == 'U'){
start--;
}
else{
start++;
}
if(start < 1 || start > n)break;
count++;
}
if(count > max){
max = count;
ans = mid;
}
if(start < 1){
l = mid+1;
}
else if(start > n){
r = mid-1;
}
else{
break;
}
// println(l + " " + r);
}
l = 1;
r = m;
max = 0;
int ans2 = 1;
while(l <= r){
int mid = (l + r)/2;
int start = mid;
int count = 0;
for(int i = 0;i<a.length();i++){
if(a.charAt(i) == 'L'){
start--;
}
else{
start++;
}
if(start < 1 || start > m)break;
count++;
}
if(count > max){
max = count;
ans2 = mid;
}
if(start < 1){
l = mid+1;
}
else if(start > m){
r = mid-1;
}
else{
break;
}
// println(l + " " + r);
}
println(ans + " " + ans2 );
}
public static int[] bringSame(int u,int v ,int parent[][],int[]depth){
if(depth[u] < depth[v]){
int temp = u;
u = v;
v = temp;
}
int k = depth[u] - depth[v];
for(int i = 0;i<=18;i++){
if((k & (1<<i)) != 0){
u = parent[u][i];
}
}
return new int[]{u,v};
}
public static void findDepth(List<List<Integer>>list,int cur,int parent,int[]depth,int[][]p){
List<Integer>temp = list.get(cur);
p[cur][0] = parent;
for(int i = 0;i<temp.size();i++){
int next = temp.get(i);
if(next != parent){
depth[next] = depth[cur]+1;
findDepth(list,next,cur,depth,p);
}
}
}
public static int lca(int u, int v,int[][]parent){
if(u == v)return u;
for(int i = 18;i>=0;i--){
if(parent[u][i] != parent[v][i]){
u = parent[u][i];
v = parent[v][i];
}
}
return parent[u][0];
}
public static void plus(int node,int low,int high,int tlow,int thigh,int[]tree){
if(low >= tlow && high <= thigh){
tree[node]++;
return;
}
if(high < tlow || low > thigh)return;
int mid = (low + high)/2;
plus(node*2,low,mid,tlow,thigh,tree);
plus(node*2 + 1 , mid + 1, high,tlow, thigh,tree);
}
public static boolean allEqual(int[]arr,int x){
for(int i = 0;i<arr.length;i++){
if(arr[i] != x)return false;
}
return true;
}
public static long helper(StringBuilder sb){
return Long.parseLong(sb.toString());
}
public static int min(int node,int low,int high,int tlow,int thigh,int[][]tree){
if(low >= tlow&& high <= thigh)return tree[node][0];
if(high < tlow || low > thigh)return Integer.MAX_VALUE;
int mid = (low + high)/2;
// println(low+" "+high+" "+tlow+" "+thigh);
return Math.min(min(node*2,low,mid,tlow,thigh,tree) ,min(node*2+1,mid+1,high,tlow,thigh,tree));
}
public static int max(int node,int low,int high,int tlow,int thigh,int[][]tree){
if(low >= tlow && high <= thigh)return tree[node][1];
if(high < tlow || low > thigh)return Integer.MIN_VALUE;
int mid = (low + high)/2;
return Math.max(max(node*2,low,mid,tlow,thigh,tree) ,max(node*2+1,mid+1,high,tlow,thigh,tree));
}
public static long[] help(List<List<Integer>>list,int[][]range,int cur){
List<Integer>temp = list.get(cur);
if(temp.size() == 0)return new long[]{range[cur][1],1};
long sum = 0;
long count = 0;
for(int i = 0;i<temp.size();i++){
long []arr = help(list,range,temp.get(i));
sum += arr[0];
count += arr[1];
}
if(sum < range[cur][0]){
count++;
sum = range[cur][1];
}
return new long[]{sum,count};
}
public static long findSum(int node,int low, int high,int tlow,int thigh,long[]tree,long mod){
if(low >= tlow && high <= thigh)return tree[node]%mod;
if(low > thigh || high < tlow)return 0;
int mid = (low + high)/2;
return((findSum(node*2,low,mid,tlow,thigh,tree,mod) % mod) + (findSum(node*2+1,mid+1,high,tlow,thigh,tree,mod)))%mod;
}
public static boolean allzero(long[]arr){
for(int i =0 ;i<arr.length;i++){
if(arr[i]!=0)return false;
}
return true;
}
public static long count(long[][]dp,int i,int[]arr,int drank,long sum){
if(i == arr.length)return 0;
if(dp[i][drank]!=-1 && arr[i]+sum >=0)return dp[i][drank];
if(sum + arr[i] >= 0){
long count1 = 1 + count(dp,i+1,arr,drank+1,sum+arr[i]);
long count2 = count(dp,i+1,arr,drank,sum);
return dp[i][drank] = Math.max(count1,count2);
}
return dp[i][drank] = count(dp,i+1,arr,drank,sum);
}
public static void help(int[]arr,char[]signs,int l,int r){
if( l < r){
int mid = (l+r)/2;
help(arr,signs,l,mid);
help(arr,signs,mid+1,r);
merge(arr,signs,l,mid,r);
}
}
public static void merge(int[]arr,char[]signs,int l,int mid,int r){
int n1 = mid - l + 1;
int n2 = r - mid;
int[]a = new int[n1];
int []b = new int[n2];
char[]asigns = new char[n1];
char[]bsigns = new char[n2];
for(int i = 0;i<n1;i++){
a[i] = arr[i+l];
asigns[i] = signs[i+l];
}
for(int i = 0;i<n2;i++){
b[i] = arr[i+mid+1];
bsigns[i] = signs[i+mid+1];
}
int i = 0;
int j = 0;
int k = l;
boolean opp = false;
while(i<n1 && j<n2){
if(a[i] <= b[j]){
arr[k] = a[i];
if(opp){
if(asigns[i] == 'R'){
signs[k] = 'L';
}
else{
signs[k] = 'R';
}
}
else{
signs[k] = asigns[i];
}
i++;
k++;
}
else{
arr[k] = b[j];
int times = n1 - i;
if(times%2 == 1){
if(bsigns[j] == 'R'){
signs[k] = 'L';
}
else{
signs[k] = 'R';
}
}
else{
signs[k] = bsigns[j];
}
j++;
opp = !opp;
k++;
}
}
while(i<n1){
arr[k] = a[i];
if(opp){
if(asigns[i] == 'R'){
signs[k] = 'L';
}
else{
signs[k] = 'R';
}
}
else{
signs[k] = asigns[i];
}
i++;
k++;
}
while(j<n2){
arr[k] = b[j];
signs[k] = bsigns[j];
j++;
k++;
}
}
public static long binaryExpo(long base,long expo){
if(expo == 0)return 1;
long val;
if(expo%2 == 1){
val = (binaryExpo(base, expo-1)*base)%mod;
}
else{
val = binaryExpo(base, expo/2);
val = (val*val)%mod;
}
return (val%mod);
}
public static boolean isSorted(int[]arr){
for(int i =1;i<arr.length;i++){
if(arr[i] < arr[i-1]){
return false;
}
}
return true;
}
//function to find the topological sort of the a DAG
public static boolean hasCycle(int[]indegree,List<List<Integer>>list,int n,List<Integer>topo){
Queue<Integer>q = new LinkedList<>();
for(int i =1;i<indegree.length;i++){
if(indegree[i] == 0){
q.add(i);
topo.add(i);
}
}
while(!q.isEmpty()){
int cur = q.poll();
List<Integer>l = list.get(cur);
for(int i = 0;i<l.size();i++){
indegree[l.get(i)]--;
if(indegree[l.get(i)] == 0){
q.add(l.get(i));
topo.add(l.get(i));
}
}
}
if(topo.size() == n)return false;
return true;
}
// function to find the parent of any given node with path compression in DSU
public static int find(int val,int[]parent){
if(val == parent[val])return val;
return parent[val] = find(parent[val],parent);
}
// function to connect two components
public static void union(int[]rank,int[]parent,int u,int v){
int a = find(u,parent);
int b= find(v,parent);
if(a == b)return;
if(rank[a] == rank[b]){
parent[b] = a;
rank[a]++;
}
else{
if(rank[a] > rank[b]){
parent[b] = a;
}
else{
parent[a] = b;
}
}
}
//
public static int findN(int n){
int num = 1;
while(num < n){
num *=2;
}
return num;
}
// code for input
public static void print(String s ){
System.out.print(s);
}
public static void print(int num ){
System.out.print(num);
}
public static void print(long num ){
System.out.print(num);
}
public static void println(String s){
System.out.println(s);
}
public static void println(int num){
System.out.println(num);
}
public static void println(long num){
System.out.println(num);
}
public static void println(){
System.out.println();
}
public static int Int(String s){
return Integer.parseInt(s);
}
public static long Long(String s){
return Long.parseLong(s);
}
public static String[] nextStringArray()throws IOException{
return bf.readLine().split(" ");
}
public static String nextString()throws IOException{
return bf.readLine();
}
public static long[] nextLongArray(int n)throws IOException{
String[]str = bf.readLine().split(" ");
long[]arr = new long[n];
for(int i =0;i<n;i++){
arr[i] = Long.parseLong(str[i]);
}
return arr;
}
public static int[][] newIntMatrix(int r,int c)throws IOException{
int[][]arr = new int[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Integer.parseInt(str[j]);
}
}
return arr;
}
public static long[][] newLongMatrix(int r,int c)throws IOException{
long[][]arr = new long[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Long.parseLong(str[j]);
}
}
return arr;
}
static class pair{
int one;
int two;
pair(int one,int two){
this.one = one ;
this.two =two;
}
}
public static long gcd(long a,long b){
if(b == 0)return a;
return gcd(b,a%b);
}
public static long lcm(long a,long b){
return (a*b)/(gcd(a,b));
}
public static boolean isPalindrome(String s){
int i = 0;
int j = s.length()-1;
while(i<=j){
if(s.charAt(i) != s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
// these functions are to calculate the number of smaller elements after self
public static void sort(int[]arr,int l,int r){
if(l < r){
int mid = (l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
smallerNumberAfterSelf(arr, l, mid, r);
}
}
public static void smallerNumberAfterSelf(int[]arr,int l,int mid,int r){
int n1 = mid - l +1;
int n2 = r - mid;
int []a = new int[n1];
int[]b = new int[n2];
for(int i = 0;i<n1;i++){
a[i] = arr[l+i];
}
for(int i =0;i<n2;i++){
b[i] = arr[mid+i+1];
}
int i = 0;
int j =0;
int k = l;
while(i<n1 && j < n2){
if(a[i] < b[j]){
arr[k++] = a[i++];
}
else{
arr[k++] = b[j++];
}
}
while(i<n1){
arr[k++] = a[i++];
}
while(j<n2){
arr[k++] = b[j++];
}
}
public static String next(){
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bf.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
static int nextInt() {
return Integer.parseInt(next());
}
static long nextLong() {
return Long.parseLong(next());
}
static double nextDouble() {
return Double.parseDouble(next());
}
static String nextLine(){
String str = "";
try {
str = bf.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// use some math tricks it might help
// sometimes just try to think in straightforward plan in A and B problems don't always complecate the questions with thinking too much differently
// always use long number to do 10^9+7 modulo
// if a problem is related to binary string it could also be related to parenthesis
// *****try to use binary search(it is a very beautiful thing it can work in some of the very unexpected problems ) in the question it might work******
// try sorting
// try to think in opposite direction of question it might work in your way
// if a problem is related to maths try to relate some of the continuous subarray with variables like - > a+b+c+d or a,b,c,d in general
// if the question is to much related to left and/or right side of any element in an array then try monotonic stack it could work.
// in range query sums try to do binary search it could work
// analyse the time complexity of program thoroughly
// anylyse the test cases properly
// if we divide any number by 2 till it gets 1 then there will be (number - 1) operation required
// try to do the opposite operation of what is given in the problem
//think about the base cases properly
//If a question is related to numbers try prime factorisation or something related to number theory
// keep in mind unique strings
//you can calculate the number of inversion in O(n log n)
// in a matrix you could sometimes think about row and cols indenpendentaly.
// Try to think in more constructive(means a way to look through various cases of a problem) way.
// observe the problem carefully the answer could be hidden in the given test cases itself. (A, B , C);
// when we have equations like (a+b = N) and we have to find the max of (a*b) then the values near to the N/2 must be chosen as (a and b);
// give emphasis to the number of occurences of elements it might help.
// if a number is even then we can find the pair for each and every number in that range whose bitwise AND is zero.
// if a you find a problem related to the graph make a graph
// There is atleast one prime number between the interval [n , 3n/2]; | Java | ["4\n1 1\nL\n1 2\nL\n3 3\nRRDLUU\n4 3\nLUURRDDLLLUU"] | 2 seconds | ["1 1\n1 2\n2 1\n3 2"] | null | Java 8 | standard input | [
"implementation"
] | 585bb4a040144da39ed240366193e705 | The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^6$$$) — the height and width of the field that the robot is located on. The second line of the description is a string $$$s$$$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $$$1$$$ to $$$10^6$$$ commands. It is guaranteed that the total length of $$$s$$$ over all test cases does not exceed $$$10^6$$$. | 1,600 | Print $$$t$$$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $$$r$$$ ($$$1 \leq r \leq n$$$) and $$$c$$$ ($$$1 \leq c \leq m$$$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible. If there are several such cells, you may output any of them. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.