Problem:


Score : 300 points

Problem Statement

AtCoDeer the deer and his friend TopCoDeer is playing a game.
The game consists of N turns.
In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition:

(※) After each turn, (the number of times the player has played Paper)≦(the number of times the player has played Rock).

Each player's score is calculated by (the number of turns where the player wins) - (the number of turns where the player loses), where the outcome of each turn is determined by the rules of Rock-paper-scissors.

(For those who are not familiar with Rock-paper-scissors: If one player plays Rock and the other plays Paper, the latter player will win and the former player will lose. If both players play the same gesture, the round is a tie and neither player will win nor lose.)

With his supernatural power, AtCoDeer was able to foresee the gesture that TopCoDeer will play in each of the N turns, before the game starts.
Plan AtCoDeer's gesture in each turn to maximize AtCoDeer's score.

The gesture that TopCoDeer will play in each turn is given by a string s. If the i-th (1≦i≦N) character in s is g, TopCoDeer will play Rock in the i-th turn. Similarly, if the i-th (1≦i≦N) character of s in p, TopCoDeer will play Paper in the i-th turn.

Constraints

1≦N≦10^5

N=|s|

Each character in s is g or p.

The gestures represented by s satisfy the condition (※).

Input

The input is given from Standard Input in the following format:

s

Output

Print the AtCoDeer's maximum possible score.

Sample Input 1

gpg

Sample Output 1

0

Playing the same gesture as the opponent in each turn results in the score of 0, which is the maximum possible score.

Sample Input 2

ggppgggpgg

Sample Output 2

2

For example, consider playing gestures in the following order: Rock, Paper, Rock, Paper, Rock, Rock, Paper, Paper, Rock, Paper. This strategy earns three victories and suffers one defeat, resulting in the score of 2, which is the maximum possible score.



Sample input:
gpg


Sample output:
0

Submission status: Accepted

Solution code:
s = input()
gp = [1, 0]
p = 0
if s[0] == 'p':
    p -= 1
for i in range(1, len(s)):
    if s[i] == 'g':
        if gp[0] > gp[1]:
            gp[1] += 1
            p += 1
        else:
            gp[0] += 1
    if s[i] == 'p':
        if gp[0] > gp[1]:
            gp[1] += 1
        else:
            gp[0] += 1
            p -= 1
print(p)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
S = S()
ans = 0
for s in S:
  if s == "g":
    ans -= 1
  else:
    ans += 1
