An alarm clock has n alarms, numbered 1 to n. At first none of them rings on any day. The day names are MON, TUE, WED, THU, FRI, SAT, SUN, with values 1, 2, 4, 8, 16, 32, 64 in that order. There are also three group names. WEEKDAYS means the five days MON to FRI, WEEKEND means the two days SAT and SUN, and EVERYDAY means all seven days. Below, a name is one of these ten day and group names. Several names together mean all the days that any of them means. There are five commands. - set i name…: alarm i now rings exactly on the days the listed names mean. - add i name…: add the listed days to alarm i. Days it already rings on stay on. - remove i name…: remove the listed days from alarm i. Days it did not ring on stay off. - flip i: flip all seven days of alarm i. Days it rang on are turned off, and days it did not ring on are turned on. - count name: print on one line the number of alarms that ring on every day the name means. An alarm that rings on only some of those days is not counted. After all commands, print one line per alarm, from alarm 1 to alarm n: its day value and its day label, separated by one space. The day value is the sum of the values of the days the alarm rings on. The day label is built as follows. - If the alarm rings on no day, it is NONE. - If it rings on all seven days, it is EVERYDAY. - Otherwise, first write WEEKDAYS if it rings on all of MON to FRI, and WEEKEND if it rings on both SAT and SUN. Then write the remaining days not covered by those groups, in the order MON, TUE, WED, THU, FRI, SAT, SUN. Separate the names with one space. Declare the days and the group names as a flags enum in which each day takes one bit, and solve it with bit operations. Grading looks only at the output.
Input
The first line has the number of alarms n (1 ≤ n ≤ 100) and the number of commands q (1 ≤ q ≤ 5,000), separated by one space. Each of the next q lines has one command. The parts of a command are separated by one space. The alarm number i satisfies 1 ≤ i ≤ n. Each name is one of the ten above, written in uppercase. A set, add or remove command lists 1 to 10 names, and the same name may appear more than once. A count command lists exactly one name
Output
For each count command, in command order, one line with the number of alarms counted at that moment (this part is empty if there is no count command). Then n lines, from alarm 1: "day value day label"
Example 1 · stdin
3 8
set 1 WEEKDAYS
add 1 SUN
set 2 WEEKEND MON
remove 2 TUE SUN
count WEEKEND
flip 3
count SAT
remove 3 WEEKDAYS
stdout
0
2
95 WEEKDAYS SUN
33 MON SAT
96 WEEKEND
Example 2 · stdin
3 5
set 1 SUN SAT MON
set 2 SUN
add 3 FRI
remove 3 FRI THU
count SUN
stdout
2
97 WEEKEND MON
64 SUN
0 NONE
main.py
Error List00F8 ↓ · ⇧F8 ↑
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 · 6 languages
This problem accepts only the languages with enums: Python, TypeScript, Java, C#, C and C++. JavaScript and Craykon have no enum syntax. If each day gets one bit (1, 2, 4, …), a set of days becomes a single integer: adding is |, removing is & ~, and "has all of" is (a & b) == b. Languages support such "flags enums" in different ways. In Python, a class inheriting enum.Flag can hold groups as members too, like WEEKDAYS = MON | TUE | WED | THU | FRI; Day["SUN"] looks a name up, and group in days means "has all of". ~days flips only within the seven declared bits. Trap 1: .name gives a name like WEEKDAYS only for a value exactly equal to a group; other combinations get the single days joined with |, as in MON|TUE|WED|THU|FRI|SUN, and the empty value gets None. Used directly, the first example's 95 becomes 95 MON TUE WED THU FRI SUN. So the solution builds the label itself. A TypeScript numeric enum can also compute values in the declaration, like MON = 1 << 0 and WEEKEND = SAT | SUN, and Day[31] returns "WEEKDAYS". Trap 2: but the values are plain numbers, so ~ flips the whole 32-bit integer. ~0 is -1, not 127. Without & Day.EVERYDAY to keep only seven bits, alarm 3 in the first example comes out as -32 WEEKEND. Python's plain int (~0 is -1) and C's unsigned (~0u is 4294967295) behave the same way, so the C solution also adds & EVERYDAY. Java enums have no bit values. Instead an EnumSet represents a set of days, and as documented it works as a bit vector inside. EnumSet.range(MON, FRI), containsAll, removeAll and EnumSet.complementOf build a group, test "has all of", remove and flip. Iteration always follows declaration order. Trap 3: an EnumSet is a mutable object. If you put a constant set such as WEEKDAYS or SUN from the name → set table into an alarm without copying it and then call addAll, the constant itself changes. In the second example set 1 SUN SAT MON modifies the constant SUN, so alarm 2 comes out as 97 WEEKEND MON. The solution collects names into a new set made with EnumSet.noneOf. In C#, an enum marked [Flags] takes |, & and ~ directly, and days.HasFlag(group) means "has all of". But ~Day.MON is -2, so C# needs & Day.EVERYDAY too. Trap 4: counting with (a & want) != 0 means "has any of". The first example's count WEEKEND becomes 2 instead of 0. Trap 5: ToString() on a [Flags] enum does use group names, but it lists names from the smallest value up, joined with , . Even with , replaced by a space, alarm 1 in the second example becomes MON WEEKEND, not the problem's order (groups first). The constants of a C enum are just labeled int values, so you give values directly, like MON = 1 << 0, and use bit operations as they are. The name strings live in a separate table. Trap 6: removing with ^ (XOR) does not remove days that were off; it turns them on. In the first example, remove 2 TUE SUN leaves alarm 2 as 35 MON TUE SAT instead of 33 MON SAT. A C++ enum class does not convert to an integer by itself, so Day::MON | Day::TUE is a compile error. The solution fixes the underlying type as unsigned and defines operator|, operator& and operator~ itself. operator~ cuts the result to seven bits, which blocks the flip trap in one place.
Pythonmain.py · 73 lines
import sysfrom enum import Flagclass Day(Flag): MON = 1 TUE = 2 WED = 4 THU = 8 FRI = 16 SAT = 32 SUN = 64 # 묶음 이름도 같은 열거형의 값이다(요일 값을 | 로 합친 것) WEEKDAYS = MON | TUE | WED | THU | FRI WEEKEND = SAT | SUN EVERYDAY = WEEKDAYS | WEEKENDSINGLES = [Day.MON, Day.TUE, Day.WED, Day.THU, Day.FRI, Day.SAT, Day.SUN]NONE = Day(0)def parse(names): days = NONE for name in names: days |= Day[name] return daysdef label(days): # .name은 묶음이 아닌 조합에 "MON|SAT|SUN"을 주므로 표시는 직접 만든다 if days == NONE: return "NONE" if days == Day.EVERYDAY: return "EVERYDAY" parts = [] rest = days for group in (Day.WEEKDAYS, Day.WEEKEND): if group in days: # Flag의 in은 "group의 비트를 모두 가졌는가" parts.append(group.name) rest &= ~group parts += [d.name for d in SINGLES if d in rest] return " ".join(parts)def main(): lines = sys.stdin.read().split("\n") n, q = map(int, lines[0].split()) alarms = [NONE] * (n + 1) out = [] for line in lines[1:q + 1]: cmd, *args = line.split() if cmd == "count": want = Day[args[0]] out.append(str(sum(1 for a in alarms[1:] if want in a))) continue i = int(args[0]) if cmd == "flip": alarms[i] = ~alarms[i] # Flag의 ~는 선언한 일곱 비트 안에서만 뒤집는다 continue days = parse(args[1:]) if cmd == "set": alarms[i] = days elif cmd == "add": alarms[i] |= days else: # remove alarms[i] &= ~days for a in alarms[1:]: out.append(f"{a.value} {label(a)}") print("\n".join(out))main()
TypeScriptmain.ts · 71 lines
import { readFileSync } from "node:fs";// 요일마다 비트 하나. 묶음 이름은 요일 값을 | 로 합친 값이다enum Day { NONE = 0, MON = 1 << 0, TUE = 1 << 1, WED = 1 << 2, THU = 1 << 3, FRI = 1 << 4, SAT = 1 << 5, SUN = 1 << 6, WEEKDAYS = MON | TUE | WED | THU | FRI, WEEKEND = SAT | SUN, EVERYDAY = WEEKDAYS | WEEKEND,}const SINGLES: Day[] = [Day.MON, Day.TUE, Day.WED, Day.THU, Day.FRI, Day.SAT, Day.SUN];const NAMES = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN", "WEEKDAYS", "WEEKEND", "EVERYDAY"] as const;type Name = (typeof NAMES)[number];function parse(names: string[]): Day { let days: Day = Day.NONE; for (const name of names) days |= Day[name as Name]; return days;}// (days & group) === group: group의 비트를 모두 가졌는가const hasAll = (days: Day, group: Day): boolean => (days & group) === group;function label(days: Day): string { if (days === Day.NONE) return "NONE"; if (days === Day.EVERYDAY) return "EVERYDAY"; const parts: string[] = []; let rest = days; for (const group of [Day.WEEKDAYS, Day.WEEKEND]) { if (hasAll(days, group)) { parts.push(Day[group]); rest &= ~group; } } for (const d of SINGLES) if (rest & d) parts.push(Day[d]); return parts.join(" ");}const lines = readFileSync(0, "utf8").split("\n");const [n, q] = lines[0].split(" ").map(Number);const alarms: Day[] = new Array<Day>(n + 1).fill(Day.NONE);const out: string[] = [];for (let k = 1; k <= q; k++) { const [cmd, ...args] = lines[k].trim().split(" "); if (cmd === "count") { const want = Day[args[0] as Name]; let c = 0; for (let i = 1; i <= n; i++) if (hasAll(alarms[i], want)) c++; out.push(String(c)); continue; } const i = Number(args[0]); if (cmd === "flip") { // ~만 쓰면 32비트 전체가 뒤집혀 음수가 된다. 일곱 비트로 잘라 낸다 alarms[i] = ~alarms[i] & Day.EVERYDAY; continue; } const days = parse(args.slice(1)); if (cmd === "set") alarms[i] = days; else if (cmd === "add") alarms[i] |= days; else alarms[i] &= ~days; // remove}for (let i = 1; i <= n; i++) out.push(`${alarms[i]} ${label(alarms[i])}`);console.log(out.join("\n"));
JavaMain.java · 90 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.EnumSet;import java.util.HashMap;import java.util.Map;public class Main { // Java 열거형은 비트 값을 갖지 않는다. 요일 묶음은 EnumSet(안에서는 비트 하나씩)으로 나타낸다 enum Day { MON, TUE, WED, THU, FRI, SAT, SUN; int value() { return 1 << ordinal(); // ordinal()은 선언 차례 0, 1, 2… } } static final EnumSet<Day> WEEKDAYS = EnumSet.range(Day.MON, Day.FRI); static final EnumSet<Day> WEEKEND = EnumSet.of(Day.SAT, Day.SUN); static final EnumSet<Day> EVERYDAY = EnumSet.allOf(Day.class); static final Map<String, EnumSet<Day>> BY_NAME = new HashMap<>(); static { for (Day d : Day.values()) BY_NAME.put(d.name(), EnumSet.of(d)); BY_NAME.put("WEEKDAYS", WEEKDAYS); BY_NAME.put("WEEKEND", WEEKEND); BY_NAME.put("EVERYDAY", EVERYDAY); } static EnumSet<Day> parse(String[] parts, int from) { // 표에 든 EnumSet은 함께 쓰는 상수다. 새 집합에 모아야 상수가 바뀌지 않는다 EnumSet<Day> days = EnumSet.noneOf(Day.class); for (int k = from; k < parts.length; k++) days.addAll(BY_NAME.get(parts[k])); return days; } static String label(EnumSet<Day> days) { if (days.isEmpty()) return "NONE"; if (days.equals(EVERYDAY)) return "EVERYDAY"; StringBuilder sb = new StringBuilder(); EnumSet<Day> rest = EnumSet.copyOf(days); if (days.containsAll(WEEKDAYS)) { sb.append("WEEKDAYS "); rest.removeAll(WEEKDAYS); } if (days.containsAll(WEEKEND)) { sb.append("WEEKEND "); rest.removeAll(WEEKEND); } for (Day d : rest) sb.append(d.name()).append(' '); // EnumSet은 선언 차례로 돈다 return sb.substring(0, sb.length() - 1); } static int value(EnumSet<Day> days) { int v = 0; for (Day d : days) v |= d.value(); return v; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] first = br.readLine().split(" "); int n = Integer.parseInt(first[0]); int q = Integer.parseInt(first[1]); @SuppressWarnings("unchecked") EnumSet<Day>[] alarms = new EnumSet[n + 1]; for (int i = 1; i <= n; i++) alarms[i] = EnumSet.noneOf(Day.class); StringBuilder out = new StringBuilder(); for (int k = 0; k < q; k++) { String[] parts = br.readLine().trim().split(" "); String cmd = parts[0]; if (cmd.equals("count")) { EnumSet<Day> want = BY_NAME.get(parts[1]); int c = 0; for (int i = 1; i <= n; i++) if (alarms[i].containsAll(want)) c++; out.append(c).append('\n'); continue; } int i = Integer.parseInt(parts[1]); switch (cmd) { case "flip" -> alarms[i] = EnumSet.complementOf(alarms[i]); case "set" -> alarms[i] = parse(parts, 2); case "add" -> alarms[i].addAll(parse(parts, 2)); default -> alarms[i].removeAll(parse(parts, 2)); // remove } } for (int i = 1; i <= n; i++) out.append(value(alarms[i])).append(' ').append(label(alarms[i])).append('\n'); System.out.print(out); }}
C#Main.cs · 83 lines
using System;using System.Collections.Generic;using System.Text;// [Flags]: 값을 비트로 합쳐 쓰는 열거형이라고 알린다(ToString이 "MON, SAT"처럼 나뉜 이름을 준다)[Flags]enum Day{ NONE = 0, MON = 1 << 0, TUE = 1 << 1, WED = 1 << 2, THU = 1 << 3, FRI = 1 << 4, SAT = 1 << 5, SUN = 1 << 6, WEEKDAYS = MON | TUE | WED | THU | FRI, WEEKEND = SAT | SUN, EVERYDAY = WEEKDAYS | WEEKEND,}class Program{ static readonly Day[] Singles = { Day.MON, Day.TUE, Day.WED, Day.THU, Day.FRI, Day.SAT, Day.SUN }; static Day Parse(string[] parts, int from) { Day days = Day.NONE; for (int k = from; k < parts.Length; k++) days |= Enum.Parse<Day>(parts[k]); return days; } // ToString()은 이름을 값이 작은 것부터 ", "로 잇고 빈 집합은 NONE이라 적는다. 문제의 표시와 달라서 직접 만든다 static string Label(Day days) { if (days == Day.NONE) return "NONE"; if (days == Day.EVERYDAY) return "EVERYDAY"; var parts = new List<string>(); Day rest = days; foreach (Day group in new[] { Day.WEEKDAYS, Day.WEEKEND }) { if (days.HasFlag(group)) // HasFlag: group의 비트를 모두 가졌는가 { parts.Add(group.ToString()); rest &= ~group; } } foreach (Day d in Singles) if (rest.HasFlag(d)) parts.Add(d.ToString()); return string.Join(" ", parts); } static void Main() { string[] first = Console.ReadLine().Split(' '); int n = int.Parse(first[0]); int q = int.Parse(first[1]); var alarms = new Day[n + 1]; // 기본값은 0 = NONE var sb = new StringBuilder(); for (int k = 0; k < q; k++) { string[] parts = Console.ReadLine().Trim().Split(' '); string cmd = parts[0]; if (cmd == "count") { Day want = Enum.Parse<Day>(parts[1]); int c = 0; for (int i = 1; i <= n; i++) if (alarms[i].HasFlag(want)) c++; sb.Append(c).Append('\n'); continue; } int a = int.Parse(parts[1]); switch (cmd) { case "flip": alarms[a] = ~alarms[a] & Day.EVERYDAY; break; // ~만 쓰면 음수가 된다 case "set": alarms[a] = Parse(parts, 2); break; case "add": alarms[a] |= Parse(parts, 2); break; default: alarms[a] &= ~Parse(parts, 2); break; // remove } } for (int i = 1; i <= n; i++) sb.Append((int)alarms[i]).Append(' ').Append(Label(alarms[i])).Append('\n'); Console.Write(sb); }}
C++main.cpp · 88 lines
#include <iostream>#include <sstream>#include <string>#include <unordered_map>#include <vector>// enum class는 |, &, ~ 를 스스로 갖지 않는다. 바탕 정수형을 정하고 연산자를 직접 만든다enum class Day : unsigned { NONE = 0, MON = 1u << 0, TUE = 1u << 1, WED = 1u << 2, THU = 1u << 3, FRI = 1u << 4, SAT = 1u << 5, SUN = 1u << 6, WEEKDAYS = MON | TUE | WED | THU | FRI, // 선언 안에서는 아직 정수로 계산된다 WEEKEND = SAT | SUN, EVERYDAY = WEEKDAYS | WEEKEND,};constexpr unsigned bits(Day d) { return static_cast<unsigned>(d); }constexpr Day operator|(Day a, Day b) { return Day(bits(a) | bits(b)); }constexpr Day operator&(Day a, Day b) { return Day(bits(a) & bits(b)); }// 일곱 비트 안에서만 뒤집는다constexpr Day operator~(Day a) { return Day(~bits(a) & bits(Day::EVERYDAY)); }Day &operator|=(Day &a, Day b) { return a = a | b; }Day &operator&=(Day &a, Day b) { return a = a & b; }constexpr bool hasAll(Day days, Day group) { return (days & group) == group; }const std::vector<std::pair<std::string, Day>> SINGLES = { {"MON", Day::MON}, {"TUE", Day::TUE}, {"WED", Day::WED}, {"THU", Day::THU}, {"FRI", Day::FRI}, {"SAT", Day::SAT}, {"SUN", Day::SUN}};const std::unordered_map<std::string, Day> BY_NAME = { {"MON", Day::MON}, {"TUE", Day::TUE}, {"WED", Day::WED}, {"THU", Day::THU}, {"FRI", Day::FRI}, {"SAT", Day::SAT}, {"SUN", Day::SUN}, {"WEEKDAYS", Day::WEEKDAYS}, {"WEEKEND", Day::WEEKEND}, {"EVERYDAY", Day::EVERYDAY}};std::string label(Day days) { if (days == Day::NONE) return "NONE"; if (days == Day::EVERYDAY) return "EVERYDAY"; std::string s; Day rest = days; auto put = [&s](const std::string &name) { s += (s.empty() ? "" : " ") + name; }; if (hasAll(days, Day::WEEKDAYS)) { put("WEEKDAYS"); rest &= ~Day::WEEKDAYS; } if (hasAll(days, Day::WEEKEND)) { put("WEEKEND"); rest &= ~Day::WEEKEND; } for (const auto &[name, d] : SINGLES) if (hasAll(rest, d)) put(name); return s;}int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n, q; std::cin >> n >> q; std::string line; std::getline(std::cin, line); std::vector<Day> alarms(n + 1, Day::NONE); std::string out; for (int k = 0; k < q; k++) { std::getline(std::cin, line); std::istringstream in(line); std::string cmd, name; in >> cmd; if (cmd == "count") { in >> name; Day want = BY_NAME.at(name); int c = 0; for (int i = 1; i <= n; i++) c += hasAll(alarms[i], want); out += std::to_string(c) + '\n'; continue; } int i; in >> i; if (cmd == "flip") { alarms[i] = ~alarms[i]; continue; } Day days = Day::NONE; while (in >> name) days |= BY_NAME.at(name); if (cmd == "set") alarms[i] = days; else if (cmd == "add") alarms[i] |= days; else alarms[i] &= ~days; // remove } for (int i = 1; i <= n; i++) out += std::to_string(bits(alarms[i])) + ' ' + label(alarms[i]) + '\n'; std::cout << out;}
Cmain.c · 77 lines
#include <stdio.h>#include <string.h>/* C enum의 값은 이름표가 붙은 int 상수다. 요일마다 비트 하나를 주고, 묶음은 | 로 합친다 */enum day { NONE = 0, MON = 1 << 0, TUE = 1 << 1, WED = 1 << 2, THU = 1 << 3, FRI = 1 << 4, SAT = 1 << 5, SUN = 1 << 6, WEEKDAYS = MON | TUE | WED | THU | FRI, WEEKEND = SAT | SUN, EVERYDAY = WEEKDAYS | WEEKEND};/* enum은 이름 문자열을 모르므로 표를 따로 둔다 */static const char *NAMES[] = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN", "WEEKDAYS", "WEEKEND", "EVERYDAY"};static const unsigned VALUES[] = {MON, TUE, WED, THU, FRI, SAT, SUN, WEEKDAYS, WEEKEND, EVERYDAY};static unsigned lookup(const char *name) { for (int k = 0; k < 10; k++) if (strcmp(NAMES[k], name) == 0) return VALUES[k]; return NONE;}static int has_all(unsigned days, unsigned group) { return (days & group) == group; }static void print_label(unsigned days) { if (days == NONE) { fputs("NONE", stdout); return; } if (days == EVERYDAY) { fputs("EVERYDAY", stdout); return; } unsigned rest = days; int first = 1; if (has_all(days, WEEKDAYS)) { fputs("WEEKDAYS", stdout); first = 0; rest &= ~(unsigned)WEEKDAYS; } if (has_all(days, WEEKEND)) { printf("%sWEEKEND", first ? "" : " "); first = 0; rest &= ~(unsigned)WEEKEND; } for (int k = 0; k < 7; k++) { if (rest & VALUES[k]) { printf("%s%s", first ? "" : " ", NAMES[k]); first = 0; } }}int main(void) { int n, q; if (scanf("%d %d", &n, &q) != 2) return 0; unsigned alarms[101] = {0}; /* n ≤ 100, 1번부터 쓴다 */ char line[256]; fgets(line, sizeof line, stdin); /* 첫 줄의 나머지 */ for (int k = 0; k < q; k++) { if (!fgets(line, sizeof line, stdin)) break; char *cmd = strtok(line, " \r\n"); if (strcmp(cmd, "count") == 0) { unsigned want = lookup(strtok(NULL, " \r\n")); int c = 0; for (int i = 1; i <= n; i++) c += has_all(alarms[i], want); printf("%d\n", c); continue; } int i; sscanf(strtok(NULL, " \r\n"), "%d", &i); if (strcmp(cmd, "flip") == 0) { alarms[i] = ~alarms[i] & EVERYDAY; /* ~만 쓰면 위쪽 25비트도 1이 된다 */ continue; } unsigned days = NONE; for (char *t = strtok(NULL, " \r\n"); t; t = strtok(NULL, " \r\n")) days |= lookup(t); if (strcmp(cmd, "set") == 0) alarms[i] = days; else if (strcmp(cmd, "add") == 0) alarms[i] |= days; else alarms[i] &= ~days; /* remove */ } for (int i = 1; i <= n; i++) { printf("%u ", alarms[i]); print_label(alarms[i]); putchar('\n'); } return 0;}