{ }codelper
filled listslist indexingappendingP0146

Theater seats and a waiting line

A small theater has n seats numbered 1 to n, all empty at first.
There is also a waiting line for when no seat is free, empty at first.
The first line gives n and the number of commands q, and each of the next q lines gives one command.
Print the result of each command on its own line. - "book name k": if that name is already seated or in the waiting line, or seat k is taken, change nothing and print 0.
Otherwise seat the name in seat k and print k. - "any name": if that name is already seated or in the waiting line, print 0.
Otherwise seat the name in the free seat with the smallest number and print that number.
If no seat is free, put the name at the end of the waiting line and print w followed directly by its place in the line (the front is 1), for example w3. - "cancel name": if that name is seated, free the seat and print the seat number.
If anyone is waiting, the person at the front leaves the line and takes that seat at once.
If the name is in the waiting line, remove it and print w followed directly by the place it had.
Everyone behind it moves up one place.
If the name is nowhere, print 0. - "where name": print the seat number of that name, or w followed directly by its current place if it is waiting, or 0 if it is nowhere. After all commands, print the seat states as n characters on the last line.
The i-th character is '#' if seat i is taken and '.' if it is free.

Input
1 ≤ n ≤ 200, 1 ≤ q ≤ 2000, 1 ≤ k ≤ n.
Names are 1 to 10 lowercase English letters or digits.
The command, name and k are separated by single spaces
Output
q + 1 lines: for each command a seat number, w with a place in line, or 0; then the n-character seat state
Example 1 · stdin
3 9
book ann 2
any bob
any cy
any dan
any eve
where eve
cancel ann
where dan
cancel eve
stdout
2
1
3
w1
w2
w2
2
2
w1
###
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

You build a list filled with the empty string "" and look up the index where a name sits.
Slot 0 is seat 1, so add 1 when printing.
Filling: Python [""] * n, JS/TS new Array(n).fill(""), Java new ArrayList<>(Collections.nCopies(n, "")), C# Enumerable.Repeat("", n).ToList(), C++ std::vector<std::string> seats(n, ""), Craykon NewList(n, "") (새목록(n, "")).
In C, set the first character of each row of char seats[200][11] to '\0' to get empty strings.
Trap one: JS new Array(n) alone only has empty slots, not "", so seats[k - 1] === "" is always false.
Java new String[n] is full of null, so calling equals throws NullPointerException (C# new string[n] is null too, but == does not crash on null).
Finding the index: Python index, JS/TS/Java indexOf, C# IndexOf, C++ std::find, Craykon IndexOf (자리찾기).
Trap two: for a missing value the others return -1, but Python index stops with ValueError, so ask with in first.
Appending to the line is Python append, JS/TS push, Java/C# add/Add, C++ push_back, Craykon Add (넣기); taking the front is Python pop(0), JS/TS shift(), Java remove(0), C# RemoveAt(0), Craykon RemoveAt(0) (자리빼기(0)).
Trap three: Python pop() takes the person at the back.

Pythonmain.py · 49 lines
import sys lines = sys.stdin.read().split("\n")n, q = map(int, lines[0].split())seats = [""] * n   # 빈 자리는 "" — 0번 칸이 1번 자리waiting = []       # 대기 줄, 맨 앞이 0번out = [] for line in lines[1:q + 1]:    p = line.split()    cmd, name = p[0], p[1]    if cmd == "book" or cmd == "any":        if name in seats or name in waiting:            out.append("0")        elif cmd == "book":            k = int(p[2])            if seats[k - 1] == "":                seats[k - 1] = name                out.append(str(k))            else:                out.append("0")        elif "" in seats:            i = seats.index("")   # 가장 작은 번호의 빈 자리            seats[i] = name            out.append(str(i + 1))        else:            waiting.append(name)            out.append(f"w{len(waiting)}")    elif cmd == "cancel":        if name in seats:            i = seats.index(name)            seats[i] = waiting.pop(0) if waiting else ""   # 대기 맨 앞 사람이 바로 앉는다            out.append(str(i + 1))        elif name in waiting:            i = waiting.index(name)            waiting.pop(i)            out.append(f"w{i + 1}")        else:            out.append("0")    else:  # where        if name in seats:            out.append(str(seats.index(name) + 1))        elif name in waiting:            out.append(f"w{waiting.index(name) + 1}")        else:            out.append("0") out.append("".join("." if s == "" else "#" for s in seats))print("\n".join(out))
JavaScriptmain.js · 47 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const [n, q] = lines[0].trim().split(" ").map(Number);const seats = new Array(n).fill(""); // 빈 자리는 "" — 0번 칸이 1번 자리const waiting = []; // 대기 줄, 맨 앞이 0번const out = []; for (const line of lines.slice(1, q + 1)) {  const [cmd, name, k] = line.trim().split(" ");  if (cmd === "book" || cmd === "any") {    if (seats.includes(name) || waiting.includes(name)) {      out.push("0");    } else if (cmd === "book") {      const at = Number(k) - 1;      if (seats[at] === "") {        seats[at] = name;        out.push(String(at + 1));      } else {        out.push("0");      }    } else if (seats.includes("")) {      const at = seats.indexOf(""); // 가장 작은 번호의 빈 자리      seats[at] = name;      out.push(String(at + 1));    } else {      waiting.push(name);      out.push(`w${waiting.length}`);    }  } else if (cmd === "cancel") {    const at = seats.indexOf(name);    const w = waiting.indexOf(name);    if (at !== -1) {      seats[at] = waiting.length > 0 ? waiting.shift() : ""; // 대기 맨 앞 사람이 바로 앉는다      out.push(String(at + 1));    } else if (w !== -1) {      waiting.splice(w, 1);      out.push(`w${w + 1}`);    } else {      out.push("0");    }  } else {    const at = seats.indexOf(name);    const w = waiting.indexOf(name);    out.push(at !== -1 ? String(at + 1) : w !== -1 ? `w${w + 1}` : "0");  }}out.push(seats.map((s) => (s === "" ? "." : "#")).join(""));console.log(out.join("\n"));
TypeScriptmain.ts · 48 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const [n, q] = lines[0].trim().split(" ").map(Number);const seats: string[] = new Array<string>(n).fill(""); // 빈 자리는 "" — 0번 칸이 1번 자리const waiting: string[] = []; // 대기 줄, 맨 앞이 0번const out: string[] = []; for (const line of lines.slice(1, q + 1)) {  const [cmd, name, k] = line.trim().split(" ");  if (cmd === "book" || cmd === "any") {    if (seats.includes(name) || waiting.includes(name)) {      out.push("0");    } else if (cmd === "book") {      const at = Number(k) - 1;      if (seats[at] === "") {        seats[at] = name;        out.push(String(at + 1));      } else {        out.push("0");      }    } else if (seats.includes("")) {      const at = seats.indexOf(""); // 가장 작은 번호의 빈 자리      seats[at] = name;      out.push(String(at + 1));    } else {      waiting.push(name);      out.push(`w${waiting.length}`);    }  } else if (cmd === "cancel") {    const at = seats.indexOf(name);    const w = waiting.indexOf(name);    if (at !== -1) {      seats[at] = waiting.shift() ?? ""; // 대기 맨 앞 사람이 바로 앉는다(없으면 빈 자리)      out.push(String(at + 1));    } else if (w !== -1) {      waiting.splice(w, 1);      out.push(`w${w + 1}`);    } else {      out.push("0");    }  } else {    const at = seats.indexOf(name);    const w = waiting.indexOf(name);    out.push(at !== -1 ? String(at + 1) : w !== -1 ? `w${w + 1}` : "0");  }}out.push(seats.map((s) => (s === "" ? "." : "#")).join(""));console.log(out.join("\n"));
JavaMain.java · 56 lines
import java.io.*;import java.util.*; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        String[] first = br.readLine().trim().split(" ");        int n = Integer.parseInt(first[0]), q = Integer.parseInt(first[1]);        // 빈 자리는 "" — new String[n]은 null로 차니 nCopies로 ""를 채운다        List<String> seats = new ArrayList<>(Collections.nCopies(n, ""));        List<String> waiting = new ArrayList<>(); // 대기 줄, 맨 앞이 0번        StringBuilder out = new StringBuilder();         for (int t = 0; t < q; t++) {            String[] p = br.readLine().trim().split(" ");            String cmd = p[0], name = p[1];            int at = seats.indexOf(name), w = waiting.indexOf(name);            String res;            if (cmd.equals("book") || cmd.equals("any")) {                if (at != -1 || w != -1) {                    res = "0";                } else if (cmd.equals("book")) {                    int k = Integer.parseInt(p[2]);                    if (seats.get(k - 1).isEmpty()) {                        seats.set(k - 1, name);                        res = String.valueOf(k);                    } else {                        res = "0";                    }                } else if (seats.contains("")) {                    int free = seats.indexOf(""); // 가장 작은 번호의 빈 자리                    seats.set(free, name);                    res = String.valueOf(free + 1);                } else {                    waiting.add(name);                    res = "w" + waiting.size();                }            } else if (cmd.equals("cancel")) {                if (at != -1) {                    seats.set(at, waiting.isEmpty() ? "" : waiting.remove(0)); // 대기 맨 앞 사람이 바로 앉는다                    res = String.valueOf(at + 1);                } else if (w != -1) {                    waiting.remove(w); // int를 넘기면 자리로 뺀다                    res = "w" + (w + 1);                } else {                    res = "0";                }            } else {                res = at != -1 ? String.valueOf(at + 1) : w != -1 ? "w" + (w + 1) : "0";            }            out.append(res).append('\n');        }        for (String s : seats) out.append(s.isEmpty() ? '.' : '#');        System.out.println(out);    }}
C#Main.cs · 72 lines
using System;using System.Collections.Generic;using System.Linq;using System.Text; class Program{    static void Main()    {        int[] first = Console.ReadLine().Trim().Split(' ').Select(int.Parse).ToArray();        int n = first[0], q = first[1];        var seats = Enumerable.Repeat("", n).ToList(); // 빈 자리는 "" — 0번 칸이 1번 자리        var waiting = new List<string>();              // 대기 줄, 맨 앞이 0번        var sb = new StringBuilder();         for (int t = 0; t < q; t++)        {            string[] p = Console.ReadLine().Trim().Split(' ');            string cmd = p[0], name = p[1];            int at = seats.IndexOf(name), w = waiting.IndexOf(name);            string res;            if (cmd == "book" || cmd == "any")            {                if (at != -1 || w != -1) res = "0";                else if (cmd == "book")                {                    int k = int.Parse(p[2]);                    if (seats[k - 1] == "")                    {                        seats[k - 1] = name;                        res = k.ToString();                    }                    else res = "0";                }                else if (seats.Contains(""))                {                    int free = seats.IndexOf(""); // 가장 작은 번호의 빈 자리                    seats[free] = name;                    res = (free + 1).ToString();                }                else                {                    waiting.Add(name);                    res = "w" + waiting.Count;                }            }            else if (cmd == "cancel")            {                if (at != -1)                {                    seats[at] = "";                    if (waiting.Count > 0) // 대기 맨 앞 사람이 바로 앉는다                    {                        seats[at] = waiting[0];                        waiting.RemoveAt(0);                    }                    res = (at + 1).ToString();                }                else if (w != -1)                {                    waiting.RemoveAt(w);                    res = "w" + (w + 1);                }                else res = "0";            }            else res = at != -1 ? (at + 1).ToString() : w != -1 ? "w" + (w + 1) : "0";            sb.Append(res).Append('\n');        }        foreach (string s in seats) sb.Append(s == "" ? '.' : '#');        Console.WriteLine(sb);    }}
C++main.cpp · 64 lines
#include <algorithm>#include <iostream>#include <string>#include <vector> // 목록에서 처음 나오는 자리, 없으면 -1int index_of(const std::vector<std::string>& v, const std::string& x) {    auto it = std::find(v.begin(), v.end(), x);    return it == v.end() ? -1 : int(it - v.begin());} int main() {    int n, q;    std::cin >> n >> q;    std::vector<std::string> seats(n, ""); // 빈 자리는 "" — 0번 칸이 1번 자리    std::vector<std::string> waiting;      // 대기 줄, 맨 앞이 0번    std::string out;     for (int t = 0; t < q; t++) {        std::string cmd, name;        std::cin >> cmd >> name;        int at = index_of(seats, name), w = index_of(waiting, name);        std::string res;        if (cmd == "book" || cmd == "any") {            int k = 0;            if (cmd == "book") std::cin >> k; // 자리 번호는 book에만 있다            if (at != -1 || w != -1) {                res = "0";            } else if (cmd == "book") {                if (seats[k - 1].empty()) {                    seats[k - 1] = name;                    res = std::to_string(k);                } else {                    res = "0";                }            } else if (int free = index_of(seats, ""); free != -1) { // 가장 작은 번호의 빈 자리                seats[free] = name;                res = std::to_string(free + 1);            } else {                waiting.push_back(name);                res = "w" + std::to_string(waiting.size());            }        } else if (cmd == "cancel") {            if (at != -1) {                seats[at] = "";                if (!waiting.empty()) { // 대기 맨 앞 사람이 바로 앉는다                    seats[at] = waiting.front();                    waiting.erase(waiting.begin());                }                res = std::to_string(at + 1);            } else if (w != -1) {                waiting.erase(waiting.begin() + w);                res = "w" + std::to_string(w + 1);            } else {                res = "0";            }        } else {            res = at != -1 ? std::to_string(at + 1) : w != -1 ? "w" + std::to_string(w + 1) : "0";        }        out += res + "\n";    }    for (const auto& s : seats) out += s.empty() ? '.' : '#';    std::cout << out << "\n";}
Cmain.c · 78 lines
#include <stdio.h>#include <string.h> #define MAXN 200#define MAXQ 2000 static char seats[MAXN][11];   /* 빈 자리는 "" — 0번 칸이 1번 자리 */static char waiting[MAXQ][11]; /* 대기 줄, 맨 앞이 0번 */static int wait_count = 0; /* 이름 목록에서 처음 나오는 자리, 없으면 -1 */static int index_of(char list[][11], int count, const char *x) {    for (int i = 0; i < count; i++)        if (strcmp(list[i], x) == 0) return i;    return -1;} /* 대기 줄에서 i번을 빼고 뒤의 사람을 한 칸씩 당긴다 */static void remove_waiting(int i) {    memmove(waiting[i], waiting[i + 1], (size_t)(wait_count - i - 1) * sizeof waiting[0]);    wait_count--;} int main(void) {    int n, q;    scanf("%d %d", &n, &q);    for (int i = 0; i < n; i++) seats[i][0] = '\0'; /* 모든 자리를 빈 문자열로 채운다 */     for (int t = 0; t < q; t++) {        char cmd[8], name[11];        scanf("%7s %10s", cmd, name);        int at = index_of(seats, n, name), w = index_of(waiting, wait_count, name);        if (strcmp(cmd, "book") == 0 || strcmp(cmd, "any") == 0) {            int k = 0;            if (cmd[0] == 'b') scanf("%d", &k);            if (at != -1 || w != -1) {                puts("0");            } else if (cmd[0] == 'b') {                if (seats[k - 1][0] == '\0') {                    strcpy(seats[k - 1], name);                    printf("%d\n", k);                } else {                    puts("0");                }            } else {                int free = index_of(seats, n, ""); /* 가장 작은 번호의 빈 자리 */                if (free != -1) {                    strcpy(seats[free], name);                    printf("%d\n", free + 1);                } else {                    strcpy(waiting[wait_count++], name);                    printf("w%d\n", wait_count);                }            }        } else if (strcmp(cmd, "cancel") == 0) {            if (at != -1) {                seats[at][0] = '\0';                if (wait_count > 0) { /* 대기 맨 앞 사람이 바로 앉는다 */                    strcpy(seats[at], waiting[0]);                    remove_waiting(0);                }                printf("%d\n", at + 1);            } else if (w != -1) {                remove_waiting(w);                printf("w%d\n", w + 1);            } else {                puts("0");            }        } else {            if (at != -1) printf("%d\n", at + 1);            else if (w != -1) printf("w%d\n", w + 1);            else puts("0");        }    }    for (int i = 0; i < n; i++) putchar(seats[i][0] == '\0' ? '.' : '#');    putchar('\n');    return 0;}
Craykonmain.cray · 78 lines
first = Console.ReadLine().Trim().Split();n = first[0].ToNumber();q = first[1].ToNumber();seats = NewList(n, ""); // 빈 자리는 "" — 0번 칸이 1번 자리waiting = []; // 대기 줄, 맨 앞이 0번 for (t = 0; t < q; t++){    p = Console.ReadLine().Trim().Split();    cmd = p[0];    name = p[1];    at = seats.IndexOf(name);    w = waiting.IndexOf(name);    res = "0";    if (cmd == "book" || cmd == "any")    {        if (at == -1 && w == -1)        {            if (cmd == "book")            {                k = p[2].ToNumber();                if (seats[k - 1] == "")                {                    seats[k - 1] = name;                    res = "" + k;                }            }            else if (seats.Contains(""))            {                free = seats.IndexOf(""); // 가장 작은 번호의 빈 자리                seats[free] = name;                res = "" + (free + 1);            }            else            {                waiting.Add(name);                res = "w" + waiting.Count;            }        }    }    else if (cmd == "cancel")    {        if (at != -1)        {            seats[at] = "";            if (waiting.Count > 0)            {                seats[at] = waiting[0];                waiting.RemoveAt(0);            }            res = "" + (at + 1);        }        else if (w != -1)        {            waiting.RemoveAt(w);            res = "w" + (w + 1);        }    }    else    {        if (at != -1)        {            res = "" + (at + 1);        }        else if (w != -1)        {            res = "w" + (w + 1);        }    }    Console.WriteLine(res);} map = "";foreach (s in seats){    map = map + (s == "" ? "." : "#");}Console.WriteLine(map);