Official
D - Unauthorized Editorial by en_translator
The problem can be solved by maintaining a flag whether Takahashi is logged in or not, while scanning the operations.
The sample code is as follows.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
int N;
cin >> N;
// A flag that maintains whether he is currently logged in. Initially he is not logged in
bool logged_in = false;
// The number of authorization errors
int unauthorized = 0;
for (int i = 0; i < N; ++i) {
string s;
cin >> s;
// If it is a log-in operation, set the flag
if (s == "login") {
logged_in = true;
}
// If it is a log-out operation, unset the flag
if (s == "logout") {
logged_in = false;
}
// If it is an attempt to access a private page while not logged in, increment the number of authorization errors
if (s == "private" && !logged_in) {
unauthorized++;
}
}
cout << unauthorized << endl;
return 0;
}
N = int(input())
# A flag that maintains whether he is currently logged in. Initially he is not logged in
logged_in = False
# The number of authorization errors
unauthorized = 0
for i in range(N):
s = input()
# If it is a log-in operation, set the flag
if s == 'login':
logged_in = True
# If it is a log-out operation, unset the flag
if s == 'logout':
logged_in = False
# If it is an attempt to access a private page while not logged in, increment the number of authorization errors
if s == 'private' and not logged_in:
unauthorized += 1
print(unauthorized)
posted:
last update: