B - Unauthorized
Source: atcoder
Difficulty: 200

Problem Statement
One day, Takahashi performed
N
operations on a certain web site.
The
i
‑th operation
(1 \le i \le N)
is represented by a string
S_i
, which is one of the following:
S _ i=
login
: He performs a login operation and becomes logged in to the site.
S _ i=
logout
: He performs a logout operation and becomes not logged in to the site.
S _ i=
public
: He accesses a public page of the site.
S _ i=
private
: He accesses a private page of the site.
The site returns an
authentication error
if and only if he accesses a private page while he is not logged in.
Logging in again while already logged in, or logging out again while already logged out, does
not
cause an error. Even after an authentication error is returned, he continues performing the remaining operations.
Initially, he is not logged in.
Print the number of operations among the
N
operations at which he receives an authentication error.
Constraints
1 \le N \le 100
N
is an integer.
Each
S_i
is one of
login
,
logout
,
public
,
private
.
(1 \le i \le N)
Input
The input is given from Standard Input in the following format:
N
S_1
S_2
\vdots
S_N
Output
Print the number of times Takahashi receives an authentication error.
Sample Input 1
6
login
private
public
logout
private
public
Sample Output 1
1
The result of each operation is as follows:
Takahashi becomes logged in.
He accesses a private page. He is logged in, so no error is returned.
He accesses a public page.
He becomes logged out.
He accesses a private page. He is not logged in, so an authentication error is returned.
He accesses a public page.
An authentication error occurs only at the 5th operation, so print
1
.
Sample Input 2
4
private
private
private
logout
Sample Output 2
3
If he tries to access private pages consecutively while not logged in, he receives an authentication error for each such operation.
Note that logging out again while already logged out does not cause an authentication error.
Sample Input 3
20
private
login
private
logout
public
logout
logout
logout
logout
private
login
login
private
login
private
login
public
private
logout
private
Sample Output 3
3

C++ solution:
/*

*/
#include <bits/stdc++.h>
#define eps 0.000001
#define ls(x) ((x) << 1)
#define rs(x) ((x) << 1 | 1)
#define mid ((l + r) >> 1)
using namespace std;
typedef __int128 i128;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
const int N = 2e5 + 5, M = 2000 + 5, mod = 998244353, base1 = 13331,base2 = 131;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
//	freopen("in.txt","r",stdin);
//  freopen("out.txt","w",stdout);
	int n;
	cin>>n;
	bool isin = false;
	int cnt = 0;
	for(int i=1;i<=n;i++){
		string s;
		cin>>s;
		if(s == "login"){
			isin = true;
		}else if(s == "logout"){
			isin = false;
		}else if(s == "private"){
			cnt += !isin;
		}
	}
	cout<<cnt;
	return 0;
}

Go solution:
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Buffer([]byte{}, math.MaxInt64)
	sc.Split(bufio.ScanWords)
}

func main() {
	n := ScanI()
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanS()
	}

	LOGOUT := "logout"
	LOGIN := "login"
	PRIVATE := "private"
	st := LOGOUT

	ans := 0
	for _, op := range s {
		if st == LOGOUT && op == PRIVATE {
			ans++
		}
		if op == LOGOUT {
			st = LOGOUT
		}
		if op == LOGIN {
			st = LOGIN
		}
	}

	fmt.Println(ans)
}

func ScanI() int {
	sc.Scan()
	str, _ := strconv.Atoi(sc.Text())
	return str
}

func ScanS() string {
	sc.Scan()
	return sc.Text()
}

func ScanIArrayNotBlank() []int {
	str := strings.Split(ScanS(), "")
	arrI := make([]int, len(str))
	for i := 0; i < len(str); i++ {
		num, _ := strconv.Atoi(str[i])
		arrI[i] = num
	}

	return arrI
}

func ScanIArrayWithBlank(n int) []int {
	arrI := make([]int, n)
	for i := 0; i < n; i++ {
		arrI[i] = ScanI()
	}

	return arrI
}

Java solution:
import java.io.*;
        import java.lang.reflect.Array;
        import java.util.*;
        import static java.lang.Math.*;

        public class Main {
            static int count = 0;

            static class SegmentTree {
                int size;
                long[] maxArr;
                long[] sumArr;

                public SegmentTree(int n) {
                    size = 1;
                    while (size < n) size *= 2;
                    maxArr = new long[2 * size];
                    sumArr = new long[2 * size];
                    Arrays.fill(maxArr, Long.MIN_VALUE);
                    Arrays.fill(sumArr, 0);
                }

                public void set(int i, int v, int x, int lx, int rx) {
                    if (rx - lx == 1) {
                        maxArr[x] = v;
                        sumArr[x] = v;
                        return;
                    }
                    int m = (lx + rx) / 2;
                    if (i < m) {
                        set(i, v, 2 * x + 1, lx, m);
                    } else {
                        set(i, v, 2 * x + 2, m, rx);
                    }
                    maxArr[x] = Math.max(maxArr[2 * x + 1], maxArr[2 * x + 2]);
                    sumArr[x] = sumArr[2 * x + 1] + sumArr[2 * x + 2];
                }

                public void set(int i, int v) {
                    set(i, v, 0, 0, size);
                }

                public long max(int l, int r, int x, int lx, int rx) {
                    if (lx >= r || l >= rx) return Long.MIN_VALUE;
                    if (lx >= l && rx <= r) return maxArr[x];
                    int m = (lx + rx) / 2;
                    long m1 = max(l, r, 2 * x + 1, lx, m);
                    long m2 = max(l, r, 2 * x + 2, m, rx);
                    return Math.max(m1, m2);
                }

                public long max(int l, int r) {
                    return max(l, r, 0, 0, size);
                }

                public long sum(int l, int r, int x, int lx, int rx) {
                    if (lx >= r || l >= rx) return 0;
                    if (lx >= l && rx <= r) return sumArr[x];
                    int m = (lx + rx) / 2;
                    long s1 = sum(l, r, 2 * x + 1, lx, m);
                    long s2 = sum(l, r, 2 * x + 2, m, rx);
                    return s1 + s2;
                }

                public long sum(int l, int r) {
                    return sum(l, r, 0, 0, size);
                }

                public void build(int[] a, int x, int lx, int rx) {
                    if (rx - lx == 1) {
                        if (lx < a.length) {
                            maxArr[x] = a[lx];
                            sumArr[x] = a[lx];
                        }
                        return;
                    }
                    int m = (lx + rx) / 2;
                    build(a, 2 * x + 1, lx, m);
                    build(a, 2 * x + 2, m, rx);
                    maxArr[x] = Math.max(maxArr[2 * x + 1], maxArr[2 * x + 2]);
                    sumArr[x] = sumArr[2 * x + 1] + sumArr[2 * x + 2];
                }

                public void build(int[] a) {
                    build(a, 0, 0, size);
                }
            }

            static final int MOD = 1_000_000_007;
            static final int INF = Integer.MAX_VALUE;
            static final long LINF = Long.MAX_VALUE;
            static FastReader in = new FastReader();
            static PrintWriter out = new PrintWriter(System.out);

            public static void main(String[] args) throws IOException {
                int t = 1;
                while (t-- > 0) {
                    solve();
                }
                out.flush();
            }

            static int fact(int n) {
                if (n == 0) return 1;
                return n * fact(n - 1);
            }








            static void solve() {
                int n = in.nextInt();

                boolean log = false;
                int cnt = 0;
                while(n-- > 0){
                    String s = in.nextLine();
                    if(s.equals("login")) log = true;
                    if(s.equals("logout")) log = false;
                    if(s.equals("private") && log == false){
                        cnt++;
                    }
                }

                out.println(cnt);
            }













            static int digitSum(int num) {
                int sum = 0;
                while (num > 0) {
                    sum += num % 10;
                    num /= 10;
                }
                return sum;
            }





            static boolean isPrime(int n){
                if(n <= 1){
                    return false;
                }
                for(int i = 2; i <= sqrt(n); i++){
                    if(n%i == 0){
                        return false;
                    }
                }
                return true;
            }



            public void reverse(int[] arr, int start, int end){

                int left = start;
                int right = end;

                while(left < right){
                    int temp = arr[left];
                    arr[left] = arr[right];
                    arr[right] = arr[left];
                    left++;
                    right--;
                }
            }






            static int popcount(int x){
                int cnt = 0;

                int mask = 1;

                int BITS = 30;
                for(int i = 0; i <= BITS; i++){
                    if((x & mask<<i) != 0) cnt++;
                }
                return cnt;
            }

            static boolean parity(int x){
                if(popcount(x) %2 == 1) return true;
                return false;
            }

            static int lowbit(int x){
                int saved = -1;


                int BIT = 32;
                for(int i = BIT; i >= 0; i--){
                    if((x & (1 << i)) != 0) saved=i;
                }
                return saved;
            }












            public static int mex(List<Integer> a) {
                int mex = 0;
                Set<Integer> set = new HashSet<>();
                for (int n : a) set.add(n);
                while (set.contains(mex)) mex++;
                return mex;
            }

            static Set<Integer> getMissing(int[] arr, int max) {
                Set<Integer> set = new HashSet<>();
                Set<Integer> miss = new HashSet<>();
                for (int n : arr) set.add(n);
                for (int i = 1; i <= max; i++) {
                    if (!set.contains(i)) miss.add(i);
                }
                return miss;
            }

            public static boolean isSubsequence(String a, String b) {
                int i = 0;
                for (int j = 0; j < b.length(); j++) {
                    if (i < a.length() && a.charAt(i) == b.charAt(j)) i++;
                }
                return i == a.length();
            }

            public static boolean isValid(int r, int c, int aR, int aC) {
                if (r == aR || c == aC) return false;
                return abs(r - aR) != abs(c - aC);
            }

            static long gcd(long a, long b) {
                return b == 0 ? a : gcd(b, a % b);
            }

            static long lcm(long a, long b) {
                return a / gcd(a, b) * b;
            }

            static class FastReader {
                BufferedReader br;
                StringTokenizer st;

                public FastReader() {
                    br = new BufferedReader(new InputStreamReader(System.in));
                }

                String next() {
                    while (st == null || !st.hasMoreTokens()) {
                        try { st = new StringTokenizer(br.readLine()); }
                        catch (IOException e) { e.printStackTrace(); }
                    }
                    return st.nextToken();
                }

                int nextInt() { return Integer.parseInt(next()); }
                long nextLong() { return Long.parseLong(next()); }
                double nextDouble() { return Double.parseDouble(next()); }
                String nextLine() {
                    String str = "";
                    try { str = br.readLine(); }
                    catch (IOException e) { e.printStackTrace(); }
                    return str;
                }
            }

            static int[] readIntArray(int n) {
                int[] a = new int[n];
                for (int i = 0; i < n; i++) a[i] = in.nextInt();
                return a;
            }

            static void printArray(int[] a) {
                for (int val : a) out.print(val + " ");
                out.println();
            }

            static long binExp(long base, long exp, long mod) {
                long result = 1;
                base %= mod;
                while (exp > 0) {
                    if ((exp & 1) == 1) {
                        result = (result * base) % mod;
                    }
                    base = (base * base) % mod;
                    exp >>= 1;
                }
                return result;
            }
        }

JavaScript solution:
process.stdin.resume();
process.stdin.setEncoding('utf8');

function main(input) {
  const args = input.split("\n");
  const N = args[0];
  let loginFlag = false;
  let errorCount = 0;
  
  for(let i=0; i<N; i++) {
      if(args[i+1]=="login") {
          loginFlag = true;
      }else if(args[i+1]=="logout") {
          loginFlag = false;
      }
      if(args[i+1]=="private" && !loginFlag) {
          errorCount+=1;
      }
  }
  console.log(errorCount);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));

Python solution:
n = int(input())
status = "logout"
cnt = 0
for i in range(n):
  s = input()
  if s == "login" or s == "logout":
    status = s
    continue
  if status == "logout" and s == "private":
    cnt += 1
print(cnt)

Ruby solution:
operation_count = gets.to_i
operations = operation_count.times.map { gets.chomp }
unauthorized_count = 0
current_status = 'logout'

operations.each do |operation|
  unauthorized_count += 1 if current_status != 'login' && operation == 'private'
  current_status = operation if operation == 'login' || operation == 'logout'
end

p unauthorized_count