print(-ans//2)

Submission status: Accepted

Solution code:


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    """
    T A
    ---

    0 0 0
    1 1 0
    0 0 1

    number of 0s >= number of 1s
    p = 1
    g = 0

    N <= 10**5

    0 0
    0 0
    1 0
    1 0
    0 0
    0 1
    0 1
    1 1
    0 1
    0 1

    1. N/2 1's will be used
    """
    s = input().strip()
    N = len(s)
    score = 0
    for i in range((N+1)//2):
        if s[i] == 'p':
            score -= 1
    for i in range((N+1)//2, N):
        if s[i] == 'g':
            score += 1
    return score



if __name__ == '__main__':
    print(solve())

Submission status: Accepted

Solution code:

def resolve():
    S = list(input())
    n_p = S.count("p")
    max_p = len(S)//2 if len(S)%2==0 else (len(S)-1)//2
    print(max_p-n_p)

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
def main():
    print(sum((1 - (-1) ** i) // 2 if j == 'g' else (1 - (-1) ** i) // 2 - 1 for i, j in enumerate(input())))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s = input()
print(len(s) // 2 - s.count('p'))

Submission status: Accepted

Solution code:
def main():
    s = input()
    print(len(s) // 2 - s.count('p'))
    

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    s = input()
    n = len(s)
    g = s.count('g')
    p = n - g
    ans = n // 2 - p
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    s = input()

    n = len(s) // 2
    p = s.count("p")
    print(n - p)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
s=input()
np=0
ng=0
ans=0
for si in s:
  if si=='g' and np<ng:
    ans+=1
    np+=1
  elif si=='g' and np>=ng:
    ng+=1
  elif si=='p' and np<ng:
    np+=1
  elif si=='p' and np>=ng:
    ans-=1
    ng+=1
print(ans)

Submission status: Accepted

Solution code:
s = input()

p = 0
g = 0
res = 0

for i in range(len(s)):
    if s[i] == 'g':
        if p < g:
            p += 1
            res += 1
        else:
            g += 1
    else:
        if p < g:
            p += 1
        else:
            g += 1
            res -= 1

print(res)

Submission status: Accepted

Solution code:
s = input()
print((s.count('g') - s.count('p')) // 2)

Submission status: Accepted

Solution code:
S = sorted(list(input()))

p = len(S) // 2
g = len(S) // 2
if len(S) % 2 ==1:
    g += 1
T = ['g'] * g + ['p'] * p
ans = 0
for i in range(len(S)):
    if T[i] == 'g' and S[i] == 'p':
        ans -= 1
    if T[i] == 'p' and S[i] == 'g':
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import permutations
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7


#############
# Main Code #
#############

S = input()
N = len(S)

def counter(str, index):
    n_s = len(str)
    cnt = 0
    if n_s == 1 and index == N - 1:
        if str == 'g':
            cnt += 1
    # 一番最初の手については両者ともg

    elif n_s == 2:
        if str == 'gg':
            cnt += 1
        # 存在しない
        elif str == 'pp':
            cnt -= 1
    return cnt

ans = 0
for i in range(-1, N, 2):
    str_S = S[max(0, i):min(N - 1, i + 1) + 1]
    ans += counter(str_S, i)
print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    s=SI()
    print(len(s)//2-s.count("p"))

main()

Submission status: Accepted

Solution code:
def main():
    S = input()
    p = sum([1 for c in S if c == 'p'])
    print(len(S) // 2 - p)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s=input()
n=len(s)
t=0
for i in range(n):
  if s[i]=="p":
    t+=1
print(int(n/2)-t)

Submission status: Accepted

Solution code:
import sys
def v():
    pt=[5,0,1,2]
    s=list(map(lambda x: '0' if x=='g' else '1', sys.stdin.readline().strip()))
    n=len(s)
    p=pt[n%4]
    for _ in range(n//4):p=(p<<4)+5
    ss=list(format(p,'b').zfill(n))
    res=0
    for a,b in zip(s,ss):
        d=int(b)-int(a)
        res = res if d==0 else res+d
    print(res)
if __name__=='__main__':v()

Submission status: Accepted

Solution code:
import sys
def v():
    pt=[5,0,1,2]
    s=list(map(lambda x: '0' if x=='g' else '1', list(sys.stdin.readline().strip())))
    n=len(s)
    p=pt[n%4]
    for _ in range(n//4):p=(p<<4)+5
    ss=list(format(p,'b').zfill(n))
    res=0
    for a,b in zip(s,ss):
        d=int(b)-int(a)
        res = res if d==0 else res+d
    print(res)
if __name__=='__main__':v()

Submission status: Accepted

Solution code:
import sys
import math
def v():
    pt=[5,0,1,2]
    N=100000
    s=list(map(lambda x: '0' if x=='g' else '1', list(sys.stdin.readline().strip())))
    n,x=len(s),int(''.join(s),2)
    s=list(format(x<<(N-n),'0100000b'))
    p=pt[n%4]
    for _ in range(n//4):p=(p<<4)+5
    ss=list(format(p<<(N-n),'010000b'))
    res=0
    for _,a,b in zip(range(n),s,ss):
        d=int(b)-int(a)
        res = res if d==0 else res+d
    print(res)
if __name__=='__main__':v()

Submission status: Accepted

Solution code:
S = input()
PossiblePaper = 0
Score = 0
for s in S:
    if s == "g":
        if PossiblePaper == 0:
            Score += 0
            PossiblePaper += 1
        else:
            Score += 1
            PossiblePaper -= 1
    else:
        if PossiblePaper == 0:
            Score -= 1
            PossiblePaper += 1
        else:
            Score += 0
            PossiblePaper -= 1
print(Score)

Submission status: Accepted

Solution code:
s = input()
n = len(s)
print(s[(n+1)//2:].count("g")-s[:(n+1)//2].count("p"))

Submission status: Accepted

Solution code:
s = input()
ls = len(s)
cnt = [0, 0]
for c in list(s):
    cnt[c != "g"] += 1

if ls % 2 == 1:
    ls -= 1

print(ls//2-cnt[1])

Submission status: Accepted

Solution code:
import numpy as np
import sys
def sinput(): return sys.stdin.readline()
def iinput(): return int(sinput())
def imap(): return map(int, sinput().split())
def fmap(): return map(float, sinput().split())
def iarr(): return list(imap())
def farr(): return list(fmap())
def sarr(): return sinput().split()

s = input()
p = g = ans = 0
for i in s:
    if i=='p':
        if p < g: p += 1
        else: ans -= 1; g += 1
    if i=='g':
        if p < g: ans += 1; p += 1
        else: g += 1
print(ans)

Submission status: Accepted

Solution code:
S = input()
ans = 0
hand = ['g', 'p']

def do(s, t):
  if s == t:
    return 0
  elif s == 'g':
    return 1
  else:
    return -1

for i, s in enumerate(S):
  ans += do(s, hand[i%2])

print(ans)

Submission status: Accepted

Solution code:
z = 0
for i, c in enumerate(input().replace("g", "r")):
    if i % 2 == 0 and c == "r":
        pass
    elif i % 2 == 0 and c == "p":
        z -= 1
    elif c == "p":
        pass
    else:
        z += 1
print(z)

Submission status: Accepted

Solution code:
s = input()
g = 0
p = 0
for i in s:
    if i == "g":
        g += 1
    else:
        p += 1
print((g-p)//2)

Submission status: Accepted

Solution code:
s = str(input())
n = len(s)

L = []
c = 0
ans = 0
for i in range(n):
    if c-1 >= 0:
        if s[i] == 'g':
            ans += 1
            c -= 1
        else:
            c -= 1
    else:
        if s[i] == 'g':
            c += 1
        else:
            ans -= 1
            c += 1
print(ans)

Submission status: Accepted

Solution code:
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7

s = list(input().rstrip())
g = 0
p = 0
res = []
ans = 0

for i in range(len(s)):
    c = g-p
    if s[i] == "g":
        if c > 0:
            #print("p")
            p += 1
            ans += 1
        else:
            #print("g")
            g += 1
    else:
        if c > 0:
            #print("p")
            p += 1
        else:
            #print("g")
            g += 1
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
s = list(input())
l = len(s)
p = s.count("p")
print(l // 2 - p)

Submission status: Accepted

Solution code:
s = input()
ng = s.count('g')
np = s.count('p')

surplus = ng - np
print(surplus // 2)

Submission status: Accepted

Solution code:
def main():
    s = input()
    score = 0
    diff = 0
    for i in range(len(s)):
        if s[i] == "g":
            if diff == 0:
                diff += 1
            else:
                diff -= 1
                score += 1
        else:
            if diff == 0:
                diff = 1
                score -= 1
            else:
                diff -= 1
    print(max(score, 0))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
g = 0
p = 0

ans = 0
for i in input():
    if i == "g":
        if p < g:
            ans += 1
            p += 1
        else:
            g += 1
    else:
        if p < g:
            p += 1
        else:
            g += 1
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
s = input()

g = s.count("g")
p = s.count("p")

max_p = (g+p)//2
max_g = g+p-(g+p)//2

print(max_p-(max_g-(g-max_p)))

Submission status: Accepted

Solution code:
s = input()
print(s.count('g')-(-((-len(s))//2)))

Submission status: Accepted

Solution code:
s=list(input())

answer=0
for i in range(len(s)):
  if i%2==0 and s[i]=="p":
    answer-=1
  elif i%2==1 and s[i]=="g":
    answer+=1

print(answer)

Submission status: Accepted

Solution code:
s=list(input())

num_g=num_p=0
answer=0
for i in range(len(s)):
  if num_g==num_p:
    num_g+=1
    if s[i]=="p":
      answer-=1
  else:
    num_p+=1
    if s[i]=="g":
      answer+=1

print(answer)

Submission status: Accepted

Solution code:
s=input()
pcount,gcount=0,0
pp=False
res=0
for ele in s:
  if pcount<gcount:
    pp=True
  else:pp=False
  if pp :
    pcount+=1
    if ele=="g":
          res+=1
  else:
      gcount+=1
      if ele=="p":
          res-=1
print("{}".format(res))

Submission status: Accepted

Solution code:
from collections import Counter
s=input()
c = Counter(s)
g = c['g']
p = c['p']
print((g-p)//2)

Submission status: Accepted

Solution code:
s = input()
n = len(s)
charge = 0
score = 0
for i in range(n):
    if s[i] == 'g':
        if charge > 0:
            score += 1
            charge -= 1
        else:
            charge += 1
    else:
        if charge > 0:
            charge -= 1
        else:
            score -= 1
            charge += 1

print(score)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    S=input()
    ans=0
    for i,s in enumerate(S):
        if i%2==0 and s=='p':
            ans-=1
        if i%2==1 and s=='g':
            ans+=1
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    s = input()
    n = len(s)
    par_counter = s.count('p')
    print(n // 2 - par_counter)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s = input()

p = 0
for x in s:
  if x == 'p':
    p += 1
    
print(len(s)//2 - p)

Submission status: Accepted

Solution code:
s = input()
p = 0
cnt = 0
for i in s:
    if i == 'g':
        if p > 0:
            cnt += 1
            p -= 1
        else:
            p += 1
    elif i == 'p':
        if p > 0:
            p -= 1
        else:
            cnt -= 1
            p += 1
print(cnt)

Submission status: Accepted

Solution code:
s=input()

cnt=0
result=0

hand=["g","p"]

for index,ss in enumerate(s):
    if ss!=hand[index%2]:
        if ss=="g":
            result+=1
        else:
            result-=1

print(result)

Submission status: Accepted

Solution code:
s = input();print(len(s)//2-s.count("p"))

Submission status: Accepted

Solution code:
s = input()
n = len(s)

g, p = 0, 0
ans = 0
for i in range(n):
  if g == p:
    g += 1
    if s[i] == "p":
      ans -= 1
  else:
    p += 1
    if s[i] == "g":
      ans += 1

print(ans)

Submission status: Accepted

Solution code:
s = input()

g = 0
p = 0
win = 0
lose = 0

for hand in s:
    if p == g:
        g += 1
        if hand == 'p':
            lose += 1
    else:
        p += 1
        if hand == 'g':
            win += 1

print(win-lose)

Submission status: Accepted

Solution code:
s = input()
print(len(s)//2 - s.count("p"))

Submission status: Accepted

Solution code:
s = input()

ans = 0

for i in range(len(s)):
    if s[i] == 'g':
        ans += 1
    else:
        ans -= 1
        
print(ans//2)

Submission status: Accepted

Solution code:
s = list(input())

n = len(s)

p = n//2

opp_p = s.count("p")

print(p-opp_p)

Submission status: Accepted

Solution code:
s=input()
N=len(s)
gcount=0
pcount=0

def janken(me,you):
    if (me=="g")and(you=="p"):
        return -1
    elif (me=="p")and(you=="g"):
        return 1
    else:
        return 0
score=0
for i in range(N):
    if gcount==pcount:
        score=score+janken("g",s[i])
        gcount=gcount+1
    else:
        score=score+janken("p",s[i])
        pcount=pcount+1
print(score)

Submission status: Accepted

Solution code:
s=input()
p=s.count("p")
print(len(s)//2-p)

Submission status: Accepted

Solution code:
s = input()
N = len(s)
ans = N//2
for i in range(N):
  if(s[i] == 'p'):
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
s=input();print(len(s)//2-s.count('p'))

Submission status: Accepted

Solution code:
s=input()
N=len(s)
ans=0
for i in range(N):
    if s[i]=='g' and i%2==1:
        ans+=1
    elif s[i]=='p' and i%2==0:
        ans-=1
print(ans)

Submission status: Accepted

Solution code:
s=input()
ans=-s.count("p")+len(s)//2
print(ans)

Submission status: Accepted

Solution code:
s = input()
n = s.count("p")
print(len(s)//2 - n)

Submission status: Accepted

Solution code:
s = input()

ctr = {"g": 0, "p": 0}
ans = 0
for i in range(len(s)):
    if s[i] == "g":
        if ctr["p"] < ctr["g"]:
            ctr["p"] += 1
            ans += 1
        else:
            ctr["g"] += 1
    else:
        # s[i] == "p"
        if ctr["p"] < ctr["g"]:
            ctr["p"] += 1
        else:
            ctr["g"] += 1
            ans -= 1
            
print(ans)

Submission status: Accepted

Solution code:
s = input()
N = len(s)
ans = 0
for c in s:
    if c == "p":
        ans -= 1
ans += N // 2
print(ans)

Submission status: Accepted

Solution code:
s=input()

atd=''
tpd=''
for i, t in enumerate(s):
  
  if t=='g':
      tpd+='0'
  else:
      tpd+='1'
      
  if i%2==0:
      atd+='0'
  else:
      atd+='1'

point=0
for a, t in zip(atd, tpd):
  
    x=int(a)-int(t)
    
    if x==1:
        point+=1
    elif x==-1:
      point-=1
      
      
print(point)

Submission status: Accepted

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret


# ここから書き始める
s = input()
cntg = s.count("g")
cntp = s.count("p")
ans = max(0, cntg - cntp) // 2
print(ans)

Submission status: Accepted

Solution code:
def main():
  s = input()
  cc_g = cc_p = 0
  for c in s:
    if c == 'g': cc_g += 1
    else: cc_p += 1
  print((cc_g - cc_p) // 2)
  return

if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
s = input()
l = len(s)
cp = s.count("p")
cg = l - cp
pmax = l//2
print(pmax-cp)

Submission status: Accepted

Solution code:
ans = 0

for i,c in enumerate(input()):
  if i%2 == 0 and c == "p": ans -= 1
  elif i%2 == 1 and c == "g": ans += 1

print(ans)

Submission status: Accepted

Solution code:
T = input().strip()
n = len(T)

p = n // 2
g = n - p

A = 'g' * g + 'p' * p

ans = 0
for a, t in zip(A, T):
    if a == 'p' and t == 'g':
        ans += 1
    if a == 'g' and t == 'p':
        ans -= 1

print(ans)

Submission status: Accepted

Solution code:
S = input()
N = len(S)
print(N // 2 - sum([int(s == 'p') for s in S]))

Submission status: Accepted

Solution code:
s = input()

gs = 0
ps = 0

for ss in s:
    if ss == 'g':
        gs += 1
    else:
        ps += 1

print(max(0,(gs - ps) // 2))