Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Collections;
- import java.util.Stack;
- public class HDNL {
- public static void main(String[] args) throws IOException {
- BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));
- int n = Integer.parseInt(scanner.readLine());
- StringBuilder answer = new StringBuilder();
- String[] tags = new String[n];
- int[] indexes = new int[n];
- for (int i = 0; i < n; i++) {
- String input = scanner.readLine();
- StringBuilder strBuilder = new StringBuilder(input);
- int number = Integer.parseInt(strBuilder.deleteCharAt(0).toString());
- tags[i] = input;
- indexes[i] = number;
- }
- int curValue = indexes[0];
- int nestLvl = 0;
- String spaces = String.join("", Collections.nCopies(nestLvl, " "));
- answer.append(spaces).append("<").append(tags[0]).append(">").append("\n");
- Stack<Tag> stack = new Stack<>();
- stack.push(new Tag(tags[0], indexes[0], nestLvl));
- for (int i = 1; i < n; i++) {
- if (indexes[i] > curValue) {
- curValue = indexes[i];
- nestLvl++;
- spaces = String.join("", Collections.nCopies(nestLvl, " "));
- answer.append(spaces).append("<").append(tags[i]).append(">").append("\n");
- stack.push(new Tag(tags[i], indexes[i], nestLvl));
- } else {
- curValue = indexes[i];
- while (!stack.isEmpty() && curValue <= stack.peek().value) {
- Tag previousTag = stack.pop();
- spaces = String.join("", Collections.nCopies(previousTag.nestLvl, " "));
- answer.append(spaces).append("</").append(previousTag.tag).append(">").append("\n");
- if (!stack.isEmpty() && curValue < previousTag.value && curValue <= stack.peek().value) {
- nestLvl--;
- nestLvl = Math.max(nestLvl, 0);
- }
- }
- spaces = String.join("", Collections.nCopies(nestLvl, " "));
- answer.append(spaces).append("<").append(tags[i]).append(">").append("\n");
- stack.push(new Tag(tags[i], indexes[i], nestLvl));
- }
- }
- while (!stack.isEmpty()) {
- Tag lastTag = stack.pop();
- spaces = String.join("", Collections.nCopies(lastTag.nestLvl, " "));
- answer.append(spaces).append("</").append(lastTag.tag).append(">").append("\n");
- }
- System.out.println(answer);
- }
- public static class Tag {
- public String tag;
- public int value;
- public int nestLvl;
- public Tag(String tag, int value, int nestLvl) {
- this.tag = tag;
- this.value = value;
- this.nestLvl = nestLvl;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement