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 | 80f1d8bb15d645c65d5bcad8e502cd50 | 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.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
// E -> CodeForcesProblemSet
public final class E {
static FastReader fr = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static final int gigamod = 1000000007;
static int t = 1;
static double epsilon = 0.00000001;
static boolean[] isPrime;
static int[] smallestFactorOf;
@SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
t = fr.nextInt();
OUTER:
for (int tc = 0; tc < t; tc++) {
int n = fr.nextInt(), m = fr.nextInt();
char[] s = fr.next().toCharArray();
int len = s.length;
// starting cell to execute as many commands
// as possible
int lo = 1, hi = len;
int maxCommands = 0;
int bestRow = 1, bestCol = 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
// we want to execute 'mid' commands
int x = 0, y = 0;
int minX = 0, maxX = 0, minY = 0, maxY = 0;
for (int i = 0; i < mid; i++) {
if (s[i] == 'U')
y--;
if (s[i] == 'D')
y++;
if (s[i] == 'R')
x++;
if (s[i] == 'L')
x--;
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
}
int leftMoves = -minX;
int rightMoves = maxX;
int upMoves = -minY;
int downMoves = maxY;
int col = leftMoves + 1;
int row = upMoves + 1;
// checking if mess
int rightReached = col + rightMoves;
int downReached = row + downMoves;
if (rightReached >= m + 1 || downReached >= n + 1) {
hi = mid - 1;
} else {
lo = mid + 1;
maxCommands = mid;
bestRow = row;
bestCol = col;
}
}
out.println(bestRow + " " + bestCol);
}
out.close();
}
static class Bipartite {
private boolean isBipartite; // is the graph bipartite?
private boolean[] color; // color[v] gives vertices on one side of bipartition
private boolean[] marked; // marked[v] = true iff v has been visited in DFS
private int[] edgeTo; // edgeTo[v] = last edge on path to v
private Stack<Integer> cycle; // odd-length cycle
/**
* Determines whether an undirected graph is bipartite and finds either a
* bipartition or an odd-length cycle.
*
* @param G the graph
*/
public Bipartite(UGraph G) {
isBipartite = true;
color = new boolean[G.V()];
marked = new boolean[G.V()];
edgeTo = new int[G.V()];
for (int v = 0; v < G.V(); v++) {
if (!marked[v]) {
dfs(G, v);
}
}
assert check(G);
}
private void dfs(UGraph G, int v) {
marked[v] = true;
for (int w : G.adj(v)) {
// short circuit if odd-length cycle found
if (cycle != null) return;
// found uncolored vertex, so recur
if (!marked[w]) {
edgeTo[w] = v;
color[w] = !color[v];
dfs(G, w);
}
// if v-w create an odd-length cycle, find it
else if (color[w] == color[v]) {
isBipartite = false;
cycle = new Stack<Integer>();
cycle.push(w); // don't need this unless you want to include start vertex twice
for (int x = v; x != w; x = edgeTo[x]) {
cycle.push(x);
}
cycle.push(w);
}
}
}
/**
* Returns true if the graph is bipartite.
*
* @return {@code true} if the graph is bipartite; {@code false} otherwise
*/
public boolean isBipartite() {
return isBipartite;
}
/**
* Returns the side of the bipartite that vertex {@code v} is on.
*
* @param v the vertex
* @return the side of the bipartition that vertex {@code v} is on; two vertices
* are in the same side of the bipartition if and only if they have the
* same color
* @throws IllegalArgumentException unless {@code 0 <= v < V}
* @throws UnsupportedOperationException if this method is called when the graph
* is not bipartite
*/
public boolean color(int v) {
validateVertex(v);
if (!isBipartite)
throw new UnsupportedOperationException("graph is not bipartite");
return color[v];
}
/**
* Returns an odd-length cycle if the graph is not bipartite, and
* {@code null} otherwise.
*
* @return an odd-length cycle if the graph is not bipartite
* (and hence has an odd-length cycle), and {@code null}
* otherwise
*/
public Iterable<Integer> oddCycle() {
return cycle;
}
private boolean check(UGraph G) {
// graph is bipartite
if (isBipartite) {
for (int v = 0; v < G.V(); v++) {
for (int w : G.adj(v)) {
if (color[v] == color[w]) {
System.err.printf("edge %d-%d with %d and %d in same side of bipartition\n", v, w, v, w);
return false;
}
}
}
}
// graph has an odd-length cycle
else {
// verify cycle
int first = -1, last = -1;
for (int v : oddCycle()) {
if (first == -1) first = v;
last = v;
}
if (first != last) {
System.err.printf("cycle begins with %d and ends with %d\n", first, last);
return false;
}
}
return true;
}
// throw an IllegalArgumentException unless {@code 0 <= v < V}
private void validateVertex(int v) {
int V = marked.length;
if (v < 0 || v >= V)
throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
}
}
static void colorDFS(int current, int from, int color, UGraph ug, int[] colorOf, boolean[] sucks, boolean[] marked) {
if (sucks[0]) return;
if (marked[current]) return;
marked[current] = true;
if (colorOf[current] != -1 && colorOf[current] != color) {
sucks[0] = true;
return;
}
if (colorOf[current] > -1) return;
colorOf[current] = color;
for (int adj : ug.adj(current))
if (adj != from)
colorDFS(adj, current, 1 - color, ug, colorOf, sucks, marked);
}
static class Domino {
int a, b;
Domino(int aa, int bb) {
a = aa;
b = bb;
}
}
static class Pair implements Comparable<Pair> {
long row;
long col;
Pair() {
}
Pair(long mm, long vv) {
row = mm;
col = vv;
}
public int compareTo(Pair that) {
if (this.row < that.row)
return -1;
if (this.row > that.row)
return 1;
return Long.compare(col, that.col);
}
}
static class UnionFind {
// Uses weighted quick-union with path compression.
private int[] parent; // parent[i] = parent of i
private int[] size; // size[i] = number of sites in tree rooted at i
// Note: not necessarily correct if i is not a root node
private int count; // number of components
public UnionFind(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
// Number of connected components.
public int count() {
return count;
}
// Find the root of p.
public int find(int p) {
while (p != parent[p])
p = parent[p];
return p;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public int numConnectedTo(int node) {
return size[find(node)];
}
// Weighted union.
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
public static int[] connectedComponents(UnionFind uf) {
// We can do this in nlogn.
int n = uf.size.length;
int[] compoColors = new int[n];
for (int i = 0; i < n; i++)
compoColors[i] = uf.find(i);
HashMap<Integer, Integer> oldToNew = new HashMap<>();
int newCtr = 0;
for (int i = 0; i < n; i++) {
int thisOldColor = compoColors[i];
Integer thisNewColor = oldToNew.get(thisOldColor);
if (thisNewColor == null)
thisNewColor = newCtr++;
oldToNew.put(thisOldColor, thisNewColor);
compoColors[i] = thisNewColor;
}
return compoColors;
}
}
static class UGraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public UGraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
adj[to].add(from);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int degree(int v) {
return adj[v].size();
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static void dfsMark(int current, boolean[] marked, UGraph g) {
if (marked[current]) return;
marked[current] = true;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, marked, g);
}
public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) {
if (marked[current]) return;
marked[current] = true;
if (from != -1)
distTo[current] = distTo[from] + 1;
HashSet<Integer> adj = g.adj(current);
int alreadyMarkedCtr = 0;
for (int adjc : adj) {
if (marked[adjc]) alreadyMarkedCtr++;
dfsMark(adjc, current, distTo, marked, g, endPoints);
}
if (alreadyMarkedCtr == adj.size())
endPoints.add(current);
}
public static void bfsOrder(int current, UGraph g) {
}
public static void dfsMark(int current, int[] colorIds, int color, UGraph g) {
if (colorIds[current] != -1) return;
colorIds[current] = color;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, colorIds, color, g);
}
public static int[] connectedComponents(UGraph g) {
int n = g.V();
int[] componentId = new int[n];
Arrays.fill(componentId, -1);
int colorCtr = 0;
for (int i = 0; i < n; i++) {
if (componentId[i] != -1) continue;
dfsMark(i, componentId, colorCtr, g);
colorCtr++;
}
return componentId;
}
public static boolean hasCycle(UGraph ug) {
int n = ug.V();
boolean[] marked = new boolean[n];
boolean[] hasCycleFirst = new boolean[1];
for (int i = 0; i < n; i++) {
if (marked[i]) continue;
hcDfsMark(i, ug, marked, hasCycleFirst, -1);
}
return hasCycleFirst[0];
}
// Helper for hasCycle.
private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) {
if (marked[current]) return;
if (hasCycleFirst[0]) return;
marked[current] = true;
HashSet<Integer> adjc = ug.adj(current);
for (int adj : adjc) {
if (marked[adj] && adj != parent && parent != -1) {
hasCycleFirst[0] = true;
return;
}
hcDfsMark(adj, ug, marked, hasCycleFirst, current);
}
}
}
static class Digraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public Digraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public Digraph reversed() {
Digraph dg = new Digraph(V());
for (int i = 0; i < V(); i++)
for (int adjVert : adj(i)) dg.addEdge(adjVert, i);
return dg;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static int[] KosarajuSharirSCC(Digraph dg) {
int[] id = new int[dg.V()];
Digraph reversed = dg.reversed();
// Gotta perform topological sort on this one to get the stack.
Stack<Integer> revStack = Digraph.topologicalSort(reversed);
// Initializing id and idCtr.
id = new int[dg.V()];
int idCtr = -1;
// Creating a 'marked' array.
boolean[] marked = new boolean[dg.V()];
while (!revStack.isEmpty()) {
int vertex = revStack.pop();
if (!marked[vertex])
sccDFS(dg, vertex, marked, ++idCtr, id);
}
return id;
}
private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) {
marked[source] = true;
id[source] = idCtr;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id);
}
public static Stack<Integer> topologicalSort(Digraph dg) {
// dg has to be a directed acyclic graph.
// We'll have to run dfs on the digraph and push the deepest nodes on stack first.
// We'll need a Stack<Integer> and a int[] marked.
Stack<Integer> topologicalStack = new Stack<Integer>();
boolean[] marked = new boolean[dg.V()];
// Calling dfs
for (int i = 0; i < dg.V(); i++)
if (!marked[i])
runDfs(dg, topologicalStack, marked, i);
return topologicalStack;
}
static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) {
marked[source] = true;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex])
runDfs(dg, topologicalStack, marked, adjVertex);
topologicalStack.add(source);
}
}
static class FastReader {
private BufferedReader bfr;
private StringTokenizer st;
public FastReader() {
bfr = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bfr.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return next().toCharArray()[0];
}
String nextString() {
return next();
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
double[] nextDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextDouble();
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
int[][] nextIntGrid(int n, int m) {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
char[] line = fr.next().toCharArray();
for (int j = 0; j < m; j++)
grid[i][j] = line[j] - 48;
}
return grid;
}
}
static class LCA {
int[] height, first, segtree;
ArrayList<Integer> euler;
boolean[] visited;
int n;
LCA(ArrayList<Point>[] outFrom, int root) {
n = outFrom.length;
height = new int[n];
first = new int[n];
euler = new ArrayList<>();
visited = new boolean[n];
dfs(outFrom, root, 0);
int m = euler.size();
segtree = new int[m * 4];
build(1, 0, m - 1);
}
void dfs(ArrayList<Point>[] outFrom, int node, int h) {
visited[node] = true;
height[node] = h;
first[node] = euler.size();
euler.add(node);
for (Point to : outFrom[node]) {
if (!visited[(int) to.x]) {
dfs(outFrom, (int) to.x, h + 1);
euler.add(node);
}
}
}
void build(int node, int b, int e) {
if (b == e) {
segtree[node] = euler.get(b);
} else {
int mid = (b + e) / 2;
build(node << 1, b, mid);
build(node << 1 | 1, mid + 1, e);
int l = segtree[node << 1], r = segtree[node << 1 | 1];
segtree[node] = (height[l] < height[r]) ? l : r;
}
}
int query(int node, int b, int e, int L, int R) {
if (b > R || e < L)
return -1;
if (b >= L && e <= R)
return segtree[node];
int mid = (b + e) >> 1;
int left = query(node << 1, b, mid, L, R);
int right = query(node << 1 | 1, mid + 1, e, L, R);
if (left == -1) return right;
if (right == -1) return left;
return height[left] < height[right] ? left : right;
}
int lca(int u, int v) {
int left = first[u], right = first[v];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
return query(1, 0, euler.size() - 1, left, right);
}
}
static class FenwickTree {
long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates
public FenwickTree(int size) {
array = new long[size + 1];
}
public long rsq(int ind) {
assert ind > 0;
long sum = 0;
while (ind > 0) {
sum += array[ind];
//Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number
ind -= ind & (-ind);
}
return sum;
}
public long rsq(int a, int b) {
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, long value) {
assert ind > 0;
while (ind < array.length) {
array[ind] += value;
//Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number
ind += ind & (-ind);
}
}
public int size() {
return array.length - 1;
}
}
static final class RedBlackCountSet {
// Manual implementation of RB-BST for C++ PBDS functionality.
// Modification required according to requirements.
// Colors for Nodes:
private static final boolean RED = true;
private static final boolean BLACK = false;
// Pointer to the root:
private Node root;
// Public constructor:
public RedBlackCountSet() {
root = null;
}
// Node class for storing key value pairs:
private class Node {
long key;
long value;
Node left, right;
boolean color;
long size; // Size of the subtree rooted at that node.
public Node(long key, long value, boolean color) {
this.key = key;
this.value = value;
this.left = this.right = null;
this.color = color;
this.size = value;
}
}
/***** Invariant Maintenance functions: *****/
// When a temporary 4 node is formed:
private Node flipColors(Node node) {
node.left.color = node.right.color = BLACK;
node.color = RED;
return node;
}
// When there's a right leaning red link and it is not a 3 node:
private Node rotateLeft(Node node) {
Node rn = node.right;
node.right = rn.left;
rn.left = node;
rn.color = node.color;
node.color = RED;
return rn;
}
// When there are 2 red links in a row:
private Node rotateRight(Node node) {
Node ln = node.left;
node.left = ln.right;
ln.right = node;
ln.color = node.color;
node.color = RED;
return ln;
}
/***** Invariant Maintenance functions end *****/
// Public functions:
public void put(long key) {
root = put(root, key);
root.color = BLACK; // One of the invariants.
}
private Node put(Node node, long key) {
// Standard insertion procedure:
if (node == null)
return new Node(key, 1, RED);
// Recursing:
int cmp = Long.compare(key, node.key);
if (cmp < 0)
node.left = put(node.left, key);
else if (cmp > 0)
node.right = put(node.right, key);
else
node.value++;
// Invariant maintenance:
if (node.left != null && node.right != null) {
if (node.right.color = RED && node.left.color == BLACK)
node = rotateLeft(node);
if (node.left.color == RED && node.left.left.color == RED)
node = rotateRight(node);
if (node.left.color == RED && node.right.color == RED)
node = flipColors(node);
}
// Property maintenance:
node.size = node.value + size(node.left) + size(node.right);
return node;
}
private long size(Node node) {
if (node == null)
return 0;
else
return node.size;
}
public long rank(long key) {
return rank(root, key);
}
// Modify according to requirements.
private long rank(Node node, long key) {
if (node == null) return 0;
int cmp = Long.compare(key, node.key);
if (cmp < 0)
return rank(node.left, key);
else if (cmp > 0)
return node.value + size(node.left) + rank(node.right, key);
else
return node.value + size(node.left);
}
}
static class SegmentTree {
private Node[] heap;
private int[] array;
private int size;
public SegmentTree(int[] array) {
this.array = Arrays.copyOf(array, array.length);
//The max size of this array is about 2 * 2 ^ log2(n) + 1
size = (int) (2 * Math.pow(2.0, Math.floor((Math.log((double) array.length) / Math.log(2.0)) + 1)));
heap = new Node[size];
build(1, 0, array.length);
}
public int size() {
return array.length;
}
//Initialize the Nodes of the Segment tree
private void build(int v, int from, int size) {
heap[v] = new Node();
heap[v].from = from;
heap[v].to = from + size - 1;
if (size == 1) {
heap[v].sum = array[from];
heap[v].min = array[from];
} else {
//Build childs
build(2 * v, from, size / 2);
build(2 * v + 1, from + size / 2, size - size / 2);
heap[v].sum = heap[2 * v].sum + heap[2 * v + 1].sum;
//min = min of the children
heap[v].min = Math.min(heap[2 * v].min, heap[2 * v + 1].min);
}
}
public int rsq(int from, int to) {
return rsq(1, from, to);
}
private int rsq(int v, int from, int to) {
Node n = heap[v];
//If you did a range update that contained this node, you can infer the Sum without going down the tree
if (n.pendingVal != null && contains(n.from, n.to, from, to)) {
return (to - from + 1) * n.pendingVal;
}
if (contains(from, to, n.from, n.to)) {
return heap[v].sum;
}
if (intersects(from, to, n.from, n.to)) {
propagate(v);
int leftSum = rsq(2 * v, from, to);
int rightSum = rsq(2 * v + 1, from, to);
return leftSum + rightSum;
}
return 0;
}
public int rMinQ(int from, int to) {
return rMinQ(1, from, to);
}
private int rMinQ(int v, int from, int to) {
Node n = heap[v];
//If you did a range update that contained this node, you can infer the Min value without going down the tree
if (n.pendingVal != null && contains(n.from, n.to, from, to)) {
return n.pendingVal;
}
if (contains(from, to, n.from, n.to)) {
return heap[v].min;
}
if (intersects(from, to, n.from, n.to)) {
propagate(v);
int leftMin = rMinQ(2 * v, from, to);
int rightMin = rMinQ(2 * v + 1, from, to);
return Math.min(leftMin, rightMin);
}
return Integer.MAX_VALUE;
}
public void update(int from, int to, int value) {
update(1, from, to, value);
}
private void update(int v, int from, int to, int value) {
//The Node of the heap tree represents a range of the array with bounds: [n.from, n.to]
Node n = heap[v];
if (contains(from, to, n.from, n.to)) {
change(n, value);
}
if (n.size() == 1) return;
if (intersects(from, to, n.from, n.to)) {
propagate(v);
update(2 * v, from, to, value);
update(2 * v + 1, from, to, value);
n.sum = heap[2 * v].sum + heap[2 * v + 1].sum;
n.min = Math.min(heap[2 * v].min, heap[2 * v + 1].min);
}
}
//Propagate temporal values to children
private void propagate(int v) {
Node n = heap[v];
if (n.pendingVal != null) {
change(heap[2 * v], n.pendingVal);
change(heap[2 * v + 1], n.pendingVal);
n.pendingVal = null; //unset the pending propagation value
}
}
//Save the temporal values that will be propagated lazily
private void change(Node n, int value) {
n.pendingVal = value;
n.sum = n.size() * value;
n.min = value;
array[n.from] = value;
}
//Test if the range1 contains range2
private boolean contains(int from1, int to1, int from2, int to2) {
return from2 >= from1 && to2 <= to1;
}
//check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2]
private boolean intersects(int from1, int to1, int from2, int to2) {
return from1 <= from2 && to1 >= from2 // (.[..)..] or (.[...]..)
|| from1 >= from2 && from1 <= to2; // [.(..]..) or [..(..)..
}
//The Node class represents a partition range of the array.
static class Node {
int sum;
int min;
//Here We store the value that will be propagated lazily
Integer pendingVal = null;
int from;
int to;
int size() {
return to - from + 1;
}
}
}
@SuppressWarnings("serial")
static class CountMap<T> extends TreeMap<T, Integer>{
CountMap() {
}
CountMap(T[] arr) {
this.putCM(arr);
}
public Integer putCM(T key) {
if (super.containsKey(key)) {
return super.put(key, super.get(key) + 1);
} else {
return super.put(key, 1);
}
}
public Integer removeCM(T key) {
Integer count = super.get(key);
if (count == null) return -1;
if (count == 1)
return super.remove(key);
else
return super.put(key, super.get(key) - 1);
}
public Integer getCM(T key) {
Integer count = super.get(key);
if (count == null)
return 0;
return count;
}
public void putCM(T[] arr) {
for (T l : arr)
this.putCM(l);
}
}
static class Point implements Comparable<Point> {
long x;
long y;
long id;
Point() {
x = y = id = 0;
}
Point(Point p) {
this.x = p.x;
this.y = p.y;
this.id = p.id;
}
Point(long a, long b, long id) {
this.x = a;
this.y = b;
this.id = id;
}
Point(long a, long b) {
this.x = a;
this.y = b;
}
@Override
public int compareTo(Point o) {
if (this.x < o.x)
return -1;
if (this.x > o.x)
return 1;
if (this.y < o.y)
return -1;
if (this.y > o.y)
return 1;
return 0;
}
public boolean equals(Point that) {
return this.compareTo(that) == 0;
}
}
static int longestPrefixPalindromeLen(char[] s) {
int n = s.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
sb.append(s[i]);
StringBuilder sb2 = new StringBuilder(sb);
sb.append('^');
sb.append(sb2.reverse());
// out.println(sb.toString());
char[] newS = sb.toString().toCharArray();
int m = newS.length;
int[] pi = piCalcKMP(newS);
return pi[m - 1];
}
static int KMPNumOcc(char[] text, char[] pat) {
int n = text.length;
int m = pat.length;
char[] patPlusText = new char[n + m + 1];
for (int i = 0; i < m; i++)
patPlusText[i] = pat[i];
patPlusText[m] = '^'; // Seperator
for (int i = 0; i < n; i++)
patPlusText[m + i] = text[i];
int[] fullPi = piCalcKMP(patPlusText);
int answer = 0;
for (int i = 0; i < n + m + 1; i++)
if (fullPi[i] == m)
answer++;
return answer;
}
static int[] piCalcKMP(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static String toBinaryString(long num, int bits) {
StringBuilder sb = new StringBuilder(Long.toBinaryString(num));
sb.reverse();
for (int i = sb.length(); i < bits; i++)
sb.append('0');
return sb.reverse().toString();
}
static long modDiv(long a, long b) {
return mod(a * power(b, gigamod - 2, gigamod));
}
static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) {
if (m > limit) return;
if (m <= limit && n <= limit)
coprimes.add(new Point(m, n));
if (coprimes.size() > numCoprimes) return;
coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes);
coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes);
coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes);
}
static long hash(long i) {
return (i * 2654435761L % gigamod);
}
static long hash2(long key) {
long h = Long.hashCode(key);
h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4);
return h & (gigamod-1);
}
static int mapTo1D(int row, int col, int n, int m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static int[] mapTo2D(int idx, int n, int m) {
// Inverse of what the one above does.
int[] rnc = new int[2];
rnc[0] = idx / m;
rnc[1] = idx % m;
return rnc;
}
static double distance(Point p1, Point p2) {
return Math.sqrt(Math.pow(p2.y-p1.y, 2) + Math.pow(p2.x-p1.x, 2));
}
/*static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) {
if (smallestFactorOf == null)
primeGenerator(200001);
CountMap<Integer> fnps = new CountMap<>();
while (num != 1) {
fnps.putCM(smallestFactorOf[num]);
num /= smallestFactorOf[num];
}
return fnps;
}*/
static HashMap<Long, Integer> primeFactorization(long num) {
// Returns map of factor and its power in the number.
HashMap<Long, Integer> map = new HashMap<>();
while (num % 2 == 0) {
num /= 2;
Integer pwrCnt = map.get(2L);
map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1);
}
for (long i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
num /= i;
Integer pwrCnt = map.get(i);
map.put(i, pwrCnt != null ? pwrCnt + 1 : 1);
}
}
// If the number is prime, we have to add it to the
// map.
if (num != 1)
map.put(num, 1);
return map;
}
static HashSet<Long> divisors(long num) {
HashSet<Long> divisors = new HashSet<Long>();
divisors.add(1L);
divisors.add(num);
for (long i = 2; i * i <= num; i++) {
if (num % i == 0) {
divisors.add(num/i);
divisors.add(i);
}
}
return divisors;
}
static int bsearch(int[] arr, int val, int lo, int hi) {
// Returns the index of the first element
// larger than or equal to val.
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
idx = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
return idx;
}
static int bsearch(long[] arr, long val, int lo, int hi) {
int idx = -2;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
idx = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
return idx;
}
static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) {
// Returns the index of the last element
// smaller than or equal to val.
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
hi = mid - 1;
} else {
idx = mid;
lo = mid + 1;
}
}
return idx;
}
static int bsearch(int[] arr, long val, int lo, int hi, boolean sMode) {
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] > val) {
hi = mid - 1;
} else {
idx = mid;
lo = mid + 1;
}
}
return idx;
}
static long factorial(long n) {
if (n <= 1)
return 1;
long factorial = 1;
for (int i = 1; i <= n; i++)
factorial = mod(factorial * i);
return factorial;
}
static long factorialInDivision(long a, long b) {
if (a == b)
return 1;
if (b < a) {
long temp = a;
a = b;
b = temp;
}
long factorial = 1;
for (long i = a + 1; i <= b; i++)
factorial = mod(factorial * i);
return factorial;
}
static long nCr(long n, long r, long[] fac) {
long p = 998244353;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
/*long fac[] = new long[(int)n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;*/
return (fac[(int)n] * modInverse(fac[(int)r], p) % p
* modInverse(fac[(int)n - (int)r], p) % p) % p;
}
static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
static long power(long x, long y, long p) {
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0) {
// If y is odd, multiply x with result
if ((y & 1)==1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long nPr(long n, long r) {
return factorialInDivision(n, n - r);
}
static int logk(long n, long k) {
return (int)(Math.log(n) / Math.log(k));
}
static boolean[] primeGenerator(int upto) {
// Sieve of Eratosthenes:
isPrime = new boolean[upto + 1];
smallestFactorOf = new int[upto + 1];
Arrays.fill(smallestFactorOf, 1);
Arrays.fill(isPrime, true);
isPrime[1] = isPrime[0] = false;
for (long i = 2; i < upto + 1; i++)
if (isPrime[(int) i]) {
smallestFactorOf[(int) i] = (int) i;
// Mark all the multiples greater than or equal
// to the square of i to be false.
for (long j = i; j * i < upto + 1; j++) {
if (isPrime[(int) j * (int) i]) {
isPrime[(int) j * (int) i] = false;
smallestFactorOf[(int) j * (int) i] = (int) i;
}
}
}
return isPrime;
}
static long gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static long gcd(long[] arr) {
int n = arr.length;
long gcd = arr[0];
for (int i = 1; i < n; i++) {
gcd = gcd(gcd, arr[i]);
}
return gcd;
}
static int gcd(int[] arr) {
int n = arr.length;
int gcd = arr[0];
for (int i = 1; i < n; i++) {
gcd = gcd(gcd, arr[i]);
}
return gcd;
}
static long lcm(long[] arr) {
long lcm = arr[0];
int n = arr.length;
for (int i = 1; i < n; i++) {
lcm = (lcm * arr[i]) / gcd(lcm, arr[i]);
}
return lcm;
}
static long lcm(long a, long b) {
return (a * b)/gcd(a, b);
}
static boolean less(int a, int b) {
return a < b ? true : false;
}
static boolean isSorted(int[] a) {
for (int i = 1; i < a.length; i++) {
if (less(a[i], a[i - 1]))
return false;
}
return true;
}
static boolean isSorted(long[] a) {
for (int i = 1; i < a.length; i++) {
if (a[i] < a[i - 1])
return false;
}
return true;
}
static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(long[] a, int i, int j) {
long temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(double[] a, int i, int j) {
double temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(char[] a, int i, int j) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void sort(int[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
}
static void sort(char[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
}
static void sort(long[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
}
static void sort(double[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
}
static void reverseSort(int[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < n/2; i++)
swap(arr, i, n - 1 - i);
}
static void reverseSort(char[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < n/2; i++)
swap(arr, i, n - 1 - i);
}
static void reverse(char[] arr) {
int n = arr.length;
for (int i = 0; i < n / 2; i++)
swap(arr, i, n - 1 - i);
}
static void reverseSort(long[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < n/2; i++)
swap(arr, i, n - 1 - i);
}
static void reverseSort(double[] arr) {
shuffleArray(arr, 0, arr.length - 1);
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < n/2; i++)
swap(arr, i, n - 1 - i);
}
static void shuffleArray(long[] arr, int startPos, int endPos) {
Random rnd = new Random();
for (int i = startPos; i < endPos; ++i) {
long tmp = arr[i];
int randomPos = i + rnd.nextInt(endPos - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
static void shuffleArray(int[] arr, int startPos, int endPos) {
Random rnd = new Random();
for (int i = startPos; i < endPos; ++i) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(endPos - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
static void shuffleArray(double[] arr, int startPos, int endPos) {
Random rnd = new Random();
for (int i = startPos; i < endPos; ++i) {
double tmp = arr[i];
int randomPos = i + rnd.nextInt(endPos - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
static void shuffleArray(char[] arr, int startPos, int endPos) {
Random rnd = new Random();
for (int i = startPos; i < endPos; ++i) {
char tmp = arr[i];
int randomPos = i + rnd.nextInt(endPos - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (long i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static String toString(int[] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++)
sb.append(dp[i] + " ");
return sb.toString();
}
static String toString(boolean[] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++)
sb.append(dp[i] + " ");
return sb.toString();
}
static String toString(long[] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++)
sb.append(dp[i] + " ");
return sb.toString();
}
static String toString(char[] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++)
sb.append(dp[i] + "");
return sb.toString();
}
static String toString(int[][] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[i].length; j++) {
sb.append(dp[i][j] + " ");
}
sb.append('\n');
}
return sb.toString();
}
static String toString(long[][] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[i].length; j++) {
sb.append(dp[i][j] + " ");
}
sb.append('\n');
}
return sb.toString();
}
static String toString(double[][] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[i].length; j++) {
sb.append(dp[i][j] + " ");
}
sb.append('\n');
}
return sb.toString();
}
static String toString(char[][] dp) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[i].length; j++) {
sb.append(dp[i][j] + " ");
}
sb.append('\n');
}
return sb.toString();
}
static long mod(long a, long m) {
return (a%m + m) % m;
}
static long mod(long num) {
return (num % gigamod + gigamod) % gigamod;
}
}
// NOTES:
// ASCII VALUE OF 'A': 65
// ASCII VALUE OF 'a': 97
// Range of long: 9 * 10^18
// ASCII VALUE OF '0': 48
// Primes upto 'n' can be given by (n / (logn)). | Java | ["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 | e9c98996482919e31ca95a1ecad6f38a | 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 Balabizo {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int tt = sc.nextInt();
while(tt-->0){
int n = sc.nextInt() , m = sc.nextInt();
char[] c = sc.next().toCharArray();
int x = 0 , y = 0 , l = 0 , r = 0 , u = 0 , d = 0;
for (char value : c) {
if (value == 'U') u = Math.min(u, --x);
else if (value == 'D') d = Math.max(d, ++x);
else if (value == 'L') l = Math.min(l, --y);
else r = Math.max(r, ++y);
if (d - u >= n) {
if (x == u) u++;
break;
}
if (r - l >= m) {
if (y == l) l++;
break;
}
}
pw.println((1-u)+" "+(1-l));
}
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws IOException {
br = new BufferedReader(new FileReader(file));
}
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 String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | 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 | 562bedb55d33c735241da4f1d11e30f8 | 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 E1607 {
static String s;
static int N, M, L;
public static void main(String[] args) throws IOException, FileNotFoundException {
Kattio in = new Kattio();
int T = in.nextInt();
while(T > 0){
N = in.nextInt();
M = in.nextInt();
s = in.next();
L = s.length();
int a = 0;
int b = L;
while(a != b){
int mid = (a + b + 1)/2;
if(works(mid)){
a = mid;
} else {
b = mid - 1;
}
}
int left = calculateMaximum('L', 'R', a);
int right = calculateMaximum('R', 'L', a);
int up = calculateMaximum('U', 'D', a);
int down = calculateMaximum('D', 'U', a);
System.out.println((1 + up) + " " + (1 + left));
T--;
}
}
public static boolean works(int last){
int left = calculateMaximum('L', 'R', last);
int right = calculateMaximum('R', 'L', last);
int up = calculateMaximum('U', 'D', last);
int down = calculateMaximum('D', 'U', last);
int minLeft = 1 + left;
int maxRight = M - right;
int minUp = 1 + up;
int maxDown = N - down;
if(minLeft <= maxRight && minUp <= maxDown){
return true;
}
return false;
}
public static int calculateMaximum(char direction, char opposite, int last){
int max = 0;
int curr = 0;
for(int i = 0; i < last; i++){
if(s.charAt(i) == direction){
curr++;
} else if (s.charAt(i) == opposite) {
curr--;
}
max = Math.max(max, curr);
}
return max;
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
public Kattio() { this(System.in, System.out); }
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(String problemName) throws IOException {
super(problemName + ".out");
r = new BufferedReader(new FileReader(problemName + ".in"));
}
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.readLine());
return st.nextToken();
} catch (Exception e) { }
return null;
}
public int nextInt() { return Integer.parseInt(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public long nextLong() { return Long.parseLong(next()); }
}
}
| Java | ["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 | 22d987230b6afae83ae4cb1d968610eb | 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.rmi.MarshalException;
import java.util.*;
public class RobotOnBoard{
static long mod = 1000000007L;
static MyScanner sc = new MyScanner();
static void solve() {
int n = sc.nextInt();
int m = sc.nextInt();
String str = sc.nextLine();
HashSet<Integer> r = new HashSet<>();
HashSet<Integer> c = new HashSet<>();
r.add(0);
c.add(0);
int cr = 0;
int cc = 0;
int i = 0;
while(r.size()<n && c.size()<m && i<str.length()){
char chr = str.charAt(i);
i++;
if(chr=='R'){
cc++;
}else if(chr=='L') cc--;
else if(chr=='U') cr--;
else cr++;
r.add(cr);
c.add(cc);
}
while(r.size()<n && i<str.length()){
char chr = str.charAt(i);
i++;
if(chr=='U') cr--;
else if(chr=='D') cr++;
else if(chr=='L') cc--;
else cc++;
if(c.contains(cc)) r.add(cr);
else break;
}
while(c.size()<m && i<str.length()){
char chr = str.charAt(i);
i++;
if(chr=='L') cc--;
else if(chr=='R') cc++;
else if(chr=='U') cr--;
else cr++;
if(r.contains(cr)) c.add(cc);
else break;
}
int ra = 1;
int ca = 1;
for(int j:r) if(j<0) ra++;
for(int j:c) if(j<0) ca++;
out.println(ra+" "+ca);
}
static class Pair implements Comparable<Pair>{
char c;
int fre;
Pair(char c,int f){
this.c= c;
fre = f;
}
public int compareTo(Pair p){
return this.fre - p.fre;
}
}
static void reverse(int arr[]){
int i = 0;int j = arr.length-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static void reverse(long arr[]){
int i = 0;int j = arr.length-1;
while(i<j){
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long pow(long a, long b) {
if (b == 0) return 1;
long res = pow(a, b / 2);
res = (res * res) % 1_000_000_007;
if (b % 2 == 1) {
res = (res * a) % 1_000_000_007;
}
return res;
}
static int lis(int arr[],int n){
int lis[] = new int[n];
lis[0] = 1;
for(int i = 1;i<n;i++){
lis[i] = 1;
for(int j = 0;j<i;j++){
if(arr[i]>arr[j]){
lis[i] = Math.max(lis[i],lis[j]+1);
}
}
}
int max = Integer.MIN_VALUE;
for(int i = 0;i<n;i++){
max = Math.max(lis[i],max);
}
return max;
}
static boolean isPali(String str){
int i = 0;
int j = str.length()-1;
while(i<j){
if(str.charAt(i)!=str.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
static long gcd(long a,long b){
if(b==0) return a;
return gcd(b,a%b);
}
static String reverse(String str){
char arr[] = str.toCharArray();
int i = 0;
int j = arr.length-1;
while(i<j){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
String st = new String(arr);
return st;
}
static boolean isprime(int n){
if(n==1) return false;
if(n==3 || n==2) return true;
if(n%2==0 || n%3==0) return false;
for(int i = 5;i*i<=n;i+= 6){
if(n%i== 0 || n%(i+2)==0){
return false;
}
}
return true;
}
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
int t = sc.nextInt();
// int t= 1;
while(t-- >0){
solve();
// solve2();
// solve3();
}
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int[] readIntArray(int n){
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = Integer.parseInt(next());
}
return arr;
}
int[] reverse(int arr[]){
int n= arr.length;
int i = 0;
int j = n-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;i++;
}
return arr;
}
long[] readLongArray(int n){
long arr[] = new long[n];
for(int i = 0;i<n;i++){
arr[i] = Long.parseLong(next());
}
return arr;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
} | Java | ["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 | dc65f647f5bfc836ed8d5cf82bbed726 | 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 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int T = scanner.nextInt();
while (T -- > 0) {
int n = scanner.nextInt();
int m = scanner.nextInt();
scanner.nextLine();
String s = scanner.nextLine();
int[] ret = solve(n, m, s);
System.out.println(ret[0] + " " + ret[1]);
}
}
static int[] solve(int n, int m, String s) {
int[] cur = new int[2];
int[] min = new int[2];
int[] max = new int[2];
int row = 0;
int col = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == 'U') {
cur[0] --;
min[0] = Math.min(cur[0], min[0]);
} else if (c == 'D') {
cur[0] ++;
max[0] = Math.max(cur[0], max[0]);
} else if (c == 'L') {
cur[1] --;
min[1] = Math.min(cur[1], min[1]);
} else {
cur[1] ++;
max[1] = Math.max(cur[1], max[1]);
}
//纵向
int a = max[0] - min[0];
//横向
int b = max[1] - min[1];
// System.out.println(b + " " + Arrays.toString(max));
if (a + 1 > n || b + 1 > m) {
break;
}
row = -min[0];
col = -min[1];
}
return new int[]{row + 1, col + 1};
}
} | 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 | a3920e24ec0bd87377c18a06c771fa94 | 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 {
static InputReader inputReader=new InputReader(System.in);
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static List<LinkedHashSet<Integer>>answer=new ArrayList<>();
static void solve() throws IOException
{
int n=inputReader.nextInt();
int m=inputReader.nextInt();
int maxdeltax=0;
int deltax=0;
int deltay=0;
int mindeltax=0;
int maxdeltay=0;
int mindeltay=0;
int ansx=1;
int ansy=1;
String str=inputReader.readString();
for (char c:str.toCharArray())
{
if (c=='L')
{
deltay--;
}
else if(c=='R')
{
deltay++;
}
else if (c=='U')
{
deltax--;
}
else
{
deltax++;
}
mindeltax=Math.min(mindeltax,deltax);
maxdeltax=Math.max(maxdeltax,deltax);
mindeltay=Math.min(mindeltay,deltay);
maxdeltay=Math.max(maxdeltay,deltay);
int x=n-maxdeltax;
int y=m-maxdeltay;
if (x>=1&&y>=1&&x+mindeltax>=1&&y+mindeltay>=1)
{
ansx=x;
ansy=y;
}
else
{
break;
}
}
out.println(ansx+" "+ansy);
}
static PrintWriter out=new PrintWriter((System.out));
static void SortDec(long arr[])
{
List<Long>list=new ArrayList<>();
for(long ele:arr) {
list.add(ele);
}
Collections.sort(list,Collections.reverseOrder());
for (int i=0;i<list.size();i++)
{
arr[i]=list.get(i);
}
}
static void Sort(long arr[])
{
List<Long>list=new ArrayList<>();
for(long ele:arr) {
list.add(ele);
}
Collections.sort(list);
for (int i=0;i<list.size();i++)
{
arr[i]=list.get(i);
}
}
public static void main(String args[])throws IOException
{
int t=inputReader.nextInt();
while (t-->0) {
solve();
}
long s = System.currentTimeMillis();
// out.println(System.currentTimeMillis()-s+"ms");
out.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} 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 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 | a697c700d592b5e27a7177a36800e1aa | 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.IOException;
import java.io.*;
import java.util.*;
public class RobotontheBoard1 {
static InputReader inputReader=new InputReader(System.in);
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static List<LinkedHashSet<Integer>>answer=new ArrayList<>();
static void solve() throws IOException
{
int n=inputReader.nextInt();
int m=inputReader.nextInt();
int maxdeltax=0;
int deltax=0;
int deltay=0;
int mindeltax=0;
int maxdeltay=0;
int mindeltay=0;
int ansx=1;
int ansy=1;
String str=inputReader.readString();
for (char c:str.toCharArray())
{
if (c=='L')
{
deltay--;
}
else if(c=='R')
{
deltay++;
}
else if (c=='U')
{
deltax--;
}
else
{
deltax++;
}
mindeltax=Math.min(mindeltax,deltax);
maxdeltax=Math.max(maxdeltax,deltax);
mindeltay=Math.min(mindeltay,deltay);
maxdeltay=Math.max(maxdeltay,deltay);
int x=n-maxdeltax;
int y=m-maxdeltay;
if (x>=1&&y>=1&&x+mindeltax>=1&&y+mindeltay>=1&&x+maxdeltax<=n&&y+maxdeltay<=m)
{
ansx=x;
ansy=y;
}
else
{
break;
}
}
out.println(ansx+" "+ansy);
}
static PrintWriter out=new PrintWriter((System.out));
static void SortDec(long arr[])
{
List<Long>list=new ArrayList<>();
for(long ele:arr) {
list.add(ele);
}
Collections.sort(list,Collections.reverseOrder());
for (int i=0;i<list.size();i++)
{
arr[i]=list.get(i);
}
}
static void Sort(long arr[])
{
List<Long>list=new ArrayList<>();
for(long ele:arr) {
list.add(ele);
}
Collections.sort(list);
for (int i=0;i<list.size();i++)
{
arr[i]=list.get(i);
}
}
public static void main(String args[])throws IOException
{
int t=inputReader.nextInt();
while (t-->0) {
solve();
}
long s = System.currentTimeMillis();
// out.println(System.currentTimeMillis()-s+"ms");
out.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} 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 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 | 5e5d0363149d23eefaa3576c71c23511 | 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.lang.Math;
public class Main {
public class MainSolution extends MainSolutionT {
// global vars
public void init(int tests_count){}
public class TestCase extends TestCaseT
{
public Object solve()
{
int n = readInt(), m = readInt();
String C = readLn();
int k = C.length();
int x = 0;
int y = 0;
int minx1=0, minx = 0;
int maxx1=0, maxx = 0;
int miny1=0, miny = 0;
int maxy1=0, maxy = 0;
for (int i=0; i<k; i++)
{
switch (C.charAt(i))
{
case 'L':
x--;
break;
case 'R':
x++;
break;
case 'U':
y--;
break;
case 'D':
y++;
break;
}
if (x>maxx)
{
maxx = x;
}
if (y>maxy)
{
maxy = y;
}
if (x<minx)
{
minx = x;
}
if (y<miny)
{
miny = y;
}
if ((maxx-minx+1>m) || (maxy-miny+1>n))
{
return strf("%d %d", -miny1+1, -minx1+1);
}
minx1 = minx;
miny1 = miny;
maxx1 = maxx;
maxy1 = maxy;
}
return strf("%d %d", -miny1+1, -minx1+1);
}
}
public void run()
{
int t = multiply_test ? readInt() : 1;
this.init(t);
for (int i = 0; i < t; i++) {
TestCase T = new TestCase();
T.run(i + 1);
}
}
public void loc_params()
{
this.log_enabled = false;
}
public void params(){
this.multiply_test = true;
}
}
public class MainSolutionT extends MainSolutionBase
{
public class TestCaseT extends TestCaseBase
{
}
}
public class MainSolutionBase
{
public boolean is_local = false;
public MainSolutionBase()
{
}
public class TestCaseBase
{
public Object solve() {
return null;
}
public int caseNumber;
public TestCaseBase() {
}
public void run(int cn){
this.caseNumber = cn;
Object r = this.solve();
if ((r != null))
{
out.println(r);
}
}
}
public String impossible(){
return "IMPOSSIBLE";
}
public String strf(String format, Object... args)
{
return String.format(format, args);
}
public BufferedReader in;
public PrintStream out;
public boolean log_enabled = false;
public boolean multiply_test = true;
public void params()
{
}
public void loc_params()
{
}
private StringTokenizer tokenizer = null;
public int readInt() {
return Integer.parseInt(readToken());
}
public long readLong() {
return Long.parseLong(readToken());
}
public double readDouble() {
return Double.parseDouble(readToken());
}
public String readLn() {
try {
String s;
while ((s = in.readLine()).length() == 0);
return s;
} catch (Exception e) {
return "";
}
}
public String readToken() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
} catch (Exception e) {
return "";
}
}
public int[] readIntArray(int n) {
int[] x = new int[n];
readIntArray(x, n);
return x;
}
public void readIntArray(int[] x, int n) {
for (int i = 0; i < n; i++) {
x[i] = readInt();
}
}
public long[] readLongArray(int n) {
long[] x = new long[n];
readLongArray(x, n);
return x;
}
public void readLongArray(long[] x, int n) {
for (int i = 0; i < n; i++) {
x[i] = readLong();
}
}
public void readLongArrayRev(long[] x, int n) {
for (int i = 0; i < n; i++) {
x[n-i-1] = readLong();
}
}
public void logWrite(String format, Object... args) {
if (!log_enabled) {
return;
}
out.printf(format, args);
}
public void readLongArrayBuf(long[] x, int n) {
char[]buf = new char[1000000];
long r = -1;
int k= 0, l = 0;
long d;
while (true)
{
try{
l = in.read(buf, 0, 1000000);
}
catch(Exception E){};
for (int i=0; i<l; i++)
{
if (('0'<=buf[i])&&(buf[i]<='9'))
{
if (r == -1)
{
r = 0;
}
d = buf[i] - '0';
r = 10 * r + d;
}
else
{
if (r != -1)
{
x[k++] = r;
}
r = -1;
}
}
if (l<1000000)
return;
}
}
public void readIntArrayBuf(int[] x, int n) {
char[]buf = new char[1000000];
int r = -1;
int k= 0, l = 0;
int d;
while (true)
{
try{
l = in.read(buf, 0, 1000000);
}
catch(Exception E){};
for (int i=0; i<l; i++)
{
if (('0'<=buf[i])&&(buf[i]<='9'))
{
if (r == -1)
{
r = 0;
}
d = buf[i] - '0';
r = 10 * r + d;
}
else
{
if (r != -1)
{
x[k++] = r;
}
r = -1;
}
}
if (l<1000000)
return;
}
}
public void printArray(long[] a, int n)
{
printArray(a, n, ' ');
}
public void printArray(int[] a, int n)
{
printArray(a, n, ' ');
}
public void printArray(long[] a, int n, char dl)
{
long x;
int i, l = 0;
for (i=0; i<n; i++)
{
x = a[i];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
x = a[i];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (i>0)
{
s[l--] = dl;
}
}
out.println(new String(s));
}
public void printArray(double[] a, int n, char dl)
{
long x;
double y;
int i, l = 0;
for (i=0; i<n; i++)
{
x = (long)a[i];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += n-1 + 10*n;
char[] s = new char[l];
l--;
boolean z;
int j;
for (i=n-1; i>=0; i--)
{
x = (long)a[i];
y = (long)(1000000000*(a[i]-x));
z = false;
if (x<0)
{
x = -x;
z = true;
}
for (j=0; j<9; j++)
{
s[l--] = (char)('0' + (y % 10));
y /= 10;
}
s[l--] = '.';
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (i>0)
{
s[l--] = dl;
}
}
out.println(new String(s));
}
public void printArray(int[] a, int n, char dl)
{
int x;
int i, l = 0;
for (i=0; i<n; i++)
{
x = a[i];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
x = a[i];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (i>0)
{
s[l--] = dl;
}
}
out.println(new String(s));
}
public void printMatrix(int[][] a, int n, int m)
{
int x;
int i,j, l = 0;
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
x = a[i][j];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += m-1;
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
for (j=m-1; j>=0; j--)
{
x = a[i][j];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (j>0)
{
s[l--] = ' ';
}
}
if (i>0)
{
s[l--] = '\n';
}
}
out.println(new String(s));
}
public void printMatrix(long[][] a, int n, int m)
{
long x;
int i,j, l = 0;
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
x = a[i][j];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += m-1;
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
for (j=m-1; j>=0; j--)
{
x = a[i][j];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (j>0)
{
s[l--] = ' ';
}
}
if (i>0)
{
s[l--] = '\n';
}
}
out.println(new String(s));
}
}
public void run()
{
MainSolution S;
try {
S = new MainSolution();
S.in = new BufferedReader(new InputStreamReader(System.in));
//S.out = System.out;
S.out = new PrintStream(new BufferedOutputStream( System.out ));
} catch (Exception e) {
return;
}
S.params();
S.run();
S.out.flush();
}
public static void main(String args[]) {
Locale.setDefault(Locale.US);
Main M = new Main();
M.run();
}
} | 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 | 0863941c7a67efcfe0eccfd0c7bce720 | 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.lang.*;
import java.util.*;
import java.io.*;
public class E_Robot_on_the_Board_1 {
public static void main(String[] arg){
Scanner s=new Scanner(System.in);
try {
int t=s.nextInt();
while(t-->0){
int n=s.nextInt();
int m=s.nextInt();
String str=s.next();
int x=0;
int y=0;
int ans_x=1,ans_y=1;
int max_left=0,max_right=0,max_up=0,max_down=0;
for(int i=0;i<str.length();i++){
char a=str.charAt(i);
if(a=='L'){
x--;
}else if(a=='R'){
x++;
}
else if(a=='U'){
y++;
}else if(a=='D'){
y--;
}
max_left=Math.min(max_left, x);
max_right=Math.max(max_right,x);
max_up=Math.max(y,max_up);
max_down=Math.min(max_down, y);
if(max_right-max_left+1>m || max_up-max_down+1>n) {
break;
}else{
ans_x=Math.abs(max_up)+1;
ans_y=Math.abs(max_left)+1;
}
}
System.out.println(ans_x+" "+ans_y);
}
} catch (Exception e) {
}
s.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 | d8fd5ff91eb78da13815fe8d1122635b | 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;
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
long nl() {
return Long.parseLong(next());
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// MAIN FUNCTION
// static long mod = (long)(1e9)+7;
// static int nn = (int)1e6;
// static long fact[] = new long[nn+1];
// static long invFact[] = new long[nn+1];
public static void main(String[] args) throws java.lang.Exception {
FastReader fr = new FastReader();
PrintWriter out = new PrintWriter(System.out);
// initForNcr();
int t = fr.ni();
while(t-->0) {
int row = fr.ni();
int col = fr.ni();
String str = fr.next();
char ch [] = str.toCharArray();
int n = ch.length;
int curX= 0, curY = 0;
int rowMin = 0 , rowMax = 0 , colMin = 0 , colMax = 0;
for(int i = 0 ; i < n ; i++) {
int x = curX , y = curY;
if(ch[i] == 'U')x--;
else if(ch[i] == 'D')x++;
else if(ch[i] == 'R')y++;
else y--;
int a = Math.min(rowMin, x);
int b = Math.max(rowMax, x);
int c = Math.min(colMin, y);
int d = Math.max(colMax, y);
if(Math.abs(b-a)+1 <= row && Math.abs(d-c)+1 <= col) {
curX = x;
curY = y;
rowMin = a;
rowMax = b;
colMin = c;
colMax = d;
}else break;
}
curX = Math.abs(rowMin)+1;
curY = Math.abs(colMin)+1;
out.println(curX + " " + curY);
}
out.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 | bc0ef76a64804c6e84d4d401189cb1a5 | 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.StringTokenizer;
/**
* @author Micgogi
* on 11/18/2021 9:54 AM
* Rahul Gogyani
*/
public class E1607 {
public static void main(String args[]) {
FastReader sc = new FastReader();
int t = sc.nextInt();
while (t-- != 0) {
int n = sc.nextInt();
int m = sc.nextInt();
String s = sc.nextLine();
int imin = 0, imax = 0, jmin = 0, jmax = 0, i = 0, j = 0;
for (int k = 0; k < s.length(); k++) {
if (s.charAt(k) == 'L') {
j--;
} else if (s.charAt(k) == 'R') {
j++;
} else if (s.charAt(k) == 'U') {
i--;
} else {
i++;
}
if(Math.max(i,imax)-Math.min(i,imin)>=n||Math.max(j,jmax)-Math.min(j,jmin)>=m){
break;
}
imin = Math.min(i,imin);
imax = Math.max(i,imax);
jmin = Math.min(j,jmin);
jmax =Math.max(j,jmax);
}
i= 1-imin;
j= 1-jmin;
System.out.println(i+" "+j);
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in), 32768);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[][] read2DArray(int n) {
int[][] a = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = nextInt();
}
}
return a;
}
int[][] read2DArray(int n, int m) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextInt();
}
}
return a;
}
}
} | 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 | 3a348bbac19707001b6208d86fbea2fb | 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 com.company;
import java.util.*;
import java.io.*;
public class RobotOnTheBoard1 {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testcases = Integer.parseInt(br.readLine());
for(int tests = 0; tests < testcases; tests++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int yLength = Integer.parseInt(st.nextToken());
int xLength = Integer.parseInt(st.nextToken());
String commands = br.readLine();
int x = 0; int xMin = 0; int xMax = 0;
int y = 0; int yMin = 0; int yMax = 0;
boolean endedPoint = false;
boolean movedRight = false; boolean movedUp = false;
StringBuilder ans = new StringBuilder();
for(int i = 0; i < commands.length(); i++) {
switch(commands.charAt(i)) {
case 'L':
x--;
break;
case 'R':
x++;
movedRight = true;
break;
case 'U':
y--;
movedUp = true;
break;
case 'D':
y++;
break;
}
if(x < xMin) xMin = x;
if(x > xMax) xMax = x;
if(y < yMin) yMin = y;
if(y > yMax) yMax = y;
if(xMax - xMin >= xLength) {
if(movedRight) {
ans.append(-yMin + 1);
ans.append(" ");
ans.append(-xMin + 1);
endedPoint = true;
break;
}
else {
ans.append(-yMin + 1);
ans.append(" ");
ans.append(-xMin);
endedPoint = true;
break;
}
}
else if(yMax - yMin >= yLength) {
if(movedUp) {
ans.append(-yMin);
ans.append(" ");
ans.append(-xMin + 1);
endedPoint = true;
break;
}
else {
ans.append(-yMin + 1);
ans.append(" ");
ans.append(-xMin + 1);
endedPoint = true;
break;
}
}
movedRight = false;
movedUp = false;
}
if(!endedPoint) {
ans.append(-yMin + 1);
ans.append(" ");
ans.append(-xMin + 1);
}
System.out.println(ans);
}
br.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 | e793378b59bc4112f1a1f1581893c604 | 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.StringTokenizer;
public class E {
public static void main(String[] args) {
new E().solve(System.in, System.out);
}
public void solve(InputStream in, OutputStream out) {
InputReader inputReader = new InputReader(in);
PrintWriter writer = new PrintWriter(new BufferedOutputStream(out));
int t = inputReader.nextInt();
for (int t1 = 0; t1 < t; t1++) {
int n = inputReader.nextInt();
int m = inputReader.nextInt();
String s = inputReader.next();
Result result = solve(n, m, s);
writer.println(result.n + " " + result.m);
}
writer.close();
}
public Result solve(int n, int m, String s) {
int minX = 0, maxX = 0, minY = 0, maxY = 0;
int x = 0, y = 0;
int i = 0;
while (true) {
if (i >= s.length()) {
break;
}
char move = s.charAt(i);
int nextX = x;
int nextY = y;
switch (move) {
case 'U': nextX--; break;
case 'D': nextX++; break;
case 'R': nextY++; break;
case 'L': nextY--; break;
default: throw new RuntimeException("No move for char " + move);
}
if (Math.max(maxX, nextX) - Math.min(minX, nextX) >= n) {
break;
}
if (Math.max(maxY, nextY) - Math.min(minY, nextY) >= m) {
break;
}
maxX = Math.max(maxX, nextX);
minX = Math.min(minX, nextX);
maxY = Math.max(maxY, nextY);
minY = Math.min(minY, nextY);
x = nextX;
y = nextY;
i++;
}
return new Result(1 - minX, 1 - minY);
}
public static class Result {
public int n;
public int m;
public Result(int n, int m) {
this.n = n;
this.m = m;
}
}
private static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public 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 | cfaf0c4291e7e2d7ad2c5b63147fac92 | 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 problem1607e {
public static void main(String[] args){
FastScanner sc = new FastScanner();
int t = sc.nextInt();
while(t-- > 0){
int n = sc.nextInt();
int m = sc.nextInt();
String s = sc.next();
int left[] = new int[s.length()+1];
int right[] = new int[s.length()+1];
int up[] = new int[s.length()+1];
int down[] = new int[s.length()+1];
int x = 0;
int y = 0;
for(int i=0; i<s.length(); i++){
if(s.charAt(i) == 'R'){
right[i+1] = Math.max(right[i], x+1);
left[i+1] = left[i];
up[i+1] = up[i];
down[i+1] = down[i];
x++;
}
if(s.charAt(i) == 'L'){
right[i+1] = right[i];
left[i+1] = Math.min(left[i], x-1);
up[i+1] = up[i];
down[i+1] = down[i];
x--;
}
if(s.charAt(i) == 'D'){
right[i+1] = right[i];
left[i+1] = left[i];
up[i+1] = up[i];
down[i+1] = Math.min(down[i], y-1);
y--;
}
if(s.charAt(i) == 'U'){
right[i+1] = right[i];
left[i+1] = left[i];
up[i+1] = Math.max(up[i], y+1);
down[i+1] = down[i];
y++;
}
}
int xans = 0;
int yans = 0;
for(int i=s.length(); i>=0; i--){
if(up[i]-down[i]+1 <= n && right[i]-left[i]+1<=m){
xans = Math.abs(left[i])+1;
yans = up[i]+1;
break;
}
}
System.out.println(yans + " " + xans);
}
}
}
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 | 3672664d70d5f5c450a70fc023e9ccd8 | 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.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.stream.Stream;
public class CasimirString {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws NumberFormatException, IOException {
int cases = Integer.parseInt(reader.readLine());
while(cases-- > 0) {
String[] firstLine = reader.readLine().split(" ");
int row = Integer.parseInt(firstLine[0]);
int col = Integer.parseInt(firstLine[1]);
String directions = reader.readLine();
int minDy = 0;
int minDx = 0;
int maxDy = 0;
int maxDx = 0;
int dx = 0;
int dy = 0;
int ansRow = 1;
int ansCol = 1;
for(int i=0;i<directions.length();i++) {
if(directions.charAt(i) == 'U') {
dy++;
}
if(directions.charAt(i) == 'D') {
dy--;
}
if(directions.charAt(i) == 'R') {
dx++;
}
if(directions.charAt(i) == 'L') {
dx--;
}
minDx = Math.min(minDx, dx);
maxDx = Math.max(maxDx, dx);
minDy = Math.min(minDy, dy);
maxDy = Math.max(maxDy, dy);
if((1+Math.abs(minDx) > col-Math.abs(maxDx)) || (1+Math.abs(maxDy) > row - Math.abs(minDy))) {
break;
}
ansRow = row-Math.abs(minDy);
ansCol = col-Math.abs(maxDx);
//System.out.println(maxDy + " " + minDy);
}
out.append(ansRow + " " + ansCol + "\n");
}
out.flush();
}
public static Integer[] convertToIntArray(String[] str) {
Integer[] arr = new Integer[str.length];
for(int i=0;i<str.length;i++) {
arr[i] = Integer.parseInt(str[i]);
}
return arr;
}
public static Long[] convertToLongArray(String[] str) {
Long[] arr = new Long[str.length];
for(int i=0;i<str.length;i++) {
arr[i] = Long.parseLong(str[i]);
}
return arr;
}
public static void printYes() throws IOException {
out.append("YES" + "\n");
}
public static void printNo() throws IOException {
out.append("NO" + "\n");
}
public static void printNumber(long num) throws IOException {
out.append(num + "\n");
}
public static long hcf(long a, long b) {
if(b==0) return a;
return hcf(b, a%b);
}
public static int findSet(int[] parent, int[] rank, int v) {
if(v==parent[v]) {
return v;
}
parent[v] = findSet(parent, rank, parent[v]);
return parent[v];
}
public static void unionSet(int[] parent, int[] rank, int a, int b) {
a = findSet(parent, rank, a);
b = findSet(parent, rank, b);
if(a == b) {
return;
}
if(rank[a] < rank[b]) {
int temp = a;
a = b;
b = temp;
}
parent[b] = a;
if(rank[a] == rank[b]) {
rank[a]++;
}
}
public static void makeSet(int[] parent, int[] rank, int v) {
parent[v] = v;
rank[v] = 0;
}
}
| 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 | 9360985d119fd4b9873ec621349aaca9 | 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 problemE {
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();
String S=sc.next();
int l=1,r=n,p=0;
int x=0,y=0;
int len=S.length();
for(int i=0;i<len;i++){
char c=S.charAt(i);
if(c=='U'){
p--;
if(l+p<1){
l=1-p;
if(l>r){
x=r;
break;
}
}
}
else if(c=='D'){
p++;
if(r+p>n){
r=n-p;
if(l>r){
x=l;
break;
}
}
}
}
if(l<=r)x=l;
l=1;
r=m;
p=0;
for(int i=0;i<len;i++){
char c=S.charAt(i);
if(c=='L'){
p--;
if(l+p<1){
l=1-p;
if(l>r){
y=r;
break;
}
}
}
else if(c=='R'){
p++;
if(r+p>m){
r=m-p;
if(l>r){
y=l;
break;
}
}
}
}
if(l<=r)y=l;
System.out.println(x+" "+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 | 1c5fd49b634fba4757cd3c6a41cca87b | 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.BigInteger;
public class code{
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')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static int GCD(int a, int b)
{
if (b == 0)
return a;
return GCD(b, a % b);
}
//@SuppressWarnings("unchecked")
public static void main(String[] arg) throws IOException{
//Reader in=new Reader();
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner(System.in);
int t=in.nextInt();
while(t-- > 0){
int n=in.nextInt();
int m=in.nextInt();
String s=in.next();
int x=0,y=0;
int dx=1,dy=1;
int xmax=0,xmin=0,ymax=0,ymin=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='L') x--;
else if(s.charAt(i)=='R') x++;
else if(s.charAt(i)=='U') y++;
else y--;
xmax=Math.max(x,xmax);
xmin=Math.min(x,xmin);
ymax=Math.max(y,ymax);
ymin=Math.min(y,ymin);
if((xmax-xmin < m) && (ymax-ymin < n)){
//System.out.println(xmax+" "+xmin+" "+ymax+" "+ymin);
dx=m-xmax;
dy=ymax+1;
}
else{
break;
}
}
out.println(dy+" "+dx);
}
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 | 4c2aff568b4bbd3d14c1d8967c94e7d4 | 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.*;
public class robot {
public static void main(String[] args) {
// Scanner sc = new Scanner(System.in);
FastReader sc = new FastReader();
int t = sc.nextInt();
for(int o = 0 ; o<t;o++) {
int n = sc.nextInt();
int m = sc.nextInt();
String s = sc.next();
int cl = 0;
int ch = 0;
int rl = 0;
int rh = 0;
int r = n-1;
int c = m-1;
int t1 = 0;
int t2 = 0;
for(int i = 0 ; i<s.length();i++) {
if(s.charAt(i) == 'D') {
// rh++;
t1++;
rh = Math.max(rh, t1);
if(rh-rl>r) {
rh--;
break;
}
}else if(s.charAt(i) == 'U') {
// rl--;
t1--;
rl = Math.min(rl, t1);
if(rh-rl>r) {
rl++;
break;
}
}else if(s.charAt(i) == 'L') {
// cl--;
t2--;
cl = Math.min(cl, t2);
if(ch-cl>c) {
cl++;
break;
}
}else {
t2++;
// ch++;
ch = Math.max(ch, t2);
if(ch-cl>c) {
ch--;
break;
}
}
}
// System.out.println(rh + " " + rl + " " + ch + " " + cl);
// System.out.println(cl + " " + rl);
int x = Math.abs(cl) + 1;
System.out.println(Math.abs(rl) + 1 + " " + x);
}
}
}
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 | b33a79b75d240522880b9a700344faac | 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 | // Main Code at the Bottom
import java.util.*;
import java.io.*;
import java.sql.Time;
public class Main implements Runnable{
//Fast IO class
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUDGE") != null;
//env=true;
if(!env) {
try {
br=new BufferedReader(new FileReader("src\\input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long MOD=(long)1e9+7;
//debug
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
//Global variables and functions
//Main function(The main code starts from here)
public void run() {
int test=1;
test=sc.nextInt();
while(test-->0) {
int n = sc.nextInt(), m = sc.nextInt();
char s[] = sc.nextLine().toCharArray();
int X = 0, Y = 0;
int x = 0, y = 0, minX = 0, minY = y, maxX = 0, maxY = 0;
for(char c: s) {
if(c == 'L') {
x -= 1;
if(x < 0) {
minX++;
maxX++;
if(maxX >= m) break;
x++;
X++;
}
maxX = Math.max(x, maxX);
minX = Math.min(x, minX);
}
else if(c == 'R') {
x += 1;
if(x >= m) {
minX--;
maxX--;
if(minX < 0) break;
X--;
x--;
}
maxX = Math.max(x, maxX);
minX = Math.min(x, minX);
}
else if(c == 'U') {
y -= 1;
if(y < 0) {
minY++;
maxY++;
if(maxY >= n) break;
y++;
Y++;
}
maxY = Math.max(y, maxY);
minY = Math.min(y, minY);
}
else {
y += 1;
if(y >= n) {
minY--;
maxY--;
if(minY < 0) break;
Y--;
y--;
}
maxY = Math.max(y, maxY);
minY = Math.min(y, minY);
}
}
out.println((Y + 1) + " " + (X + 1));
}
out.flush();
out.close();
}
public static void main (String[] args) throws java.lang.Exception {
new Thread(null, new Main(), "anything", (1<<28)).start();
}
} | 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 | 1d659ae07865a92dbd4052fbddce46c0 | 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) {
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=input.nextInt();
while(T-->0)
{
int n=input.nextInt();
int m=input.nextInt();
String s=input.next();
int l=0,r=s.length();
int a=0,b=0;
while(l<r)
{
int mid=(l+r)/2;
int le=0,ri=0,u=0,d=0;
int x=0,y=0;
for(int i=0;i<=mid;i++)
{
if(s.charAt(i)=='R') x++;
else if(s.charAt(i)=='L') x--;
else if(s.charAt(i)=='U') y++;
else y--;
if(x<0) le=Math.max(le,Math.abs(x));
else ri=Math.max(ri,x);
if(y<0) d=Math.max(d,Math.abs(y));
else u=Math.max(u,y);
}
int row=1+u;
int col=1+le;
if(n-row>=d && m-col>=ri)
{
a=row;b=col;
l=mid+1;
}
else
{
r=mid;
}
}
l--;
if(l<0)
{
out.println(1+" "+1);
}
else
{
out.println(a+" "+b);
}
}
out.close();
}
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 | 0e33d36ab55db4756d1f8422d31818a9 | 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: RonWonWon
* CREATED: 06.11.2021 01:21:21
/*==========================================================================*/
import java.io.*;
import java.util.*;
public class E {
public static void main(String[] args) throws IOException {
/*
in.ini();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
*/
long startTime = System.nanoTime();
int t = in.nextInt(), T = 1;
while(t-->0) {
int mxL = 0, mxR = 0, mxU = 0, mxD = 0;
int n = in.nextInt(), m = in.nextInt();
char ch[] = in.next().toCharArray();
int lr = 0, ud = 0, ans = 0;
for(int i=0;i<ch.length;i++){
if(ch[i]=='L') lr--;
if(ch[i]=='R') lr++;
if(ch[i]=='U') ud++;
if(ch[i]=='D') ud--;
int curL = mxL, curR = mxR;
if(lr<0) curL = Math.max(curL,-lr);
else if(lr>0) curR = Math.max(curR,lr);
int curU = mxU, curD = mxD;
if(ud<0) curD = Math.max(curD,-ud);
else if(ud>0) curU = Math.max(curU,ud);
if(curL+curR>=m) break;
if(curU+curD>=n) break;
ans++;
mxU = curU; mxD = curD; mxL = curL; mxR = curR;
}
//out.println(ans);
if(mxU==-1) mxU = 0;
if(mxL==-1) mxL = 0;
out.println((mxU+1)+" "+(mxL+1));
//out.println("Case #"+T+": "+ans); T++;
}
/*
startTime = System.nanoTime() - startTime;
System.err.println("Time: "+(startTime/1000000));
*/
out.flush();
}
static FastScanner in = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
static int oo = Integer.MAX_VALUE;
static long ooo = Long.MAX_VALUE;
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
void ini() throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
String next() {
while(!st.hasMoreTokens())
try { st = new StringTokenizer(br.readLine()); }
catch(IOException e) {}
return st.nextToken();
}
String nextLine(){
try{ return br.readLine(); }
catch(IOException e) { } return "";
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int a[] = new int[n];
for(int i=0;i<n;i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] readArrayL(int n) {
long a[] = new long[n];
for(int i=0;i<n;i++) a[i] = nextLong();
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] readArrayD(int n) {
double a[] = new double[n];
for(int i=0;i<n;i++) a[i] = nextDouble();
return a;
}
}
static final Random random = new Random();
static void ruffleSort(int[] a){
int n = a.length;
for(int i=0;i<n;i++){
int j = random.nextInt(n), temp = a[j];
a[j] = a[i]; a[i] = temp;
}
Arrays.sort(a);
}
static void ruffleSortL(long[] a){
int n = a.length;
for(int i=0;i<n;i++){
int j = random.nextInt(n);
long temp = a[j];
a[j] = a[i]; a[i] = temp;
}
Arrays.sort(a);
}
}
| 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 | 4db8e502e23a29686ffee748d5ed9dc1 | 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.*;
//CODE FORCES
public class anshulvmc {
public 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);
}
public static int gcd(int a, int b) {
if (b==0) return a;
return gcd(b, a%b);
}
public static void google(int t) {
System.out.println("Case #"+t+": ");
}
// public static void gt(int[][] arr,int k) {
// int n = arr.length+1;
// k = Math.min(k,n+1);
//
// Node[] nodes = new Node[n];
// for(int i=0;i<n;i++) nodes[i] = new Node();
// for(int i=0;i<n-1;i++) {
// int a = arr[i][0];
// int b = arr[i][1];
// System.out.println(a+" "+b);
// nodes[a].adj.add(nodes[b]);
// nodes[b].adj.add(nodes[a]);
// }
//
// ArrayDeque<Node> bfs = new ArrayDeque<>();
// for(Node nn:nodes) {
// if(nn.adj.size()<2) {
// bfs.addLast(nn);
// nn.dist=0;
// }
// }
//
// while(bfs.size()>0) {
// Node nn = bfs.removeFirst();
// for(Node a : nn.adj) {
// if(a.dist!=-1) continue;
// a.usedDegree++;
// if(a.adj.size() - a.usedDegree <= 1) {
// a.dist = nn.dist+1;
// bfs.addLast(a);
// }
// }
// }
//
// int[] cs = new int[n+1];
// for(Node nn:nodes) {
// cs[nn.dist]++;
// }
// for(int i=1;i<cs.length;i++) cs[i]+=cs[i-1];
// System.out.println(n-cs[k-1]);
// }
public static class Node{
ArrayList<Node> adj = new ArrayList<>();
int dist = -1;
int usedDegree = 0;
}
public static void cat_mice(int dest,int[] arr) {
sort(arr);
int time = dest;
int timeleft = dest-1;
int counter=0;
for(int i=arr.length-1;i>=0;i--) {
int val = arr[i];
int takes = time - val;
if(takes <= timeleft) {
timeleft -= takes;
counter++;
}
}
System.out.println(counter);
}
public static void minex(int n,int[] arr) {
sort(arr);
int ans=arr[0];
for(int i=0;i<arr.length-1;i++) {
ans = Math.max(ans,arr[i+1] - arr[i]);
}
System.out.println(ans);
}
public static void func(long start,long n) {
long x = start;
if(n==0){
System.out.println(x);
return;
}
long k=n-1;
long c=k/4;
long rem=k%4;
long ans=x;
if(x%2 == 0) {
ans -= 1;
ans -= (c * 4);
if(rem == 1) {
ans += n;
}
else if(rem == 2) {
ans += n + n-1;
}
else if(rem == 3){
ans += (n-2) + (n-1) - n;
}
}
else {
ans += 1;
ans += (c * 4);
if(rem == 1) {
ans -= n;
}
else if(rem == 2) {
ans -= n + n-1;
}
else if(rem == 3) {
ans -= n-2 + n-1 - n;
}
}
System.out.println(ans);
}
public static boolean redblue(int[] num, String chnum) {
ArrayList<Integer> blue = new ArrayList<>();
ArrayList<Integer> red = new ArrayList<>();
for(int i=0;i<chnum.length();i++) {
char ch = chnum.charAt(i);
if(ch == 'B') {
blue.add(num[i]);
}
else {
red.add(num[i]);
}
}
Collections.sort(blue);
Collections.sort(red);
// System.out.println(blue);
// System.out.println(red);
for(int i=0;i<blue.size();i++) {
if(blue.get(i) >= i+1) {
}
else {
return false;
}
}
for(int i=0;i<red.size();i++) {
if(red.get(i) > i+1 + blue.size()) {
// System.out.println(red.get(i)+" "+(i+1 + blue.size()));
return false;
}
}
return true;
}
public static void robot(int n,int m,String moves) {
int left = 0;
int right = 0;
int up = 0;
int down = 0;
int v = 0;
int h = 0;
int ans_x = 1;
int ans_y = 1;
for(int i=0;i<moves.length();i++) {
char ch = moves.charAt(i);
if(ch == 'L') {
h--;
}
else if(ch == 'R') {
h++;
}
else if(ch == 'U') {
v++;
}
else {
v--;
}
left = Math.min(h,left);
right = Math.max(h,right);
up = Math.max(v,up);
down = Math.min(down,v);
if(right - left + 1 > m || up - down + 1 > n) {
// System.out.println((right - left + 1) +" exit "+( up - down + 1));
break;
}
else {
ans_y = Math.abs(left)+1;
ans_x = Math.abs(up) + 1;
}
}
System.out.println(ans_x+" "+ans_y);
}
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
int test = scn.nextInt();
for(int i=0;i<test;i++) {
int n = scn.nextInt();
int m = scn.nextInt();
String str = scn.next();
robot(n,m,str);
}
// int n = 1;
// int[] dp = new int[2];
// System.out.println(fact(n,dp));
}
} | 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 | 40ebab7a98e0aa2a52cfefbf9afb3655 | 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 sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
int m = sc.nextInt();
String s = sc.next();
int dx=0,dy=0,maxdx=0,maxdy=0,mindx=0,mindy=0;
int ansx=1,ansy=1;
for(int i=0;i<s.length();i++){
char cc = s.charAt(i);
if(cc=='U'){
dx--;
}
else if(cc=='D'){
dx++;
}
else if(cc=='R'){
dy++;
}
else{
dy--;
}
maxdx = Math.max(maxdx, dx);
mindx = Math.min(mindx, dx);
maxdy = Math.max(maxdy, dy);
mindy = Math.min(mindy, dy);
int maxx = n - maxdx;
int maxy = m - maxdy;
int miny = 1 - mindy;
int minx = 1 - mindx;
if(minx<=maxx && miny<=maxy){
ansx = minx;
ansy = miny;
}
}
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 | 1848e6205323bf09d6786a394a43f153 | 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.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class TaskB {
static long mod = 1000000007;
static FastScanner scanner;
static final StringBuilder result = new StringBuilder();
public static void main(String[] args) {
scanner = new FastScanner();
int T = scanner.nextInt();
for (int t = 0; t < T; t++) {
solve(t + 1);
result.append("\n");
}
System.out.println(result);
}
static void solve(int t) {
int n = scanner.nextInt();
int m = scanner.nextInt();
String s = scanner.nextToken();
int x = 0;
int y = 0;
int minX, maxX, minY, maxY;
minX = maxX = minY = maxY = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case 'L': x--; break;
case 'R': x++; break;
case 'U': y--; break;
case 'D': y++; break;
}
int nextminX = Math.min(x, minX);
int nextmaxX = Math.max(x, maxX);
int nextminY = Math.min(y, minY);
int nextmaxY = Math.max(y, maxY);
if (nextmaxX - nextminX + 1 > m || nextmaxY - nextminY + 1 > n) break;
minX = nextminX;
maxX = nextmaxX;
minY = nextminY;
maxY = nextmaxY;
}
result.append(Math.abs(minY) + 1).append(" ").append(Math.abs(minX) + 1);
}
static class WithIdx implements Comparable<WithIdx> {
int val, idx;
public WithIdx(int val, int idx) {
this.val = val;
this.idx = idx;
}
@Override
public int compareTo(WithIdx o) {
if (val == o.val) {
return Integer.compare(idx, o.idx);
}
return Integer.compare(val, o.val);
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
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();
}
String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
long[] nextLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) res[i] = nextLong();
return res;
}
String[] nextStringArray(int n) {
String[] res = new String[n];
for (int i = 0; i < n; i++) res[i] = nextToken();
return res;
}
}
static class PrefixSums {
long[] sums;
public PrefixSums(long[] sums) {
this.sums = sums;
}
public long sum(int fromInclusive, int toExclusive) {
if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value");
return sums[toExclusive] - sums[fromInclusive];
}
public static PrefixSums of(int[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
public static PrefixSums of(long[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
}
static class ADUtils {
static void sort(int[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
static void reverse(int[] arr) {
int last = arr.length / 2;
for (int i = 0; i < last; i++) {
int tmp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = tmp;
}
}
static void sort(long[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
long a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
}
static class MathUtils {
static long[] FIRST_PRIMES = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051};
static long[] primes(int to) {
long[] all = new long[to + 1];
long[] primes = new long[to + 1];
all[1] = 1;
int primesLength = 0;
for (int i = 2; i <= to; i++) {
if (all[i] == 0) {
primes[primesLength++] = i;
all[i] = i;
}
for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j];
j++) {
all[(int) (i * primes[j])] = primes[j];
}
}
return Arrays.copyOf(primes, primesLength);
}
static long modpow(long b, long e, long m) {
long result = 1;
while (e > 0) {
if ((e & 1) == 1) {
/* multiply in this bit's contribution while using modulus to keep
* result small */
result = (result * b) % m;
}
b = (b * b) % m;
e >>= 1;
}
return result;
}
static long submod(long x, long y, long m) {
return (x - y + m) % m;
}
static long modInverse(long a, long m) {
long g = gcdF(a, m);
if (g != 1) {
throw new IllegalArgumentException("Inverse doesn't exist");
} else {
// If a and m are relatively prime, then modulo
// inverse is a^(m-2) mode m
return modpow(a, m - 2, m);
}
}
static public long gcdF(long a, long b) {
while (b != 0) {
long na = b;
long nb = a % b;
a = na;
b = nb;
}
return a;
}
}
}
/*
5
3 2 3 8 8
2 8 5 10 1
*/ | 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 | 5f7b783b7052e8ee9799406d09942810 | 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.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution
{
public static void main (String[] args) throws java.lang.Exception
{
InputReader sc=new InputReader(System.in);
int t = sc.readInt();
PrintWriter pw=new PrintWriter(System.out);
while(t-->0){
int n = sc.readInt();
int m = sc.readInt();
String op = sc.readLine();
int x=0 ,y=0 ,xmin=0,xmax=0,ymin=0,ymax=0;
int i;
for(i=0;i<op.length();i++){
if(op.charAt(i)=='L'){
x--;
if(x<xmin){
if(xmax-x>=m){
break;
}
xmin=x;
}
}
else if(op.charAt(i)=='R'){
x++;
if(x>xmax){
if(x-xmin>=m){
break;
}
xmax=x;
}
}
else if(op.charAt(i)=='D'){
y--;
if(y<ymin){
if(ymax-y>=n){
break;
}
ymin=y;
}
}
else{
y++;
if(y>ymax){
if(y-ymin>=n){
break;
}
ymax=y;
}
}
}
pw.println((ymax+1) +" "+(-1*xmin+1));
//pw.println(i+" "+xmax+" "+xmin+" "+ymax+" "+ymin);
}
pw.close();
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 String readLine() {
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 double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| 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 | ca2fb00c9763ee6ac8adf1682e29de3c | 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 new1{
public static void main(String[] args) throws IOException{
FastReader s = new FastReader();
//long l1 = System.currentTimeMillis();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int t = s.nextInt();
for(int z = 0; z < t; z++) {
int n = s.nextInt();
int m = s.nextInt();
int h1 = 0, h2 = 0;
int v1 = 0, v2 = 0;
int x = 0, y = 0;
String str = s.next();
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(ch == 'U') {
x--;
v1 = Math.min(x, v1);
if(Math.abs(v1 - v2) + 1 > n) {
x++; v1++; break;
}
}
else if(ch == 'D') {
x++;
v2 = Math.max(x, v2);
if(Math.abs(v1 - v2) + 1> n) {
x--; v2--; break;
}
}
else if(ch == 'L') {
y--;
h1 = Math.min(y, h1);
if(Math.abs(h1 - h2) + 1 > m) {
y++;; h1++; break;
}
}
else {
y++;
h2 = Math.max(y, h2);
if(Math.abs(h1 - h2) + 1 > m) {
y--; h2--; break;
}
}
//System.out.println(x + " " + y + " " + v1 + " " + h1 + " " + v2 + " " + h2);
}
System.out.println((-v1 + 1) + " " + (-h1 + 1));
}
//output.write((System.currentTimeMillis() - l1) + "\n");
//output.flush();
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}} | Java | ["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 | d805a67a077da9fb93b2bf0e7071ceac | 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.*;
import java.util.concurrent.ThreadLocalRandom;
// 3 3
// RRDLUU
public class Z {
private static void sport(String s, int r, int c) {
int currRow = 0;
int currCol = 0;
int minr = 0;
int minc = 0;
int maxr = 0;
int maxc = 0;
for (char c1 : s.toCharArray()) {
if (c1 == 'R') {
currCol++;
} else if (c1 == 'L') {
currCol--;
} else if (c1 == 'U') {
currRow--;
} else {
currRow++;
}
maxc = Math.max(currCol, maxc);
maxr = Math.max(currRow, maxr);
minc = Math.min(currCol, minc);
minr = Math.min(currRow, minr);
if (maxc - minc <= c - 1 && maxr - minr <= r - 1) {
continue;
} else {
int lastr = 0;
int lastc = 0;
if (c1 == 'R') {
lastc = 1;
} else if (c1 == 'L') {
lastc = -1;
} else if (c1 == 'U') {
lastr = -1;
} else {
lastr = 1;
}
if (lastc != 0) {
if (lastc > 0) {
maxc--;
} else {
minc++;
}
} else {
if (lastr > 0) {
maxr--;
} else {
minr++;
}
}
int ansc = -minc;
int ansr = -minr;
System.out.println((ansr + 1) + " " + (ansc + 1));
return;
}
}
int ansc = -minc;
int ansr = -minr;
System.out.println((ansr + 1) + " " + (ansc + 1));
}
public static void main(String[] args) throws IOException {
FastScanner sc = new FastScanner();
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int r = sc.nextInt();
int c = sc.nextInt();
String s = sc.next();
sport(s, r, c);
}
}
static void shuffleArray(int[] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
void nextLine() throws IOException {
br.readLine();
}
long[] readArrayLong(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
int[] readArrayInt(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 | e82fe4edf2dad759eb5605c289349e97 | 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 IOException
{
FastScanner f= new FastScanner();
int ttt=1;
ttt=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
outer: for(int tt=0;tt<ttt;tt++) {
int r=f.nextInt();
int m=f.nextInt();
char[] l=f.next().toCharArray();
int maxx=0;
int minx=0;
int maxy=0;
int miny=0;
int currx=0;
int curry=0;
for(int i=0;i<l.length;i++) {
if(l[i]=='L') {
currx--;
if(maxx-Math.min(minx, currx)>=m) {
currx++;
break;
}
minx=Math.min(minx, currx);
}
else if(l[i]=='R') {
currx++;
if(Math.max(maxx, currx)-minx>=m) {
currx--;
break;
}
maxx=Math.max(maxx, currx);
}
else if(l[i]=='U') {
curry--;
if(maxy-Math.min(miny, curry)>=r){
curry++;
break;
}
miny=Math.min(miny, curry);
}
else {
curry++;
if(Math.max(maxy, curry)-miny>=r){
curry--;
break;
}
maxy=Math.max(maxy, curry);
}
// System.out.println(currx);
}
// System.out.println(maxx+" "+minx);
// System.out.println(maxy+" "+miny);
int ansx=1;
int ansy=1;
if(minx+maxx>=0){
ansx=m-maxx;
}
else {
ansx=-minx+1;
}
if(miny+maxy>=0){
ansy=r-maxy;
}
else {
ansy=-miny+1;
}
System.out.println(ansy+" "+ansx);
}
out.close();
}
static void sort(int[] p) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: p) q.add( i);
Collections.sort(q);
for (int i = 0; i < p.length; i++) p[i] = q.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());
}
double nextDouble() {
return Double.parseDouble(next());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
} | 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 | 87d41e8a8530cb7c948f4b53775b0814 | 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 sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int m=sc.nextInt();
String s=sc.next();
int val=0;
int x=0;int y=0;
int max=0;
int min=0;
for(int i=0;i<s.length();i++)
{if(max-min>=m-1)
break;
if(s.charAt(i)=='R')
val++;
if(s.charAt(i)=='L')
val--;
max=Math.max(max, val);
min=Math.min(min, val);
}
if(min<=0 && max>=0)
y=y-min;
val=0;max=0;
min=0;
for(int i=0;i<s.length();i++)
{if(max-min>=n-1)
break;
if(s.charAt(i)=='D')
val++;
if(s.charAt(i)=='U')
val--;
max=Math.max(max, val);
min=Math.min(min, val);
}
if(min<=0 && max>=0)
x=x-min;
System.out.println(x+1+" "+(y+1) );}
}}
| 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 | 8733aa8796e9bea4f75d58a7cdc6ab38 | 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 | b8cfb90d42342ea31cad3ca26df94a6c | 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.lang.*;
// import java.math.*;
public class Codeforces {
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
static long mod=1000000007;
// static long mod=998244353;
static int MAX=Integer.MAX_VALUE;
static int MIN=Integer.MIN_VALUE;
static long MAXL=Long.MAX_VALUE;
static long MINL=Long.MIN_VALUE;
static ArrayList<Integer> graph[];
static long fact[];
static StringBuffer sb;
public static void main (String[] args) throws java.lang.Exception
{
// code goes here
int t=I();
outer:while(t-->0)
{
int n=I(),m=I();
char c[]=S().toCharArray();
int h=0,v=0,pbh=0,nbh=0,pbv=0,nbv=0;
int i;
if(n==1 && m==1){
out.println("1 1");
continue;
}
for(i=0;i<c.length;i++){
if(c[i]=='R')h++;
else if(c[i]=='L')h--;
else if(c[i]=='U')v++;
else v--;
if(pbh<h)pbh=h;
if(nbh>h)nbh=h;
if(pbv<v)pbv=v;
if(nbv>v)nbv=v;
if(Math.abs(pbh-nbh)>=m || Math.abs(pbv-nbv)>=n)break;
// out.println(i+" "+h+" "+v+" "+pbh+" "+nbh+" "+pbv+" "+nbv);
}
// out.println(i+" "+h+" "+v+" "+pbh+" "+nbh+" "+pbv+" "+nbv);
h=0;v=0;pbh=0;nbh=0;pbv=0;nbv=0;
for(int j=0;j<i;j++){
if(c[j]=='R')h++;
else if(c[j]=='L')h--;
else if(c[j]=='U')v++;
else v--;
if(pbh<h)pbh=h;
if(nbh>h)nbh=h;
if(pbv<v)pbv=v;
if(nbv>v)nbv=v;
}
int p=1,q=1;
q+=Math.abs(nbh);
p+=pbv;
out.println(p+" "+q);
}
out.close();
}
public static class pair
{
long a;
long b;
public pair(long val,long index)
{
a=val;
b=index;
}
}
public static class myComp implements Comparator<pair>
{
//sort in ascending order.
// public int compare(pair p1,pair p2)
// {
// if(p1.a==p2.a)
// return 0;
// else if(p1.a<p2.a)
// return -1;
// else
// return 1;
// }
//sort in descending order.
public int compare(pair p1,pair p2)
{
if(p1.a==p2.a)
return 0;
else if(p1.a<p2.a)
return 1;
else
return -1;
}
}
public static long nPr(int n,int r)
{
long ans=divide(fact(n),fact(n-r),mod);
return ans;
}
public static long nCr(int n,int r)
{
long ans=divide(fact[n],mul(fact[n-r],fact[r]),mod);
return ans;
}
public static long kadane(long a[],int n) //largest sum subarray
{
long max_sum=Long.MIN_VALUE,max_end=0;
for(int i=0;i<n;i++){
max_end+=a[i];
if(max_sum<max_end){max_sum=max_end;}
if(max_end<0){max_end=0;}
}
return max_sum;
}
public static void DFS(int s,boolean visited[])
{
visited[s]=true;
for(int i:graph[s]){
if(!visited[i]){
DFS(i,visited);
}
}
}
public static void setGraph(int n,int m)
{
graph=new ArrayList[n+1];
for(int i=0;i<=n;i++){
graph[i]=new ArrayList<>();
}
for(int i=0;i<m;i++){
int u=I(),v=I();
graph[u].add(v);
graph[v].add(u);
}
}
public static int BS(long a[],long x,int ii,int jj)
{
// int n=a.length;
int mid=0;
int i=ii,j=jj;
while(i<=j)
{
mid=(i+j)/2;
if(a[mid]<x){
i=mid+1;
}else if(a[mid]>x){
j=mid-1;
}else{
return mid;
}
}
return -1;
}
//LOWER_BOUND and UPPER_BOUND functions
public static int lower_bound(long arr[],int start, int end, long X) //start=0,end=n-1
{
if(arr[arr.length-1]<X)return end;
if(arr[0]>X)return -1;
int left=start,right=end;
while(left<right){
int mid=(left+right)/2;
if(arr[mid]==X){ //Returns last index of lower bound value.
if(mid<end && arr[mid+1]==X){
left=mid+1;
}else{
return mid;
}
}
// if(arr[mid]==X){ //Returns first index of lower bound value.
// if(mid>start && arr[mid-1]==X){
// right=mid-1;
// }else{
// return mid;
// }
// }
else if(arr[mid]>X){
if(mid>start && arr[mid-1]<X){
return mid-1;
}else{
right=mid-1;
}
}else{
if(mid<end && arr[mid+1]>X){
return mid;
}else{
left=mid+1;
}
}
}
return left;
}
public static int upper_bound(long arr[],int start,int end,long X) //start=0,end=n-1
{
if(arr[0]>=X)return start;
if(arr[arr.length-1]<X)return -1;
int left=start,right=end;
while(left<right){
int mid=(left+right)/2;
if(arr[mid]==X){ //returns first index of upper bound value.
if(mid>start && arr[mid-1]==X){
right=mid-1;
}else{
return mid;
}
}
// if(arr[mid]==X){ //returns last index of upper bound value.
// if(mid<end && arr[mid+1]==X){
// left=mid+1;
// }else{
// return mid;
// }
// }
else if(arr[mid]>X){
if(mid>start && arr[mid-1]<X){
return mid;
}else{
right=mid-1;
}
}else{
if(mid<end && arr[mid+1]>X){
return mid+1;
}else{
left=mid+1;
}
}
}
return left;
}
//END
public static boolean isSorted(int a[])
{
int n=a.length;
for(int i=0;i<n-1;i++){
if(a[i]>a[i+1])return false;
}
return true;
}
public static boolean isSorted(long a[])
{
int n=a.length;
for(int i=0;i<n-1;i++){
if(a[i]>a[i+1])return false;
}
return true;
}
public static int computeXOR(int n) //compute XOR of all numbers between 1 to n.
{
if (n % 4 == 0)
return n;
if (n % 4 == 1)
return 1;
if (n % 4 == 2)
return n + 1;
return 0;
}
public static ArrayList<Integer> primeSieve(int n)
{
ArrayList<Integer> arr=new ArrayList<>();
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
arr.add(i);
}
return arr;
}
// Fenwick / BinaryIndexed Tree USE IT - FenwickTree ft1=new FenwickTree(n);
public static class FenwickTree
{
int farr[];
int n;
public FenwickTree(int c)
{
n=c+1;
farr=new int[n];
}
// public void update_range(int l,int r,long p)
// {
// update(l,p);
// update(r+1,(-1)*p);
// }
public void update(int x,int p)
{
for(;x<n;x+=x&(-x))
{
farr[x]+=p;
}
}
public long get(int x)
{
long ans=0;
for(;x>0;x-=x&(-x))
{
ans=ans+farr[x];
}
return ans;
}
}
//Disjoint Set Union
public static class DSU
{
int par[],rank[];
public DSU(int c)
{
par=new int[c+1];
rank=new int[c+1];
for(int i=0;i<=c;i++)
{
par[i]=i;
rank[i]=0;
}
}
public int find(int a)
{
if(a==par[a])
return a;
return par[a]=find(par[a]);
}
public void union(int a,int b)
{
int a_rep=find(a),b_rep=find(b);
if(a_rep==b_rep)
return;
if(rank[a_rep]<rank[b_rep])
par[a_rep]=b_rep;
else if(rank[a_rep]>rank[b_rep])
par[b_rep]=a_rep;
else
{
par[b_rep]=a_rep;
rank[a_rep]++;
}
}
}
public static class myComp1 implements Comparator<pair1>
{
//sort in ascending order.
public int compare(pair1 p1,pair1 p2)
{
if(p1.a==p2.a)
return 0;
else if(p1.a<p2.a)
return -1;
else
return 1;
}
//sort in descending order.
// public int compare(pair p1,pair p2)
// {
// if(p1.a==p2.a)
// return 0;
// else if(p1.a<p2.a)
// return 1;
// else
// return -1;
// }
}
public static class pair1
{
long a;
long b;
public pair1(long val,long index)
{
a=val;
b=index;
}
}
public static ArrayList<pair1> mergeIntervals(ArrayList<pair1> arr)
{
//****************use this in main function-Collections.sort(arr,new myComp1());
ArrayList<pair1> a1=new ArrayList<>();
if(arr.size()<=1)
return arr;
a1.add(arr.get(0));
int i=1,j=0;
while(i<arr.size())
{
if(a1.get(j).b<arr.get(i).a)
{
a1.add(arr.get(i));
i++;
j++;
}
else if(a1.get(j).b>arr.get(i).a && a1.get(j).b>=arr.get(i).b)
{
i++;
}
else if(a1.get(j).b>=arr.get(i).a)
{
long a=a1.get(j).a;
long b=arr.get(i).b;
a1.remove(j);
a1.add(new pair1(a,b));
i++;
}
}
return a1;
}
public static ArrayList<Long> primeFact(long a)
{
ArrayList<Long> arr=new ArrayList<>();
while(a%2==0){
arr.add(2L);
a=a/2;
}
for(long i=3;i*i<=a;i+=2){
while(a%i==0){
arr.add(i);
a=a/i;
}
}
if(a>2)arr.add(a);
return arr;
}
public static boolean isInteger(double N)
{
int X = (int)N;
double temp2 = N - X;
if (temp2 > 0)
{
return false;
}
return true;
}
public static boolean isPalindrome(String s,int n)
{
for(int i=0;i<=n/2;i++){
if(s.charAt(i)!=s.charAt(n-i-1)){
return false;
}
}
return true;
}
public static int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
public static long gcd(long a,long b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
public static long fact(long n)
{
long fact=1;
for(long i=2;i<=n;i++){
fact=((fact%mod)*(i%mod))%mod;
}
return fact;
}
public static long fact(int n)
{
long fact=1;
for(int i=2;i<=n;i++){
fact=((fact%mod)*(i%mod))%mod;
}
return fact;
}
public static boolean isPrime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean isPrime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static void printArray(long a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(int a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(char a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]);
}
out.println();
}
public static void printArray(String a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(boolean a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(pair a[])
{
for(pair p:a){
out.println(p.a+"->"+p.b);
}
}
public static void printArray(int a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(long a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(char a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArrayL(ArrayList<Long> arr)
{
for(int i=0;i<arr.size();i++){
out.print(arr.get(i)+" ");
}
out.println();
}
public static void printArrayI(ArrayList<Integer> arr)
{
for(int i=0;i<arr.size();i++){
out.print(arr.get(i)+" ");
}
out.println();
}
public static void printArrayS(ArrayList<String> arr)
{
for(int i=0;i<arr.size();i++){
out.print(arr.get(i)+" ");
}
out.println();
}
public static void printMapInt(HashMap<Integer,Integer> hm){
for(Map.Entry<Integer,Integer> e:hm.entrySet()){
out.println(e.getKey()+"->"+e.getValue());
}out.println();
}
public static void printMapLong(HashMap<Long,Long> hm){
for(Map.Entry<Long,Long> e:hm.entrySet()){
out.println(e.getKey()+"->"+e.getValue());
}out.println();
}
//Modular Arithmetic
public static long add(long a,long b)
{
a+=b;
if(a>=mod)a-=mod;
return a;
}
public static long sub(long a,long b)
{
a-=b;
if(a<0)a+=mod;
return a;
}
public static long mul(long a,long b)
{
return ((a%mod)*(b%mod))%mod;
}
public static long divide(long a,long b,long m)
{
a=mul(a,modInverse(b,m));
return a;
}
public static long modInverse(long a,long m)
{
int x=0,y=0;
own p=new own(x,y);
long g=gcdExt(a,m,p);
if(g!=1){
out.println("inverse does not exists");
return -1;
}else{
long res=((p.a%m)+m)%m;
return res;
}
}
public static long gcdExt(long a,long b,own p)
{
if(b==0){
p.a=1;
p.b=0;
return a;
}
int x1=0,y1=0;
own p1=new own(x1,y1);
long gcd=gcdExt(b,a%b,p1);
p.b=p1.a - (a/b) * p1.b;
p.a=p1.b;
return gcd;
}
public static long pwr(long m,long n)
{
long res=1;
if(m==0)
return 0;
while(n>0)
{
if((n&1)!=0)
{
res=(res*m);
}
n=n>>1;
m=(m*m);
}
return res;
}
public static long modpwr(long m,long n)
{
long res=1;
m=m%mod;
if(m==0)
return 0;
while(n>0)
{
if((n&1)!=0)
{
res=(res*m)%mod;
}
n=n>>1;
m=(m*m)%mod;
}
return res;
}
public static class own
{
long a;
long b;
public own(long val,long index)
{
a=val;
b=index;
}
}
//Modular Airthmetic
public static void sort(int[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
public static void sort(char[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
char tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
public static void sort(long[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
public static int I(){return sc.I();}
public static long L(){return sc.L();}
public static String S(){return sc.S();}
public static double D(){return sc.D();}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int I(){
return Integer.parseInt(next());
}
long L(){
return Long.parseLong(next());
}
double D(){
return Double.parseDouble(next());
}
String S(){
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
| Java | ["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 | 5b72ba68d29299d982eb95c2c16698fb | 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 fastTemp {
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();
int x=0;
int y=0;
int lx = 0;
int ly=0;
int hy=0;
int hx=0;
int r=1;
int col=1;
char[] c = s.toCharArray();
for(int i=0;i<c.length;i++){
if(c[i]=='L') x--;
else if(c[i]=='R') x++;
else if(c[i]=='U') y--;
else y++;
lx = Math.min(lx,x);
hx = Math.max(hx,x);
ly = Math.min(ly,y);
hy = Math.max(hy,y);
if(hx-lx < m && hy-ly < n){
r = 1-lx;
col = 1-ly;
}
}
out.println(col+" "+r);
}
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 | 4ca4c16a5bf155f8b83ccefeadb0caff | 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 | // Problem: E. Robot on the Board 1
// Contest: Codeforces - Codeforces Round #753 (Div. 3)
// URL: https://codeforces.com/contest/1607/problem/E
// Memory Limit: 256 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
import java.io.*;
import java.util.*;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
public class Main {
private void preparation() {
}
private void clear() {
}
private void solve() throws Exception {
rf();
int n = ri();
int m = ri();
rf();
char [] c = rs2c();
int an = 1, am = 1;
int ml = 0, mr = 0, md = 0, mu = 0;
int x = 0, y = 0;
for(int i = 0; i < c.length; i++){
switch(c[i]){
case 'L': x -= 1;break;
case 'R': x += 1;break;
case 'D': y += 1;break;
case 'U': y -= 1;break;
}
if(x < 0){
ml = max(ml, abs(x));
}else{
mr = max(mr, x);
}
if(y < 0){
mu = max(mu, abs(y));
}else{
md = max(md, y);
}
if(mu + md < n && ml + mr < m){
an = mu + 1;
am = ml + 1;
}else{
break;
}
}
addAns(an + " " + am);
}
private void run() throws Exception {
int T = 1;
rf();
T = ri();
preparation();
while (T-- > 0) {
solve();
if (T != 0) {
clear();
}
}
printAns();
}
public static void main(String[] args) throws Exception {
new Main().run();
}
StringBuilder sb = new StringBuilder();
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer strT;
private void addAns(int a){
sb.append(a + "\n");
}
private void addAns(long a){
sb.append(a + "\n");
}
private void addAns(String s){
sb.append(s + "\n");
}
private void rf() throws IOException {
strT = new StringTokenizer(infile.readLine());
}
private int ri() {
return Integer.parseInt(strT.nextToken());
}
private long rl() {
return Long.parseLong(strT.nextToken());
}
private char [] rs2c(){
return strT.nextToken().toCharArray();
}
private String rs(){
return strT.nextToken();
}
private void printAns() {
System.out.println(sb);
}
private int[] readArr(int N) throws Exception {
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(strT.nextToken());
}
return arr;
}
private long[] readArr2(int N) throws Exception {
long[] arr = new long[N];
for (int i = 0; i < N; i++) {
arr[i] = Long.parseLong(strT.nextToken());
}
return arr;
}
private void print(String format, Object ... args){
System.out.println(String.format(format,args));
}
private void print(int[] arr, int x) {
//for debugging only
for (int i = 0;i < min(arr.length, x); i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
private void print(long[] arr, int x) {
//for debugging only
for (int i = 0;i < min(arr.length, x); i++) {
System.out.print(arr[i] + " ");
}
System.out.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 | bda41501a994064e6dbd7e51fd3c890e | 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 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 E_Robot_on_the_Board_1{
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){
long n=s.nextLong();
long m=s.nextLong();
String str=s.nextToken();
long maxy=n;//less karo
long maxh=m;
long l1=0;
long l2=0;
long u1=0;
long u2=0;
long currl=0;
long curru=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)=='R'){
currl++;
long o2=Math.max(l2,currl);
if(o2-l1>=maxh){
break;
}
else{
l2=o2;
}
}
else if(str.charAt(i)=='L'){
currl--;
long o2=Math.min(l1,currl);
if(l2-o2>=maxh){
break;
}
else{
l1=o2;
}
}
else if(str.charAt(i)=='U'){
curru++;
long o2=Math.max(u2,curru);
if(o2-u1>=maxy){
break;
}
else{
u2=o2;
}
}
else{
curru--;
long o2=Math.min(u1,curru);
if(u2-o2>=maxy){
break;
}
else{
u1=o2;
}
}
}
long col=m-l2;
long row=1+u2;
res.append(row+" "+col+" \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());
}
}
} | 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 | d8ebe09c0f0fe2a57dc8ff93141334d5 | 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 IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
String s = sc.nextLine();
int v = 0;
int h = 0;
int maxL = 0;
int maxR = 0;
int maxU = 0;
int maxD = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'L') {
h--;
if(h<=0) {
maxL = Math.max(maxL, Math.abs(h));
if(maxL+maxR+1>m) {
maxL--;
break;
}
}
}
if (s.charAt(i) == 'R') {
h++;
if(h>=0) {
maxR = Math.max(maxR, Math.abs(h));
if(maxL+maxR+1>m) {
maxR--;
break;
}
}
}
if (s.charAt(i) == 'U') {
v++;
if(v>=0) {
maxU = Math.max(maxU, v);
if(maxU+maxD+1>n) {
maxU--;
break;
}
}
}
if (s.charAt(i) == 'D') {
v--;
if(v<=0) {
maxD = Math.max(maxD, -v);
if(maxU+maxD+1>n) {
maxD--;
break;
}
}
}
}
pw.println((maxU+1)+" "+(maxL+1));
}
pw.flush();
}
}
class FenwickTree { // one-based DS
int n;
int[] ft;
FenwickTree(int size) {
n = size;
ft = new int[n + 1];
}
int rsq(int b) // O(log n)
{
int sum = 0;
while (b > 0) {
sum += ft[b];
b -= b & -b;
} // min?
return sum;
}
int rsq(int a, int b) {
return rsq(b) - rsq(a - 1);
}
void point_update(int k, int val) // O(log n), update = increment
{
while (k <= n) {
ft[k] += val;
k += k & -k;
} // min?
}
int point_query(int idx) // c * O(log n), c < 1
{
int sum = ft[idx];
if (idx > 0) {
int z = idx ^ (idx & -idx);
--idx;
while (idx != z) {
sum -= ft[idx];
idx ^= idx & -idx;
}
}
return sum;
}
void scale(int c) {
for (int i = 1; i <= n; ++i)
ft[i] *= c;
}
int findIndex(int cumFreq) {
int msk = n;
while ((msk & (msk - 1)) != 0)
msk ^= msk & -msk; // msk will contain the MSB of n
int idx = 0;
while (msk != 0) {
int tIdx = idx + msk;
if (tIdx <= n && cumFreq >= ft[tIdx]) {
idx = tIdx;
cumFreq -= ft[tIdx];
}
msk >>= 1;
}
if (cumFreq != 0)
return -1;
return idx;
}
}
class edge implements Comparable<edge> {
int from;
int dest;
long cost;
public edge(int from, int dest, long cost) {
this.from = from;
this.dest = dest;
this.cost = cost;
}
public String toString() {
return from + " " + dest + " " + cost;
}
@Override
public int compareTo(edge o) {
// return cost - o.cost;
if (cost < o.cost)
return -1;
if (cost > o.cost)
return 1;
return 0;
}
}
class pair {
int a;
int b;
public pair(int a, int b) {
this.a = a;
this.b = b;
}
}
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 int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
} | Java | ["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 | 06af0df1a04d23a63cce0541a67e2feb | 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.IOException;
import java.io.InputStream;
import java.io.PrintWriter; // System.out is a PrintStream
import java.util.InputMismatchException;
public class E {
private static int MOD = (int)1e9 + 7, mod = 99_82_44_353;
private static double PI = 3.14159265358979323846;
public static void main(String[] args) throws IOException {
FasterScanner scn = new FasterScanner();
PrintWriter out = new PrintWriter(System.out);
loop:
for (int tc = scn.nextInt(); tc > 0; tc--) {
int N = scn.nextInt(), M = scn.nextInt();
char[] str = scn.next().toCharArray();
int sz = str.length;
int[][] pos = new int[sz][];
pos[0] = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }; // U R D L, mnR mnC mxR mxC
command(pos[0], str[0]);
for (int i = 1; i < sz; i++) {
pos[i] = pos[i - 1].clone();
command(pos[i], str[i]);
}
int[] prev = { 1, 1 };
for (int i = 0; i < sz; i++) {
// System.out.print(pos[i][0] + " U ");
// System.out.print(pos[i][1] + " R ");
// System.out.print(pos[i][2] + " D ");
// System.out.print(pos[i][3] + " L | ");
// System.out.print(pos[i][4] + " mnR");
// System.out.print(pos[i][5] + " mnC");
// System.out.print(pos[i][6] + " mxR");
// System.out.print(pos[i][7] + " mxC");
int r = -Math.min(0, pos[i][4]), c = -Math.min(0, pos[i][5]);
if (N - r - 1 < pos[i][6] || M - c - 1 < pos[i][7]) {
out.println(prev[0] + " " + prev[1]);
continue loop;
}
prev = new int[] { r + 1, c + 1 };
// System.out.println();
}
out.println(prev[0] + " " + prev[1]);
}
out.close();
}
private static void command(int[] arr, char c) {
if (c == 'U') {
arr[0]++;
} else if (c == 'R') {
arr[1]++;
} else if (c == 'D') {
arr[2]++;
} else {
arr[3]++;
}
arr[4] = Math.min(arr[4], arr[2] - arr[0]);
arr[5] = Math.min(arr[5], arr[1] - arr[3]);
arr[6] = Math.max(arr[6], arr[2] - arr[0]);
arr[7] = Math.max(arr[7], arr[1] - arr[3]);
}
/* ------------------- Sorting ------------------- */
private static void ruffleSort(int[] arr) {
// int N = arr.length;
// Random rand = new Random();
// for (int i = 0; i < N; i++) {
// int oi = rand.nextInt(N), temp = arr[i];
// arr[i] = arr[oi];
// arr[oi] = temp;
// }
// Arrays.sort(arr);
}
/* ------------------- Sorting ------------------- */
private static boolean isPalindrome(String str) {
for (int i = 0, j = str.length() - 1; i < j; i++, j--) {
if (str.charAt(i) != str.charAt(j)) {
return false;
}
}
return true;
}
private static boolean isPalindrome(char[] str) {
for (int i = 0, j = str.length - 1; i < j; i++, j--) {
if (str[i] != str[j]) {
return false;
}
}
return true;
}
/* ------------------- Pair class ------------------- */
private static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
return this.x == o.x ? this.y - o.y : this.x - o.x;
}
}
/* ------------------- HCF and LCM ------------------- */
private static int gcd(int num1, int num2) {
int temp = 0;
while (num2 != 0) {
temp = num1;
num1 = num2;
num2 = temp % num2;
}
return num1;
}
private static int lcm(int num1, int num2) {
return (int)((1L * num1 * num2) / gcd(num1, num2));
}
/* ------------------- primes and prime factorization ------------------- */
private static boolean[] seive(int N) {
// true means not prime, false means is a prime number :)
boolean[] notPrimes = new boolean[N + 1];
notPrimes[0] = notPrimes[1] = true;
for (int i = 2; i * i <= N; i++) {
if (notPrimes[i]) continue;
for (int j = i * i; j <= N; j += i) {
notPrimes[j] = true;
}
}
return notPrimes;
}
/*
private static TreeMap<Integer, Integer> primeFactors(long N) {
TreeMap<Integer, Integer> primeFact = new TreeMap<>();
for (int i = 2; i <= Math.sqrt(N); i++) {
int count = 0;
while (N % i == 0) {
N /= i;
count++;
}
if (count != 0) {
primeFact.put(i, count);
}
}
if (N != 1) {
primeFact.put((int)N, 1);
}
return primeFact;
}
*/
/* ------------------- Binary Search ------------------- */
private static long factorial(int N) {
long ans = 1L;
for (int i = 2; i <= N; i++) {
ans *= i;
}
return ans;
}
private static long[] factorialDP(int N) {
long[] factDP = new long[N + 1];
factDP[0] = factDP[1] = 1;
for (int i = 2; i <= N; i++) {
factDP[i] = factDP[i - 1] * i;
}
return factDP;
}
private static long factorialMod(int N, int mod) {
long ans = 1L;
for (int i = 2; i <= N; i++) {
ans = ((ans % mod) * (i % mod)) % mod;
}
return ans;
}
/* ------------------- Binary Search ------------------- */
private static int floorSearch(int[] arr, int st, int ed, int tar) {
int ans = -1;
while (st <= ed) {
int mid = ((ed - st) >> 1) + st;
if (arr[mid] <= tar) {
ans = mid;
st = mid + 1;
} else {
ed = mid - 1;
}
}
return ans;
}
private static int ceilingSearch(int[] arr, int st, int ed, int tar) {
int ans = -1;
while (st <= ed) {
int mid = ((ed - st) >> 1) + st;
if (arr[mid] < tar) {
st = mid + 1;
} else {
ans = mid;
ed = mid - 1;
}
}
return ans;
}
/* ------------------- Power Function ------------------- */
public static long pow(long x, long y) {
long res = 1;
while (y > 0) {
if ((y & 1) != 0) {
res = (res * x);
y--;
}
x = (x * x);
y >>= 1;
}
return res;
}
public static long powMod(long x, long y, int mod) {
long res = 1;
while (y > 0) {
if ((y & 1) != 0) {
res = (res * x) % mod;
y--;
}
x = (x * x) % mod;
y >>= 1;
}
return res % mod;
}
/* ------------------- Disjoint Set(Union and Find) ------------------- */
private static class DSU {
public int[] parent, rank;
DSU(int N) {
parent = new int[N];
rank = new int[N];
for (int i = 0; i < N; i++) {
parent[i] = i;
rank[i] = 1;
}
}
public int find(int a) {
if (parent[a] == a) {
return a;
}
return parent[a] = find(parent[a]);
}
public boolean union(int a, int b) {
int parA = find(a), parB = find(b);
if (parA == parB) return false;
if (rank[parA] > rank[parB]) {
parent[parB] = parA;
} else if (rank[parA] < rank[parB]) {
parent[parA] = parB;
} else {
parent[parA] = parB;
rank[parB]++;
}
return true;
}
}
/* ------------------- Scanner class for input ------------------- */
private static class FasterScanner {
private InputStream stream;
private byte[] buffer = new byte[1024];
private int curChar, numChars;
private SpaceCharFilter filter;
public FasterScanner() {
// default
this.stream = System.in;
}
public FasterScanner(InputStream stream) {
this.stream = stream;
}
private int readChar() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buffer);
} catch (IOException e) {
throw new InputMismatchException(e.getMessage());
}
if (numChars <= 0) {
return -1;
}
}
return buffer[curChar++];
}
private boolean isWhiteSpace(int c) {
if (filter != null) {
return filter.isWhiteSpace(c);
}
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isNewLine(int ch) {
if (filter != null) {
return filter.isNewLine(ch);
}
return ch == '\r' || ch == '\n' || ch == -1;
}
public char nextChar() {
int ch = readChar();
char res = '\0';
while (isWhiteSpace(ch)) {
ch = readChar();
}
do {
res = (char)ch;
ch = readChar();
} while (!isWhiteSpace(ch));
return res;
}
public String next() {
int ch = readChar();
StringBuilder res = new StringBuilder();
while (isWhiteSpace(ch)) {
ch = readChar();
}
do {
res.appendCodePoint(ch);
ch = readChar();
} while (!isWhiteSpace(ch));
return res.toString();
}
public String nextLine() {
int ch = readChar();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(ch);
ch = readChar();
} while (!isNewLine(ch));
return res.toString();
}
public int nextInt() {
int ch = -1, sgn = 1, res = 0;
do {
ch = readChar();
} while (isWhiteSpace(ch));
if (ch == '-') {
sgn = -1;
ch = readChar();
}
do {
if (ch < '0' || ch > '9') {
throw new InputMismatchException("not a number");
}
res = (res * 10) + (ch - '0');
ch = readChar();
} while (!isWhiteSpace(ch));
return res * sgn;
}
public long nextLong() {
int ch = -1, sgn = 1;
long res = 0L;
do {
ch = readChar();
} while (isWhiteSpace(ch));
if (ch == '-') {
sgn = -1;
ch = readChar();
}
do {
if (ch < '0' || ch > '9') {
throw new InputMismatchException("not a number");
}
res = (10L * res) + (ch - '0');
ch = readChar();
} while (!isWhiteSpace(ch));
return 1L * res * sgn;
}
public double nextDouble() {
return Double.parseDouble(next());
}
/* for custom delimiters */
public interface SpaceCharFilter {
public boolean isWhiteSpace(int ch);
public boolean isNewLine(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 | cc4eadc987da01e1966922f993a995fb | 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) {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int T = fs.nextInt();
while (T > 0) {
int height = fs.nextInt();
int width = fs.nextInt();
String direction = fs.next();
int maxL = 0, maxR = 0, maxD = 0, maxU = 0, posX = 0, posY = 0;
int lastMove = 0; boolean broken = false;
for (int i = 0; i < direction.length(); i++) {
lastMove = i;
if (direction.charAt(i) == 'L') posX--;
else if (direction.charAt(i) == 'R') posX++;
else if (direction.charAt(i) == 'D') posY++;
else if (direction.charAt(i) == 'U') posY--;
if (posX > maxR) maxR = posX;
else if (posX < maxL) maxL = posX;
else if (posY > maxD) maxD = posY;
else if (posY < maxU) maxU = posY;
if (maxR - maxL >= width) {
broken = true;
break;
}
else if (maxD - maxU >= height) {
broken = true;
break;
}
}
if (broken) {
if (direction.charAt(lastMove) == 'L') maxL++;
else if (direction.charAt(lastMove) == 'U') maxU++;
}
posX = (-maxL + 1);
posY = (-maxU + 1);
out.println(posY + " " + posX);
T--;
}
out.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) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
}
} | 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 | 2a8d4bb640003af1c3077fe96d6e333e | 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.*;
// Link - https://codeforces.com/contest/1607/problem/E
public class RobotOnBoard {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int n, m;
String seq;
List<List<Integer>> result = new ArrayList<>();
for (int testCase = 0; testCase < T; testCase++) {
n = sc.nextInt();
m = sc.nextInt();
seq = sc.next();
int rowSpan = 0, columnSpan = 0;
int rowInitial = 0, columnInitial = 0;
int rowTop = 0, rowBottom = 0, colLeft = 0, colRight = 0;
List<Integer> sol = new ArrayList<>();
for (char command : seq.toCharArray()) {
switch (command) {
case 'U': {
rowSpan -= 1;
break;
}
case 'D': {
rowSpan += 1;
break;
}
case 'R': {
columnSpan += 1;
break;
}
case 'L': {
columnSpan -= 1;
break;
}
}
if(rowTop > rowSpan){
rowTop = rowSpan;
}
if(rowBottom < rowSpan) {
rowBottom = rowSpan;
}
if(colRight < columnSpan) {
colRight = columnSpan;
}
if(colLeft > columnSpan) {
colLeft = columnSpan;
}
if(colRight - colLeft > m-1 || rowBottom - rowTop > n-1) {
break;
}
rowInitial = rowInitial + rowSpan < 0 ? rowInitial+1 : rowInitial;
columnInitial = columnInitial + columnSpan < 0 ? columnInitial+1 : columnInitial;
}
sol.add(rowInitial+1);
sol.add(columnInitial+1);
result.add(sol);
}
result.forEach(res -> System.out.println(res.get(0)+" "+res.get(1)));
sc.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 11 | 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 | 0d58a8a783115a466be2501c67f78969 | 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 CodeForces{
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void main(String[] args) throws IOException{
openIO();
int testCase = 1;
testCase = sc.nextInt();
preCompute();
for (int i = 1; i <= testCase; i++) solve(i);
closeIO();
}
public static void solve(int tCase)throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
char[] str = sc.next().toCharArray();
Deque<Character> lr = new ArrayDeque<>();
Deque<Character> ud = new ArrayDeque<>();
int l = 1,r = m,u=1,d=n;
for(char c : str){
if(c=='U'){
if(!ud.isEmpty() && ud.peek() == 'D')ud.pop();
else ud.push('U');
}
if(c=='D'){
if(!ud.isEmpty() && ud.peek() == 'U')ud.pop();
else ud.push('D');
}
if(c=='L'){
if(!lr.isEmpty() && lr.peek() == 'R')lr.pop();
else lr.push('L');
}
if(c=='R'){
if(!lr.isEmpty() && lr.peek() == 'L')lr.pop();
else lr.push('R');
}
int nL = l;
if(!lr.isEmpty() && lr.peek() == 'L')nL = Math.max(nL,lr.size()+1);
int nR = r;
if(!lr.isEmpty() && lr.peek() == 'R')nR = Math.min(nR,m - lr.size());
int nU = u;
if(!ud.isEmpty() && ud.peek() == 'U')nU = Math.max(nU,ud.size()+1);
int nD = d;
if(!ud.isEmpty() && ud.peek() == 'D')nD = Math.min(nD,n - ud.size());
if(nL > nR || nU > nD)break;
l = nL;
r = nR;
d = nD;
u = nU;
}
out.println(d+" "+r);
}
private static void preCompute(){
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException{
sc = new FastestReader();
out = new PrintWriter(System.out);
}
/*------------------------------------------HELPER FUNCTION STARTS HERE------------------------------------------*/
public static final int mod = (int) 1e9 +7;
private static final int mod2 = 998244353;
public static final int inf_int = (int) 2e9;
public static final long inf_long = (long) 4e18;
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
if (a == 0)
return b;
return _gcd(b % a, a);
}
public static long _lcm(long a, long b) {
// lcm(a,b) * gcd(a,b) = a * b
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _power(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
//sieve/first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
firstDivisor[j] = i;
return firstDivisor;
}
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
public static void _sort(int[] arr,boolean isAscending){
int n = arr.length;
List<Integer> list = new ArrayList<>();
for(int ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
public static void _sort(long[] arr,boolean isAscending){
int n = arr.length;
List<Long> list = new ArrayList<>();
for(long ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
/*------------------------------------------HELPER FUNCTION ENDS HERE-------------------------------------------*/
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
public static void closeIO() throws IOException{
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) { return -ret; }
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) { buffer[0] = -1; }
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) { fillBuffer(); }
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
} | Java | ["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 11 | 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 | a979830d50d76ee868bab39720634d10 | 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 CodeForces{
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void main(String[] args) throws IOException{
openIO();
int testCase = 1;
testCase = sc.nextInt();
preCompute();
for (int i = 1; i <= testCase; i++) solve(i);
closeIO();
}
public static void solve(int tCase)throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
char[] str = sc.next().toCharArray();
Deque<Character> lr = new ArrayDeque<>();
Deque<Character> ud = new ArrayDeque<>();
int l = 1,r = m,u=1,d=n;
for(char c : str){
if(c=='U'){
if(!ud.isEmpty() && ud.peek() == 'D')ud.pop();
else ud.push('U');
}
if(c=='D'){
if(!ud.isEmpty() && ud.peek() == 'U')ud.pop();
else ud.push('D');
}
if(c=='L'){
if(!lr.isEmpty() && lr.peek() == 'R')lr.pop();
else lr.push('L');
}
if(c=='R'){
if(!lr.isEmpty() && lr.peek() == 'L')lr.pop();
else lr.push('R');
}
int nL = l;
if(!lr.isEmpty() && lr.peek() == 'L')nL = Math.max(nL,lr.size()+1);
int nR = r;
if(!lr.isEmpty() && lr.peek() == 'R')nR = Math.min(nR,m - lr.size());
int nU = u;
if(!ud.isEmpty() && ud.peek() == 'U')nU = Math.max(nU,ud.size()+1);
int nD = d;
if(!ud.isEmpty() && ud.peek() == 'D')nD = Math.min(nD,n - ud.size());
if(nL > nR || nU > nD)break;
l = nL;
r = nR;
d = nD;
u = nU;
}
out.println(u+" "+l);
}
private static void preCompute(){
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException{
sc = new FastestReader();
out = new PrintWriter(System.out);
}
/*------------------------------------------HELPER FUNCTION STARTS HERE------------------------------------------*/
public static final int mod = (int) 1e9 +7;
private static final int mod2 = 998244353;
public static final int inf_int = (int) 2e9;
public static final long inf_long = (long) 4e18;
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
if (a == 0)
return b;
return _gcd(b % a, a);
}
public static long _lcm(long a, long b) {
// lcm(a,b) * gcd(a,b) = a * b
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _power(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
//sieve/first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
firstDivisor[j] = i;
return firstDivisor;
}
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
public static void _sort(int[] arr,boolean isAscending){
int n = arr.length;
List<Integer> list = new ArrayList<>();
for(int ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
public static void _sort(long[] arr,boolean isAscending){
int n = arr.length;
List<Long> list = new ArrayList<>();
for(long ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
/*------------------------------------------HELPER FUNCTION ENDS HERE-------------------------------------------*/
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
public static void closeIO() throws IOException{
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) { return -ret; }
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') { c = read(); }
final boolean neg = c == '-';
if (neg) { c = read(); }
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) { return -ret; }
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) { buffer[0] = -1; }
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) { fillBuffer(); }
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
} | Java | ["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 11 | 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 | cd999722c321ba2c5c7b9830221e9861 | 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 Main {
static int mod=1000000007;
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();
char[] ch = sc.next().toCharArray();
int row = 0, col = 0;
int rowmin = 0, rowmax= 0, colmin = 0, colmax= 0;
for(char e : ch) {
if (e == 'L') {
colmin = Math.min(colmin, --col);
}else if(e=='R') {
colmax = Math.max(colmax, ++col);
}else if (e =='U') {
rowmin = Math.min(rowmin, --row);
}else {
rowmax = Math.max(rowmax, ++row);
}
if (rowmax - rowmin >= n ) {
if(row == rowmin)
rowmin++;
break;
}
if (colmax - colmin >= m ) {
if(col == colmin)
colmin++;
break;
}
}
System.out.println((1 - rowmin) + " " + (1 - colmin));
}
}
} | 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 11 | 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 | b56ee112819e8e77433e0f27ec29ffa1 | 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.*;
/**
__ __
( _) ( _)
/ / \\ / /\_\_
/ / \\ / / | \ \
/ / \\ / / |\ \ \
/ / , \ , / / /| \ \
/ / |\_ /| / / / \ \_\
/ / |\/ _ '_| \ / / / \ \\
| / |/ 0 \0\ / | | \ \\
| |\| \_\_ / / | \ \\
| | |/ \.\ o\o) / \ | \\
\ | /\\`v-v / | | \\
| \/ /_| \\_| / | | \ \\
| | /__/_ `-` / _____ | | \ \\
\| [__] \_/ |_________ \ | \ ()
/ [___] ( \ \ |\ | | //
| [___] |\| \| / |/
/| [____] \ |/\ / / ||
( \ [____ / ) _\ \ \ \| | ||
\ \ [_____| / / __/ \ / / //
| \ [_____/ / / \ | \/ //
| / '----| /=\____ _/ | / //
__ / / | / ___/ _/\ \ | ||
(/-(/-\) / \ (/\/\)/ | / | /
(/\/\) / / //
_________/ / /
\____________/ (
*/
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-- >0) {
int n=sc.nextInt();
int m=sc.nextInt();
String str=sc.next();
int dx=0;
int dy=0;
int mindx=0;
int maxdx=0;
int mindy=0;
int maxdy=0;
int ansx=1;
int ansy=1;
for(int i=0;i<str.length();i++) {
char ch=str.charAt(i);
if(ch=='L') {
dy=dy-1;
}
if(ch=='R') {
dy=dy+1;
}
if(ch=='U') {
dx=dx-1;
}
if(ch=='D'){
dx=dx+1;
}
mindx=Math.min(mindx, dx);
maxdx=Math.max(maxdx, dx);
mindy=Math.min(mindy, dy);
maxdy=Math.max(maxdy, dy);
int x=n-maxdx;
int y=m-maxdy;
if(x+mindx>=1 && y+mindy>=1 && x<=n && y<=m) {
ansx=x;
ansy=y;
}
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 11 | 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 | 533c09e2ab947ebf1755a699e23a390d | 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.*;
import static java.lang.Math.log;
import static java.lang.Math.min;
public class Main {
//------------------------------------------CONSTANTS---------------------------------------------------------------
public static final int MOD = (int) (1e9 + 7);
//---------------------------------------------I/0------------------------------------------------------------------
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void print(String s) {
System.out.println(s);
}
public static void main(String[] args) {
FastReader sc = new FastReader();
int t = 1;
t = sc.nextInt();
for(int i = 0; i<t; i++) {
System.out.println(solve(sc));
}
}
//------------------------------------------------SOLVE-------------------------------------------------------------
public static String solve(FastReader sc) {
int n = sc.nextInt(); int m = sc.nextInt();
char[] s = sc.next().toCharArray(); int k = s.length;
int l = 1, r = m, u = 1, d = n;
int oH = 0, oV = 0;
boolean broke = false;
for (int i = 0; i<k; i++) {
if (broke) break;
switch (s[i]) {
case 'L':
oH--;
break;
case 'R':
oH++;
break;
case 'U':
oV--;
break;
case 'D':
oV++;
break;
}
if (oH<0) {
while (l+oH<1) {
l++;
if (l > r) {
broke = true;
l--;
break;
}
}
} else if (oH>0) {
while (r+oH>m) {
r--;
if (l > r) {
broke = true;
r++;
break;
}
}
}
if (oV<0) {
while (u+oV<1) {
u++;
if (u > d) {
broke = true;
u--;
break;
}
}
} else if (oV>0) {
while (d+oV>n) {
d--;
if (u > d) {
broke = true;
d++;
break;
}
}
}
}
return u + " " + l;
}
public static int firstNotDivisor(int n, int z) {
for (int i = z; i>=1; i--) {
if (n%i!=0)
return i;
}
return -1;
}
public static int factorial(int n) {
if (n == 0)
return 1;
int fact = 1;
for (int i = 2; i<=n; i++) {
fact *= i;
}
return fact;
}
public static int maxFactorial(int n) {
int k = 1;
int fact = 1;
while ((k+1)*fact < n) {
k++;
fact *= k;
}
return k;
}
public static boolean isPalindrome(String s) {
for (int i = 0; i<s.length()/2; i++) {
if (s.charAt(i) != s.charAt(s.length()-1-i))
return false;
}
return true;
}
//-----------------------------------------------FUNCTIONS----------------------------------------------------------
public static String printArray(int[] a) {
StringBuilder r = new StringBuilder("");
for(int i = 0; i<a.length; i++) {
r.append(a[i] + " ");
}
return r.toString();
}
public static <T> String printList(List<T> a) {
StringBuilder r = new StringBuilder("");
for (T x: a) {
r.append(x.toString() + " ");
}
return r.toString();
}
// first element that is not less than target
public static int lowerBound(int[] arr, int begin, int end, int target) {
while(begin < end) {
int mid = begin + (end - begin) / 2;
// When the element is less than the mid target
if(arr[mid] < target)
// begin to mid + 1, arr [begin] value is less than or equal target
begin = mid + 1;
// When the mid target element when greater than or equal
else if(arr[mid] >= target)
end = mid;
}
return begin;
}
// first element that is greater than target
public static int upperBound(int[] arr, int begin, int end, int target) {
while(begin < end) {
int mid = begin + (end - begin) / 2;
if(arr[mid] <= target)
begin = mid + 1;
else
end = mid;
}
return begin;
}
// generate permutations (call search and access through permutations)
public static class Permutations {
List<List<Integer>> permutations = new ArrayList<>();
List<Integer> permutation = new ArrayList<>();
boolean[] taken;
int[] a;
public Permutations(int[] a) {
this.a = a;
taken = new boolean[a.length];
}
void search() {
if (permutation.size()==a.length) {
permutations.add(new ArrayList<>(permutation));
} else {
for (int i = 0; i<a.length; i++) {
if (taken[i]) {
continue;
}
taken[i] = true;
permutation.add(a[i]);
search();
taken[i] = false;
permutation.remove(permutation.size()-1);
}
}
}
}
// generate subsets (call search and access subsets)
public static class Subsets {
List<List<Integer>> subsets = new ArrayList<>();
List<Integer> subset = new ArrayList<>();
void search(int[] a, int x) {
if (x == a.length) {
subsets.add(new ArrayList<>(subset));
} else {
subset.add(a[x]);
search(a, x+1);
subset.remove(subset.size() - 1);
search(a, x+1);
}
}
}
public static int gcd(int a, int b) {
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
public static int lcm(int a, int b) {
return (a*b)/gcd(a, b);
}
public static int[] prefixSum(int[] a) {
int n = a.length;
int[] ps = new int[n];
ps[0] = a[0];
for (int i = 1; i<n; i++) {
ps[i] = ps[i-1] + a[i];
}
return ps;
}
public static int[][] prefixSum2D(int[][] a) {
int n = a.length;
int m = a[0].length;
int[][] ps = new int[n][m];
ps[0][0] = a[0][0];
for (int j = 1; j<m; j++) {
ps[0][j] = ps[0][j-1] + a[0][j];
}
for (int i = 1; i<n; i++) {
ps[i][0] = ps[i-1][0] + a[i][0];
}
for (int i = 1; i<n; i++) {
for (int j = 1; j<m; j++) {
ps[i][j] = ps[i-1][j] + ps[i][j-1] - ps[i-1][j-1] + a[i][j];
}
}
return ps;
}
public static double log2(double a) {
return log(a)/log(2);
}
//----------------------------------------DATA-STRUCTURES-----------------------------------------------------------
// Range queries (i.e. RMQ) in O(1), others with functions in O(log n)
public static class SparseTable {
int[][] st;
int n;
int k;
public SparseTable(int[] a) {
n = a.length;
k = (int) log2(n);
st = new int[n][k+1];
for (int i = 0; i<n; i++) {
st[i][0] = a[i];
}
// 1<<j == 2^j
for (int j = 1; j<=k; j++) {
for (int i = 0; i + (1 << j) <= n; i++) {
st[i][j] = min(st[i][j-1], st[i + (1 << (j - 1))][j - 1]);
}
}
}
//not always available O(log n) -- change the constructor to use it
public long sumQuery(int l, int r) {
long sum = 0;
for (int j = k; j>=0; j--) {
if ((1 << j) <= r - l + 1) {
sum += st[l][j];
l += 1 << j;
}
}
return sum;
}
//always available O(1) -- change this and the constructor for rangeMaxQuery
public int rangeMinQuery(int l, int r) {
int j = (int) log2(r - l + 1);
int min = min(st[l][j], st[r - (1 << j) + 1][j]);
return min;
}
}
//Range Sum Dynamic Queries O(log n)
public static class BinaryIndexedTree {
int[] bit;
public BinaryIndexedTree(int[] a) {
int n = a.length;
bit = new int[n+1];
// Store the actual values in BITree[]
// using update()
for(int i = 0; i < n; i++)
updateBit(i, a[i]);
}
// O(log n) update delta at index in the array (do it on the array and then call this function)
public void updateBit(int index, int delta) {
index += 1;
while (index <= bit.length) {
bit[index] += delta;
index += index & (-index);
}
}
// Computes sum a[0...index] in O(log n)
public int getSum(int index) {
int sum = 0;
index += 1;
while (index > 0) {
sum += bit[index];
index -= index & (-index);
}
return sum;
}
}
public static class UnionFind {
int[] link;
int[] size;
UnionFind(int n) {
link = new int[n];
size = new int[n];
for (int i = 0; i<n; i++) {
link[i] = i;
size[i] = 1;
}
}
int find(int x) {
while (x != link[x]) x = link[x];
return x;
}
boolean same(int a, int b) {
return find(a) == find(b);
}
void unite(int a, int b) {
a = find(a);
b = find(b);
if (size[a] < size[b]) {
int temp = a;
a = b;
b = temp;
}
size[a] += size[b];
link[b] = a;
}
}
public static class SegmentTree {
int st[];
public SegmentTree(int arr[]) {
int n = arr.length;
int x = (int) (Math.ceil(log2(n)));
int maxSize = 2 * (int) Math.pow(2, x) - 1;
st = new int[maxSize];
build(arr, 0, n-1, 0);
}
int build(int arr[], int ss, int se, int si) {
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
int mid = ss + (se - ss) / 2; //ss+se/2
st[si] = build(arr, ss, mid, si * 2 + 1) +
build(arr, mid + 1, se, si * 2 + 2);
return st[si];
}
private int getSumUtil(int ss, int se, int l, int r, int si) {
if (l <= ss && r >= se) {
return st[si];
}
if (se < l || ss > r) {
return 0;
}
int mid = ss + (se - ss) / 2;
return getSumUtil(ss, mid, l, r, 2 * si + 1) +
getSumUtil(mid + 1, se, l, r, 2 * si + 2);
}
void updateValueUtil(int ss, int se, int i, int diff, int si) {
if (i < ss || i > se) {
return;
}
st[si] = st[si] + diff;
if (se != ss) {
int mid = ss + (se - ss) / 2;
updateValueUtil(ss, mid, i, diff, 2 * si + 1);
updateValueUtil(mid + 1, se, i, diff, 2 * si + 2);
}
}
int getSum(int n, int l, int r) {
if (l < 0 || r > n - 1 || l > r) {
return -1;
}
return getSumUtil(0, n-1, l, r, 0);
}
// don't do it directly on the array but use this function that will
// do everything for you
void updateValue(int arr[], int n, int i, int newValue) {
if (i < 0 || i > n - 1) {
return;
}
int diff = newValue - arr[i];
arr[i] = newValue;
updateValueUtil(0, n - 1, i, diff, 0);
}
}
// Similar to Pair in c++, non-null objects as parameters
public static class Pair<T extends Comparable<T>, Q extends Comparable<Q>> implements Comparable<Pair<T, Q>>{
T a;
Q b;
public Pair(T a, Q b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return a.equals(pair.a) && b.equals(pair.b);
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
@Override
public int compareTo(Pair<T, Q> tqPair) {
int compareA = this.a.compareTo(tqPair.a);
if (compareA == 0) {
return this.b.compareTo(tqPair.b);
} else {
return compareA;
}
}
}
// Uses Map + TreeSet to get the structure
public static class OrderedMultiSet<T extends Comparable<T>> {
private final TreeSet<T> set = new TreeSet<>();
private final Map<T, Integer> frequencies = new HashMap<>();
private int size = 0;
public OrderedMultiSet() {}
public OrderedMultiSet(List<T> a) {
for (T x: a) {
this.add(x);
size++;
}
}
public void add(T element) {
set.add(element);
if (!frequencies.containsKey(element)) {
frequencies.put(element, 0);
}
frequencies.put(element, frequencies.get(element) + 1);
size++;
}
public boolean remove(T element) {
if (frequencies.containsKey(element)) {
int x = frequencies.get(element);
x--;
if (x == 0) {
frequencies.remove(element);
set.remove(element);
} else {
frequencies.put(element, frequencies.get(element) - 1);
}
size--;
return true;
}
return false;
}
public int size() {
return size;
}
public T first() {
return set.first();
}
public T last() {
return set.last();
}
public T pollFirst() {
T t = set.first();
remove(t);
return t;
}
public T pollLast() {
T t = set.last();
set.
remove(t);
return t;
}
}
} | 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 11 | 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 | 4cde7b11e093cf984734d5ef5862d7aa | 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 practise {
static boolean multipleTC = true;
final static int Mod = 1000000007;
final static int Mod2 = 998244353;
final double PI = 3.14159265358979323846;
int MAX = 1000000007;
void pre() throws Exception {
}
long combination(int n, int r, long fact[], long ifact[]) {
long val1 = fact[n];
long val2 = ifact[(n - r)];
long val3 = ifact[r];
return (((val1 * val2) % Mod) * val3) % Mod;
}
long expo(long a, long b, long mod) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1)
res = (res * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return res;
}
long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
long mminvprime(long a, long b) {
return expo(a, b - 2, b);
}
boolean check(long arr[], long x, int n) {
long temp[] = new long[n+1];
for(int i=1;i<=n;i++)
temp[i] = arr[i];
for(int i=n;i>=3;i--) {
if(temp[i] < x)
return false;
long d = Math.min(arr[i], temp[i] - x)/3;
temp[i-1] += d;
temp[i-2] += 2*d;
}
if(temp[1] >= x && temp[2] >= x)
return true;
return false;
}
long checkcol(List<Character> list, long mid, long m) {
long ans = -1;
long curridx = 0, maxleft = 0, maxright = 0;
for(int i=0;i<=mid;i++) {
if(list.get(i) == 'L') {
curridx--;
maxleft = Math.min(maxleft, curridx);
}
else {
curridx++;
maxright = Math.max(maxright, curridx);
}
}
for(int i=1;i<=m;i++) {
if(i+maxleft >= 1 && i+maxright <= m) {
ans = i;
return ans;
}
}
return ans;
}
long checkrow(List<Character> list, long mid, long n) {
long ans = -1;
long curridx = 0, maxup = 0, maxdown = 0;
for(int i=0;i<=mid;i++) {
if(list.get(i) == 'U') {
curridx--;
maxup = Math.min(maxup, curridx);
}
else {
curridx++;
maxdown = Math.max(maxdown, curridx);
}
}
for(int i=1;i<=n;i++) {
if(i+maxup >= 1 && i+maxdown <= n) {
ans = i;
return ans;
}
}
return ans;
}
void solve(int t) throws Exception {
long n = ni();
long m = ni();
char str[] = n().toCharArray();
List<Character> col = new ArrayList<>();
List<Character> row = new ArrayList<>();
List<Integer> colcnt = new ArrayList<>();
List<Integer> rowcnt = new ArrayList<>();
for(int i=0;i<str.length;i++) {
if(str[i] == 'L' || str[i] == 'R')
col.add(str[i]);
else
row.add(str[i]);
}
// Calculating Index for column
long lo = 0, hi = col.size()-1, idx = 1;
while(lo <= hi) {
long mid = lo + (hi-lo)/2;
long ans = checkcol(col, mid, m);
if(ans != -1) {
idx = ans;
lo = mid+1;
}
else {
hi = mid-1;
}
}
// Calculating Index for row
lo = 0; hi = row.size()-1;
long idy = 1;
while(lo <= hi) {
long mid = lo + (hi-lo)/2;
long ans = checkrow(row, mid, n);
if(ans != -1) {
idy = ans;
lo = mid+1;
}
else {
hi = mid-1;
}
}
pn(idy + " " + idx);
}
double dist(int x1, int y1, int x2, int y2) {
double a = x1 - x2, b = y1 - y2;
return Math.sqrt((a * a) + (b * b));
}
long xor_sum_upton(long n) {
if (n % 4 == 0)
return n;
if (n % 4 == 1)
return 1;
if (n % 4 == 2)
return n + 1;
return 0;
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(int arr[], int left, int right) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = left; i <= right; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = left; i <= right; i++)
arr[i] = list.get(i - left);
}
void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
String bin(long n) {
return Long.toBinaryString(n);
}
String bin(int n) {
return Integer.toBinaryString(n);
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
void p(Object o) {
out.print(o);
}
void pn(Object o) {
out.println(o);
}
void pni(Object o) {
out.println(o);
out.flush();
}
void pn(int[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
void pn(long[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
String n() throws Exception {
return in.next();
}
String nln() throws Exception {
return in.nextLine();
}
char c() throws Exception {
return in.next().charAt(0);
}
int ni() throws Exception {
return Integer.parseInt(in.next());
}
long nl() throws Exception {
return Long.parseLong(in.next());
}
double nd() throws Exception {
return Double.parseDouble(in.next());
}
public static void main(String[] args) throws Exception {
new practise().run();
}
FastReader in;
PrintWriter out;
void run() throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++)
solve(t);
out.flush();
out.close();
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
} | Java | ["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 11 | 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 | 08335e1a94bf02274697bedec018419a | 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 codeforce {
static boolean multipleTC = true;
final static int Mod = 1000000007;
final static int Mod2 = 998244353;
final double PI = 3.14159265358979323846;
int MAX = 1000000007;
void pre() throws Exception {
}
long combination(int n, int r, long fact[], long ifact[]) {
long val1 = fact[n];
long val2 = ifact[(n - r)];
long val3 = ifact[r];
return (((val1 * val2) % Mod) * val3) % Mod;
}
long expo(long a, long b, long mod) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1)
res = (res * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return res;
}
long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
long mminvprime(long a, long b) {
return expo(a, b - 2, b);
}
long checkcol(List<Character> list, long m) {
long ans = 1;
long curridx = 0, maxleft = 0, maxright = 0;
for(int i=0;i<list.size();i++) {
if(list.get(i) == 'L') {
curridx--;
maxleft = Math.min(maxleft, curridx);
if(Math.abs(maxleft) >= m || Math.abs(maxright) >= m)
return ans;
long idx = 1 + Math.abs(maxleft);
if(idx + maxright <= m) {
ans = idx;
}
else
return ans;
}
else {
curridx++;
maxright = Math.max(maxright, curridx);
if(Math.abs(maxleft) >= m || Math.abs(maxright) >= m)
return ans;
long idx = m - Math.abs(maxright);
if(idx + maxleft >= 1) {
ans = idx;
}
else
return ans;
}
}
return ans;
}
long checkrow(List<Character> list, long n) {
long ans = 1;
long curridx = 0, maxup = 0, maxdown = 0;
for(int i=0;i<list.size();i++) {
if(list.get(i) == 'U') {
curridx--;
maxup = Math.min(maxup, curridx);
if(Math.abs(maxup) >= n || Math.abs(maxdown) >= n)
return ans;
long idx = 1 + Math.abs(maxup);
if(idx + maxdown <= n) {
ans = idx;
}
else
return ans;
}
else {
curridx++;
maxdown = Math.max(maxdown, curridx);
if(Math.abs(maxup) >= n || Math.abs(maxdown) >= n)
return ans;
long idx = n - Math.abs(maxdown);
if(idx + maxup >= 1) {
ans = idx;
}
else
return ans;
}
}
return ans;
}
void solve(int t) throws Exception {
long n = ni();
long m = ni();
char str[] = n().toCharArray();
List<Character> col = new ArrayList<>();
List<Character> row = new ArrayList<>();
for(int i=0;i<str.length;i++) {
if(str[i] == 'L' || str[i] == 'R')
col.add(str[i]);
else
row.add(str[i]);
}
// Calculating Index for column
long idy = checkcol(col, m);
// Calculating Index for row
long idx = checkrow(row, n);
pn(idx + " " + idy);
}
double dist(int x1, int y1, int x2, int y2) {
double a = x1 - x2, b = y1 - y2;
return Math.sqrt((a * a) + (b * b));
}
long xor_sum_upton(long n) {
if (n % 4 == 0)
return n;
if (n % 4 == 1)
return 1;
if (n % 4 == 2)
return n + 1;
return 0;
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(int arr[], int left, int right) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = left; i <= right; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = left; i <= right; i++)
arr[i] = list.get(i - left);
}
void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
String bin(long n) {
return Long.toBinaryString(n);
}
String bin(int n) {
return Integer.toBinaryString(n);
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
void p(Object o) {
out.print(o);
}
void pn(Object o) {
out.println(o);
}
void pni(Object o) {
out.println(o);
out.flush();
}
void pn(int[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
void pn(long[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
String n() throws Exception {
return in.next();
}
String nln() throws Exception {
return in.nextLine();
}
char c() throws Exception {
return in.next().charAt(0);
}
int ni() throws Exception {
return Integer.parseInt(in.next());
}
long nl() throws Exception {
return Long.parseLong(in.next());
}
double nd() throws Exception {
return Double.parseDouble(in.next());
}
public static void main(String[] args) throws Exception {
new codeforce().run();
}
FastReader in;
PrintWriter out;
void run() throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++)
solve(t);
out.flush();
out.close();
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
} | Java | ["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 11 | 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 | 3a57aa045ba3c8cd8e7a199bbc296cc6 | 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.*;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
*/
public class MS_8_A {
static int[][] turns = new int[500][];
static {
turns['L'] = new int[]{0, -1};
turns['R'] = new int[]{0, 1};
turns['U'] = new int[]{-1, 0};
turns['D'] = new int[]{1, 0};
}
private void solveOne() {
Random random = new Random();
int n = nextInt();
int m = nextInt();
char[] s = nextString().toCharArray();
int commands = s.length;
Robot robot = new Robot(random.nextInt(n) + 1, random.nextInt(m) + 1, n, m);
int p = 0;
while (true) {
//go
robot.moveRobot(s[p++]);
if (!robot.onTheBoard()) {
if (!robot.moveStartPoint()) {
break;
}
}
if (p == commands) {
break;
}
//in(c, n, r, m) && p < commands
}
//𝑟 (1≤𝑟≤𝑛) and 𝑐 (1≤𝑐≤𝑚),
System.out.println(robot.startR + " " + robot.startC);
}
static class Robot {
int startR;
int startC;
int r;
int c;
int n;
int m;
////𝑟 (1≤𝑟≤𝑛) and 𝑐 (1≤𝑐≤𝑚),
Robot(int startR, int startC, int n, int m) {
this.startR = startR;
this.startC = startC;
r = startR;
c = startC;
this.n = n;
this.m = m;
minR = startR;
maxR = startR;
minC = startC;
maxC = startC;
}
int minR;
int maxR;
int minC;
int maxC;
void moveRobot(char move) {
int[] turn = turns[move];
r += turn[0];
c += turn[1];
maxR = Math.max(maxR, r);
minR = Math.min(minR, r);
maxC = Math.max(maxC, c);
minC = Math.min(minC, c);
}
boolean onTheBoard() {
return 1 <= r && r <= n && 1 <= c && c <= m;
}
boolean moveStartPoint() {
int width = maxC + 1 - minC;
if (width > m) {
return false;
}
int height = maxR + 1 - minR;
if (height > n) {
return false;
}
//we have a place
char fixMove = '\0';
//Right
if (c == 0) {
fixMove = 'R';
}
//Down
if (r == 0) {
fixMove = 'D';
}
//Left
if (c == m + 1) {
fixMove = 'L';
}
//Up
if (r == n + 1) {
fixMove = 'U';
}
int[] fixTurn = turns[fixMove];
r += fixTurn[0];
c += fixTurn[1];
startR += fixTurn[0];
startC += fixTurn[1];
maxR += fixTurn[0];
minR += fixTurn[0];
maxC += fixTurn[1];
minC += fixTurn[1];
return true;
}
@Override
public String toString() {
return startR + " " + startC;
}
}
boolean in(int x, int n, int y, int m) {
return 1 <= x && x <= n && 1 <= y && y <= m;
}
private void solve() {
int t = nextInt();
for (int tt = 0; tt < t; tt++) {
solveOne();
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(Object expected,
Object actual, Object... input) {
super("expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new MS_8_A().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
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 FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(int[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(int[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readInt();
}
}
}
public void readLongArrays(long[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readLong();
}
}
}
public void readDoubleArrays(double[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readDouble();
}
}
}
public char[][] readTable(int rowCount, int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readCharArray(columnCount);
}
return table;
}
public int[][] readIntTable(int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readIntArray(columnCount);
}
return table;
}
public double[][] readDoubleTable(int rowCount, int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readDoubleArray(columnCount);
}
return table;
}
public long[][] readLongTable(int rowCount, int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readLongArray(columnCount);
}
return table;
}
public String[][] readStringTable(int rowCount, int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readStringArray(columnCount);
}
return table;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public void readStringArrays(String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readString();
}
}
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
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 peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
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 11 | 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 | 438e4e9e8fd8a3723b3eab366be3add8 | 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.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
*/
public class MS_8_A {
static int[][] turns = new int[500][];
static {
turns['L'] = new int[]{0, -1};
turns['R'] = new int[]{0, 1};
turns['U'] = new int[]{-1, 0};
turns['D'] = new int[]{1, 0};
}
private void solveOne() {
int n = nextInt();
int m = nextInt();
char[] s = nextString().toCharArray();
int commands = s.length;
Robot robot = new Robot(1, 1, n, m);
int p = 0;
while (true) {
//go
robot.moveRobot(s[p++]);
if (!robot.onTheBoard()) {
if (!robot.moveStartPoint()) {
break;
}
}
if (p == commands) {
break;
}
//in(c, n, r, m) && p < commands
}
//𝑟 (1≤𝑟≤𝑛) and 𝑐 (1≤𝑐≤𝑚),
System.out.println(robot.startR + " " + robot.startC);
}
static class Robot {
int startR;
int startC;
int r;
int c;
int n;
int m;
Robot(int startR, int startC, int n, int m) {
this.startR = startR;
this.startC = startC;
r = startR;
c = startC;
this.n = n;
this.m = m;
minR = startR;
maxR = startR;
minC = startC;
maxC = startC;
}
int minR;
int maxR;
int minC;
int maxC;
void moveRobot(char move) {
int[] turn = turns[move];
r += turn[0];
c += turn[1];
maxR = Math.max(maxR, r);
minR = Math.min(minR, r);
maxC = Math.max(maxC, c);
minC = Math.min(minC, c);
}
boolean onTheBoard() {
return 1 <= r && r <= n && 1 <= c && c <= m;
}
boolean moveStartPoint() {
int width = maxC + 1 - minC;
if (width > m) {
return false;
}
int height = maxR + 1 - minR;
if (height > n) {
return false;
}
//we have a place
char fixMove = '\0';
//Right
if (c == 0) {
fixMove = 'R';
}
//Down
if (r == 0) {
fixMove = 'D';
}
//Left
if (c == m + 1) {
fixMove = 'L';
}
//Up
if (r == n + 1) {
fixMove = 'U';
}
int[] fixTurn = turns[fixMove];
r += fixTurn[0];
c += fixTurn[1];
startR += fixTurn[0];
startC += fixTurn[1];
maxR += fixTurn[0];
minR += fixTurn[0];
maxC += fixTurn[1];
minC += fixTurn[1];
return true;
}
@Override
public String toString() {
return startR + " " + startC;
}
}
boolean in(int x, int n, int y, int m) {
return 1 <= x && x <= n && 1 <= y && y <= m;
}
private void solve() {
int t = nextInt();
for (int tt = 0; tt < t; tt++) {
solveOne();
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(Object expected,
Object actual, Object... input) {
super("expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new MS_8_A().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
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 FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(int[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(int[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readInt();
}
}
}
public void readLongArrays(long[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readLong();
}
}
}
public void readDoubleArrays(double[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readDouble();
}
}
}
public char[][] readTable(int rowCount, int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readCharArray(columnCount);
}
return table;
}
public int[][] readIntTable(int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readIntArray(columnCount);
}
return table;
}
public double[][] readDoubleTable(int rowCount, int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readDoubleArray(columnCount);
}
return table;
}
public long[][] readLongTable(int rowCount, int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readLongArray(columnCount);
}
return table;
}
public String[][] readStringTable(int rowCount, int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readStringArray(columnCount);
}
return table;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public void readStringArrays(String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readString();
}
}
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
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 peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
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 11 | 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 | c573e958bc4b4bfe879e687567da504c | 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.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
*/
public class MS_8_A {
static Map<Character, int[]> turns = new HashMap<>() {
{
put('L', new int[]{0, -1});
put('R', new int[]{0, 1});
put('U', new int[]{-1, 0});
put('D', new int[]{1, 0});
}
};
private void solveOne() {
int n = nextInt();
int m = nextInt();
char[] s = nextString().toCharArray();
int commands = s.length;
Robot robot = new Robot(1, 1, n, m);
int p = 0;
while (true) {
//go
robot.moveRobot(s[p++]);
if (!robot.onTheBoard()) {
if (!robot.moveStartPoint()) {
break;
}
}
if (p == commands) {
break;
}
//in(c, n, r, m) && p < commands
}
//𝑟 (1≤𝑟≤𝑛) and 𝑐 (1≤𝑐≤𝑚),
System.out.println(robot.startR + " " + robot.startC);
}
static class Robot {
int startR = 1;
int startC = 1;
int r = startR;
int c = startC;
int n;
int m;
Robot(int startR, int startC, int n, int m) {
this.startR = startR;
this.startC = startC;
this.n = n;
this.m = m;
}
int minC = startC;
int maxC = startC;
int minR = startR;
int maxR = startR;
void moveRobot(char move) {
int[] turn = turns.get(move);
r += turn[0];
c += turn[1];
maxR = Math.max(maxR, r);
minR = Math.min(minR, r);
maxC = Math.max(maxC, c);
minC = Math.min(minC, c);
}
boolean onTheBoard() {
return 1 <= r && r <= n && 1 <= c && c <= m;
}
boolean moveStartPoint() {
int width = maxC + 1 - minC;
if (width > m) {
return false;
}
int height = maxR + 1 - minR;
if (height > n) {
return false;
}
//we have a place
char fixMove = '\0';
//Right
if (c == 0) {
fixMove = 'R';
}
//Down
if (r == 0) {
fixMove = 'D';
}
//Left
if (c == m + 1) {
fixMove = 'L';
}
//Up
if (r == n + 1) {
fixMove = 'U';
}
int[] fixTurn = turns.get(fixMove);
r += fixTurn[0];
c += fixTurn[1];
startR += fixTurn[0];
startC += fixTurn[1];
maxR += fixTurn[0];
minR += fixTurn[0];
maxC += fixTurn[1];
minC += fixTurn[1];
return true;
}
@Override
public String toString() {
return startR + " " + startC;
}
}
boolean in(int x, int n, int y, int m) {
return 1 <= x && x <= n && 1 <= y && y <= m;
}
private void solve() {
int t = nextInt();
for (int tt = 0; tt < t; tt++) {
solveOne();
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(Object expected,
Object actual, Object... input) {
super("expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new MS_8_A().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
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 FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(int[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(int[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readInt();
}
}
}
public void readLongArrays(long[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readLong();
}
}
}
public void readDoubleArrays(double[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readDouble();
}
}
}
public char[][] readTable(int rowCount, int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readCharArray(columnCount);
}
return table;
}
public int[][] readIntTable(int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readIntArray(columnCount);
}
return table;
}
public double[][] readDoubleTable(int rowCount, int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readDoubleArray(columnCount);
}
return table;
}
public long[][] readLongTable(int rowCount, int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readLongArray(columnCount);
}
return table;
}
public String[][] readStringTable(int rowCount, int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readStringArray(columnCount);
}
return table;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public void readStringArrays(String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readString();
}
}
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
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 peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
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 11 | 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 | 0035da4697f8f023ed9d32b5320ff3a1 | 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.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
/**
* Provide prove of correctness before implementation. Implementation can cost a lot of time.
* Anti test that prove that it's wrong.
* <p>
* Do not confuse i j k g indexes, upTo and length. Do extra methods!!! Write more informative names to simulation
* <p>
* Will program ever exceed limit?
* Try all approaches with prove of correctness if task is not obvious.
* If you are given formula/rule: Try to play with it.
* Analytic solution/Hardcoded solution/Constructive/Greedy/DP/Math/Brute force/Symmetric data
* Number theory
* Game theory (optimal play) that consider local and global strategy.
*/
public class MS_8_A {
Map<Character, int[]> turns = new HashMap<>() {
{
put('L', new int[]{0, -1});
put('R', new int[]{0, 1});
put('U', new int[]{-1, 0});
put('D', new int[]{1, 0});
}
};
private void solveOne() {
int n = nextInt();
int m = nextInt();
char[] s = nextString().toCharArray();
int commands = s.length;
int startR = 1;
int startC = 1;
int r = startR;
int c = startC;
int minC = startC;
int maxC = startC;
int minR = startR;
int maxR = startR;
int p = 0;
while (true) {
//go
char ch = s[p++];
int[] turn = turns.get(ch);
r += turn[0];
c += turn[1];
maxR = Math.max(maxR, r);
minR = Math.min(minR, r);
maxC = Math.max(maxC, c);
minC = Math.min(minC, c);
if (!in(c, m, r, n)) {
int width = maxC + 1 - minC;
if (width > m) {
break;
}
int height = maxR + 1 - minR;
if (height > n) {
break;
}
//we have a place
char fixMove = '\0';
//Right
if (c == 0) {
fixMove = 'R';
}
//Down
if (r == 0) {
fixMove = 'D';
}
//Left
if (c == m + 1) {
fixMove = 'L';
}
//Up
if (r == n + 1) {
fixMove = 'U';
}
int[] fixTurn = turns.get(fixMove);
r += fixTurn[0];
c += fixTurn[1];
startR += fixTurn[0];
startC += fixTurn[1];
maxR += fixTurn[0];
minR += fixTurn[0];
maxC += fixTurn[1];
minC += fixTurn[1];
}
if (p == commands) {
break;
}
//in(c, n, r, m) && p < commands
}
//𝑟 (1≤𝑟≤𝑛) and 𝑐 (1≤𝑐≤𝑚),
System.out.println(startR + " " + startC);
}
boolean in(int x, int n, int y, int m) {
return 1 <= x && x <= n && 1 <= y && y <= m;
}
private void solve() {
int t = nextInt();
for (int tt = 0; tt < t; tt++) {
solveOne();
}
}
class AssertionRuntimeException extends RuntimeException {
AssertionRuntimeException(Object expected,
Object actual, Object... input) {
super("expected = " + expected + ",\n actual = " + actual + ",\n " + Arrays.deepToString(input));
}
}
private int nextInt() {
return System.in.readInt();
}
private long nextLong() {
return System.in.readLong();
}
private String nextString() {
return System.in.readString();
}
private int[] nextIntArr(int n) {
return System.in.readIntArray(n);
}
private long[] nextLongArr(int n) {
return System.in.readLongArray(n);
}
public static void main(String[] args) {
new MS_8_A().run();
}
static class System {
private static FastInputStream in;
private static FastPrintStream out;
}
private void run() {
System.in = new FastInputStream(java.lang.System.in);
System.out = new FastPrintStream(java.lang.System.out);
solve();
System.out.flush();
}
private static class FastPrintStream {
private static final int BUF_SIZE = 8192;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastPrintStream() {
this(java.lang.System.out);
}
public FastPrintStream(OutputStream os) {
this.out = os;
}
public FastPrintStream(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastPrintStream print(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastPrintStream print(char c) {
return print((byte) c);
}
public FastPrintStream print(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastPrintStream print(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
//can be optimized
public FastPrintStream print0(char[] s) {
if (ptr + s.length < BUF_SIZE) {
for (char c : s) {
buf[ptr++] = (byte) c;
}
} else {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
}
return this;
}
//can be optimized
public FastPrintStream print0(String s) {
if (ptr + s.length() < BUF_SIZE) {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
}
} else {
for (int i = 0; i < s.length(); i++) {
buf[ptr++] = (byte) s.charAt(i);
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 FastPrintStream print(int x) {
if (x == Integer.MIN_VALUE) {
return print((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(long x) {
if (x == Long.MIN_VALUE) {
return print("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
print((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 FastPrintStream print(double x, int precision) {
if (x < 0) {
print('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
print((long) x).print(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
print((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastPrintStream println(int[] a, int from, int upTo, char separator) {
for (int i = from; i < upTo; i++) {
print(a[i]);
print(separator);
}
print('\n');
return this;
}
public FastPrintStream println(int[] a) {
return println(a, 0, a.length, ' ');
}
public FastPrintStream println(char c) {
return print(c).println();
}
public FastPrintStream println(int x) {
return print(x).println();
}
public FastPrintStream println(long x) {
return print(x).println();
}
public FastPrintStream println(String x) {
return print(x).println();
}
public FastPrintStream println(double x, int precision) {
return print(x, precision).println();
}
public FastPrintStream println() {
return print((byte) '\n');
}
public FastPrintStream printf(String format, Object... args) {
return print(String.format(format, args));
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
}
private static class FastInputStream {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastInputStream(InputStream stream) {
this.stream = stream;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = readDouble();
}
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++) {
array[i] = readString();
}
return array;
}
public char[] readCharArray(int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = readCharacter();
}
return array;
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readInt();
}
}
}
public void readLongArrays(long[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readLong();
}
}
}
public void readDoubleArrays(double[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readDouble();
}
}
}
public char[][] readTable(int rowCount, int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readCharArray(columnCount);
}
return table;
}
public int[][] readIntTable(int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readIntArray(columnCount);
}
return table;
}
public double[][] readDoubleTable(int rowCount, int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readDoubleArray(columnCount);
}
return table;
}
public long[][] readLongTable(int rowCount, int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = readLongArray(columnCount);
}
return table;
}
public String[][] readStringTable(int rowCount, int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++) {
table[i] = this.readStringArray(columnCount);
}
return table;
}
public String readText() {
StringBuilder result = new StringBuilder();
while (true) {
int character = read();
if (character == '\r') {
continue;
}
if (character == -1) {
break;
}
result.append((char) character);
}
return result.toString();
}
public void readStringArrays(String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++) {
arrays[j][i] = readString();
}
}
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
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 peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int peekNonWhitespace() {
while (isWhitespace(peek())) {
read();
}
return peek();
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, readInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return readString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
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 11 | 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 | 901386d35b22d176fa51d89be1712a9d | 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;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public class P1607E {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
IntStream.range(0, T).forEach(t -> {
int heightOfTheField = sc.nextInt();
int widthOfTheField = sc.nextInt();
String commandSequence = sc.next();
printOptimalCells(commandSequence, heightOfTheField, widthOfTheField);
});
}
private static void printOptimalCells(String commandSequence, int heightOfTheField, double widthOfTheField) {
AtomicInteger currentRow = new AtomicInteger(1);
AtomicInteger startingRow = new AtomicInteger(1), downMostColumnVisited = new AtomicInteger(1);
AtomicBoolean shouldIterateX = new AtomicBoolean(true);
AtomicInteger currentColumn = new AtomicInteger(1);
AtomicInteger startingColumn = new AtomicInteger(1), rightMostColumnVisited = new AtomicInteger(1);
AtomicBoolean shouldIterateY = new AtomicBoolean(true);
IntStream.range(0, commandSequence.length())
.forEach(i -> {
char currentCommand = commandSequence.charAt(i);
if (shouldIterateX.get()) {
if (currentCommand == 'U') {
if (currentRow.get() > 1) {
currentRow.decrementAndGet();
} else {
if (startingRow.get() < heightOfTheField && downMostColumnVisited.get() < heightOfTheField) {
downMostColumnVisited.incrementAndGet();
startingRow.incrementAndGet();
} else {
shouldIterateX.set(false);
}
}
} else if (currentCommand == 'D') {
if (currentRow.get() < heightOfTheField) {
currentRow.incrementAndGet();
downMostColumnVisited.set(Math.max(currentRow.get(), downMostColumnVisited.get()));
} else {
shouldIterateY.set(false);
}
}
}
if (shouldIterateY.get()) {
if (currentCommand == 'L') {
if (currentColumn.get() > 1) {
currentColumn.decrementAndGet();
} else {
if (startingColumn.get() < widthOfTheField && rightMostColumnVisited.get() < widthOfTheField) {
rightMostColumnVisited.incrementAndGet();
startingColumn.incrementAndGet();
} else {
shouldIterateY.set(false);
}
}
} else if (currentCommand == 'R') {
if (currentColumn.get() < widthOfTheField) {
currentColumn.incrementAndGet();
rightMostColumnVisited.set(Math.max(currentColumn.get(), rightMostColumnVisited.get()));
} else {
shouldIterateY.set(false);
}
}
}
});
System.out.println(startingRow.get() + " " + startingColumn.get());
}
} | 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 11 | 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 | 441c16b9175ec683ae434bf0219a6922 | 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;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public class P1607E {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
IntStream.range(0, T).forEach(t -> {
int heightOfTheField = sc.nextInt();
int widthOfTheField = sc.nextInt();
String commandSequence = sc.next();
printOptimalCell(heightOfTheField, widthOfTheField, commandSequence);
});
}
private static void printOptimalCell(int heightOfTheField, int widthOfTheField, String commandSequence) {
int startingRow = getStartingIndex(commandSequence, heightOfTheField, 'U', 'D');
int startingColumn = getStartingIndex(commandSequence, widthOfTheField, 'L', 'R');
System.out.println(startingRow + " " + startingColumn);
}
private static int getStartingIndex(String commandSequence, int axisLength, char decrementCommand, char incrementCommand) {
AtomicInteger currentIndex = new AtomicInteger(1);
AtomicInteger finalStartingIndex = new AtomicInteger(1), oppositeCommandMostVisitedIndex = new AtomicInteger(1);
AtomicBoolean shouldIterate = new AtomicBoolean(true);
IntStream.range(0, commandSequence.length())
.takeWhile(i -> shouldIterate.get())
.forEach(i -> {
char currentCommand = commandSequence.charAt(i);
if (currentCommand == decrementCommand) {
if (currentIndex.get() > 1) {
currentIndex.decrementAndGet();
} else {
if (finalStartingIndex.get() < axisLength && oppositeCommandMostVisitedIndex.get() < axisLength) {
oppositeCommandMostVisitedIndex.incrementAndGet();
finalStartingIndex.incrementAndGet();
} else {
shouldIterate.set(false);
}
}
} else if (currentCommand == incrementCommand) {
if (currentIndex.get() < axisLength) {
currentIndex.incrementAndGet();
oppositeCommandMostVisitedIndex.set(Math.max(currentIndex.get(), oppositeCommandMostVisitedIndex.get()));
} else {
shouldIterate.set(false);
}
}
});
return finalStartingIndex.get();
}
} | 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 11 | 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 | faa712cfea39d2182e0b4bd350dfac15 | 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;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public class P1607E {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
IntStream.range(0, T).forEach(t -> {
int heightOfTheField = sc.nextInt();
int widthOfTheField = sc.nextInt();
String commandSequence = sc.next();
printOptimalCell(heightOfTheField, widthOfTheField, commandSequence);
});
}
private static void printOptimalCell(int heightOfTheField, int widthOfTheField, String commandSequence) {
int startingColumn = getStartingColumn(commandSequence, widthOfTheField);
int startingRow = getStartingRow(commandSequence, heightOfTheField, 'U', 'D');
System.out.println(startingRow + " " + startingColumn);
}
private static int getStartingRow(String commandSequence, int heightOfTheField, char decrementCommand, char incrementCommand) {
AtomicInteger currentRow = new AtomicInteger(1);
AtomicInteger startingRow = new AtomicInteger(1), downMostColumnVisited = new AtomicInteger(1);
AtomicBoolean shouldIterate = new AtomicBoolean(true);
IntStream.range(0, commandSequence.length())
.takeWhile(i -> shouldIterate.get())
.forEach(i -> {
char currentCommand = commandSequence.charAt(i);
if (currentCommand == decrementCommand) {
if (currentRow.get() > 1) {
currentRow.decrementAndGet();
} else {
if (startingRow.get() < heightOfTheField && downMostColumnVisited.get() < heightOfTheField) {
downMostColumnVisited.incrementAndGet();
startingRow.incrementAndGet();
} else {
shouldIterate.set(false);
}
}
} else if (currentCommand == incrementCommand) {
if (currentRow.get() < heightOfTheField) {
currentRow.incrementAndGet();
downMostColumnVisited.set(Math.max(currentRow.get(), downMostColumnVisited.get()));
} else {
shouldIterate.set(false);
}
}
});
return startingRow.get();
}
private static int getStartingColumn(String commandSequence, int widthOfTheField) {
AtomicInteger currentColumn = new AtomicInteger(1);
AtomicInteger startingColumn = new AtomicInteger(1), rightMostColumnVisited = new AtomicInteger(1);
AtomicBoolean shouldIterate = new AtomicBoolean(true);
IntStream.range(0, commandSequence.length())
.takeWhile(i -> shouldIterate.get())
.forEach(i -> {
char currentCommand = commandSequence.charAt(i);
if (currentCommand == 'L') {
if (currentColumn.get() > 1) {
currentColumn.decrementAndGet();
} else {
if (startingColumn.get() < widthOfTheField && rightMostColumnVisited.get() < widthOfTheField) {
rightMostColumnVisited.incrementAndGet();
startingColumn.incrementAndGet();
} else {
shouldIterate.set(false);
}
}
} else if (currentCommand == 'R') {
if (currentColumn.get() < widthOfTheField) {
currentColumn.incrementAndGet();
rightMostColumnVisited.set(Math.max(currentColumn.get(), rightMostColumnVisited.get()));
} else {
shouldIterate.set(false);
}
}
});
return startingColumn.get();
}
} | 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 11 | 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 | f9f86f6f1acd3c737df47a15d5d55690 | 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;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public class P1607E {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
IntStream.range(0, T).forEach(t -> {
int heightOfTheField = sc.nextInt();
int widthOfTheField = sc.nextInt();
String commandSequence = sc.next();
printOptimalCell(heightOfTheField, widthOfTheField, commandSequence);
});
}
private static void printOptimalCell(int heightOfTheField, int widthOfTheField, String commandSequence) {
int startingColumn = getStartingColumn(commandSequence, widthOfTheField);
int startingRow = getStartingRow(commandSequence, heightOfTheField);
System.out.println(startingRow + " " + startingColumn);
}
private static int getStartingRow(String commandSequence, int heightOfTheField) {
AtomicInteger currentRow = new AtomicInteger(1);
AtomicInteger startingRow = new AtomicInteger(1), downMostColumnVisited = new AtomicInteger(1);
AtomicBoolean shouldIterate = new AtomicBoolean(true);
IntStream.range(0, commandSequence.length())
.takeWhile(i -> shouldIterate.get())
.forEach(i -> {
char currentCommand = commandSequence.charAt(i);
if (currentCommand == 'U') {
if (currentRow.get() > 1) {
currentRow.decrementAndGet();
} else {
if (startingRow.get() < heightOfTheField && downMostColumnVisited.get() < heightOfTheField) {
downMostColumnVisited.incrementAndGet();
startingRow.incrementAndGet();
} else {
shouldIterate.set(false);
}
}
} else if (currentCommand == 'D') {
if (currentRow.get() < heightOfTheField) {
currentRow.incrementAndGet();
downMostColumnVisited.set(Math.max(currentRow.get(), downMostColumnVisited.get()));
} else {
shouldIterate.set(false);
}
}
});
return startingRow.get();
}
private static int getStartingColumn(String commandSequence, int widthOfTheField) {
AtomicInteger currentColumn = new AtomicInteger(1);
AtomicInteger startingColumn = new AtomicInteger(1), rightMostColumnVisited = new AtomicInteger(1);
AtomicBoolean shouldIterate = new AtomicBoolean(true);
IntStream.range(0, commandSequence.length())
.takeWhile(i -> shouldIterate.get())
.forEach(i -> {
char currentCommand = commandSequence.charAt(i);
if (currentCommand == 'L') {
if (currentColumn.get() > 1) {
currentColumn.decrementAndGet();
} else {
if (startingColumn.get() < widthOfTheField && rightMostColumnVisited.get() < widthOfTheField) {
rightMostColumnVisited.incrementAndGet();
startingColumn.incrementAndGet();
} else {
shouldIterate.set(false);
}
}
} else if (currentCommand == 'R') {
if (currentColumn.get() < widthOfTheField) {
currentColumn.incrementAndGet();
rightMostColumnVisited.set(Math.max(currentColumn.get(), rightMostColumnVisited.get()));
} else {
shouldIterate.set(false);
}
}
});
return startingColumn.get();
}
} | 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 11 | 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 | 0fd4a6789fd4ed8ce3dd473c6409e1b0 | 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 cp
{
public static void main(String[] args) throws IOException
{
//Your Solve
FastReader s = new FastReader();
// Scanner s = new Scanner(System.in);
int t = s.nextInt();
for(int p = 0;p < t;p++) {
int n = s.nextInt();
int m = s.nextInt();
String str = s.next();
int Hcurr = 0,Vcurr=0,Hmax=0,Hmin=0,Vmax=0,Vmin=0;
int VmaxTemp = 0,VminTemp=0,HmaxTemp=0,HminTemp=0;
for(int i = 0;i < str.length();i++) {
char ch = str.charAt(i);
if(ch == 'L') {
Hcurr--;
}else if(ch == 'R') {
Hcurr++;
}else if(ch == 'D') {
Vcurr--;
}else {
Vcurr++;
}
if(Vcurr>Vmax) {
VmaxTemp=Vcurr;
}
if(Vcurr<Vmin) {
VminTemp=Vcurr;
}
if(Hcurr>Hmax) {
HmaxTemp=Hcurr;
}
if(Hcurr<Hmin) {
HminTemp=Hcurr;
}
if(Math.abs(HminTemp)+HmaxTemp >= m || Math.abs(VminTemp)+VmaxTemp >= n) {
break;
}else {
Vmin = VminTemp;
Vmax = VmaxTemp;
Hmax = HmaxTemp;
Hmin = HminTemp;
}
}
System.out.println((1+Vmax)+" "+(m-Hmax));
}
}
public static boolean palindrome(Vector<Integer> v) {
int start = 0;int end = v.size()-1;
while(start<end) {
if(v.get(start) != v.get(end)) {
return false;
}
start++;
end--;
}
return true;
}
static void shuffleArray(int[] ar)
{
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
/* Iterative Function to calculate (x^y) in O(log y) */
static long power(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long getPairsCount(int n, long sum,long arr[])
{
HashMap<Long, Integer> hm = new HashMap<>();
// Store counts of all elements in map hm
for (int i = 0; i < n; i++) {
// initializing value to 0, if key not found
if (!hm.containsKey(arr[i]))
hm.put(arr[i], 0);
hm.put(arr[i], hm.get(arr[i]) + 1);
}
long twice_count = 0;
// iterate through each element and increment the
// count (Notice that every pair is counted twice)
for (int i = 0; i < n; i++) {
if (hm.get(sum - arr[i]) != null)
twice_count += hm.get(sum - arr[i]);
// if (arr[i], arr[i]) pair satisfies the
// condition, then we need to ensure that the
// count is decreased by one such that the
// (arr[i], arr[i]) pair is not considered
if (sum - arr[i] == arr[i])
twice_count--;
}
// return the half of twice_count
return twice_count / 2;
}
public static HashMap<String, Integer>
sortByValue(HashMap<String, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<String, Integer> > list
= new LinkedList<Map.Entry<String, Integer> >(
hm.entrySet());
// Sort the list using lambda expression
Collections.sort(
list,
(i1,
i2) -> i1.getValue().compareTo(i2.getValue()));
// put data from sorted list to hashmap
HashMap<String, Integer> temp
= new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
public static String palin(String str) {
StringBuilder ans = new StringBuilder();
for(int i = str.length()-1;i >= 0 ;i--) {
ans.append(str.charAt(i));
}
return ans.toString();
}
public static String palin(StringBuilder str) {
StringBuilder ans = new StringBuilder();
for(int i = str.length()-1;i >= 0 ;i--) {
ans.append(str.charAt(i));
}
return ans.toString();
}
public static int getInt(char ch) {
int ans = 0;
if(ch >= '0' && ch <= '9') {
ans = ch-'0';
}else if(ch >= 'A' && ch <= 'Z') {
ans = ch-'A' + 10;
}else if(ch >= 'a' && ch <= 'z') {
ans = ch-'a' + 36;
}else if(ch == '-') {
ans = 62;
}else {
ans = 63;
}
return ans;
}
public static int getZeroes(int base64) {
int count = 0;
int iters = 0;
while(iters != 6) {
if(base64%2 == 0) {
count++;
}
base64 /= 2;
iters++;
}
return count;
}
static int lower_bound(long array[], long key,long start,long end)
{
// Initialize starting index and
// ending index
long low = start, high = end;
long mid;
// Till high does not crosses low
while (low < high) {
// Find the index of the middle element
mid = low + (high - low) / 2;
// If key is less than or equal
// to array[mid], then find in
// left subarray
if (key <= array[(int)mid]) {
high = mid;
}
// If key is greater than array[mid],
// then find in right subarray
else {
low = mid + 1;
}
}
// If key is greater than last element which is
// array[n-1] then lower bound
// does not exists in the array
if (low < end && array[(int)low] < key) {
low++;
}
// Returning the lower_bound index
return (int)low;
}
static int upper_bound(long array[], long key,long start,long end)
{
// Initialize starting index and
// ending index
long low = start, high = end;
long mid;
// Till high does not crosses low
while (low < high) {
// Find the index of the middle element
mid = low + (high - low) / 2;
// If key is less than or equal
// to array[mid], then find in
// left subarray
if (key >= array[(int)mid]) {
low = mid+1;
}
// If key is greater than array[mid],
// then find in right subarray
else {
high = mid;
}
}
// If key is greater than last element which is
// array[n-1] then lower bound
// does not exists in the array
if (low < end && array[(int)low] <= key) {
low++;
}
// Returning the lower_bound index
return (int)low;
}
public static long search1(long x,long k) {
long start = 1,end = k;
long mid = start + (end-start)/2;
while(start < end) {
mid = start + (end-start)/2;
if(x>mid*(mid+1)/2) {
start = mid+1;
}else {
end = mid;
}
}
if(start<end && mid*(mid+1)/2 <= x) {
start++;
}
return start;
}
public static long search2(long x,long k) {
long start = 1,end = k;
long mid = start + (end-start)/2;
while(start < end) {
mid = start + (end-start)/2;
if(x>mid*(2*k-mid-1)/2) {
start = mid+1;
}else {
end = mid;
}
}
if(start<end && mid*(2*k-mid-1)/2 <= x) {
start++;
}
return start;
}
public static int countGreater(int arr[], int k,int l, int r)
{
int leftGreater = r+1;
int R = r;
while (l<=r) {
int m = l + (r - l) / 2;
if (arr[m] >= k) {
leftGreater = m;
r = m - 1;
}
else {
l = m + 1;
}
}
return (R-leftGreater+1);
}
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 11 | 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 | 8cba42bdd5e10b3d419734cc9e56ced1 | 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 cp
{
public static void main(String[] args) throws IOException
{
//Your Solve
FastReader s = new FastReader();
// Scanner s = new Scanner(System.in);
int t = s.nextInt();
for(int p = 0;p < t;p++) {
int n = s.nextInt();
int m = s.nextInt();
String str = s.next();
int Hcurr = 0,Vcurr=0,Hmax=0,Hmin=0,Vmax=0,Vmin=0;
int VmaxTemp = 0,VminTemp=0,HmaxTemp=0,HminTemp=0;
for(int i = 0;i < str.length();i++) {
char ch = str.charAt(i);
if(ch == 'L') {
Hcurr--;
}else if(ch == 'R') {
Hcurr++;
}else if(ch == 'D') {
Vcurr--;
}else {
Vcurr++;
}
if(Vcurr>Vmax) {
VmaxTemp=Vcurr;
}
if(Vcurr<Vmin) {
VminTemp=Vcurr;
}
if(Hcurr>Hmax) {
HmaxTemp=Hcurr;
}
if(Hcurr<Hmin) {
HminTemp=Hcurr;
}
if(Math.abs(HminTemp)+HmaxTemp >= m || Math.abs(VminTemp)+VmaxTemp >= n) {
break;
}else {
Vmin = VminTemp;
Vmax = VmaxTemp;
Hmax = HmaxTemp;
Hmin = HminTemp;
}
}
System.out.println((1+Vmax)+" "+(1-Hmin));
}
}
public static boolean palindrome(Vector<Integer> v) {
int start = 0;int end = v.size()-1;
while(start<end) {
if(v.get(start) != v.get(end)) {
return false;
}
start++;
end--;
}
return true;
}
static void shuffleArray(int[] ar)
{
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
/* Iterative Function to calculate (x^y) in O(log y) */
static long power(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long getPairsCount(int n, long sum,long arr[])
{
HashMap<Long, Integer> hm = new HashMap<>();
// Store counts of all elements in map hm
for (int i = 0; i < n; i++) {
// initializing value to 0, if key not found
if (!hm.containsKey(arr[i]))
hm.put(arr[i], 0);
hm.put(arr[i], hm.get(arr[i]) + 1);
}
long twice_count = 0;
// iterate through each element and increment the
// count (Notice that every pair is counted twice)
for (int i = 0; i < n; i++) {
if (hm.get(sum - arr[i]) != null)
twice_count += hm.get(sum - arr[i]);
// if (arr[i], arr[i]) pair satisfies the
// condition, then we need to ensure that the
// count is decreased by one such that the
// (arr[i], arr[i]) pair is not considered
if (sum - arr[i] == arr[i])
twice_count--;
}
// return the half of twice_count
return twice_count / 2;
}
public static HashMap<String, Integer>
sortByValue(HashMap<String, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<String, Integer> > list
= new LinkedList<Map.Entry<String, Integer> >(
hm.entrySet());
// Sort the list using lambda expression
Collections.sort(
list,
(i1,
i2) -> i1.getValue().compareTo(i2.getValue()));
// put data from sorted list to hashmap
HashMap<String, Integer> temp
= new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
public static String palin(String str) {
StringBuilder ans = new StringBuilder();
for(int i = str.length()-1;i >= 0 ;i--) {
ans.append(str.charAt(i));
}
return ans.toString();
}
public static String palin(StringBuilder str) {
StringBuilder ans = new StringBuilder();
for(int i = str.length()-1;i >= 0 ;i--) {
ans.append(str.charAt(i));
}
return ans.toString();
}
public static int getInt(char ch) {
int ans = 0;
if(ch >= '0' && ch <= '9') {
ans = ch-'0';
}else if(ch >= 'A' && ch <= 'Z') {
ans = ch-'A' + 10;
}else if(ch >= 'a' && ch <= 'z') {
ans = ch-'a' + 36;
}else if(ch == '-') {
ans = 62;
}else {
ans = 63;
}
return ans;
}
public static int getZeroes(int base64) {
int count = 0;
int iters = 0;
while(iters != 6) {
if(base64%2 == 0) {
count++;
}
base64 /= 2;
iters++;
}
return count;
}
static int lower_bound(long array[], long key,long start,long end)
{
// Initialize starting index and
// ending index
long low = start, high = end;
long mid;
// Till high does not crosses low
while (low < high) {
// Find the index of the middle element
mid = low + (high - low) / 2;
// If key is less than or equal
// to array[mid], then find in
// left subarray
if (key <= array[(int)mid]) {
high = mid;
}
// If key is greater than array[mid],
// then find in right subarray
else {
low = mid + 1;
}
}
// If key is greater than last element which is
// array[n-1] then lower bound
// does not exists in the array
if (low < end && array[(int)low] < key) {
low++;
}
// Returning the lower_bound index
return (int)low;
}
static int upper_bound(long array[], long key,long start,long end)
{
// Initialize starting index and
// ending index
long low = start, high = end;
long mid;
// Till high does not crosses low
while (low < high) {
// Find the index of the middle element
mid = low + (high - low) / 2;
// If key is less than or equal
// to array[mid], then find in
// left subarray
if (key >= array[(int)mid]) {
low = mid+1;
}
// If key is greater than array[mid],
// then find in right subarray
else {
high = mid;
}
}
// If key is greater than last element which is
// array[n-1] then lower bound
// does not exists in the array
if (low < end && array[(int)low] <= key) {
low++;
}
// Returning the lower_bound index
return (int)low;
}
public static long search1(long x,long k) {
long start = 1,end = k;
long mid = start + (end-start)/2;
while(start < end) {
mid = start + (end-start)/2;
if(x>mid*(mid+1)/2) {
start = mid+1;
}else {
end = mid;
}
}
if(start<end && mid*(mid+1)/2 <= x) {
start++;
}
return start;
}
public static long search2(long x,long k) {
long start = 1,end = k;
long mid = start + (end-start)/2;
while(start < end) {
mid = start + (end-start)/2;
if(x>mid*(2*k-mid-1)/2) {
start = mid+1;
}else {
end = mid;
}
}
if(start<end && mid*(2*k-mid-1)/2 <= x) {
start++;
}
return start;
}
public static int countGreater(int arr[], int k,int l, int r)
{
int leftGreater = r+1;
int R = r;
while (l<=r) {
int m = l + (r - l) / 2;
if (arr[m] >= k) {
leftGreater = m;
r = m - 1;
}
else {
l = m + 1;
}
}
return (R-leftGreater+1);
}
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 11 | 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 | ce4dcaa84b4a189e96a7668a0182eae5 | 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 javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main extends PrintWriter {
static BufferedReader s = new BufferedReader(new InputStreamReader(System.in));Main () { super(System.out); }public static void main(String[] args) throws IOException{ Main d1=new Main ();d1.main();d1.flush(); }
void main() throws IOException {
StringBuilder sb = new StringBuilder();
int t = 1;
t = i(s()[0]);
while (t-- > 0) {
int X = 1; int Y = 1;
String[] s1 = s();
int n = i(s1[0]); int m = i(s1[1]);
char[] a = s()[0].toCharArray();
int maxRight = 0; int maxLeft = 0; int maxUp = 0; int maxDown = 0;
int x = 0; int y = 0;
int ans = 0;
for(int i = 0; i < a.length; i++){
if(a[i] == 'R'){
x++;
maxRight = Math.max(maxRight, x);
}else if(a[i] == 'L'){
x--;
maxLeft = Math.min(maxLeft, x);
}else if(a[i] == 'U'){
y--;
maxUp = Math.min(maxUp, y);
}else {
y++;
maxDown = Math.max(maxDown, y);
}
int curX = -maxUp;
if(n - curX > 0 && n - curX > maxDown){}
else break;
int curY = -maxLeft;
if(m - curY > 0 && m - curY > maxRight){}
else break;
// System.out.println(curX + " " + curY + " " + i);
X = curX + 1; Y = curY + 1;
}
sb.append(X + " " + Y + "\n");
}
System.out.println(sb);
}
static String[] s() throws IOException { return s.readLine().trim().split("\\s+"); }
static int i(String ss) {return Integer.parseInt(ss); }
static long l(String ss) {return Long.parseLong(ss); }
public void arr(long[] a,int n) throws IOException {String[] s2=s();for(int i=0;i<n;i++){ a[i]=l(s2[i]); }}
public void arri(int[] a,int n) throws IOException {String[] s2=s();for(int i=0;i<n;i++){ a[i]=(i(s2[i])); }}
}class Pair{
int start, end;
public Pair(long a, long b){
this.start = (int)a ; this.end = (int)b;
}
}
| 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 11 | 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 | 61f80f5c483b8e54dd9124efee90e325 | 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 static java.lang.Math.*;
import java.util.*;
import java.io.*;
public class Solution {
public static int[] find(int n, int m, char[] a) {
int r = (n-1)/2;
int c = (m-1)/2;
int cr = r;
int cc = c;
int mu = r;
int md = r;
int mr = c;
int ml = c;
// System.out.println("r: " + r);
// System.out.println("c: " + c);
for (char ch: a) {
if (ch == 'U') {
if (cr > 0) {
cr--;
mu = min(mu, cr);
}
else if (r == n-1) {
break;
}
else {
if (md == n-1) break;
r++;
md++;
}
}
else if (ch == 'R') {
if (cc < m-1) {
cc++;
mr = max(mr, cc);
}
else if (c == 0) break;
else {
if (ml == 0) break;
c--;
ml--;
}
}
else if (ch == 'D') {
if (cr < n-1) {
cr++;
md = max(md, cr);
}
else if (r == 0) break;
else {
if (mu == 0) break;
r--;
mu--;
}
}
else {
if (cc > 0) {
cc--;
ml = min(ml, cc);
}
else if (c == m-1) break;
else {
if (mr == m-1) break;
c++;
mr++;
}
}
}
// System.out.println("reached");
// System.out.println("i: " + i);
// System.out.println("j: " + j);
// System.out.println("uv: " + uv);
// System.out.println("rv: " + rv);
// System.out.println("dv: "+ dv);
// System.out.println("lv: " + lv);
return new int[]{r + 1, c + 1};
}
static class Pair {
int i; int j;
public Pair(int i, int j) {
this.i = i;
this.j = j;
}
@Override
public String toString() {
return "Pair{" +
"i=" + i +
", j=" + j +
'}';
}
}
public static void main(String[] args) throws Exception {
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = in.readInt();
for (int tt = 0; tt < t; tt++) {
int n = in.readInt();
int m = in.readInt();
char[] a = in.readString().toCharArray();
int[] res = find(n, m, a);
pw.println(res[0] + " " + res[1]);
}
pw.flush();
pw.close();
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = readInt();
}
return a;
}
public long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = readLong();
}
return a;
}
public String next() {
return readString();
}
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 11 | 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 | 375b01b5bf7fefae24953e6b731ead5d | 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.*;
// Created by @thesupremeone on 02-11-2021
public class E {
int n,m;
int getOptimalValue(ArrayList<Integer> list, int limit){
int min = 0;
int max = 0;
int current = 0;
int optimal = 1;
for(int e : list){
current += e;
min = Math.min(min, current);
max = Math.max(max, current);
int lower = 1+(-1*min);
int upper = limit-max;
if(upper>=lower){
optimal = lower;
}else {
break;
}
}
return optimal;
}
void solve() throws IOException {
int ts = getInt();
for (int t = 1; t <= ts; t++) {
n = getInt();
m = getInt();
String s = getLine();
ArrayList<Integer> x = new ArrayList<>();
ArrayList<Integer> y = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c=='L'){
y.add(-1);
x.add(0);
}else if(c=='R'){
y.add(+1);
x.add(0);
}else if(c=='U'){
x.add(-1);
y.add(0);
}else {
x.add(+1);
y.add(0);
}
}
int r = getOptimalValue(x, n);
int c = getOptimalValue(y, m);
println(r+" "+c);
}
}
public static void main(String[] args) throws Exception {
if (isOnlineJudge()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
new E().solve();
out.flush();
} else {
localJudge = new Thread();
in = new BufferedReader(new FileReader("input.txt"));
out = new BufferedWriter(new FileWriter("output.txt"));
localJudge.start();
new E().solve();
out.flush();
localJudge.suspend();
}
}
static boolean isOnlineJudge(){
try {
return System.getProperty("ONLINE_JUDGE")!=null
|| System.getProperty("LOCAL")==null;
}catch (Exception e){
return true;
}
}
// Fast Input & Output
static Thread localJudge = null;
static BufferedReader in;
static StringTokenizer st;
static BufferedWriter out;
static String getLine() throws IOException{
return in.readLine();
}
static String getToken() throws IOException{
if(st==null || !st.hasMoreTokens())
st = new StringTokenizer(getLine());
return st.nextToken();
}
static int getInt() throws IOException {
return Integer.parseInt(getToken());
}
static long getLong() throws IOException {
return Long.parseLong(getToken());
}
static void print(Object s) throws IOException{
out.write(String.valueOf(s));
}
static void println(Object s) throws IOException{
out.write(String.valueOf(s));
out.newLine();
}
} | 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 11 | 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 | 233083abdf0c2acc8bbfb086b9a413da | 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 Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
// sc.nextLine();
while(test-->0){
int n = sc.nextInt();
int m = sc.nextInt();
sc.nextLine();
String s = sc.nextLine();
/* Deque<Integer> row = new LinkedList<>();
Deque<Integer> col = new LinkedList<>();
for (int i =1; i<=n; i++){
row.addLast(i);
}
for (int i =1; i<=m; i++){
col.addLast(i);
}*/
// for (int i =2; i)
int[] row = new int[2];
row[0] =1;
row[1] =n;
int[] col = new int[2];
col[0] =1;
col[1]= m;
int countl =0; int countr =0; int countu =0; int countd=0;
boolean bool = false;
for (int i =0; i<s.length(); i++){
if (s.charAt(i)=='U'){
if (countd>0){
countd--;
countu++;
}
else{
int x = row[0];
row[0]++;
if(row[0]>row[1]){
bool = true;
System.out.print(x + " " + col[0]);
break;
}
countu++;
}
}
else if (s.charAt(i)=='L'){
if (countr>0){
countr--;
countl++;
}
else{
int x =col[0];
col[0]++;
if(col[0]>col[1]){
//col.add(x);
bool = true;
System.out.print(row[0] + " "+ x);
break;
}
countl++;
}
}
else if (s.charAt(i)=='D'){
if(countu>0){
countu--;
countd++;
}
else{
int x =row[1];
row[1]--;
if(row[0]>row[1]){
//row.add(x);
bool = true;
System.out.print(x + " " + col[1]);
break;
}
countd++;
}
}
else if (s.charAt(i) =='R') {
if(countl>0){
countl--;
countr++;
}
else{
int z =col[1];
col[1]--;
if(col[0]>col[1]){
// col.add(z);
bool = true;
System.out.print(row[1] + " "+ z );
break;
}
countr++;
}
}
}
if(!bool)
System.out.print(row[0] + " " + col[1]);
System.out.println();
}
//System.out.println("Hello World");
}
} | 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 11 | 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 | d0844eebcdea4d106d73608f0c55b68a | 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.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class _1607_E1 {
private static final FastScanner in = new FastScanner();
private static final PrintWriter out = new PrintWriter(System.out);
private static final PrintWriter err = new PrintWriter(System.err);
public static void solve() {
int n = in.nextInt();
int m = in.nextInt();
String commands = in.nextLine();
Robot r = new Robot(m, n);
for (char c : commands.toCharArray()) {
if (c == 'U') {
r.attempt(0, -1);
} else if (c == 'D') {
r.attempt(0, 1);
} else if (c == 'L') {
r.attempt(-1, 0);
} else if (c == 'R') {
r.attempt(1, 0);
}
if (r.isBroken()) {
break;
}
}
out.println(r.startY + " " + r.startX);
}
static class Robot {
final int boardX;
final int boardY;
int startX = 1;
int startY = 1;
int x = 1;
int y = 1;
int minX = 1;
int maxX = 1;
int minY = 1;
int maxY = 1;
private boolean isBroken = false;
Robot(int boardX, int boardY) {
this.boardX = boardX;
this.boardY = boardY;
}
public void attempt(int diffX, int diffY) {
int newX = x + diffX;
if (newX >= 1 && newX <= boardX) {
x = newX;
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
} else if (newX < 1) {
if (maxX < boardX) {
startX++;
minX++;
maxX++;
x++;
x = x + diffX;
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
} else {
isBroken = true;
}
} else if (newX > boardX) {
if (minX > 1) {
startX--;
minX--;
maxX--;
x--;
x = x + diffX;
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
} else {
isBroken = true;
}
}
int newY = y + diffY;
if (newY >= 1 && newY <= boardY) {
y = newY;
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
} else if (newY < 1) {
if (maxY < boardY) {
startY++;
minY++;
maxY++;
y++;
y = y + diffY;
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
} else {
isBroken = true;
}
} else if (newY > boardY) {
if (minY > 1) {
startY--;
minY--;
maxY--;
y--;
y = y + diffY;
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
} else {
isBroken = true;
}
}
}
public boolean isBroken() {
return isBroken;
}
}
// Boilerplate
public static void main(String[] args) {
int t = in.nextInt();
while (t-- > 0) {
solve();
}
err.close();
out.close();
}
@SuppressWarnings("unused")
static class FastScanner {
StringTokenizer tok = new StringTokenizer("");
BufferedReader in;
FastScanner() {
in = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (!tok.hasMoreElements()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tok.nextToken();
}
String nextLine() {
String line;
try {
line = in.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
List<Integer> nextIntegerList(int n) {
ArrayList<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(nextInt());
}
return list;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
List<Long> nextLongList(int n) {
ArrayList<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(nextLong());
}
return list;
}
ArrayList<Integer>[] nextGraph(int n, int m) {
@SuppressWarnings("unchecked")
ArrayList<Integer>[] adj = (ArrayList<Integer>[]) new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int v = nextInt();
int t = nextInt();
adj[v - 1].add(t - 1);
adj[t - 1].add(v - 1);
}
return adj;
}
}
} | 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 11 | 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 | 94653cab07ce5110a098968b4fbc288e | 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 static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
/**
*
* @Har_Har_Mahadev
*/
/**
* Main , Solution , Remove Public
*/
public class E {
public static void process() throws IOException {
int n = sc.nextInt(),m = sc.nextInt();
String s = sc.next();
int ansX = 0,ansY = 0;
int maxX = 0,minX = 0;
int maxY = 0,minY = 0;
int x = 0,y = 0;
for(int i =0; i<s.length(); i++) {
if(s.charAt(i) == 'R') {
y++;
if(y<m) {
maxX = max(maxX, x);
minX = min(minX, x);
maxY = max(maxY, y);
minY = min(minY, y);
continue;
}
y--;
if(minY > 0) {
minY--;
ansY--;
continue;
}
System.out.println((ansX+1)+" "+(ansY+1));
return;
}
if(s.charAt(i) == 'D') {
x++;
if(x<n) {
maxX = max(maxX, x);
minX = min(minX, x);
maxY = max(maxY, y);
minY = min(minY, y);
continue;
}
x--;
if(minX > 0) {
minX--;
ansX--;
continue;
}
System.out.println((ansX+1)+" "+(ansY+1));
return;
}
if(s.charAt(i) == 'L') {
y--;
if(y>=0) {
maxX = max(maxX, x);
minX = min(minX, x);
maxY = max(maxY, y);
minY = min(minY, y);
continue;
}
y++;
if(maxY<m-1) {
maxY++;
ansY++;
continue;
}
System.out.println((ansX+1)+" "+(ansY+1));
return;
}
if(s.charAt(i) == 'U') {
x--;
if(x>=0) {
maxX = max(maxX, x);
minX = min(minX, x);
maxY = max(maxY, y);
minY = min(minY, y);
continue;
}
x++;
if(maxX<n-1) {
maxX++;
ansX++;
continue;
}
System.out.println((ansX+1)+" "+(ansY+1));
return;
}
}
System.out.println((ansX+1)+" "+(ansY+1));
}
//=============================================================================
//--------------------------The End---------------------------------
//=============================================================================
private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353;
private static int N = 0;
private static void google(int tt) {
System.out.print("Case #" + (tt) + ": ");
}
static FastScanner sc;
static FastWriter out;
public static void main(String[] args) throws IOException {
boolean oj = true;
if (oj) {
sc = new FastScanner();
out = new FastWriter(System.out);
} else {
sc = new FastScanner("input.txt");
out = new FastWriter("output.txt");
}
long s = System.currentTimeMillis();
int t = 1;
t = sc.nextInt();
int TTT = 1;
while (t-- > 0) {
// google(TTT++);
process();
}
out.flush();
// tr(System.currentTimeMillis()-s+"ms");
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void tr(Object... o) {
if (!oj)
System.err.println(Arrays.deepToString(o));
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
/*
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair key = (Pair) o;
return x == key.x && y == key.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
*/
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long sqrt(long z) {
long sqz = (long) Math.sqrt(z);
while (sqz * 1L * sqz < z) {
sqz++;
}
while (sqz * 1L * sqz > z) {
sqz--;
}
return sqz;
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static long gcd(long a, long b) {
if (a > b)
a = (a + b) - (b = a);
if (a == 0L)
return b;
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int lower_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] > x) {
high = mid - 1;
} else {
ans = mid;
low = mid + 1;
}
}
return ans;
}
public static int upper_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = arr.length;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void reverseArray(int[] a) {
int n = a.length;
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long arr[] = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
//custom multiset (replace with HashMap if needed)
public static void push(TreeMap<Integer, Integer> map, int k, int v) {
//map[k] += v;
if (!map.containsKey(k))
map.put(k, v);
else
map.put(k, map.get(k) + v);
}
public static void pull(TreeMap<Integer, Integer> map, int k, int v) {
//assumes map[k] >= v
//map[k] -= v
int lol = map.get(k);
if (lol == v)
map.remove(k);
else
map.put(k, lol - v);
}
// compress Big value to Time Limit
public static int[] compress(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int boof = 1; //min value
for (int x : ls)
if (!map.containsKey(x))
map.put(x, boof++);
int[] brr = new int[arr.length];
for (int i = 0; i < arr.length; i++)
brr[i] = map.get(arr[i]);
return brr;
}
// Fast Writer
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE)
innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000)
return 10;
if (l >= 100000000)
return 9;
if (l >= 10000000)
return 8;
if (l >= 1000000)
return 7;
if (l >= 100000)
return 6;
if (l >= 10000)
return 5;
if (l >= 1000)
return 4;
if (l >= 100)
return 3;
if (l >= 10)
return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L)
return 19;
if (l >= 100000000000000000L)
return 18;
if (l >= 10000000000000000L)
return 17;
if (l >= 1000000000000000L)
return 16;
if (l >= 100000000000000L)
return 15;
if (l >= 10000000000000L)
return 14;
if (l >= 1000000000000L)
return 13;
if (l >= 100000000000L)
return 12;
if (l >= 10000000000L)
return 11;
if (l >= 1000000000L)
return 10;
if (l >= 100000000L)
return 9;
if (l >= 10000000L)
return 8;
if (l >= 1000000L)
return 7;
if (l >= 100000L)
return 6;
if (l >= 10000L)
return 5;
if (l >= 1000L)
return 4;
if (l >= 100L)
return 3;
if (l >= 10L)
return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map)
write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
// Fast Inputs
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[] readArray(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readArrayLong(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public int[][] readArrayMatrix(int N, int M, int Index) {
if (Index == 0) {
int[][] res = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
int[][] res = new int[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
public long[][] readArrayMatrixLong(int N, int M, int Index) {
if (Index == 0) {
long[][] res = new long[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = nextLong();
}
return res;
}
long[][] res = new long[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = 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[] readArrayDouble(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 11 | 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 | 3276b936e6492a080b85a001896cbe5b | 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 11 | 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 | 19a050b689c8eb1550ceb5923a109f03 | 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.lang.*;
import java.util.*;
public class ComdeFormces {
public static boolean gl;
public static ArrayList<Integer> anss;
public static int ans;
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
// Reader.init(System.in);
FastReader sc=new FastReader();
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
// OutputStream out = new BufferedOutputStream ( System.out );
int t=sc.nextInt();
int tc=1;
while(t--!=0) {
int n=sc.nextInt();
int m=sc.nextInt();
char a[]=sc.next().toCharArray();
int ai=1;
int aj=1;
int num=0;
int mx=Integer.MIN_VALUE;
for(int i=0;i<a.length;i++) {
if(a[i]=='L') {
num--;
if(num<0) {
if(mx==Integer.MIN_VALUE || mx+1<m) {
if(mx!=Integer.MIN_VALUE)mx+=1;
aj++;
num=0;
if(aj==m)break;
if(aj>m) {
aj--;
break;
}
}
else break;
}
}
if(a[i]=='R') {
num++;
mx=Math.max(mx, num);
if(num>=m)break;
}
}
num=0;
mx=Integer.MIN_VALUE;
for(int i=0;i<a.length;i++) {
if(a[i]=='U') {
num--;
if(num<0) {
if(mx==Integer.MIN_VALUE || mx+1<n) {
if(mx!=Integer.MIN_VALUE)mx+=1;
ai++;
num=0;
if(ai==n)break;
if(ai>n) {
ai--;
break;
}
}
else break;
}
}
if(a[i]=='D') {
num++;
mx=Math.max(mx, num);
if(num>=n)break;
}
}
log.write(ai+" "+aj+"\n");
log.flush();
}
}
public static class Node{
int data;
Node left,right;
public Node(int data) {
this.data=data;
this.left=this.right=null;
}
}
public static int dfs(ArrayList<ArrayList<Integer>> ar,int src, boolean vis[],int cnt[]) {
vis[src]=true;
for(int k:ar.get(src)) {
if(!vis[k]) {
cnt[src]+=dfs(ar,k,vis,cnt);
}
}
cnt[src]+=1;
return cnt[src];
}
public static int eval(ArrayList<ArrayList<Integer>> ar,int cnt[],int src,boolean vis[]) {
vis[src]=true;
int vl=-1;
int nd=-1;
int ch[]= {-1,-1};
int p=0;
for(int k:ar.get(src)) {
if(!vis[k]) {
ch[p++]=k;
}
}
if(ch[0]==-1 && ch[1]==-1)return 0;
int ans=0;
for(int i=0;i<2;i++) {
if(i==0) {
if(ch[1]==-1) {
ans+=cnt[ch[0]]-1;
return ans;
}
else {
ans=Math.max(ans, cnt[ch[1]]-1+eval(ar,cnt,ch[0],vis));
}
}
else {
ans=Math.max(ans, cnt[ch[0]]-1+eval(ar,cnt,ch[1],vis));
}
}
return ans;
}
public static void build(long a[][],long b[]) {
for(int i=0;i<b.length;i++) {
a[i][0]=b[i];
}
int jmp=2;
while(jmp<=b.length) {
for(int j=0;j<b.length;j++) {
int ind=(int)(Math.log(jmp/2)/Math.log(2));
int ind2=(int)(Math.log(jmp)/Math.log(2));
if(j+jmp-1<b.length) {
a[j][ind2]=Math.max(a[j][ind],a[j+(jmp/2)][ind]);
}
}
jmp*=2;
}
// for(int i=0;i<a.length;i++) {
// for(int j=0;j<33;j++) {
// System.out.print(a[i][j]+" ");
// }
// System.out.println();
// }
}
public static long serst(long a[][],int i,int j) {
int len=j-i+1;
int hp=1;
int tlen=len>>=1;
// System.out.println(tlen);
while(tlen!=0) {
tlen>>=1;
hp<<=1;
}
// System.out.println(hp);
int ind=(int)(Math.log(hp)/Math.log(2));
int i2=j+1-hp;
return Math.max(a[i][ind], a[i2][ind]);
}
static void update(int f[],int upd,int ind) {
int vl=ind;
while(vl<f.length) {
f[vl]+=upd;
int tp=~vl;
tp++;
tp&=vl;
vl+=tp;
}
}
static long ser(int f[],int ind) {
int vl=ind;
long sm=0;
while(vl!=0) {
sm+=f[vl];
int tp=~vl;
tp++;
tp&=vl;
vl-=tp;
}
return sm;
}
static int find(int el,int p[]) {
if(p[el]<0)return el;
return p[el]=find(p[el],p);
}
static boolean union(int a,int b,int p[]) {
int p1=find(a,p);
int p2=find(b,p);
if(p1>=0 && p1==p2)return false;
else {
if(p[p1]<p[p2]) {
p[p1]+=p[p2];
p[p2]=p1;
}
else {
p[p2]+=p[p1];
p[p1]=p2;
}
return true;
}
}
public static void radixSort(int a[]) {
int n=a.length;
int res[]=new int[n];
int p=1;
for(int i=0;i<=8;i++) {
int cnt[]=new int[10];
for(int j=0;j<n;j++) {
a[j]=res[j];
cnt[(a[j]/p)%10]++;
}
for(int j=1;j<=9;j++) {
cnt[j]+=cnt[j-1];
}
for(int j=n-1;j>=0;j--) {
res[cnt[(a[j]/p)%10]-1]=a[j];
cnt[(a[j]/p)%10]--;
}
p*=10;
}
}
static int bits(long n) {
int ans=0;
while(n!=0) {
if((n&1)==1)ans++;
n>>=1;
}
return ans;
}
public static int kadane(int a[]) {
int sum=0,mx=Integer.MIN_VALUE;
for(int i=0;i<a.length;i++) {
sum+=a[i];
mx=Math.max(mx, sum);
if(sum<0) sum=0;
}
return mx;
}
public static int m=(int)(1e9+7);
public static int mul(int a, int b) {
return ((a%m)*(b%m))%m;
}
public static long mul(long a, long b) {
return ((a%md)*(b%md))%md;
}
public static int add(int a, int b) {
return ((a%m)+(b%m))%m;
}
public static long add(long a, long b) {
return ((a%m)+(b%m))%m;
}
//debug
public static <E> void p(E[][] a,String s) {
System.out.println(s);
for(int i=0;i<a.length;i++) {
for(int j=0;j<a[0].length;j++) {
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
public static void p(int[] a,String s) {
System.out.print(s+"=");
for(int i=0;i<a.length;i++)System.out.print(a[i]+" ");
System.out.println();
}
public static void p(long[] a,String s) {
System.out.print(s+"=");
for(int i=0;i<a.length;i++)System.out.print(a[i]+" ");
System.out.println();
}
public static <E> void p(E a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(ArrayList<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(LinkedList<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(HashSet<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(Stack<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(Queue<E> a,String s){
System.out.println(s+"="+a);
}
//utils
static ArrayList<Integer> divisors(int n){
ArrayList<Integer> ar=new ArrayList<>();
for (int i=2; i<=Math.sqrt(n); i++){
if (n%i == 0){
if (n/i == i) {
ar.add(i);
}
else {
ar.add(i);
ar.add(n/i);
}
}
}
return ar;
}
static ArrayList<Integer> prime(int n){
ArrayList<Integer> ar=new ArrayList<>();
int cnt=0;
boolean pr=false;
while(n%2==0) {
ar.add(2);
n/=2;
}
for(int i=3;i*i<=n;i+=2) {
pr=false;
while(n%i==0) {
n/=i;
ar.add(i);
pr=true;
}
}
if(n>2) ar.add(n);
return ar;
}
static long gcd(long a,long b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static int gcd(int a,int b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static long factmod(long n,long mod,long img) {
if(n==0)return 1;
long ans=1;
long temp=1;
while(n--!=0) {
if(temp!=img) {
ans=((ans%mod)*((temp)%mod))%mod;
}
temp++;
}
return ans%mod;
}
static int ncr(int n, int r){
if(r>n-r)r=n-r;
int ans=1;
for(int i=0;i<r;i++){
ans*=(n-i);
ans/=(i+1);
}
return ans;
}
public static class trip{
double a;
int b;
int c;
public trip(double a,int b,int c) {
this.a=a;
this.b=b;
this.c=c;
}
// public int compareTo(trip q) {
// return this.b-q.b;
// }
}
static void mergesort(long[] a,int start,int end) {
if(start>=end)return ;
int mid=start+(end-start)/2;
mergesort(a,start,mid);
mergesort(a,mid+1,end);
merge(a,start,mid,end);
}
static void merge(long[] a, int start,int mid,int end) {
int ptr1=start;
int ptr2=mid+1;
long b[]=new long[end-start+1];
int i=0;
while(ptr1<=mid && ptr2<=end) {
if(a[ptr1]<a[ptr2]) {
b[i]=a[ptr1];
ptr1++;
i++;
}
else {
b[i]=a[ptr2];
ptr2++;
i++;
}
}
while(ptr1<=mid) {
b[i]=a[ptr1];
ptr1++;
i++;
}
while(ptr2<=end) {
b[i]=a[ptr2];
ptr2++;
i++;
}
for(int j=start;j<=end;j++) {
a[j]=b[j-start];
}
}
public static class FastReader {
BufferedReader b;
StringTokenizer s;
public FastReader() {
b=new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(s==null ||!s.hasMoreElements()) {
try {
s=new StringTokenizer(b.readLine());
}
catch(IOException e) {
e.printStackTrace();
}
}
return s.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str="";
try {
str=b.readLine();
}
catch(IOException e) {
e.printStackTrace();
}
return str;
}
boolean hasNext() {
if (s != null && s.hasMoreTokens()) {
return true;
}
String tmp;
try {
b.mark(1000);
tmp = b.readLine();
if (tmp == null) {
return false;
}
b.reset();
} catch (IOException e) {
return false;
}
return true;
}
}
public static class pair{
int a;
int b;
public pair(int a,int b) {
this.a=a;
this.b=b;
}
// public int compareTo(pair b) {
// return this.a-b.a;
//
// }
// // public int compareToo(pair b) {
// return this.b-b.b;
// }
@Override
public String toString() {
return "{"+this.a+" "+this.b+"}";
}
}
static long pow(long a, long pw) {
long temp;
if(pw==0)return 1;
temp=pow(a,pw/2);
if(pw%2==0)return temp*temp;
return a*temp*temp;
}
public static int md=998244353;
static long mpow(long a, long pw) {
long temp;
if(pw==0)return 1;
temp=pow(a,pw/2)%md;
if(pw%2==0)return mul(temp,temp);
return mul(a,mul(temp,temp));
}
static int pow(int a, int pw) {
int temp;
if(pw==0)return 1;
temp=pow(a,pw/2);
if(pw%2==0)return temp*temp;
return a*temp*temp;
}
} | Java | ["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 11 | 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 | 3c22e29652ac7949d9d9ac955ed5bc69 | 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.util.Map.Entry;
import java.math.*;
import java.sql.Array;
public class Simple{
public static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
public int compareTo(Pair other){
return (int) (this.y - other.y);
}
public boolean equals(Pair other){
if(this.x == other.x && this.y == other.y)return true;
return false;
}
public int hashCode(){
return 31*x + y;
}
// @Override
// public int compareTo(Simple.Pair o) {
// // TODO Auto-generated method stub
// return 0;
// }
}
static int power(int x, int y, int p)
{
// Initialize result
int res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
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 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;
}
static int nCrModp(int n, int r, int p)
{
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int C[] = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
public static class Node{
int root;
ArrayList<Node> al;
Node par;
public Node(int root,ArrayList<Node> al,Node par){
this.root = root;
this.al = al;
this.par = par;
}
}
// public static int helper(int arr[],int n ,int i,int j,int dp[][]){
// if(i==0 || j==0)return 0;
// if(dp[i][j]!=-1){
// return dp[i][j];
// }
// if(helper(arr, n, i-1, j-1, dp)>=0){
// return dp[i][j]=Math.max(helper(arr, n, i-1, j-1,dp)+arr[i-1], helper(arr, n, i-1, j,dp));
// }
// return dp[i][j] = helper(arr, n, i-1, j,dp);
// }
// public static void dfs(ArrayList<ArrayList<Integer>> al,int levelcount[],int node,int count){
// levelcount[count]++;
// for(Integer x : al.get(node)){
// dfs(al, levelcount, x, count+1);
// }
// }
public static long __gcd(long a, long b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
public static long helper(int arr1[][],int m){
Arrays.sort(arr1, (int a[],int b[])-> a[0]-b[0]);
long ans =0;
for(int i=1;i<m;i++){
long count =0;
for(int j=0;j<i;j++){
if(arr1[i][1] > arr1[j][1])count++;
}
ans+=count;
}
return ans;
}
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int t =s.nextInt();
for(int t1 = 1;t1<=t;t1++){
// System.out.println("OUT");
int n = s.nextInt();
int m = s.nextInt();
String str = s.next();
int len = str.length();
int minx = 1;
int maxx = 1;
int miny = 1;
int maxy = 1;
int x = 1,y=1;
int ansx = 1;
int ansy = 1;
// int g =0 ;
for(int i=0;i<len;i++){
char c = str.charAt(i);
// g++;
if(c=='R')x++;
if(c=='L')x--;
if(c=='U')y--;
if(c=='D')y++;
minx = Math.min(x, minx);
miny = Math.min(y, miny);
maxx = Math.max(maxx, x);
maxy = Math.max(maxy, y);
// System.out.println(maxx - minx);
if(maxx-minx==m || maxy-miny==n)break;
// System.out.println("hello");
ansx = 1 + (1-minx);
ansy = 1 + (1-miny);
}
// System.out.println(g);
System.out.println(ansy+" "+ansx);
}
}
}
/*
4 2 2 7
0 2 5
-2 3
5
0*x1 + 1*x2 + 2*x3 + 3*x4
*/ | 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 11 | 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 | 49b6771c3718e72cd001cc0016d42f0f | 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 Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int tt = in.nextInt();
while (tt-- > 0) {
int n = in.nextInt();
int m = in.nextInt();
String s;
s = in.next();
int x = 0, y = 0, mx = 0, mxn = 0, my = 0, myn = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'R') {
mx = Math.max(++x, mx);
} else if (s.charAt(i) == 'L') {
mxn = Math.min(--x, mxn);
} else if (s.charAt(i) == 'U') {
myn = Math.min(--y, myn);
} else if (s.charAt(i) == 'D') {
my = Math.max(++y, my);
}
if (mx - mxn >= m) {
if (x == mxn) mxn++;
break;
}
if (my - myn >= n) {
if (y == myn) myn++;
break;
}
}
int ans1 = 1 - myn;
int ans2 = 1 - mxn;
System.out.println(ans1 + " " + ans2);
}
}
} | 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 11 | 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 | 2bdf8211d2e896087fd13b6954454d3b | 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.StringTokenizer;
public class E {
static FastReader reader = new FastReader();
static OutputWriter out = new OutputWriter(System.out);
public static void main(String[] args) {
int tests = reader.nextInt();
for (int test = 1; test <= tests; test++) {
int n = reader.nextInt();
int m = reader.nextInt();
char[] arr = reader.next().toCharArray();
int maxH = 0;
int minH = 0;
int minV = 0;
int maxV = 0;
int curH = 0;
int curV = 0;
int answerX = 1;
int answerY = 1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 'L') {
curH--;
} else if (arr[i] == 'R') {
curH++;
} else if(arr[i] == 'U') {
curV++;
} else {
curV--;
}
if (curH < 0) minH = Math.min(minH, curH);
if (curH > 0) maxH = Math.max(maxH, curH);
if (curV < 0) minV = Math.min(curV, minV);
if (curV > 0) maxV = Math.max(curV, maxV);
if (maxH - minH <= m - 1 && maxV - minV <= n - 1) {
answerX = 1 + Math.abs(minH);
answerY = 1 + Math.abs(minV);
} else {
break;
}
}
out.println(n - (answerY - 1), answerX);
}
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 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(char[] array) {
writer.print(array);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(double[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void println(int[] array) {
print(array);
writer.println();
}
public void println(double[] array) {
print(array);
writer.println();
}
public void println(long[] array) {
print(array);
writer.println();
}
public void println() {
writer.println();
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void print(char i) {
writer.print(i);
}
public void println(char i) {
writer.println(i);
}
public void println(char[] array) {
writer.println(array);
}
public void printf(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
public void print(long i) {
writer.print(i);
}
public void println(long i) {
writer.println(i);
}
public void print(int i) {
writer.print(i);
}
public void println(int i) {
writer.println(i);
}
public void separateLines(int[] array) {
for (int i : array) {
println(i);
}
}
}
}
| 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 11 | 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 | f4fed4766a0afd8d3d4100cac63c8fa4 | 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 A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder str = new StringBuilder();
int t = sc.nextInt();
for (int xx = 0; xx < t; xx++) {
int n = sc.nextInt();
int m = sc.nextInt();
String s = sc.next();
int rMin = 0;
int rMax = 0;
int cMin = 0;
int cMax = 0;
int r = 0;
int c = 0;
int ansR = 1 - rMin;
int ansC = 1 - cMin;
for (int i = 0; i < s.length(); i++) {
char d = s.charAt(i);
if (d == 'U') {
r--;
} else if (d == 'D') {
r++;
} else if (d == 'L') {
c--;
} else {
c++;
}
rMin = Math.min(rMin, r);
rMax = Math.max(rMax, r);
cMin = Math.min(cMin, c);
cMax = Math.max(cMax, c);
if (rMax - rMin + 1 > n || cMax - cMin + 1 > m) {
break;
}
ansR = 1 - rMin;
ansC = 1 - cMin;
}
str.append(ansR + " " + ansC+"\n");
}
System.out.print(str);
sc.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 11 | 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 | f01525fd5c5f02afd7a6dc577792319c | 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 | // "static void main" must be defined in a public class.
import java.util.*;
import java.io.*;
public class Main {
static int k=0;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
try{
FastReader sc = new FastReader();
StringBuilder str = new StringBuilder();int t=sc.nextInt();
while(t-->0)
{
long n=sc.nextInt();
long m=sc.nextInt();
String s=sc.nextLine();
char ch[]=s.toCharArray();
int l=0;int r=0;int u=0;int d=0;int lm=0;int lmi=0;int um=0;int umi=0;
int x=0;int y=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]=='L')
{
x--;
if(x<lmi)
{
lmi=x;
l++;
}
}
else if(ch[i]=='R')
{
x++;
if(x>lm)
{
lm=x;
r++;
}
}
else if(ch[i]=='U')
{
y++;
if(y>um)
{
um=y;
u++;
}
}
else
{
y--;
if(y<umi)
{
umi=y;
d++;
}
}
}
x=0;y=0;
if(l+r==0)
{
x=1;
}
else if(l+r+1<=m)
{
x=l+1;
}
else
{
int minx=0;int maxx=0;
for(int i=0;i<ch.length;i++)
{
if((maxx-minx)==m-1)
{
break;
}
if(ch[i]=='L')
{
x--;
if(x<minx)
{
minx=x;
}
}
else if(ch[i]=='R')
{
x++;
if(x>maxx)
{
maxx=x;
}
}
}
x=(int)m-maxx;
}
if(u+d==0)
{
y=1;
}
else if(u+d+1<=n)
{
y=u+1;
}
else
{
int miny=0;int maxy=0;
for(int i=0;i<ch.length;i++)
{
if((maxy-miny)==n-1)
{
break;
}
if(ch[i]=='D')
{
y--;
if(y<miny)
{
miny=y;
}
}
else if(ch[i]=='U')
{
y++;
if(y>maxy)
{
maxy=y;
}
}
}
y=maxy+1;
}
//System.out.println(l+" "+r+" "+u+" "+d+" dsfdsfs"+" "+" "+n+" "+m);
System.out.println(y+" "+x);
}
// System.out.println(str.toString());
}
catch(Exception e)
{
System.out.println("sdf");
}
}
} | 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 11 | 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 | abfc3278a5ce75de83258f45266040bc | 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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
/**
* @author Mubtasim Shahriar
*/
public class RobotOnTheBoard {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
int t = sc.nextInt();
// int t = 1;
while (t-- != 0) {
solver.solve(sc, out);
}
out.close();
}
static class Solver {
public void solve(InputReader sc, PrintWriter out) {
int n = sc.nextInt();
int m = sc.nextInt();
char[] seq = sc.next().toCharArray();
int sl = seq.length;
int[] up = new int[sl];
int[] dn = new int[sl];
int[] lt = new int[sl];
int[] rt = new int[sl];
int leftright = 0;
int updn = 0;
for (int i = 0; i < sl; i++) {
char c = seq[i];
if(c=='L') {
leftright--;
}
else if(c=='R') {
leftright++;
}
else if(c=='D') {
updn++;
}
else {
updn--;
}
if(i==0) up[i] = Math.min(0,updn);
else up[i] = Math.min(up[i-1],updn);
if(i==0) dn[i] = Math.max(0,updn);
else dn[i] = Math.max(dn[i-1],updn);
if(i==0) rt[i] = Math.max(0,leftright);
else rt[i] = Math.max(rt[i-1],leftright);
if(i==0) lt[i] = Math.min(0,leftright);
else lt[i] = Math.min(lt[i-1],leftright);
}
int max = -1;
int ansx = 1;
int ansy = 1;
for(int i = 0; i < sl; i++) {
if(dn[i]-up[i]+1<=n && -lt[i]+rt[i]+1<=m) {
max = i;
ansx = Math.max(ansx,Math.abs(up[i])+1);
ansy = Math.max(ansy,Math.abs(lt[i])+1);
} else break;
}
// out.println(max+1);
out.println(ansx + " " + ansy);
}
}
static void sort(int[] arr) {
ArrayList<Integer> al = new ArrayList();
for (int i : arr) al.add(i);
Collections.sort(al);
int idx = 0;
for (int i : al) arr[idx++] = i;
}
static void sort(long[] arr) {
ArrayList<Long> al = new ArrayList();
for (long i : arr) al.add(i);
Collections.sort(al);
int idx = 0;
for (long i : al) arr[idx++] = i;
}
static void sortDec(int[] arr) {
ArrayList<Integer> al = new ArrayList();
for (int i : arr) al.add(i);
Collections.sort(al, Collections.reverseOrder());
int idx = 0;
for (int i : al) arr[idx++] = i;
}
static void sortDec(long[] arr) {
ArrayList<Long> al = new ArrayList();
for (long i : arr) al.add(i);
Collections.sort(al, Collections.reverseOrder());
int idx = 0;
for (long i : al) arr[idx++] = i;
}
static class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int array[] = nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n) {
int[] array = new int[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] nextSumLongArray(int n) {
long[] array = new long[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextSortedLongArray(int n) {
long array[] = nextLongArray(n);
Arrays.sort(array);
return array;
}
}
}
| 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 11 | 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 | 1e58d7558b31d0482bbb9c2f9e51c0dc | 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 E {
public static void main(String[] args) {
FastScanner fs = new FastScanner();
int t = fs.nextInt();
StringBuilder st = new StringBuilder();
for (int tt = 0; tt < t; tt++) {
int cnt = 1;
int cnt2 = 1;
int n = fs.nextInt();
int m = fs.nextInt();
String s = fs.next();
int row = 0;
int col = 0;
int l = 0;
int r = 0;
int u = 0;
int d = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == 'U') {
row--;
u = Math.min(u, row);
} else if (c == 'D') {
row++;
d = Math.max(d, row);
} else if (c == 'L') {
col--;
l = Math.min(l, col);
} else {
col++;
r = Math.max(r, col);
}
if (r - l + 1 <= m && d - u + 1 <= n) {
if (l < 0) {
cnt = Math.abs(l) + 1;
} else {
cnt = 1;
}
if (u < 0) {
cnt2 = Math.abs(u) + 1;
} else {
cnt2 = 1;
}
} else {
break;
}
}
System.out.println(cnt2 + " " + cnt);
}
}
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());
}
}
} | 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 11 | 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 | 25098875a897feb93069b0f5aeba4514 | 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 currentContest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.StringTokenizer;
public class P1 {
public static boolean isreq(String s) {
int flag=0;
for(int i=1;i<s.length();i++) {
if(s.charAt(i)!=s.charAt(i-1)) {
flag++;
}
}
if(flag%2==0) {
return true;
}else {
return false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader sc = new FastReader();
int t = sc.nextInt();;
StringBuilder st = new StringBuilder();
while (t-- != 0) {
int n=sc.nextInt();
int m=sc.nextInt();
String c=sc.nextLine();
int maxx=0;
int maxy=0;
int minx=0;
int miny=0;
int ix=0;
int iy=0;
int ansx=0;
int ansy=0;
for(int i=0;i<c.length();i++) {
if(c.charAt(i)=='L') {
ix=ix-1;
}else if(c.charAt(i)=='R') {
ix=ix+1;
}else if(c.charAt(i)=='U') {
iy=iy-1;
}else {
iy=iy+1;
}
maxx=Math.max(maxx, ix);
maxy=Math.max(maxy, iy);
minx=Math.min(minx, ix);
miny=Math.min(miny, iy);
if(minx<0) {
int tomove=Math.abs(minx);
if(tomove+maxx<m) {
ansx=ansx+tomove;
ix=ix+tomove;
minx=0;
maxx=maxx+tomove;
}else {
break;
}
}
if(miny<0) {
int tomove=Math.abs(miny);
if(tomove+maxy<n) {
ansy=ansy+tomove;
iy=iy+tomove;
miny=0;
maxy=maxy+tomove;
}else {
break;
}
}
if(maxx>=m) {
break;
}
if(maxy>=n) {
break;
}
//System.out.println(ansx+" "+ansy);
}
st.append((ansy+1)+" "+(ansx+1)+"\n");
}
System.out.println(st);
}
static FastReader sc = new FastReader();
public static void solvegraph() {
int n = sc.nextInt();
int edge[][] = new int[n - 1][2];
for (int i = 0; i < n - 1; i++) {
edge[i][0] = sc.nextInt() - 1;
edge[i][1] = sc.nextInt() - 1;
}
ArrayList<ArrayList<Integer>> ad = new ArrayList<>();
for (int i = 0; i < n; i++) {
ad.add(new ArrayList<Integer>());
}
for (int i = 0; i < n - 1; i++) {
ad.get(edge[i][0]).add(edge[i][1]);
ad.get(edge[i][1]).add(edge[i][0]);
}
int parent[] = new int[n];
Arrays.fill(parent, -1);
parent[0] = n;
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(0);
int child[] = new int[n];
Arrays.fill(child, 0);
ArrayList<Integer> lv = new ArrayList<Integer>();
while (!queue.isEmpty()) {
int toget = queue.getFirst();
queue.removeFirst();
child[toget] = ad.get(toget).size() - 1;
for (int i = 0; i < ad.get(toget).size(); i++) {
if (parent[ad.get(toget).get(i)] == -1) {
parent[ad.get(toget).get(i)] = toget;
queue.addLast(ad.get(toget).get(i));
}
}
lv.add(toget);
}
child[0]++;
}
static void sort(int[] A) {
int n = A.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
int tmp = A[i];
int randomPos = i + rnd.nextInt(n - i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static void sort(long[] A) {
int n = A.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
long tmp = A[i];
int randomPos = i + rnd.nextInt(n - i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static String sort(String s) {
Character ch[] = new Character[s.length()];
for (int i = 0; i < s.length(); i++) {
ch[i] = s.charAt(i);
}
Arrays.sort(ch);
StringBuffer st = new StringBuffer("");
for (int i = 0; i < s.length(); i++) {
st.append(ch[i]);
}
return st.toString();
}
public static long gcd(long a, long b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["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 11 | 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 | 8d437d7d536c105227ba12bbbad72b4d | 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.text.DecimalFormat;
import java.util.*;
public class Main
{
static class Pair
{
long a,b;
public Pair(long a,long b)
{
this.a=a;
this.b=b;
}
// @Override
// public int compareTo(Pair p) {
// return Long.compare(l, p.l);
// }
}
static final int INF = 1 << 30;
static final long INFL = 1L << 60;
static final long NINF = INFL * -1;
static final long mod = (long) 1e9 + 7;
static final long mod2 = 998244353;
static DecimalFormat df = new DecimalFormat("0.00000000000000");
public static final double PI = 3.141592653589793d, eps = 1e-9;
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC
{
public static void solve(int testNumber, InputReader in, OutputWriter out)
{
int t = in.ni();
//int t=1;
while (t-->0)
{
int n=in.ni();
int m=in.ni();
char[] ch=in.ns().toCharArray();
int l=0,r=0,u=0,d=0;
int h=0,v=0;
int x=1,y=1;
for(int i=0;i<ch.length;i++)
{
if(ch[i]=='U')
{
--v;
u=Math.min(u,v);
}
else if(ch[i]=='D')
{
++v;
d=Math.max(d,v);
}
else if(ch[i]=='L')
{
--h;
l=Math.min(l,h);
}
else
{
++h;
r=Math.max(r,h);
}
//out.printLine(l+" "+r+" "+u+" "+d);
if((d-u)<n && (r-l)<m)
{
x=1-l;
y=1-u;
}
}
out.printLine((y)+" "+(x));
}
}
}
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 ni() {
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;
}
private char nc() { return (char)skip(); }
public int[] na(int arraySize) {
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = ni();
}
return array;
}
private int skip() {
int b;
while ((b = read()) != -1 && isSpaceChar(b)) ;
return b;
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = read();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
int[][] nim(int h, int w) {
int[][] a = new int[h][w];
for (int i = 0; i < h; i++) {
a[i] = na(w);
}
return a;
}
long[][] nlm(int h, int w) {
long[][] a = new long[h][w];
for (int i = 0; i < h; i++) {
a[i] = nla(w);
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isNewLine(int c) {
return c == '\n';
}
public String nextLine() {
int c = read();
StringBuilder result = new StringBuilder();
do {
result.appendCodePoint(c);
c = read();
} while (!isNewLine(c));
return result.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
long result = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
result *= 10;
result += c & 15;
c = read();
} while (!isSpaceChar(c));
return result * sign;
}
public long[] nla(int arraySize) {
long array[] = new long[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextLong();
}
return array;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = (byte) read();
while (c <= ' ') {
c = (byte) read();
}
boolean neg = (c == '-');
if (neg) {
c = (byte) read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = (byte) read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = (byte) read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
public static class CP {
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n == 2 || n == 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; (long) i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
public static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static long pow(long a, long n, long mod) {
// a %= mod;
long ret = 1;
int x = 63 - Long.numberOfLeadingZeros(n);
for (; x >= 0; x--) {
ret = ret * ret % mod;
if (n << 63 - x < 0)
ret = ret * a % mod;
}
return ret;
}
public static boolean isComposite(long n) {
if (n < 2)
return true;
if (n == 2 || n == 3)
return false;
if (n % 2 == 0 || n % 3 == 0)
return true;
for (long i = 6L; i * i <= n; i += 6)
if (n % (i - 1) == 0 || n % (i + 1) == 0)
return true;
return false;
}
static int ifnotPrime(int[] prime, int x) {
return (prime[x / 64] & (1 << ((x >> 1) & 31)));
}
static int log2(long n) {
return (int) (Math.log10(n) / Math.log10(2));
}
static void makeComposite(int[] prime, int x) {
prime[x / 64] |= (1 << ((x >> 1) & 31));
}
public static String swap(String a, int i, int j) {
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
static void reverse(long arr[]){
int l = 0, r = arr.length-1;
while(l<r){
long temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
static void reverse(int arr[]){
int l = 0, r = arr.length-1;
while(l<r){
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
public static int[] sieveEratosthenes(int n) {
if (n <= 32) {
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int i = 0; i < primes.length; i++) {
if (n < primes[i]) {
return Arrays.copyOf(primes, i);
}
}
return primes;
}
int u = n + 32;
double lu = Math.log(u);
int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];
ret[0] = 2;
int pos = 1;
int[] isnp = new int[(n + 1) / 32 / 2 + 1];
int sup = (n + 1) / 32 / 2 + 1;
int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int tp : tprimes) {
ret[pos++] = tp;
int[] ptn = new int[tp];
for (int i = (tp - 3) / 2; i < tp << 5; i += tp)
ptn[i >> 5] |= 1 << (i & 31);
for (int j = 0; j < sup; j += tp) {
for (int i = 0; i < tp && i + j < sup; i++) {
isnp[j + i] |= ptn[i];
}
}
}
// 3,5,7
// 2x+3=n
int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4,
13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14};
int h = n / 2;
for (int i = 0; i < sup; i++) {
for (int j = ~isnp[i]; j != 0; j &= j - 1) {
int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];
int p = 2 * pp + 3;
if (p > n)
break;
ret[pos++] = p;
if ((long) p * p > n)
continue;
for (int q = (p * p - 3) / 2; q <= h; q += p)
isnp[q >> 5] |= 1 << q;
}
}
return Arrays.copyOf(ret, pos);
}
static long digit(long s) {
long brute = 0;
while (s > 0) {
brute+=s%10;
s /= 10;
}
return brute;
}
public static int[] primefacts(int n, int[] primes) {
int[] ret = new int[15];
int rp = 0;
for (int p : primes) {
if (p * p > n) break;
int i;
for (i = 0; n % p == 0; n /= p, i++) ;
if (i > 0) ret[rp++] = p;
}
if (n != 1) ret[rp++] = n;
return Arrays.copyOf(ret, rp);
}
static ArrayList<Integer> bitWiseSieve(int n) {
ArrayList<Integer> al = new ArrayList<>();
int prime[] = new int[n / 64 + 1];
for (int i = 3; i * i <= n; i += 2) {
if (ifnotPrime(prime, i) == 0)
for (int j = i * i, k = i << 1;
j < n; j += k)
makeComposite(prime, j);
}
al.add(2);
for (int i = 3; i <= n; i += 2)
if (ifnotPrime(prime, i) == 0)
al.add(i);
return al;
}
public static long[] sort(long arr[]) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list);
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static long[] revsort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static int[] revsort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static ArrayList<Integer> reverse(
ArrayList<Integer> data,
int left, int right)
{
// Reverse the sub-array
while (left < right)
{
int temp = data.get(left);
data.set(left++,
data.get(right));
data.set(right--, temp);
}
// Return the updated array
return data;
}
static ArrayList<Integer> sieve(long size) {
ArrayList<Integer> pr = new ArrayList<Integer>();
boolean prime[] = new boolean[(int) size];
for (int i = 2; i < prime.length; i++) prime[i] = true;
for (int i = 2; i * i < prime.length; i++) {
if (prime[i]) {
for (int j = i * i; j < prime.length; j += i) {
prime[j] = false;
}
}
}
for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i);
return pr;
}
static boolean[] sieve1(long size) {
ArrayList<Integer> pr = new ArrayList<Integer>();
boolean prime[] = new boolean[(int) size];
for (int i = 2; i < prime.length; i++) prime[i] = true;
for (int i = 2; i * i < prime.length; i++) {
if (prime[i]) {
for (int j = i * i; j < prime.length; j += i) {
prime[j] = false;
}
}
}
//for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i);
return prime;
}
static ArrayList<Integer> segmented_sieve(int l, int r, ArrayList<Integer> primes) {
ArrayList<Integer> al = new ArrayList<>();
if (l == 1) ++l;
int max = r - l + 1;
int arr[] = new int[max];
for (int p : primes) {
if (p * p <= r) {
int i = (l / p) * p;
if (i < l) i += p;
for (; i <= r; i += p) {
if (i != p) {
arr[i - l] = 1;
}
}
}
}
for (int i = 0; i < max; ++i) {
if (arr[i] == 0) {
al.add(l + i);
}
}
return al;
}
static boolean isfPrime(long n, int iteration) {
if (n == 0 || n == 1)
return false;
if (n == 2)
return true;
if (n % 2 == 0)
return false;
Random rand = new Random();
for (int i = 0; i < iteration; i++) {
long r = Math.abs(rand.nextLong());
long a = r % (n - 1) + 1;
if (modPow(a, n - 1, n) != 1)
return false;
}
return true;
}
static long modPow(long a, long b, long c) {
long res = 1;
for (int i = 0; i < b; i++) {
res *= a;
res %= c;
}
return res % c;
}
private static long binPower(long a, long l, long mod) {
long res = 0;
while (l > 0) {
if ((l & 1) == 1) {
res = mulmod(res, a, mod);
l >>= 1;
}
a = mulmod(a, a, mod);
}
return res;
}
private static long mulmod(long a, long b, long c) {
long x = 0, y = a % c;
while (b > 0) {
if (b % 2 == 1) {
x = (x + y) % c;
}
y = (y * 2L) % c;
b /= 2;
}
return x % c;
}
static long binary_Expo(long a, long b) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res *= a;
--b;
}
a *= a;
b /= 2;
}
return res;
}
static void swap(int a, int b) {
int tp = b;
b = a;
a = tp;
}
static long Modular_Expo(long a, long b, long mod) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res = (res * a) % mod;
--b;
}
a = (a * a) % mod;
b /= 2;
}
return res % mod;
}
static int i_gcd(int a, int b) {
while (true) {
if (b == 0)
return a;
int c = a;
a = b;
b = c % b;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long ceil_div(long a, long b) {
return (a + b - 1) / b;
}
static int getIthBitFromInt(int bits, int i) {
return (bits >> (i - 1)) & 1;
}
static long getIthBitFromLong(long bits, int i) {
return (bits >> (i - 1)) & 1;
}
// static boolean isPerfectSquare(long a, long b)
// {
// long sq=Math.sqrt()
// }
private static TreeMap<Long, Long> primeFactorize(long n) {
TreeMap<Long, Long> pf = new TreeMap<>(Collections.reverseOrder());
long cnt = 0;
long total = 1;
for (long i = 2; (long) i * i <= n; ++i) {
if (n % i == 0) {
cnt = 0;
while (n % i == 0) {
++cnt;
n /= i;
}
pf.put(cnt, i);
//total*=(cnt+1);
}
}
if (n > 1) {
pf.put(1L, n);
//total*=2;
}
return pf;
}
//less than or equal
private static int lower_bound(ArrayList<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;
hi = mid - 1;
} else {
lo = 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(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;
}
// ==================== LIS & LNDS ================================
private static int[] LIS(long arr[], int n) {
List<Long> list = new ArrayList<>();
int[] cnt=new int[n];
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]);
cnt[i]=list.size();
}
return cnt;
}
private static int find1(List<Long> list, long 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;
}
private static long nCr(long n, long r,long mod) {
if (n - r > r)
r = n - r;
long ans = 1L;
for (long i = r + 1; i <= n; i++)
ans = (ans%mod*i%mod)%mod;
for (long i = 2; i <= n - r; i++)
ans /= i;
return ans%mod;
}
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;
}
static ArrayList<StringBuilder> permutations(StringBuilder s)
{
int n=s.length();
ArrayList<StringBuilder> al=new ArrayList<>();
getpermute(s,al,0,n);
return al;
}
// static String longestPalindrome(String s)
// {
// int st=0,ans=0,len=0;
//
//
// }
static void getpermute(StringBuilder s,ArrayList<StringBuilder> al,int l, int r)
{
if(l==r)
{
al.add(s);
return;
}
for(int i=l+1;i<r;++i)
{
char c=s.charAt(i);
s.setCharAt(i,s.charAt(l));
s.setCharAt(l,c);
getpermute(s,al,l+1,r);
c=s.charAt(i);
s.setCharAt(i,s.charAt(l));
s.setCharAt(l,c);
}
}
static void initStringHash(String s,long[] dp,long[] inv,long p)
{
long pow=1;
inv[0]=1;
int n=s.length();
dp[0]=((s.charAt(0)-'a')+1);
for(int i=1;i<n;++i)
{
pow=(pow*p)%mod;
dp[i]=(dp[i-1]+((s.charAt(i)-'a')+1)*pow)%mod;
inv[i]=CP.modinv(pow,mod)%mod;
}
}
static long getStringHash(long[] dp,long[] inv,int l,int r)
{
long ans=dp[r];
if(l-1>=0)
{
ans-=dp[l-1];
}
ans=(ans*inv[l])%mod;
return ans;
}
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();
}
static boolean isSquarefactor(int x, int factor, int target) {
int s = (int) Math.round(Math.sqrt(x));
return factor * s * s == target;
}
static boolean isSquare(long x) {
long s = (long) Math.round(Math.sqrt(x));
return x * x == s;
}
static int bs(ArrayList<Integer> al, int val) {
int l = 0, h = al.size() - 1, mid = 0, ans = -1;
while (l <= h) {
mid = (l + h) >> 1;
if (al.get(mid) == val) {
return mid;
} else if (al.get(mid) > val) {
h = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
static void sort(int a[]) // heap sort
{
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 0; i < a.length; i++)
q.add(a[i]);
for (int i = 0; i < a.length; i++)
a[i] = q.poll();
}
static void shuffle(int[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * in.length);
fast_swap(in, idx, i);
}
}
public static int[] radixSort2(int[] a) {
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for (int v : a) {
c0[(v & 0xff) + 1]++;
c1[(v >>> 8 & 0xff) + 1]++;
c2[(v >>> 16 & 0xff) + 1]++;
c3[(v >>> 24 ^ 0x80) + 1]++;
}
for (int i = 0; i < 0xff; i++) {
c0[i + 1] += c0[i];
c1[i + 1] += c1[i];
c2[i + 1] += c2[i];
c3[i + 1] += c3[i];
}
int[] t = new int[n];
for (int v : a) t[c0[v & 0xff]++] = v;
for (int v : t) a[c1[v >>> 8 & 0xff]++] = v;
for (int v : a) t[c2[v >>> 16 & 0xff]++] = v;
for (int v : t) a[c3[v >>> 24 ^ 0x80]++] = v;
return a;
}
static int[] computeLps(String pat) {
int len = 0, i = 1, m = pat.length();
int lps[] = new int[m];
lps[0] = 0;
while (i < m) {
if (pat.charAt(i) == pat.charAt(len)) {
++len;
lps[i] = len;
++i;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = len;
++i;
}
}
}
return lps;
}
static ArrayList<Integer> kmp(String s, String pat) {
ArrayList<Integer> al = new ArrayList<>();
int n = s.length(), m = pat.length();
int lps[] = computeLps(pat);
int i = 0, j = 0;
while (i < n) {
if (s.charAt(i) == pat.charAt(j)) {
i++;
j++;
if (j == m) {
al.add(i - j);
j = lps[j - 1];
}
} else {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return al;
}
static void reverse_ruffle_sort(int a[]) {
shuffle(a);
Arrays.sort(a);
for (int l = 0, r = a.length - 1; l < r; ++l, --r)
fast_swap(a, l, r);
}
static void ruffle_sort(int a[]) {
shuffle(a);
Arrays.sort(a);
}
static int getMax(int arr[], int n) {
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
static ArrayList<Long> primeFact(long n) {
ArrayList<Long> al = new ArrayList<>();
al.add(1L);
while (n % 2 == 0) {
if (!al.contains(2L)) {
al.add(2L);
}
n /= 2L;
}
for (long i = 3; (long) i * i <= n; i += 2) {
while ((n % i == 0)) {
if (!al.contains((long) i)) {
al.add((long) i);
}
n /= i;
}
}
if (n > 2) {
if (!al.contains(n)) {
al.add(n);
}
}
return al;
}
public static long totFact(long n) {
long cnt = 0, tot = 1;
while (n % 2 == 0) {
n /= 2;
++cnt;
}
tot *= (cnt + 1);
for (int i = 3; i <= Math.sqrt(n); i += 2) {
cnt = 0;
while (n % i == 0) {
n /= i;
++cnt;
}
tot *= (cnt + 1);
}
if (n > 2) {
tot *= 2;
}
return tot;
}
static int[] z_function(String s) {
int n = s.length(), z[] = new int[n];
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = Math.min(z[i - l], r - i + 1);
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))
++z[i];
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
static void fast_swap(int[] a, int idx1, int idx2) {
if (a[idx1] == a[idx2])
return;
a[idx1] ^= a[idx2];
a[idx2] ^= a[idx1];
a[idx1] ^= a[idx2];
}
public static void fast_sort(long[] array) {
ArrayList<Long> copy = new ArrayList<>();
for (long i : array)
copy.add(i);
Collections.sort(copy);
for (int i = 0; i < array.length; i++)
array[i] = copy.get(i);
}
static int factorsCount(int n) {
boolean hash[] = new boolean[n + 1];
Arrays.fill(hash, true);
for (int p = 2; p * p < n; p++)
if (hash[p] == true)
for (int i = p * 2; i < n; i += p)
hash[i] = false;
int total = 1;
for (int p = 2; p <= n; p++) {
if (hash[p]) {
int count = 0;
if (n % p == 0) {
while (n % p == 0) {
n = n / p;
count++;
}
total = total * (count + 1);
}
}
}
return total;
}
static long binomialCoeff(long n, long k) {
long res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res = (res * (n - i));
res /= (i + 1);
}
return res;
}
static long nck(long fact[], long inv[], long n, long k) {
if (k > n) return 0;
long res = fact[(int) n]%mod;
res = (int) ((res%mod* inv[(int) k]%mod))%mod;
res = (int) ((res%mod*inv[(int) (n - k)]%mod))%mod;
return res % mod;
}
public static long fact(long x) {
long fact = 1;
for (int i = 2; i <= x; ++i) {
fact = fact * i;
}
return fact;
}
public static ArrayList<Long> getFact(long x) {
ArrayList<Long> facts = new ArrayList<>();
facts.add(1L);
for (long i = 2; i * i <= x; ++i) {
if (x % i == 0) {
facts.add(i);
if (i != x / i) {
facts.add(x / i);
}
}
}
return facts;
}
static void matrix_ex(long n, long[][] A, long[][] I) {
while (n > 0) {
if (n % 2 == 0) {
Multiply(A, A);
n /= 2;
} else {
Multiply(I, A);
n--;
}
}
}
static void Multiply(long[][] A, long[][] B) {
int n = A.length, m = A[0].length, p = B[0].length;
long[][] C = new long[n][p];
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < m; k++) {
C[i][j] += ((A[i][k] % mod) * (B[k][j] % mod)) % mod;
C[i][j] = C[i][j] % mod;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
A[i][j] = C[i][j];
}
}
}
public static HashMap<Long, Integer> sortMapDesc(HashMap<Long,Integer> map) {
List<Map.Entry<Long, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
HashMap<Long, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Long, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Character, Integer> sortMapDescch(HashMap<Character, Integer> map) {
List<Map.Entry<Character, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
HashMap<Character, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Character, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Long,Long> sortMapAsclng(HashMap<Long,Long> map) {
List<Map.Entry<Long,Long>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> (int)(o1.getValue() - o2.getValue()));
HashMap<Long,Long> temp = new LinkedHashMap<>();
for (Map.Entry<Long,Long> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Integer, Integer> sortMapAsc(HashMap<Integer, Integer> map) {
List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue());
HashMap<Integer, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Integer, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static long lcm(long l, long l2) {
long val = gcd(l, l2);
return (l * l2) / val;
}
public static boolean isSubsequence(String s, String t) {
int n = s.length();
int m = t.length();
if (m > n) {
return false;
}
int i = 0, j = 0, skip = 0;
while (i < n && j < m) {
if (s.charAt(i) == t.charAt(j)) {
--skip;
++j;
}
++skip;
++i;
}
return j==m;
}
public static long[][] combination(int l, int r) {
long[][] pascal = new long[l + 1][r + 1];
pascal[0][0] = 1;
for (int i = 1; i <= l; ++i) {
pascal[i][0] = 1;
for (int j = 1; j <= r; ++j) {
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
}
return pascal;
}
public static long gcd(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = gcd(ret, array[i]);
return ret;
}
public static long lcm(int... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = lcm(ret, array[i]);
return ret;
}
public static int min(int a, int b) {
return a < b ? a : b;
}
public static int min(int... array) {
int ret = array[0];
for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]);
return ret;
}
public static long min(long a, long b) {
return a < b ? a : b;
}
public static long min(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]);
return ret;
}
public static int max(int a, int b) {
return a > b ? a : b;
}
public static int max(int... array) {
int ret = array[0];
for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]);
return ret;
}
public static long max(long a, long b) {
return a > b ? a : b;
}
public static long max(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]);
return ret;
}
public static long sum(int... array) {
long ret = 0;
for (int i : array) ret += i;
return ret;
}
public static long sum(long... array) {
long ret = 0;
for (long i : array) ret += i;
return ret;
}
public static long[] facts(int n)
{
long[] fact=new long[1005];
fact[0]=1;
fact[1]=1;
for(int i=2;i<n;i++)
{
fact[i]=(long)(i*fact[i-1])%mod;
}
return fact;
}
public static long[] inv(long[] fact,int n)
{
long[] inv=new long[n];
inv[n-1]= CP.Modular_Expo(fact[n-1],mod-2,mod)%mod;
for(int i=n-2;i>=0;--i)
{
inv[i]=(inv[i+1]*(i+1))%mod;
}
return inv;
}
public static int modinv(long x, long mod) {
return (int) (CP.Modular_Expo(x, mod - 2, mod) % mod);
}
public static int lcs(String s, String t) {
int n = s.length(), m = t.length();
int dp[][] = new int[n + 1][m + 1];
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= m; ++j) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[n][m];
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void printLine(long[] array) {
print(array);
writer.println();
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
public void printLine(int i) {
writer.println(i);
}
public void printLine(char c) {
writer.println(c);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void py()
{
print("YES");
writer.println();
}
public void pn()
{
print("NO");
writer.println();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
void flush() {
writer.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 11 | 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 | f4db4f5a1f21f765dda2106bc2158af1 | 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 mod = 1000000007;
public static void main(String[] args) {
FastScanner fs = new FastScanner();
int t = fs.nextInt();
outer: while (t-- > 0) {
int n = fs.nextInt();
int m = fs.nextInt();
char[] ch = fs.next().toCharArray();
int ver = 0, hor = 0;
int vermin = 0, vermax = 0, hormin = 0, hormax = 0;
for (char e : ch) {
if (e == 'L') {
hormin = Math.min(hormin, --hor);
} else if (e == 'R') {
hormax = Math.max(hormax, ++hor);
} else if (e == 'U') {
vermin = Math.min(vermin, --ver);
} else {
vermax = Math.max(vermax, ++ver);
}
if (vermax - vermin >= n) {
if (ver == vermin)
vermin++;
break;
}
if (hormax - hormin >= m) {
if (hor == hormin)
hormin++;
break;
}
}
System.out.println((1 - vermin) + " " + (1 - hormin));
}
}
static int mex(HashSet<Integer> set) {
int i = 0;
while (set.contains(i))
i++;
return i;
}
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;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
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);
}
// 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();
}
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());
}
ArrayList<Integer> readList(int n) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(nextInt());
return list;
}
}
static class Pair {
int one;
int two;
public Pair(int one, int two) {
this.one = one;
this.two = two;
}
}
}
| 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 11 | 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 | 5982d9f5893e6c503b45cca6a350cecf | 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.StringTokenizer;
public class Robot {
public static void main(String[] args) throws Exception {
FastIO in = new FastIO();
int t = in.nextInt();
for (int i=0; i<t; i++) {
int n = in.nextInt();
int m = in.nextInt();
String directions = in.next();
int currX=0, currY=0;
int minX=0, maxX=0, minY=0, maxY=0;
int ansX=0, ansY=0;
for (int j=0; j<directions.length(); j++) {
if (directions.charAt(j)=='R') currX++;
if (directions.charAt(j)=='L') currX--;
if (directions.charAt(j)=='U') currY++;
if (directions.charAt(j)=='D') currY--;
minX = Math.min(minX, currX);
maxX = Math.max(maxX, currX);
minY = Math.min(minY, currY);
maxY = Math.max(maxY, currY);
// System.out.println(minX+" "+maxX+" "+minY+" "+maxY);
if (maxY-minY+1>n) break;
if (maxX-minX+1>m) break;
ansX = maxY;
ansY = m-maxX-1;
}
System.out.println((ansX+1)+" "+(ansY+1));
}
}
static class FastIO {
BufferedReader br;
StringTokenizer st;
public FastIO() throws IOException
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); }
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public String nextLine() throws IOException
{
String str = br.readLine();
return str;
}
}
}
| Java | ["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 11 | 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 | f7306c14c6e4c18e5392152fc73b64e0 | 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 E {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int p = 0; p < t; p++) {
long n = in.nextLong();
long m = in.nextLong();
String move = in.next();
solve(n, m, move);
}
}
private static void solve(long n, long m, String move) {
long x = 0, y = 0, ax = 1, ay = 1;
long up = 0, down = 0, left = 0, right = 0;
for (char dir : move.toCharArray()) {
if (dir == 'U') {
y++;
} else if (dir == 'D') {
y--;
} else if (dir == 'L') {
x--;
} else {
x++;
}
left = Math.min(x, left);
right = Math.max(x, right);
up = Math.max(y, up);
down = Math.min(y, down);
if (right - left + 1 > m || up - down + 1 > n) {
break;
} else {
ay = Math.abs(left) + 1;
ax = Math.abs(up) + 1;
}
}
System.out.println(ax + " " + ay);
}
}
| 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 11 | 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 | 9399ff777ac9218b25b3794f9e8a1952 | 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 void print(String s) {
System.out.print(s);
}
static void printLine(String s) {
System.out.println(s);
}
static double parseDouble(String s) {
return Double.parseDouble(s.trim());
}
static int parseInt(String s) {
return Integer.parseInt(s.trim());
}
static String[] split(String s) {
return s.split("\\s+");
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
StringTokenizer st;
int test = parseInt(br.readLine());
for (int t = 0; t < test; t++) {
st = new StringTokenizer(br.readLine());
int rows = parseInt(st.nextToken());
int cols = parseInt(st.nextToken());
line = br.readLine();
int l, maxL, r, maxR, u, maxU, d, maxD;
l = maxL = r = maxR = u = maxU = d = maxD = 0;
boolean exit = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == 'L') {
l++;r--;
maxL = Math.max(maxL, l);
if (maxL + maxR >= cols) {
exit = true;
System.out.printf("%d %d\n", maxU + 1, maxL);
break;
}
}
if (c == 'R') {
l--;r++;
maxR = Math.max(maxR, r);
if (maxL + maxR >= cols) {
exit = true;
System.out.printf("%d %d\n", maxU + 1, cols - maxR + 1);
break;
}
}
if (c == 'U') {
u++;d--;
maxU = Math.max(maxU, u);
if (maxU + maxD >= rows) {
exit = true;
System.out.printf("%d %d\n", maxU, maxL + 1);
break;
}
}
if (c == 'D') {
u--;d++;
maxD = Math.max(maxD, d);
if (maxU + maxD >= rows) {
exit = true;
System.out.printf("%d %d\n", rows - maxD + 1, maxL + 1);
break;
}
}
}
if (!exit) {
System.out.printf("%d %d\n", maxU + 1, maxL + 1);
}
}
}
}
| 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 11 | 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 | 7657daba06e11d95d7095ebe5a11daf3 | 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_Robot_on_the_Board_1 {
static final int MOD = (int) 1e9 + 7;
static final int INT_POSITIVE_INFINITY = Integer.MAX_VALUE;
static final long LONG_POSITIVE_INFINITY = Long.MAX_VALUE;
static final int INT_NEGATIVE_INFINITY = Integer.MIN_VALUE;
static final long LONG_NEGATIVE_INFINITY = Long.MIN_VALUE;
static StringBuilder result = new StringBuilder();
static class Pair {
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
public static void main(String args[]) throws IOException {
FastReader fr = new FastReader();
int tc = fr.nextInt();
while (tc-- > 0) {
int m = fr.nextInt();
int n = fr.nextInt();
String moves = fr.nextLine();
int x = 0;
int y = 0;
int l = 0;
int r = 0;
int u = 0;
int d = 0;
for (char ch : moves.toCharArray()) {
if (ch == 'R') {
x++;
} else if (ch == 'L') {
x--;
} else if (ch == 'U') {
y--;
} else if (ch == 'D') {
y++;
}
l = Math.min(l, x);
r = Math.max(r, x);
u = Math.min(u, y);
d = Math.max(d, y);
if ((r - l + 1) > n || (d - u + 1) > m) {
if (ch == 'L') {
l++;
} else if (ch == 'U') {
u++;
}
break;
}
}
result.append((1 - u) + " " + (1 - l) + "\n");
}
System.out.print(result);
}
static class FastReader {
InputStreamReader ir;
BufferedReader br;
StringTokenizer st;
public FastReader() {
ir = new InputStreamReader(System.in);
br = new BufferedReader(ir);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static int fastPow(long b, long e) {
long curr = b;
long res = 1;
while (e != 0) {
if ((e & 1) != 0) {
res = (res * curr) % MOD;
}
curr = (curr * curr) % MOD;
e >>= 1;
}
return (int) res;
}
static int gcd(int a, int b) {
if (b > a) {
return gcd(b, a);
}
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
} | 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 11 | 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 | 8bd182fdcf84b220b732328412cddcfa | 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.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main{
public static String nextLine(){
String str="";
try{
str = input.readLine().trim();
}
catch(IOException e){
e.printStackTrace();
}
return str;
}
public static String next() {
while (!tokenizer.hasMoreTokens())
try {
tokenizer=new StringTokenizer(input.readLine().trim());
} catch (IOException e) {
e.printStackTrace();
}
return tokenizer.nextToken();
}
public static int nextInt() {
return Integer.parseInt(next());
}
public static int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
public static long nextLong() {
return Long.parseLong(next());
}
static void out(String s){
output.append(s);
}
static void out(int s){
output.append(s);
}
static void out(double s){
output.append(s);
}
static void out(long s){
output.append(s);
}
static void out(int a[]){
for(int each:a){
output.append(each);
output.append(" ");
}
}static void out(long a[]){
for(long each:a){
output.append(each);
output.append(" ");
}
}
static void out(boolean a[]){
for(boolean each:a){
output.append(each);
output.append(" ");
}
}
static void out(char a[]){
for(char each:a){
output.append(each);
output.append(" ");
}
}
static void line(){
output.append(line);
}
static void space(){
output.append(" ");
}
static void out(Object a[]){
for(Object each:a){
output.append(each.toString());
output.append(" ");
}
}
static void out(Object s){
output.append(s.toString());
}
static class pair implements Comparable<pair>{
int a,b;
pair(int a,int b){
this.a=a;
this.b=b;
}
pair(){}
public int compareTo(pair p){
return this.a-p.a;
}
public String toString(){
return "{"+this.a+","+this.b+"} ";
}
}
static int max(int ...a){
int max=a[0];
for(int i=1;i<a.length;i++)
max=Math.max(max, a[i]);
return max;
}
static int min(int ...a){
int min=a[0];
for(int i=1;i<a.length;i++)
min=Math.min(min, a[i]);
return min;
}
static long max(long ...a){
long max=a[0];
for(int i=1;i<a.length;i++)
max=Math.max(max, a[i]);
return max;
}
static long min(long ...a){
long min=a[0];
for(int i=1;i<a.length;i++)
min=Math.min(min, a[i]);
return min;
}
static int gcd(int a, int b ){
if(b==0)return a ;
else return gcd(b,a%b) ;
}
static long gcd(long a, long b ){
if(b==0)return a ;
else return gcd(b,a%b) ;
}
static int binarySearch(int a[],int ele,int l,int h){
while(l<=h){
int mid=(l+h)/2;
if(a[mid]==ele) return mid;
if(ele<a[mid]) h=mid-1;
else l=mid+1;
}
return -1;
}
static int binarySearch(int a[],int ele){
return binarySearch(a,ele,0,a.length-1);
}
static int binarySearch(long a[],long ele,int l,int h){
while(l<=h){
int mid=(l+h)/2;
if(a[mid]==ele) return mid;
if(ele<a[mid]) h=mid-1;
else l=mid+1;
}
return -1;
}
static int binarySearch(long a[],long ele){
return binarySearch(a,ele,0,a.length-1);
}
static int ceil(int a[],int l,int h,int ele){
int ans=-1;
while(l<=h){
int mid=(l+h)/2;
if(a[mid]>=ele){
ans=mid;
h=mid-1;
}
else l=mid+1;
}
return ans;
}
static int floor(int a[],int l,int h,int ele){
int ans=-1;
while(l<=h){
int mid=(l+h)/2;
if(a[mid]<=ele){
ans=mid;
l=mid+1;
}
else h=mid-1;
}
return ans;
}
static int ceil(long a[],int l,int h,long ele){
int ans=-1;
while(l<=h){
int mid=(l+h)/2;
if(a[mid]>=ele){
ans=mid;
h=mid-1;
}
else l=mid+1;
}
return ans;
}
static int floor(long a[],int l,int h,long ele){
int ans=-1;
while(l<=h){
int mid=(l+h)/2;
if(a[mid]<=ele){
ans=mid;
l=mid+1;
}
else h=mid-1;
}
return ans;
}
static int floor(int a[],int ele){
return floor(a, 0, a.length-1, ele);
}
static int ceil(int a[],int ele){
return ceil(a,0,a.length-1,ele);
}
static int floor(long a[],long ele){
return floor(a, 0, a.length-1, ele);
}
static int ceil(long a[],long ele){
return ceil(a,0,a.length-1,ele);
}
public static void sort(int a[]){
Arrays.sort(a);
}
public static void sort(long a[]){
Arrays.sort(a);
}
public static void reverse(int a[]){
int i=0,j=a.length-1;
while(i<j){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
i++;
j--;
}
}
public static void reverse(long a[]){
int i=0,j=a.length-1;
while(i<j){
long temp=a[i];
a[i]=a[j];
a[j]=temp;
i++;
j--;
}
}
static ArrayList<Integer> seive(int n){
ArrayList<Integer> l= new ArrayList<Integer>();
boolean prime[]=new boolean[n+1];
prime[2]=true;
for(int i=3;i<=n;i+=2)
prime[i]=true;
for(int i=3;i*i<=n;i+=2){
if(prime[i]){
for(int j=i*i;j<=n;j+=2*i)
prime[j]=false;
}
}
l.add(2);
for(int i=3;i<=n;i+=2)
if(prime[i]) l.add(i);
return l;
}
static boolean[] seiveArray(int n){
boolean prime[]=new boolean[n+1];
prime[2]=true;
for(int i=3;i<=n;i+=2)
prime[i]=true;
for(int i=3;i*i<=n;i+=2){
if(prime[i]){
for(int j=i*i;j<=n;j+=2*i)
prime[j]=false;
}
}
return prime;
}
static BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tokenizer=new StringTokenizer("");
static StringBuilder output=new StringBuilder();
static String line="\n";
static void setJudge() throws Exception{
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
if(oj){
input=new BufferedReader(new FileReader(new File("input.txt")));
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
}
else
input=new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String args[]) throws Exception{
// setJudge();
int t=nextInt();
// int t=1;
while(t>0){
solve();
t--;
}
System.out.print(output);
}
static void solve() throws Exception {
int x=nextInt(),y=nextInt();
int ansi=1,ansj=1;
int i=1,j=1,mini=1,minj=1,maxi=1,maxj=1;
char c[]=nextLine().toCharArray();
outer:for(char each:c){
if(each=='R'){
j++;
if(j>y)
break outer;
}
else if(each=='L'){
j--;
// out(i+" "+j+"\n");
if(j<=0){
if(maxj>=y || ansj+1>y)
break outer;
ansj++;
maxj++;
j++;
}
// out(ansi+" "+ansj+"\n");
}
else if(each=='U'){
i--;
if(i<=0){
if(maxi>=x) break outer;
ansi++;
maxi++;
i++;
}
}
else{
i++;
if(i>x)
break outer;
}
mini=min(mini,i);
minj=min(minj,j);
maxj=max(maxj,j);
maxi=max(maxi,i);
// out(maxi+" max "+maxj+"\n");
}
out(ansi);
space();
out(ansj);
line();
}
} | 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 11 | 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 | 1999798d746048bc12fed28a076b6938 | 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.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class codeforces_753_E {
private static void solve(FastIOAdapter io) {
int n = io.nextInt();
int m = io.nextInt();
char[] s = io.next().toCharArray();
int[] xy = new int[]{1, 1};
int[] cur = new int[]{1, 1};
int horizontal = 0, horizontalS = 0, horizontalE = 0;
int vertical = 0, verticalS = 0, verticalE = 0;
for (char c : s) {
if (c == 'L') {
horizontal--;
cur[1]--;
} else if (c == 'R') {
horizontal++;
cur[1]++;
} else if (c == 'U') {
vertical--;
cur[0]--;
} else {
vertical++;
cur[0]++;
}
horizontalS = Math.min(horizontalS, horizontal);
horizontalE = Math.max(horizontalE, horizontal);
verticalS = Math.min(verticalS, vertical);
verticalE = Math.max(verticalE, vertical);
if (verticalE - verticalS >= n || horizontalE - horizontalS >= m) {
break;
} else if (cur[0] < 1) {
xy[0]++;
cur[0] = 1;
} else if (cur[0] > n) {
xy[0]--;
cur[0] = n;
} else if (cur[1] < 1) {
xy[1]++;
cur[1] = 1;
} else if (cur[1] > m) {
xy[1]--;
cur[1] = m;
}
}
io.out.println(xy[0] + " " + xy[1]);
}
public static void main(String[] args) throws Exception {
try (FastIOAdapter ioAdapter = new FastIOAdapter()) {
int count = 1;
count = ioAdapter.nextInt();
while (count-- > 0) {
solve(ioAdapter);
}
}
}
static void ruffleSort(int[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
Arrays.sort(arr);
}
static class FastIOAdapter implements AutoCloseable {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter((System.out))));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
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[] readArrayLong(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());
}
@Override
public void close() throws Exception {
out.flush();
out.close();
br.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 11 | 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 | 44f0facf24514ef76de8b286221e63c8 | 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 {
// For fast input output
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{ try {br = new BufferedReader(
new FileReader("input.txt"));
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);}
catch(Exception e) { br = new BufferedReader(new InputStreamReader(System.in));}
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {
e.printStackTrace();}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() {return Double.parseDouble(next()); }
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// end of fast i/o code
public static void main(String[] args) {
FastReader reader = new FastReader();
StringBuilder sb = new StringBuilder("");
int t = reader.nextInt();
int ans = 0;
while(t-->0){
ans = 0;
int n = reader.nextInt();
int m = reader.nextInt();
String s = reader.next();
int left = 1;
int right = 1;
int down = 1;
int up = 1;
int curr_x = 1, curr_y = 1;
int len = 1, br = 1;
int size = s.length();
char c;
for(int i=0; i<size; i++){
c = s.charAt(i);
if(c=='L'){
curr_y--;
}else if(c=='U'){
curr_x--;
}else if(c=='R'){
curr_y++;
}else if(c=='D'){
curr_x++;
}
int temp_left = Math.min(left, curr_y);
int temp_right = Math.max(right, curr_y);
int temp_up = Math.min(up, curr_x);
int temp_down = Math.max(down, curr_x);
len = temp_down-temp_up+1;
br = temp_right-temp_left + 1;
// System.out.println(temp_left+" "+temp_right+" "+temp_up+" "+temp_down);
// System.out.println(len+" "+br);
if(len>n){
// sb.append((1-(up)+1)+" "+(1-(left)+1)+"\n");
break;
}
if(br>m){
// sb.append((1-(up)+1)+" "+(1-(left)+1)+"\n");
break;
}
left = temp_left;
right = temp_right;
up = temp_up;
down = temp_down;
}
sb.append((1-(up)+1)+" "+(1-(left)+1)+"\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 11 | 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 | 1e5982887ad8dedbd4f7cdcf3b3ba6dd | 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 static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
/*
-> Give your 100%, that's it!
-> Rules To Solve Any Problem:
1. Read the problem.
2. Think About It.
3. Solve it!
*/
public class Template {
static int mod = 1000000007;
public static void main(String[] args){
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int yo = sc.nextInt();
while (yo-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
char[] s = sc.next().toCharArray();
int len = s.length;
int index = len-1;
int R = 0;
int D = 0;
int size = 0;
int max = 0;
int min = 0;
for(int i = 0; i < len; i++){
if(s[i] == 'R' || s[i] == 'L'){
if(s[i] == 'R') R++;
else R--;
max = max(R,max);
min = min(R,min);
size = (max-min+1);
if(size > m){
index = min(index,i-1);
break;
}
}
}
size = 0;
max = 0;
min = 0;
for(int i = 0; i < len; i++){
if(s[i] == 'D' || s[i] == 'U'){
if(s[i] == 'D') D++;
else D--;
max = max(D,max);
min = min(D,min);
size = (max-min+1);
if(size > n){
index = min(index,i-1);
break;
}
}
}
int row = 0;
int minR = 0;
int col = 0;
int minC = 0;
// out.println(index);
for(int i = 0; i <= index; i++){
if(s[i] == 'R' || s[i] == 'L'){
if(s[i] == 'R') row++;
else row--;
if(row < 0){
minR = min(minR,row);
}
}
else {
if(s[i] == 'D') col++;
else col--;
if(col < 0){
minC = min(minC,col);
}
}
}
if(minR < 0){
row = minR*-1;
}
else {
row = 0;
}
if(minC < 0){
col = minC*-1;
}
else {
col = 0;
}
out.println((col+1) + " " + (row+1));
}
out.close();
}
/*
Source: hu_tao
Random stuff to try when stuck:
- use bruteforcer
- always check for n = 1, n = 2, so on
-if it's 2C then it's dp
-for combo/probability problems, expand the given form we're interested in
-make everything the same then build an answer (constructive, make everything 0 then do something)
-something appears in parts of 2 --> model as graph
-assume a greedy then try to show why it works
-find way to simplify into one variable if multiple exist
-treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them)
-find lower and upper bounds on answer
-figure out what ur trying to find and isolate it
-see what observations you have and come up with more continuations
-work backwards (in constructive, go from the goal to the start)
-turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements)
-instead of solving for answer, try solving for complement (ex, find n-(min) instead of max)
-draw something
-simulate a process
-dont implement something unless if ur fairly confident its correct
-after 3 bad submissions move on to next problem if applicable
-do something instead of nothing and stay organized
-write stuff down
Random stuff to check when wa:
-if code is way too long/cancer then reassess
-switched N/M
-int overflow
-switched variables
-wrong MOD
-hardcoded edge case incorrectly
Random stuff to check when tle:
-continue instead of break
-condition in for/while loop bad
Random stuff to check when rte:
-switched N/M
-long to int/int overflow
-division by 0
-edge case for empty list/data structure/N=1
*/
public static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void sort(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
for (int i = 0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] sieve(int N) {
boolean[] sieve = new boolean[N + 1];
for (int i = 2; i <= N; i++)
sieve[i] = true;
for (int i = 2; i <= N; i++) {
if (sieve[i]) {
for (int j = 2 * i; j <= N; j += i) {
sieve[j] = false;
}
}
}
return sieve;
}
public static long power(long x, long y, long p) {
long res = 1L;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y >>= 1;
x = (x * x) % p;
}
return res;
}
public static void print(int[] arr, PrintWriter out) {
//for debugging only
for (int x : arr)
out.print(x + " ");
out.println();
}
public static int log2(int a){
return (int)(Math.log(a)/Math.log(2));
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
// For Input.txt and Output.txt
// FileInputStream in = new FileInputStream("input.txt");
// FileOutputStream out = new FileOutputStream("output.txt");
// PrintWriter pw = new PrintWriter(out);
// Scanner sc = new Scanner(in);
} | Java | ["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 11 | 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 | a42b19c7da328ed9375c5024b4d5998d | 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.StringTokenizer;
public class Main {
static AReader scan = new AReader();
static void solve() {
int n = scan.nextInt();
int m = scan.nextInt();
char[] cs = scan.next().toCharArray();
int l = 1,r = m;
int cnt = 0;
for(char c:cs){
if(l >= r) break;
if(c == 'L') cnt--;
else if(c == 'R') cnt++;
else continue;
while(l + cnt <=0) l++;
while(r + cnt > m) r--;
}
int ll = 1,rr = n;
cnt = 0;
for(char c:cs){
if(ll >= rr) break;
if(c == 'U') cnt--;
else if(c == 'D') cnt++;
else continue;
while(ll + cnt <=0) ll++;
while(rr + cnt > n) rr--;
}
System.out.println(ll+" " + l);
}
public static void main(String[] args) {
int T = scan.nextInt();
while (T-- > 0) {
solve();
}
}
}
class AReader {
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
private String innerNextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String nextLine = innerNextLine();
if (nextLine == null) {
return false;
}
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public String nextLine() {
tokenizer = new StringTokenizer("");
return innerNextLine();
}
public String next() {
hasNext();
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 Pair {
int x,y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
class Node{
int l,r;
int val;
int lazy;
int cnt = 0,lnum,rnum;
public Node(int l, int r) {
this.l = l;
this.r = r;
}
}
| 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 11 | 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 | 9a9319bb6b5375d9831b95ac8d2245ad | 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 Solution {
static long[] fac;
static int m = (int)1e9+7;
static int c = 1;
// static int[] x = {1,-1,0,0};
// static int[] y = {0,0,1,-1};
// static int cycle_node;
public static void main(String[] args) throws IOException {
Reader.init(System.in);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
// Do not delete this //
//Uncomment this before using nCrModPFermat
// fac = new long[200000 + 1];
// fac[0] = 1;
//
// for (int i = 1; i <= 200000; i++)
// fac[i] = (fac[i - 1] * i % 1000000007);
// long[] fact = factorial((int)1e6);
int te = Reader.nextInt();
// int te = 1;
while(te-->0) {
int n = Reader.nextInt();
int m = Reader.nextInt();
char[] arr = Reader.next().toCharArray();
int l = 0, r = 0, u = 0, d = 0;
int hor = 0, ver = 0;
int idx = arr.length-1;
for(int i = 0;i<arr.length;i++){
char ch = arr[i];
if(ch=='L') hor--;
else if(ch=='R') hor++;
else if(ch=='D') ver++;
else ver--;
l = Math.min(l,hor);
r = Math.max(r,hor);
d = Math.max(d,ver);
u = Math.min(u,ver);
if((r-l)>=m || (d-u)>=n){
idx = i-1;
break;
}
}
hor = 0;
ver = 0;
l = 0;
r = 0;
d = 0;
u = 0;
for(int i = 0;i<=idx;i++){
char ch = arr[i];
if(ch=='L') hor--;
else if(ch=='R') hor++;
else if(ch=='D') ver++;
else ver--;
l = Math.min(l,hor);
r = Math.max(r,hor);
d = Math.max(d,ver);
u = Math.min(u,ver);
}
// System.out.println(idx+" "+r+" "+d);
System.out.println((n-d)+" "+(m-r));
}
output.close();
}
// Recursive function to return (x ^ n) % m
static long modexp(long x, long n)
{
if (n == 0) {
return 1;
}
else if (n % 2 == 0) {
return modexp((x * x) % m, n / 2);
}
else {
return (x * modexp((x * x) % m, (n - 1) / 2) % m);
}
}
// Function to return the fraction modulo mod
static long getFractionModulo(long a, long b)
{
long c = gcd(a, b);
a = a / c;
b = b / c;
// (b ^ m-2) % m
long d = modexp(b, m - 2);
// Final answer
long ans = ((a % m) * (d % m)) % m;
return ans;
}
public static boolean isP(String n){
StringBuilder s1 = new StringBuilder(n);
StringBuilder s2 = new StringBuilder(n);
s2.reverse();
for(int i = 0;i<s1.length();i++){
if(s1.charAt(i)!=s2.charAt(i)) return false;
}
return true;
}
public static long[] factorial(int n){
long[] factorials = new long[n+1];
factorials[0] = 1;
factorials[1] = 1;
for(int i = 2;i<=n;i++){
factorials[i] = (factorials[i-1]*i)%1000000007;
}
return factorials;
}
public static long numOfBits(long n){
long ans = 0;
while(n>0){
n = n & (n-1);
ans++;
}
return ans;
}
public static long ceilOfFraction(long x, long y){
// ceil using integer division: ceil(x/y) = (x+y-1)/y
// using double may go out of range.
return (x+y-1)/y;
}
public static 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;
}
// Returns n^(-1) mod p
public static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
public static long nCrModPFermat(int n, int r, int p) {
if (n<r) return 0;
if (r == 0) return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;
}
public static long ncr(long n, long r) {
long p = 1, k = 1;
if (n - r < r) {
r = n - r;
}
if (r != 0) {
while (r > 0) {
p *= n;
k *= r;
long m = gcd(p, k);
p /= m;
k /= m;
n--;
r--;
}
} else {
p = 1;
}
return p;
}
public 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; (long) i * i <= n; i = i + 6){
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
public static int powOf2JustSmallerThanN(int n) {
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n ^ (n >> 1);
}
public static long merge(int[] arr, int[] aux, int low, int mid, int high)
{
int k = low, i = low, j = mid + 1;
long inversionCount = 0;
// while there are elements in the left and right runs
while (i <= mid && j <= high)
{
if (arr[i] <= arr[j]) {
aux[k++] = arr[i++];
}
else {
aux[k++] = arr[j++];
inversionCount += (mid - i + 1); // NOTE
}
}
// copy remaining elements
while (i <= mid) {
aux[k++] = arr[i++];
}
/* no need to copy the second half (since the remaining items
are already in their correct position in the temporary array) */
// copy back to the original array to reflect sorted order
for (i = low; i <= high; i++) {
arr[i] = aux[i];
}
return inversionCount;
}
public static long mergesort(int[] arr, int[] aux, int low, int high)
{
if (high <= low) { // if run size <= 1
return 0;
}
int mid = (low + ((high - low) >> 1));
long inversionCount = 0;
// recursively split runs into two halves until run size <= 1,
// then merges them and return up the call chain
// split/merge left half
inversionCount += mergesort(arr, aux, low, mid);
// split/merge right half
inversionCount += mergesort(arr, aux, mid + 1, high);
// merge the two half runs
inversionCount += merge(arr, aux, low, mid, high);
return inversionCount;
}
public static void reverseArray(int[] arr,int start, int end) {
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
public static long gcd(long a, long b){
if(a==0){
return b;
}
return gcd(b%a,a);
}
public static long lcm(long a, long b){
if(a>b) return a/gcd(b,a) * b;
return b/gcd(a,b) * a;
}
public static long largeExponentMod(long x,long y,long mod){
// computing (x^y) % mod
x%=mod;
long ans = 1;
while(y>0){
if((y&1)==1){
ans = (ans*x)%mod;
}
x = (x*x)%mod;
y = y >> 1;
}
return ans;
}
public static boolean[] numOfPrimesInRange(long L, long R){
boolean[] isPrime = new boolean[(int) (R-L+1)];
Arrays.fill(isPrime,true);
long lim = (long) Math.sqrt(R);
for (long i = 2; i <= lim; i++){
for (long j = Math.max(i * i, (L + i - 1) / i * i); j <= R; j += i){
isPrime[(int) (j - L)] = false;
}
}
if (L == 1) isPrime[0] = false;
return isPrime;
}
public static ArrayList<Long> primeFactors(long n){
ArrayList<Long> factorization = new ArrayList<>();
if(n%2==0){
factorization.add(2L);
}
while(n%2==0){
n/=2;
}
if(n%3==0){
factorization.add(3L);
}
while(n%3==0){
n/=3;
}
if(n%5==0){
factorization.add(5L);
}
while(n%5==0){
// factorization.add(5L);
n/=5;
}
int[] increments = {4, 2, 4, 2, 4, 6, 2, 6};
int i = 0;
for (long d = 7; d * d <= n; d += increments[i++]) {
if(n%d==0){
factorization.add(d);
}
while (n % d == 0) {
// factorization.add(d);
n /= d;
}
if (i == 8)
i = 0;
}
if (n > 1)
factorization.add(n);
return factorization;
}
}
class DSU {
int[] size, parent;
int n;
public DSU(int n){
this.n = n;
size = new int[n];
parent = new int[n];
for(int i = 0;i<n;i++){
parent[i] = i;
size[i] = 1;
}
}
public int find(int u){
if(parent[u]==u){
return u;
}
return parent[u] = find(parent[u]);
}
public void merge(int u, int v){
u = find(u);
v = find(v);
if(u!=v){
if(size[u]>size[v]){
parent[v] = u;
size[u] += size[v];
}
else{
parent[u] = v;
size[v] += size[u];
}
}
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException {
return reader.readLine();
}
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 SegTree{
int n; // array size
// Max size of tree
public int[] tree;
public SegTree(int n){
this.n = n;
tree = new int[4*n];
}
// function to build the tree
void update(int pos, int val, int s, int e, int treeIdx){
if(pos < s || pos > e){
return;
}
if(s == e){
tree[treeIdx] = val;
return;
}
int mid = s + (e - s) / 2;
update(pos, val, s, mid, 2 * treeIdx);
update(pos, val, mid + 1, e, 2 * treeIdx + 1);
tree[treeIdx] = tree[2 * treeIdx] + tree[2 * treeIdx + 1];
}
void update(int pos, int val){
update(pos, val, 1, n, 1);
}
int query(int qs, int qe, int s, int e, int treeIdx){
if(qs <= s && qe >= e){
return tree[treeIdx];
}
if(qs > e || qe < s){
return 0;
}
int mid = s + (e - s) / 2;
int subQuery1 = query(qs, qe, s, mid, 2 * treeIdx);
int subQuery2 = query(qs, qe, mid + 1, e, 2 * treeIdx + 1);
int res = subQuery1 + subQuery2;
return res;
}
int query(int l, int r){
return query(l, r, 1, n, 1);
}
} | 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 11 | 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 | e91f17768aaa68b9ea2c4be0ba3bc55e | 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 Main {
static int n;
static int m;
public static boolean isValid(int l,int r,int d,int u){
if (l < m && r < m && d < n && u < n && l + r < m && d + u < n) return true;
return false;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(t-->0){
n = in.nextInt();
m = in.nextInt();
in.nextLine();
String line = in.nextLine();
int al=0,ar=0,ad=0,au=0;
int l = 0,r = 0,d = 0,u = 0;
int x = 0,y = 0;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == 'R') x++;
else if (line.charAt(i) == 'L') x--;
else if (line.charAt(i) == 'D') y++;
else y--;
if (x > 0) r = Math.max(x,r);
if (x < 0) l = Math.max(l,-x);
if (y > 0) d = Math.max(d,y);
if (y < 0) u = Math.max(u,-y);
if (isValid(l,r,d,u)){
al = l;
ar = r;
ad = d;
au = u;
}else break;
}
System.out.printf("%d %d\n",au+1,al+1);
}
}
}
| 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 11 | 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 | 022664e3941cc149309f4e2f1b3f486d | 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 robotboard {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int t = Integer.parseInt(st.nextToken());
for (int test = 0; test < t; test++){
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
String str = st.nextToken();
int len = str.length();
int horizontalSum = 0;
int verticalSum = 0;
int minH = 0;
int maxH = 0;
int minV = 0;
int maxV = 0;
int end = Integer.MAX_VALUE;
for(int i = 0; i < len; i++){
if (str.charAt(i) == 'R'){
horizontalSum++;
}
else if(str.charAt(i) == 'L'){
horizontalSum--;
}
maxH = Math.max(horizontalSum,maxH);
minH = Math.min(horizontalSum,minH);
if(Math.abs(maxH - minH) >= m){
end = Math.min(i,end);
if(minH == horizontalSum){
minH++;
}
break;
}
}
for(int i = 0; i < len; i++){
if (str.charAt(i) == 'D'){
verticalSum++;
}
else if(str.charAt(i) == 'U'){
verticalSum--;
}
maxV = Math.max(verticalSum,maxV);
minV = Math.min(verticalSum,minV);
if(Math.abs(maxV - minV) >= n){
end = Math.min(i,end);
if(minV == verticalSum){
minV++;
}
break;
}
}
int jCoord = 1 - minH;
int iCoord = 1 - minV;
// if (end != Integer.MAX_VALUE){
// if(str.charAt(end) == 'L'){
// jCoord--;
// }
// if(str.charAt(end) == 'U'){
// iCoord--;
// }
// }
System.out.println(iCoord+" "+jCoord);
}
}
}
| 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 11 | 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 | a4ada8eb5bf22d7e74e590de6a32e344 | 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.StringTokenizer;
public class E {
static class RealScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
public static void main(String[] args) {
RealScanner sc = new RealScanner();
int t = sc.nextInt();
while (t-- > 0) {
int n, m;
String s;
n = sc.nextInt();
m = sc.nextInt();
s = sc.next();
int a_col = 0, b_row = 0;
int max_a_col = 0, min_a_col = 0, max_b_row = 0, min_b_row = 0;
int row = 1, col = 1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'L') {
a_col--;
}
if (s.charAt(i) == 'R') {
a_col++;
}
if (s.charAt(i) == 'U') {
b_row--;
}
if (s.charAt(i) == 'D') {
b_row++;
}
// System.out.println(b_row + " " + a_col);
min_a_col = Math.min(min_a_col, a_col);
max_a_col = Math.max(max_a_col, a_col);
min_b_row = Math.min(min_b_row, b_row);
max_b_row = Math.max(max_b_row, b_row);
if (max_a_col - min_a_col + 1 > m || max_b_row - min_b_row + 1 > n) {
break;
}
col = 1 - min_a_col;
row = 1 - min_b_row;
}
System.out.println(row + " " + col);
}
}
}
| 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 11 | 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 | f9f0b34dd20910af049fd12e4d0c913d | 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.*;
// THIS TEMPLATE MADE BY AKSH BANSAL.
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void sort(int a[]){ // int -> long
ArrayList<Integer> arr=new ArrayList<>(); // Integer -> Long
for(int i=0;i<a.length;i++)
arr.add(a[i]);
Collections.sort(arr);
for(int i=0;i<a.length;i++)
a[i]=arr.get(i);
}
private static long gcd(long a, long b){
if(b==0)return a;
return gcd(b,a%b);
}
private static long pow(long x,long y){
if(y==0)return 1;
long temp = pow(x, y/2);
if(y%2==1){
return x*temp*temp;
}
else{
return temp*temp;
}
}
static int log(long n){
int res = 0;
while(n>0){
res++;
n/=2;
}
return res;
}
static int mod = (int)1e9+7;
static PrintWriter out;
static FastReader sc ;
public static void main(String[] args) throws IOException {
sc = new FastReader();
out = new PrintWriter(System.out);
// primes();
// ________________________________
int test = sc.nextInt();
StringBuilder output = new StringBuilder();
while (test-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
String s = sc.nextLine();
output.append(solver(n,m,s)).append("\n");
}
out.print(output);
// _______________________________
// int n = sc.nextInt();
// out.println(solver());
// ________________________________
out.flush();
}
public static String solver(int n, int m, String s) {
int[][] dir = new int[4][2];
int curX = 0;
int curY = 0;
int len = s.length();
for(int i=0;i<len;i++){
if(s.charAt(i)=='U'){
curY++;
}
else if(s.charAt(i)=='L'){
curX--;
}
else if(s.charAt(i)=='R'){
curX++;
}
else if(s.charAt(i)=='D'){
curY--;
}
dir[0][0] = dir[0][1];
dir[1][0] = dir[1][1];
dir[2][0] = dir[2][1];
dir[3][0] = dir[3][1];
dir[0][1] = Math.max(dir[0][1], curY);
dir[1][1] = Math.max(dir[1][1], curX);
dir[2][1] = Math.max(dir[2][1], -curY);
dir[3][1] = Math.max(dir[3][1], -curX);
// for(int j=0;j<4;j++){
// System.out.print( dir[j][1]+" ");
// }
// System.out.println( );
if(dir[1][1]+dir[3][1]>m-1 || dir[0][1]+dir[2][1]>n-1){
dir[0][1] = dir[0][0];
dir[1][1] = dir[1][0];
dir[2][1] = dir[2][0];
dir[3][1] = dir[3][0];
break;
}
}
String res = Math.min(n,dir[0][1]+1)+" "+Math.min(m,dir[3][1]+1);
return res;
}
}
| 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 11 | 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 | a6aaba418f326a9afc0e2739eb070928 | 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 Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int c = in.nextInt();
while(c-->0){
int n = in.nextInt(), m = in.nextInt();
if(n == m && n == 1){
in.next();
System.out.println("1 1");
continue;
}
int x = 0, y = 0; //x横向移动,y纵向移动
int max_x = 0, max_y = 0, min_x = 0, min_y = 0;
String string = in.next();
int index = 0;
boolean flag = true;
while(flag && index < string.length()){
switch (string.charAt(index++)){
case 'R':
x++;
if(x > max_x){
if(x-min_x<=m-1){
max_x = x;
}else
flag = false;
}
break;
case 'L':
x--;
if(x<min_x){
if(max_x - x<=m-1){
min_x = x;
}else
flag = false;
}
break;
case 'U':
y++;
if(y > max_y){
if(y-min_y<=n-1){
max_y = y;
}else
flag = false;
}
break;
case 'D':
y--;
if(y <min_y){
if(max_y - y<=n-1){
min_y = y;
}else
flag = false;
}
break;
}
}
// System.out.println(max_x+" "+min_x);
// System.out.println(max_y+" "+min_y);
System.out.println((max_y+1)+" "+(1-min_x));
}
in.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 11 | 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 | 5062ce72253b7c159ee071a7203fe3be | 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.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Test {
static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
StringTokenizer st = new StringTokenizer(r.readLine());
int q = Integer.parseInt(st.nextToken());
for (int i = 0; i < q; i++) {
st = new StringTokenizer(r.readLine());
int height = Integer.parseInt(st.nextToken());
int width = Integer.parseInt(st.nextToken());
st = new StringTokenizer(r.readLine());
String in = st.nextToken();
int currX = 0;
int currY = 0;
int right = 0;
int left = 0;
int up = 0;
int down = 0;
int j = 0;
if (0 == width && 0 == height) {
j = in.length();
}
boolean tooLong = false;
while (j < in.length())
{
switch(in.charAt(j))
{
case 'R':
++currX;
right = Math.max(currX, right);
if (right - left + 1 > width) {
if (right == currX)
right--;
tooLong = true;
}
break;
case 'L':
--currX;
left = Math.min(currX, left);
if (right - left + 1 > width) {
if (left == currX)
left++;
tooLong = true;
}
break;
case 'U':
++currY;
up = Math.max(currY, up);
if (up - down + 1 > height) {
if (up == currY)
up--;
tooLong = true;
}
break;
case 'D':
--currY;
down = Math.min(currY, down);
if (up - down + 1 > height) {
if (down == currY)
down++;
tooLong = true;
}
break;
}
if (tooLong)
break;
++j;
}
up++;
left = -left;
left++;
System.out.println(up + " " + left);
}
}
} | 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 11 | 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 | 06e3895c101c78c3c91caefd0fc09386 | 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 Robot{
int x;
int y;
int ny= 0;
int nx= 0;
int fx;
int fy;
public Robot(int y, int x ){
this.x = x;
this.y = y;
}
public void ans(String s){
int r = 0;
int l = 0;
int maxx = 0;
int maxy = 0;
int minx = 0;
int miny = 0;
for(int i = 0 ; i < s.length() ;i++){
fy = 1 + maxy;
fx = 1 - minx;
switch(s.charAt(i)){
case 'U':{
ny++;
break;
}
case 'D':{
ny--;
break;
}
case 'L':{
nx--;
break;
}
case 'R':{
nx++;
break;
}
}
maxx = Math.max(nx,maxx);
minx = Math.min(nx,minx);
maxy = Math.max(ny,maxy);
miny = Math.min(ny,miny);
r = Math.max(r,maxy-miny+1);
l = Math.max(l,maxx-minx+1);
if(r>y||l>x) {
break;
}
fy = 1 + maxy;
fx = 1 - minx;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
for(int i = 0 ; i < num ; i++) {
int y = input.nextInt();
int x = input.nextInt();
Robot robot = new Robot(y,x) ;
String s = input.next();
robot.ans(s);
System.out.println(robot.fy +" " + robot.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 11 | 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 | bded1bbfe5a22058b993d5a792e6d316 | 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 Robot_on_the_Board_1
{
public static void process()throws IOException
{
int n=I();
int m=I();
String s=S();
int n1=s.length();
int minV=0;
int maxV=0;
int minH=0;
int maxH=0;
int v=0;int h=0;
int ansx=1;int ansy=1;
for(int i=0;i<n1;i++)
{
char ch=s.charAt(i);
if(ch=='L')
{
h=h-1;
}
else
if(ch=='R')
{
h=h+1;
}
else
if(ch=='U')
{
v=v-1;
}
else
{
v=v+1;
}
maxV=Math.max(v, maxV);
maxH=Math.max(h, maxH);
minV=Math.min(v, minV);
minH=Math.min(h, minH);
int x=n-maxV;
int y=m-maxH;
if(x>=1 && x<=n && x+minV>=1 && x+maxV<=n && y>=1 && y<=m && y+minH>=1 && y+maxH<=m)
{
ansx=x;
ansy=y;
}
else
{
break;
}
}
pn(ansx+" "+ansy);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void sort(char[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
char temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static void pn(Object o){out.println(o);}
static void p(Object o){out.print(o);}
static void pni(Object o){out.println(o);}
static int I() throws IOException{return sc.nextInt();}
static long L() throws IOException{return sc.nextLong();}
static double D() throws IOException{return sc.nextDouble();}
static String S() throws IOException{return sc.next();}
static char C() throws IOException{return sc.next().charAt(0);}
static int[] Ai(int n) throws IOException{int[] arr = new int[n];for (int i = 0; i < n; i++)arr[i] = I();return arr;}
static String[] As(int n) throws IOException{String s[] = new String[n];for (int i = 0; i < n; i++)s[i] = S();return s;}
static long[] Al(int n) throws IOException {long[] arr = new long[n];for (int i = 0; i < n; i++)arr[i] = L();return arr;}
static void dyn(int dp[][],int n,int m,int z)throws IOException {for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ dp[i][j]=z;}} }
// *--------------------------------------------------------------------------------------------------------------------------------*//
public static void main(String[] args)throws IOException{try{boolean oj=true;if(oj==true)
{PrintWriter out=new PrintWriter(System.out);}
else
{out=new PrintWriter("output.txt");}
long T=L();while(T-->0)
{ process();
}out.close();}catch(Exception e){return;}}}
//*-----------------------------------------------------------------------------------------------------------------------------------*//
| 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 11 | 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 | a5dba4d73765c9a83f4c713763ab8c7e | 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 Main {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
int t=in.nextInt();
StringBuilder res=new StringBuilder();
loop:
while(t-->0)
{
int n= in.nextInt();
int m=in.nextInt();
int l_left=0;
int r_left=m-1;
int d_max=0;
int d_left=n-1;
int u_left=0;
int l_min=0;
int r_max=1;
int r_cur=1;
int u_min=0;
int d_cur=1;
String s=in.next();
int ans[]=solve(n,m,s);
res.append(ans[0]+" "+ans[1]+"\n");
continue loop;
// int x=1;
// int y=1;
// for(int i=0;i<s.length();i++)
// {
// if(s.charAt(i)=='R')
// {
// if(r_left>0)
// {
// r_left--;
// l_left++;
// r_cur++;
// r_max=Math.max(r_max,r_cur);
// }
// else
// {
// res.append(x+" "+y+"\n");
// }
// }
// else if(s.charAt(i)=='L')
// {
// if(l_left>0)
// {
// r_left++;
// l_left--;
// r_cur--;
// }
// else
// {
// if(r_max<m)
// {
// x++;
// }
// else
// {
// res.append(x+" "+y+"\n");
// continue loop;
// }
// }
// }
// else if(s.charAt(i)=='U')
// {
// if(u_left>0)
// {
// d_left++;
// u_left--;
// d_cur--;
// }
// else
// {
// if(d_max<n)
// {
// y++;
// }
// else
// {
// res.append(x+" "+y+"\n");
// continue loop;
// }
// }
// }
// else{
// if(s.charAt(i)=='D')
// {
// if(d_left>0)
// {
// d_left--;
// u_left++;
// d_cur++;
// d_max=Math.max(d_max,d_cur);
// }
// else
// {
// res.append(x+" "+y+"\n");
// continue loop;
// }
// }
// }
// }
// res.append(y+" "+x+"\n");
}
System.out.println(res);
}
static int [] solve(int row,int col,String s)
{
int ans[]=new int[2];
Arrays.fill(ans,1);
int min=0;
int max=0;
int cur=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='U')
{
cur--;
}
else if(s.charAt(i)=='D')
{
cur++;
}
min=Math.min(min,cur);
max=Math.max(max,cur);
if(max-min>=row)
{
break;
}
ans[0]=-1*min+1;
}
min=0;
max=0;
cur=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='L')
{
cur--;
}
else if(s.charAt(i)=='R')
{
cur++;
}
min=Math.min(min,cur);
max=Math.max(max,cur);
if(max-min>=col)
{
break;
}
ans[1]=-1*min+1;
}
return ans;
}
static class Node implements Comparable<Node>{
int val;
char ch;
Node(int x,char y)
{
val=x;
ch=y;
}
@Override
public int compareTo(Node o) {
if(val>o.val)
{
return 1;
}
if(val==o.val)
{
return 0;
}
return -1;
}
}
}
| 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 11 | 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 | 19fd77dd2f60194375dc08a9eea18dd8 | 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 E_1607 {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt(), m = sc.nextInt();
char[] moves = sc.next().toCharArray();
int len = moves.length;
int minX = 0, maxX = 0, minY = 0, maxY = 0;
int curX = 0, curY = 0;
int ansX = 0, ansY = 0;
for(int i = 0; i < len; i++) {
if(moves[i] == 'L')
curY--;
else if(moves[i] == 'R')
curY++;
else if(moves[i] == 'U')
curX--;
else
curX++;
minX = Math.min(minX, curX);
minY = Math.min(minY, curY);
maxX = Math.max(maxX, curX);
maxY = Math.max(maxY, curY);
int left = -minY, right = m - maxY - 1;
int up = -minX, down = n - maxX - 1;
if(left <= right && up <= down) {
ansX = up;
ansY = left;
} else {
break;
}
}
pw.println((ansX + 1) + " " + (ansY + 1));
}
pw.flush();
}
public 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[] nextIntArray(int n) throws IOException {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++)
array[i] = new Integer(nextInt());
return array;
}
public long[] nextLongArray(int n) throws IOException {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
public static int[] shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
| 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 11 | 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 | c37e2a20f103c9c20ca8820418728d3a | 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.*;
import java.lang.*;
public class Test{
// static int mod = 998244353;
static int mod = 1000000007;
private static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws Exception {
FastReader scn = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
int t = scn.nextInt();
outer : while(t-->0){
int n = scn.nextInt();
int m = scn.nextInt();
String s = scn.nextLine();
int maxL = m-1;
int le = 0, re = 0, x = 0;
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
if(ch == 'L'){
x--;
le = Math.min(x, le);
int diff = re - le;
if(diff > maxL){
le++;
break;
}
}else if(ch == 'R'){
x++;
re = Math.max(x, re);
int diff = re - le;
if(diff > maxL){
re--;
break;
}
}
}
int maxW = n-1;
int de = 0, ue = 0;
x = 0;
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
if(ch == 'U'){
x++;
ue = Math.max(ue, x);
int diff = ue - de;
if(diff > maxW){
ue--;
break;
}
}else if(ch == 'D'){
x--;
de = Math.min(de, x);
int diff = ue - de;
if(diff > maxW){
de++;
break;
}
}
}
int r = 1 + ue;
int c = m - re;
pw.println(r + " " + c);
}
pw.close();
}
public static class Pair{
int x;
int y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for(int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
// private static void sort(Pair[] arr) {
// List<Pair> list = new ArrayList<>();
// for(int i=0; i<arr.length; i++){
// list.add(arr[i]);
// }
// Collections.sort(list); // collections.sort uses nlogn in backend
// for (int i = 0; i < arr.length; i++){
// arr[i] = list.get(i);
// }
// }
private static void reverseSort(int[] arr){
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list, Collections.reverseOrder()); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void reverseSort(long[] arr){
List<Long> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list, Collections.reverseOrder()); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void reverseSort(ArrayList<Integer> list){
Collections.sort(list, Collections.reverseOrder());
}
private static int lowerBound(int[] arr, int x){
int n = arr.length, si = 0, ei = n - 1;
while(si <= ei){
int mid = si + (ei - si)/2;
if(arr[mid] == x){
if(mid-1 >= 0 && arr[mid-1] == arr[mid]){
ei = mid-1;
}else{
return mid;
}
}else if(arr[mid] > x){
ei = mid - 1;
}else{
si = mid+1;
}
}
return si;
}
private static int upperBound(int[] arr, int x){
int n = arr.length, si = 0, ei = n - 1;
while(si <= ei){
int mid = si + (ei - si)/2;
if(arr[mid] == x){
if(mid+1 < n && arr[mid+1] == arr[mid]){
si = mid+1;
}else{
return mid + 1;
}
}else if(arr[mid] > x){
ei = mid - 1;
}else{
si = mid+1;
}
}
return si;
}
private static int upperBound(ArrayList<Integer> list, int x){
int n = list.size(), si = 0, ei = n - 1;
while(si <= ei){
int mid = si + (ei - si)/2;
if(list.get(mid) == x){
if(mid+1 < n && list.get(mid+1) == list.get(mid)){
si = mid+1;
}else{
return mid + 1;
}
}else if(list.get(mid) > x){
ei = mid - 1;
}else{
si = mid+1;
}
}
return si;
}
// (x^y)%p in O(logy)
private static long power(long x, long y){
long res = 1;
x = x % mod;
while(y > 0){
if ((y & 1) == 1){
res = (res * x) % mod;
}
y = y >> 1;
x = (x * x) % mod;
}
return res;
}
public static boolean nextPermutation(int[] arr) {
if(arr == null || arr.length <= 1){
return false;
}
int last = arr.length-2;
while(last >= 0){
if(arr[last] < arr[last+1]){
break;
}
last--;
}
if (last < 0){
return false;
}
if(last >= 0){
int nextGreater = arr.length-1;
for(int i=arr.length-1; i>last; i--){
if(arr[i] > arr[last]){
nextGreater = i;
break;
}
}
swap(arr, last, nextGreater);
}
reverse(arr, last+1, arr.length-1);
return true;
}
private static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static void reverse(int[] arr, int i, int j){
while(i < j){
swap(arr, i++, j--);
}
}
private static String reverseStr(String s){
StringBuilder sb = new StringBuilder(s);
return sb.reverse().toString();
}
// TC- O(logmax(a,b))
private static int gcd(int a, int b) {
if(a == 0){
return b;
}
return gcd(b%a, a);
}
private static long gcd(long a, long b) {
if(a == 0L){
return b;
}
return gcd(b%a, a);
}
private static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
// TC- O(logmax(a,b))
private static int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
private static long inv(long x){
return power(x, mod - 2);
}
private static long summation(long n){
return (n * (n + 1L)) >> 1;
}
} | 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 11 | 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 | 208ac5c54c60fb6d4e5983d3499d2783 | 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.math.*;
import java.util.*;
// @author : Dinosparton
public class test {
static class Pair{
long x;
long y;
Pair(long x,long y){
this.x = x;
this.y = y;
}
}
static class Sort implements Comparator<Pair>
{
@Override
public int compare(Pair a, Pair b)
{
if(a.x!=b.x)
{
return (int)(a.x - b.x);
}
else
{
return (int)(a.y-b.y);
}
}
}
static class Compare {
void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
if(p1.x!=p2.x) {
return (int)(p1.x - p2.x);
}
else {
return (int)(p1.y - p2.y);
}
}
});
// for (int i = 0; i < n; i++) {
// System.out.print(arr[i].x + " " + arr[i].y + " ");
// }
// System.out.println();
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner();
StringBuilder res = new StringBuilder();
int tc = sc.nextInt();
while(tc-->0) {
int n = sc.nextInt();
int m = sc.nextInt();
String s = sc.next();
int x = 1;
int y = 1;
int row = 1;
int col = 1;
int l = 1;
int r = 1;
int u = 1;
int d = 1;
for(int i=0;i<s.length();i++) {
if(s.charAt(i)=='L') {
y--;
}
else if(s.charAt(i)=='R') {
y++;
}
else if(s.charAt(i)=='U') {
x--;
}
else {
x++;
}
l = Math.min(l, y);
r = Math.max(r, y);
u = Math.min(u, x);
d = Math.max(d, x);
if(r-l>=m || d-u>=n) {
break;
}
else {
col = 1 + Math.abs(l-1);
row = 1 + Math.abs(u-1);
}
}
res.append(row+" "+col+"\n");
}
System.out.println(res);
}
}
| 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 11 | 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 | 819b6fb5d5f204ae11e025b42445f5c5 | 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 codechef;
import java.io.*;
import java.util.*;
public class cp_2 {
static int mod=998244353;
// static Reader sc=new Reader();
static FastReader sc=new FastReader(System.in);
static int[] sp;
static int size=(int)1e6;
public static void main(String[] args) throws IOException {
long tc=sc.nextLong();
// Scanner sc=new Scanner(System.in);
// int tc=1;
// primeSet=new HashSet<>();
// sieveOfEratosthenes((int)1e5);
while(tc-->0)
{
int n=sc.nextInt();
int m=sc.nextInt();
String seq=sc.next();
int x=0,y=0;
int minx=0,miny=0,maxx=0,maxy=0;
int posx=0,posy=0;
for(int i=0;i<seq.length();i++)
{
if(seq.charAt(i)=='L')
x--;
else if (seq.charAt(i)=='R') {
x++;
}
else if (seq.charAt(i)=='D') {
y++;
}
else {
y--;
}
minx=Math.min(x, minx);
maxx=Math.max(x, maxx);
miny=Math.min(y, miny);
maxy=Math.max(y, maxy);
if(maxx-minx+1>m)
break;
if(maxy-miny+1>n)
break;
posx=-minx;
posy=-miny;
}
posx++;
posy++;
out.println(posy+" "+posx);
}
out.flush();
out.close();
System.gc();
}
/*
...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...
*/
static int N = 501;
// Array to store inverse of 1 to N
static long[] factorialNumInverse = new long[N + 1];
// Array to precompute inverse of 1! to N!
static long[] naturalNumInverse = new long[N + 1];
// Array to store factorial of first N numbers
static long[] fact = new long[N + 1];
// Function to precompute inverse of numbers
public static void InverseofNumber(int p)
{
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i <= N; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] *
(long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
public static void InverseofFactorial(int p)
{
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// Precompute inverse of natural numbers
for(int i = 2; i <= N; i++)
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p;
}
// Function to calculate factorial of 1 to N
public static void factorial(int p)
{
fact[0] = 1;
// Precompute factorials
for(int i = 1; i <= N; i++)
{
fact[i] = (fact[i - 1] * (long)i) % p;
}
}
// Function to return nCr % p in O(1) time
public static long Binomial(int N, int R, int p)
{
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) %
p * factorialNumInverse[N - R]) % p;
return ans;
}
static String tr(String s)
{
int now = 0;
while (now + 1 < s.length() && s.charAt(now)== '0')
++now;
return s.substring(now);
}
static ArrayList<Integer> ans;
static void dfs(int node,Graph gg,int cnt,int k,ArrayList<Integer> temp)
{
if(cnt==k)
return;
for(Integer each:gg.list[node])
{
if(each==0)
{
temp.add(each);
ans=new ArrayList<>(temp);
temp.remove(temp.size()-1);
continue;
}
temp.add(each);
dfs(each,gg,cnt+1,k,temp);
temp.remove(temp.size()-1);
}
return;
}
static HashSet<Integer> factors(int x)
{
HashSet<Integer> a=new HashSet<Integer>();
for(int i=2;i*i<=x;i++)
{
if(x%i==0)
{
a.add(i);
a.add(x/i);
}
}
return a;
}
static class Node
{
int vertex;
HashSet<Node> adj;
boolean rem;
Node(int ver)
{
vertex=ver;
rem=false;
adj=new HashSet<Node>();
}
@Override
public String toString()
{
return vertex+" ";
}
}
static class Tuple{
int a;
int b;
int c;
public Tuple(int a,int b,int c) {
this.a=a;
this.b=b;
this.c=c;
}
}
//function to find prime factors of n
static HashMap<Integer,Integer> findFactors(int n)
{
HashMap<Integer,Integer> ans=new HashMap<>();
if(n%2==0)
{
ans.put(2, 0);
while((n&1)==0)
{
n=n>>1;
ans.put(2, ans.get(2)+1);
}
}
for(int i=3;i*i<=n;i+=2)
{
if(n%i==0)
{
ans.put(i, 0);
while(n%i==0)
{
n=n/i;
ans.put(i, ans.get(i)+1);
}
}
}
if(n!=1)
ans.put(n, ans.getOrDefault(n, 0)+1);
return ans;
}
//fenwick tree implementaion
static class fwt
{
int n;
long BITree[];
fwt(int n)
{
this.n=n;
BITree=new long[n+1];
}
fwt(int arr[], int n)
{
this.n=n;
BITree=new long[n+1];
for(int i = 0; i < n; i++)
updateBIT(n, i, arr[i]);
}
long getSum(int index)
{
long sum = 0;
index = index + 1;
while(index>0)
{
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
void updateBIT(int n, int index,int val)
{
index = index + 1;
while(index <= n)
{
BITree[index] += val;
index += index & (-index);
}
}
void print()
{
for(int i=0;i<n;i++)
out.print(getSum(i)+" ");
out.println();
}
}
//Function to find number of set bits
static int setBitNumber(long n)
{
if (n == 0)
return 0;
int msb = 0;
n = n / 2;
while (n != 0) {
n = n / 2;
msb++;
}
return msb;
}
static int getFirstSetBitPos(long n)
{
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
static ArrayList<Integer> primes;
static HashSet<Integer> primeSet;
static boolean prime[];
static void sieveOfEratosthenes(int n)
{
// Create a boolean array
// "prime[0..n]" and
// initialize all entries
// it as true. A value in
// prime[i] will finally be
// false if i is Not a
// prime, else true.
prime= new boolean[n + 1];
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
primeSet.add(i);
}
}
static long mod(long a, long b) {
long c = a % b;
return (c < 0) ? c + b : c;
}
static void swap(long arr[],int i,int j)
{
long temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
static boolean util(int a,int b,int c)
{
if(b>a)util(b, a, c);
while(c>=a)
{
c-=a;
if(c%b==0)
return true;
}
return (c%b==0);
}
static void flag(boolean flag)
{
out.println(flag ? "YES" : "NO");
out.flush();
}
static void print(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print(long a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print_int(ArrayList<Integer> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void print_long(ArrayList<Long> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void printYesNo(boolean condition)
{
if (condition) {
out.println("Yes");
}
else {
out.println("No");
}
}
static int LowerBound(int a[], int x)
{ // x is the target value or key
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int lowerIndex(int arr[], int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
static int upperIndex(int arr[], int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
static int upperIndex(long arr[], int n, long y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
static int UpperBound(int a[], int x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static int UpperBound(long a[], long x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static class DisjointUnionSets
{
int[] rank, parent;
int n;
// Constructor
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
// Creates n sets with single item in each
void makeSet()
{
for (int i = 0; i < n; i++)
parent[i] = i;
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
// Unites the set that includes x and the set
// that includes x
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else // if ranks are the same
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
// if(xRoot!=yRoot)
// parent[y]=x;
}
int connectedComponents()
{
int cnt=0;
for(int i=0;i<n;i++)
{
if(parent[i]==i)
cnt++;
}
return cnt;
}
}
static class Graph
{
int v;
ArrayList<Integer> list[];
Graph(int v)
{
this.v=v;
list=new ArrayList[v+1];
for(int i=1;i<=v;i++)
list[i]=new ArrayList<Integer>();
}
void addEdge(int a, int b)
{
this.list[a].add(b);
}
}
// static class GraphMap{
// Map<String,ArrayList<String>> graph;
// GraphMap() {
// // TODO Auto-generated constructor stub
// graph=new HashMap<String,ArrayList<String>>();
//
// }
// void addEdge(String a,String b)
// {
// if(graph.containsKey(a))
// this.graph.get(a).add(b);
// else {
// this.graph.put(a, new ArrayList<>());
// this.graph.get(a).add(b);
// }
// }
// }
// static void dfsMap(GraphMap g,HashSet<String> vis,String src,int ok)
// {
// vis.add(src);
//
// if(g.graph.get(src)!=null)
// {
// for(String each:g.graph.get(src))
// {
// if(!vis.contains(each))
// {
// dfsMap(g, vis, each, ok+1);
// }
// }
// }
//
// cnt=Math.max(cnt, ok);
// }
static double sum[];
static long cnt;
static void DFS(Graph g, boolean[] visited, int u)
{
visited[u]=true;
for(int i=0;i<g.list[u].size();i++)
{
int v=g.list[u].get(i);
if(!visited[v])
{
cnt=cnt*2;
DFS(g, visited, v);
}
}
}
static class Pair implements Comparable<Pair>
{
int x,y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
return this.x-o.x;
}
}
static long sum_array(int a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static long sum_array(long a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static void sort(int[] a)
{
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void reverse_array(int a[])
{
int n=a.length;
int i,t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static void reverse_array(long a[])
{
int n=a.length;
int i; long t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
// static long modInverse(long a, long m)
// {
// long g = gcd(a, m);
//
// return power(a, m - 2, m);
//
// }
static long power(long x, long y)
{
long res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
//cnt+=a/b;
return gcd(b%a,a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
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')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static PrintWriter out=new PrintWriter(System.out);
static int int_max=Integer.MAX_VALUE;
static int int_min=Integer.MIN_VALUE;
static long long_max=Long.MAX_VALUE;
static long long_min=Long.MIN_VALUE;
}
| 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 11 | 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 | a3dcb86eec49f0c69b43d4720d86541a | 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 | //Avoid division by decimal digits :). Always try to multiply with whole numbers or fractions instead.
//if getting wrong answer then use long/double instead of int/float
//e + e = o; o + o = e; e + o = o;
//see stuff in a jugaad way... if you are being complicated you are doing it wrong
//If a=b+1 and b is even, then a∧b=1
//If there is a statement in the question that it can be proved that ... then it means there is a very very simple logic behind it, and is not a simulation or dp question.
//Be confident in Maths you are not that bad at it.
// add break statement where you are stopping. Do not forget that, as people may use that weakness to hack your solution.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner reader = new Scanner(System.in);
int test = reader.nextInt();
for (int o = 0; o < test; o++) {
int n = reader.nextInt();
int m = reader.nextInt();
char[] arr = reader.next().toCharArray();
int min_x = 0; int min_y = 0; int max_x = 0; int max_y = 0;
int bx = 0; int by = 0;
for (int i = 0; i < arr.length; i++){
if (arr[i] == 'L'){by -= 1; min_y = Math.min(min_y, by);}
else if (arr[i] == 'R'){by += 1; max_y = Math.max(max_y, by);}
else if (arr[i] == 'D'){bx += 1; max_x = Math.max(max_x, bx);}
else {bx -= 1; min_x = Math.min(min_x, bx);}
if (-min_x + max_x >= n){
if (bx == min_x) min_x += 1;
break;
}
if (-min_y + max_y >=m ){
if (by == min_y) min_y += 1;
break;
}
}
int xx = 1 - min_x; int yy = 1 - min_y;
System.out.println(xx + " " + yy);
}
}
}
//------------------------------------XX---Templatecode---XX--------------------------------------
class Template{
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);
}
}
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 11 | 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 | 249c38bfde494222f7c2dca01e48f30f | 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.io.PrintWriter;
import java.util.*;
public class Main {
static long mod = 1_000_000_007;
public static void main(String[] args) {
FastScanner f = new FastScanner();
PrintWriter p = new PrintWriter(System.out);
int t=f.nextInt();
while(t-->0) {
int n=f.nextInt();
int m=f.nextInt();
char c[]=f.next().toCharArray();
int l=0;int r=0;int u=0;int d=0;
int x=0;int y=0;
for(int i=0;i<c.length;i++) {
if(c[i]=='R') {
r=Math.max(r, ++y);
}else if(c[i]=='L') {
l=Math.min(l, --y);
}else if(c[i]=='U') {
u=Math.min(u, --x);
}else {
d=Math.max(d, ++x);
}
if(r-l>=m) {
if(y==l) l++;
break;
}
if(d-u>=n) {
if(x==u) u++;
break;
}
}
int resx=1-u;
int resy=1-l;
p.println(resx+" "+resy);
}
p.close();
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
static int offx[] = { -1, -1, -1, 0, 1, 1, 1, 0 };
static int offy[] = { -1, 0, 1, 1, 1, 0, -1, -1 };
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long add(long x, long y) {
x += y;
if (x >= mod)
return (x % mod);
return x;
}
static long sub(long x, long y) {
x -= y;
if (x < 0)
return (x + mod);
return x;
}
static long mul(long x, long y) {
return (x * y) % mod;
}
static long bin_pow(long x, long p) {
if (p == 0)
return 1;
if ((p & 1) != 0)
return mul(x, bin_pow(x, p - 1));
return bin_pow(mul(x, x), p / 2);
}
static long rev(long x) {
return bin_pow(x, mod - 2);
}
static long div(long x, long y) {
return mul(x, rev(y));
}
// will work till array size of 65537---fastest sorting time
static long[] radixSort(long[] f) {
return radixSort(f, f.length);
}
static long[] radixSort(long[] f, int n) {
long[] to = new long[n];
{
int[] b = new int[65537];
for (int i = 0; i < n; i++)
b[1 + (int) (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++)
b[i] += b[i - 1];
for (int i = 0; i < n; i++)
to[b[(int) (f[i] & 0xffff)]++] = f[i];
long[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < n; i++)
b[1 + (int) (f[i] >>> 16 & 0xffff)]++;
for (int i = 1; i <= 65536; i++)
b[i] += b[i - 1];
for (int i = 0; i < n; i++)
to[b[(int) (f[i] >>> 16 & 0xffff)]++] = f[i];
long[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < n; i++)
b[1 + (int) (f[i] >>> 32 & 0xffff)]++;
for (int i = 1; i <= 65536; i++)
b[i] += b[i - 1];
for (int i = 0; i < n; i++)
to[b[(int) (f[i] >>> 32 & 0xffff)]++] = f[i];
long[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < n; i++)
b[1 + (int) (f[i] >>> 48 & 0xffff)]++;
for (int i = 1; i <= 65536; i++)
b[i] += b[i - 1];
for (int i = 0; i < n; i++)
to[b[(int) (f[i] >>> 48 & 0xffff)]++] = f[i];
long[] d = f;
f = to;
to = d;
}
return f;
}
// Function to sort an array using quick sort algorithm.
static void quickSort(long arr[], int low, int high) {
if (low < high) {
int p = partition(arr, low, high);
quickSort(arr, low, p - 1);
quickSort(arr, p + 1, high);
}
}
static int partition(long arr[], int low, int high) {
long pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
long temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
/// Ceils
static long ceil(long x, long m) {
long res = x / m;
if (x % m != 0) {
res++;
}
return res;
}
// ------------------------------------------------------------------------------------------------
// makes the prefix sum array
static long[] prefixSum(long arr[], int n) {
long psum[] = new long[n];
psum[0] = arr[0];
for (int i = 1; i < n; i++) {
psum[i] = psum[i - 1] + arr[i];
}
return psum;
}
// ------------------------------------------------------------------------------------------------
// makes the suffix sum array
static long[] suffixSum(long arr[], int n) {
long ssum[] = new long[n];
ssum[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--) {
ssum[i] = ssum[i + 1] + arr[i];
}
return ssum;
}
//------------------------------------------------------------------------------------------
// BINARY EXPONENTIATION OF A NUMBER MODULO M FASTER METHOD WITHOUT RECURSIVE
// OVERHEADS
// static long m = (long) (1e9 + 7);
static long binPower(long a, long n, long m) {
if (n == 0)
return 1;
long res = 1;
while (n > 0) {
if ((n & 1) != 0) {
res *= a;
}
a *= a;
n >>= 1;
}
return res;
}
//-------------------------------------------------------------------------------------------
// gcd
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
//------------------------------------------------------------------------------------------
// lcm
static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
// ------------------------------------------------------------------------------------------
// BRIAN KERNINGHAM TO CHECK NUMBER OF SET BITS
// O(LOGn)
static int setBits(int n) {
int count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}
//------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
// 0 based indexing
static boolean KthBitSet(int n, int k) {
int mask = 1;
mask = mask <<= k;
if ((mask & n) != 0)
return true;
else
return false;
}
//------------------------------------------------------------------------------------------
// EXTENDED EUCLIDEAN THEOREM
// TO REPRESENT GCD IN TERMS OF A AND B
// gcd(a,b) = a.x + b.y where x and y are integers
static long x = -1;
static long y = -1;
static long gcdxy(long a, long b) {
if (b == 0) {
x = 1;
y = 0;
return a;
} else {
long d = gcdxy(b, a % b);
long x1 = y;
long y1 = x - (a / b) * y;
x = x1;
y = y1;
return d;
}
}
//-------------------------------------------------------------------------------------------------
}
| 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 11 | 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 | ca1a54ff60b45f441be29637a98b279a | 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.StringTokenizer;
public class RobotOnTheBoard1 {
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 nextFloat() { return Float.parseFloat(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n)
{
int[] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
long[] nextArrayLong(int n)
{
long[] a = new long[n];
for (int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
}
public static void solve(int n, int m, String s) {
int maxX = 1;
int minX = 1;
int maxY = 1;
int minY = 1;
int currentX = 1;
int currentY = 1;
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (c == 'L') {
if (maxX-currentX+2>m) {
break;
}
currentX -= 1;
}
else if (c == 'R'){
if (currentX-minX+2>m) {
break;
}
currentX += 1;
}
else if (c == 'U'){
if (maxY-currentY+2>n) {
break;
}
currentY -= 1;
}
else {
if (currentY-minY+2>n) {
break;
}
currentY += 1;
}
maxX = Math.max(maxX, currentX);
minX = Math.min(minX, currentX);
maxY = Math.max(maxY, currentY);
minY = Math.min(minY, currentY);
}
currentX = 1;
currentY = 1;
currentX += Math.max(0, 1-minX);
currentX -= Math.max(0, maxX-m);
currentY += Math.max(0, 1-minY);
currentY -= Math.max(0, maxY-n);
System.out.println(currentY + " " + currentX);
}
public static void main(String[] args) {
FastReader in = new FastReader();
int t = in.nextInt();
while (t-- > 0) {
solve(in.nextInt(), in.nextInt(), in.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 11 | 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 | 777e075ae7231ce51caf93d9057d1b82 | 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 {
private static FS sc = new FS();
private static class FS {
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());
}
}
private static class extra {
static int[] intArr(int size) {
int[] a = new int[size];
for(int i = 0; i < size; i++) a[i] = sc.nextInt();
return a;
}
static long[] longArr(int size) {
long[] a = new long[size];
for(int i = 0; i < size; i++) a[i] = sc.nextLong();
return a;
}
static long intSum(int[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static long longSum(long[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static LinkedList[] graphD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
}
return temp;
}
static LinkedList[] graphUD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
temp[y].add(x);
}
return temp;
}
static void printG(LinkedList[] temp) {
for(LinkedList<Integer> aa:temp) System.out.println(aa);
}
static long cal(long val, long pow, long mod) {
if(pow == 0) return 1;
long res = cal(val, pow/2, mod);
long ret = (res*res)%mod;
if(pow%2 == 0) return ret;
return (val*ret)%mod;
}
static long gcd(long a, long b) { return b == 0 ? a:gcd(b, a%b); }
}
static int mod = (int) 1e9 + 7;
static LinkedList<String>[] temp, temp2;
static int inf = (int) 1e9;
// static long inf = Long.MAX_VALUE;
public static void main(String[] args) {
int t = sc.nextInt();
// int t = 1;
StringBuilder ret = new StringBuilder();
while(t-- > 0) {
int n = sc.nextInt(), m = sc.nextInt();
String s = sc.next();
int deltaX = 0, deltaY = 0;
int maxDeltaX = 0, minDeltaX = 0;
int maxDeltaY = 0, minDeltaY = 0;
int ansX = 1,ansY = 1;
for(int i = 0; i < s.length(); i++) {
char x = s.charAt(i);
if (x == 'L') deltaY--;
if (x == 'R') deltaY++;
if (x == 'U') deltaX--;
if (x == 'D') deltaX++;
minDeltaX = Math.min(minDeltaX,deltaX);
minDeltaY = Math.min(minDeltaY,deltaY);
maxDeltaX = Math.max(maxDeltaX,deltaX);
maxDeltaY = Math.max(maxDeltaY,deltaY);
int maxX = n - maxDeltaX;
int minX = 1 - minDeltaX;
int maxY = m - maxDeltaY;
int minY = 1 - minDeltaY;
if (minX <= maxX && minY <= maxY){
ansX = minX;
ansY = minY;
}
else break;
}
ret.append(ansX + " " + ansY + "\n");
}
System.out.println(ret);
}
}
| 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 11 | 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.