Java 城市交通规划模拟:铁路修建与最远可达城市查询
import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int t = sc.nextInt(); int[] left = new int[n + 1]; // left[i]表示从i开始往左最远能到达的城市编号 int[] right = new int[n + 1]; // right[i]表示从i开始往右最远能到达的城市编号 for (int i = 1; i <= n; i++) { left[i] = i; right[i] = i; } for (int i = 0; i < t; i++) { String op = sc.next(); int x = sc.nextInt(); if (op.equals('L')) { if (x > 1 && left[x - 1] == x - 1) { // x左边有城市且未修建铁路 left[x] = left[x - 1]; // 更新left[x] right[left[x - 1]] = x; // 更新right[left[x-1]] } } else if (op.equals('R')) { if (x < n && right[x + 1] == x + 1) { // x右边有城市且未修建铁路 right[x] = right[x + 1]; // 更新right[x] left[right[x + 1]] = x; // 更新left[right[x+1]] } } else { // op.equals('Q') System.out.println(left[x] + ' ' + right[x]); } } sc.close(); } }
原文地址: https://www.cveoy.top/t/topic/oE5q 著作权归作者所有。请勿转载和采集!