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: Time Limit Exceeded

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
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)

# ここから書き始める
s = input()
ans = -INF  
n = len(s)
def dfs(g_cnt, p_cnt, p, i):
    global ans
    if g_cnt < p_cnt:
        return
    if i == n:
        ans = max(ans, p)
        return 
    if s[i] == "g":
        dfs(g_cnt + 1, p_cnt, p, i + 1)
        dfs(g_cnt, p_cnt + 1, p + 1, i + 1)
    else:
        dfs(g_cnt, p_cnt + 1, p, i + 1)
        dfs(g_cnt + 1, p_cnt, p - 1, i + 1)
dfs(0, 0, 0, 0)
print(ans)

Submission status: Time Limit Exceeded

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
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)

# ここから書き始める
s = input()
ans = -INF  
n = len(s)
def dfs(g_cnt, p_cnt, p, i):
    global ans
    if g_cnt < p_cnt:
        return
    if i == n:
        ans = max(ans, p)
        return 
    if s[i] == "g":
        dfs(g_cnt + 1, p_cnt, p, i + 1)
        dfs(g_cnt, p_cnt + 1, p + 1, i + 1)
    dfs(g_cnt, p_cnt + 1, p, i + 1)
    dfs(g_cnt + 1, p_cnt, p - 1, i + 1)
dfs(0, 0, 0, 0)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
S_list = list(input())
n = len(S_list)

result_list = []
total_sum = 0
for i in range(2 ** n):
    # pの位置を決める
    ans_str = ['g']*n
    result = 0
    for j in range(n):
        if ((i >> j) & 1 &(ans_str[:j].count('p')<ans_str[:j].count('g'))):
            ans_str[j]= 'p'
            if S_list[j] == 'g':
                result+=1
        else:
            if S_list[j] == 'p':
                result-=1
    result_list.append(result)

print(max(result_list))

Submission status: Time Limit Exceeded

Solution code:
S=list(input())
N = len(S)
dp=[[0]*(N+1) for _ in range(N+1)]
for n in range(1,N+1):
  s = S[n-1]
  if s=='p':
    os = -1
  else:
    os = 0
  for g in range(1,n+1):
    if (n+1)//2<=g<=n-1:
      dp[n][g]=max(dp[n-1][g-1],dp[n-1][g]+1)+os
    else:
      dp[n][g]=dp[n-1][g-1]+os
print(max(dp[-1]))

Submission status: Time Limit Exceeded

Solution code:
S=list(input())
N = len(S)
dp=[[0]*(N+1) for _ in range(N+1)]
for n in range(1,N+1):
  s = S[n-1]
  if s=='p':
    for g in range(1,n+1):
      if n-1-g<g and n-1>=g:
        dp[n][g]=max(dp[n-1][g-1]-1,dp[n-1][g])
      else:
        dp[n][g]=dp[n-1][g-1]-1
#      print(n,g,dp)
  else:
    for g in range(1,n+1):
      if n-1-g<g and n-1>=g:
        dp[n][g]=max(dp[n-1][g-1],dp[n-1][g]+1)
      else:
        dp[n][g]=dp[n-1][g-1]
#      print(n,g,dp)
print(max(dp[-1]))

Submission status: Time Limit Exceeded

Solution code:
# dpぽい気がするのでそうする
# なぜかREなる....
# pythonだとrecursion limitがアレなのを忘れていた...

import sys

sys.setrecursionlimit(10 ** 8)


s = input()
dp = {}


def rec(i, cur_g, cur_p, tmp):
    if i in dp:
        return dp[i]
    if i == len(s):
        ret = 0
        for j in range(len(s)):
            if tmp[j] == "p" and s[j] == "g":
                ret += 1
            elif tmp[j] == "g" and s[j] == "p":
                ret -= 1
        dp[i] = ret
        return ret
    if cur_g > cur_p:
        # パーを出せる（出さなくてもいい）
        ret = max(
            rec(i + 1, cur_g, cur_p + 1, tmp + "p"),
            rec(i + 1, cur_g + 1, cur_p, tmp + "g"),
        )
        dp[i] = ret
        return ret

    else:
        # 勝てるかどうかにかかわらずグーを出すしか無い
        ret = rec(i + 1, cur_g + 1, cur_p, tmp + "g")
        dp[i] = ret
        return ret


print(rec(0, 0, 0, ""))

Submission status: Time Limit Exceeded

Solution code:
# dpぽい気がするのでそうする
# なぜかREなる....
# pythonだとrecursion limitがアレなのを忘れていた...

import sys

sys.setrecursionlimit(10 ** 8)


s = input()
dp = {}


def rec(i, cur_g, cur_p, tmp):
    if i in dp:
        return dp[i]
    if i == len(s):
        ret = 0
        for j in range(len(s)):
            if tmp[j] == "p" and s[j] == "g":
                ret += 1
            elif tmp[j] == "g" and s[j] == "p":
                ret -= 1
        return ret
    if cur_g > cur_p:
        # パーを出せる（出さなくてもいい）
        ret = max(
            rec(i + 1, cur_g, cur_p + 1, tmp + "p"),
            rec(i + 1, cur_g + 1, cur_p, tmp + "g"),
        )
        dp[i] = ret
        return ret

    else:
        # 勝てるかどうかにかかわらずグーを出すしか無い
        ret = rec(i + 1, cur_g + 1, cur_p, tmp + "g")
        dp[i] = ret
        return ret


print(rec(0, 0, 0, ""))

Submission status: Time Limit Exceeded

Solution code:
s = input()
n = len(s)
list_count = []
for i in range(1, n + 1):
  sub_str = s[:i]
  count_g = sub_str.count("g")
  count_p = sub_str.count("p")
  list_count.append(count_g - count_p)

point = 0
while list_count[-1] >= 2:
  for back_index in range(n)[::-1]:
    if list_count[back_index] < 2:
      list_count = [value if index <= back_index else value - 2 for index, value in enumerate(list_count)]
      point += 1
      break
print(point)

Submission status: Time Limit Exceeded

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

# dp[何文字目][パーを出した回数]
dp = [[0] * (N // 2 + 1) for _ in range(N + 1)]
for i in range(1, N + 1) :
    p = (s[i-1] == 'p')
    dp[i][0] = dp[i-1][0] - (1 if p else 0)
    for j in range(1, i // 2 + 1) :
        dp[i][j] = max(dp[i-1][j-1] + (0 if p else 1), dp[i-1][j] - (1 if p else 0))
        
        
print(max(dp[-1]))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
import copy
S=list(input())
N=len(S)
point=0
hand=copy.deepcopy(S)
panum=sum([j=="p" for j in hand])
pamax=N//2#ポイントの上限
for i in range(N):
    if S[i]=="g":
        pa=sum([hand[j]=="p" for j in range(i+1)])#今まで出したパーの数
        if pa<(i+1)//2 and point<pamax-panum:
            hand[i]="p"
            point+=1
    if point>=pamax-panum:
        break
print(point)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
import copy
S=list(input())
N=len(S)
point=0
hand=copy.deepcopy(S)
panum=sum([j=="p" for j in hand])
pamax=N//2#ポイントの上限
for i in range(N):
    pa=sum([hand[j]=="p" for j in range(i+1)])#今まで出したパーの数
    if pa<(i+1)//2 and point<pamax-panum:
        hand[i]="p"
        point+=1
print(point)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
import copy
S=list(input())
N=len(S)
point=0
hand=copy.deepcopy(S)
panum=sum([j=="p" for j in hand])
pamax=N//2#ポイントの上限
for i in range(N):
    pa=sum([j=="p" for j in hand[:i+1]])#今まで出したパーの数
    if pa<(i+1)//2 and point<pamax-panum:
        hand[i]="p"
        point+=1
print(point)

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8

def win(p,e):
    if p=="g" and e=="p":
        return -1
    elif p=="p" and e=="g":
        return 1
    else:
        return 0

def f(memo,e_str,pt,gt,i): 
    if len(e_str)<=i:
        return 0

    if memo[pt][gt]!=-0xffff:
        return memo[pt][gt]
    else:
        point_p=-0xffff
        if pt+1<=gt:
            point_p=f(memo,e_str,pt+1,gt,i+1)+win("p",e_str[i])
            
        point_g=f(memo,e_str,pt,gt+1,i+1)+win("g",e_str[i])

        memo[pt][gt]=max(point_p,point_g)
    return memo[pt][gt]

if __name__ == "__main__":
    e_str=list(input())
    memo=[[-0xffff for i in range(len(e_str))] for j in range(len(e_str))]
    print(f(memo,e_str,0,0,0))

Submission status: Time Limit Exceeded

Solution code:
s = raw_input()
N = len(s)


def judge(x):
    score = 0
    for a, b in zip(s, x):
        if (a, b) == ('p', 'g'):
            score -= 1
        elif (a, b) == ('g', 'p'):
            score += 1
    return score

if N % 2 == 0:
    x  = 'g' * (N / 2) + 'p' * (N / 2)
    score = judge(x)
else:
    score = 0
    for i in xrange(N / 2 + 1):
        x = 'g' * (N / 2) + 'p' * i + 'g' + 'p' * (N / 2 - i)
        score = max(score, judge(x))
print score

Submission status: Time Limit Exceeded

Solution code:
s = input()
n = len(s)
a = [['_' for i in range(n)] for i in range(n)]
def dp(i,j):
    if i==n:
        return 0
    if a[i][j] != '_':
        return a[i][j]
    if j==0:
        a[i][j] = dp(i+1,1) + (0 if s[i]=='g' else -1)
        return a[i][j]
    else:
        x = dp(i+1,j+1) + (0 if s[i]=='g' else -1)
        y = dp(i+1,j-1) + (1 if s[i]=='g' else 0)
        a[i][j] = max(x,y)
        return a[i][j]
print(dp(0,0))

Submission status: Time Limit Exceeded

Solution code:
s = input()
n = len(s)
dp = [0]

for i, c in enumerate(s):
    new = [0] * (i + 2)
    km = c == 'g'
    for j in range(i % 2, i + 1, 2):
        new[j + 1] = dp[j] - (not km)
        if j:
            new[j - 1] = max(new[j - 1], dp[j] + km)
    dp = new

print(max(dp))

Submission status: Time Limit Exceeded

Solution code:
s = input()
n = len(s)
dp = [0]

for i, c in enumerate(s):
    new = [0] * (i + 2)
    for j in range(i % 2, i + 1, 2):
        new[j + 1] = dp[j] - int(c == 'p')
        if j:
            new[j - 1] = dp[j] + int(c == 'g')
    dp = new

print(max(dp))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import math
s = input()
 
ans = 0
 
r = 0
p = 0
c = 0
for j in s:
  c = r-p
  if j == 'g':
    if c > 0:
      p += 1
      ans += 1
    else:
      r += 1
  else:
    if c > 0:
      p += 1
    else:
      r += 1
      ans -= 1
print (ans)

Submission status: Accepted

Solution code:
s=input()
g=s.count("g")
l=len(s)
print(g-(l+1)//2)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, copy,bisect
from operator import itemgetter
#from heapq import heappush, heappop
#import numpy as np
#from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
#from scipy.sparse import csr_matrix
#from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

stdin = sys.stdin

ni = lambda: int(ns())
nf = lambda: float(ns())
na = lambda: list(map(int, stdin.readline().split()))
nb = lambda: list(map(float, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

s = ns()
ans = 0
ct = 0
for i in range(len(s)):
    if ct == 0:
        ct += 1
        if s[i] == 'p':
            ans -= 1
    else:
        ct -= 1
        if s[i] == 'g':
            ans += 1
print(ans)

Submission status: Accepted

Solution code:
from math import floor 
s = input()
n = len(s)
p = s.count('p')
print(floor(n/2)-p)

Submission status: Accepted

Solution code:
s = input()
s0 = s[::2]
s1 = s[1::2]
print(s1.count('g') - s0.count('p'))

Submission status: Accepted

Solution code:
s = input()
n = len(s)
p = 0
for e in s:
  if e == 'p':
    p += 1
print(n//2 - p)

Submission status: Accepted

Solution code:
from collections import Counter
s = input()

n = len(s)

c = Counter(s)
print(n // 2 - c['p'])

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

def main():
    S = input()
    gp = [0, 0]
    ans = 0
    for c in S:
        if gp[0] > gp[1] and c == 'g':
            ans += 1
            gp[1] += 1
        elif gp[0] > gp[1] and c == 'p':
            gp[1] += 1
        elif c == 'g':
            gp[0] += 1
        else:
            ans -= 1
            gp[0] += 1
    print(ans)




if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
S = input()
from collections import defaultdict as dd
Hand = dd(lambda:0)
for s in S:
    Hand[s] += 1
ans = len(S)//2 - Hand['p']
print(ans)

Submission status: Accepted

Solution code:
s = input()
gu = 1
pa = 0
point = 0
if s[0] == "p":
  point -= 1
  
for hand in s[1:]:
  if hand == "g":
    if pa<gu:
      point += 1
      pa += 1
    else:
      gu += 1
  elif hand == "p":
    if pa<gu:
      pa += 1
    else:
      gu += 1
      point -= 1
print(point)

Submission status: Accepted

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

t = 'gp' * (n//2)
if n% 2== 1:
    t += 'g'

ans = 0
for i in range(n):
    if s[i] == 'g' and t[i] == 'p':
        ans += 1
    elif s[i] == 'p' and t[i] == 'g':
        ans -= 1
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# 全部グーを出すことは可能、その時、スコアは　-(相手のパーの数)
# グーをパーに変更すると、-1->0 or 0->1  となる、
# すなわち、相手の手がなんであろうと点数が+1される
# グー、パー、グー、パー、...と出すのが最適
# -(相手のパーの数) + (N//2)

S = list(input())
N = len(S)
a = S.count("p")
b = N // 2
ans = -a + b
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
s = list(input())
g = 0
p = 0
ans = 0
for i in range(len(s)):
    if s[i] == "g":
        if p+1 <= g:
            ans += 1
            p += 1
        else:
            g += 1
    else:
        if p+1 <= g:
            p += 1
        else:
            ans -= 1
            g += 1
print(ans)

Submission status: Accepted

Solution code:
c = 0 # counts of paper to be ok to use
r = 0
t = []
for l in raw_input():
	if l == 'g':
		if c:
			r +=1
			c -=1
		else:
			c+=1
	elif l == 'p':
		if c:
			c-=1
		else:
			r -=1
			c +=1

print r

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
S = input()
p = 0
g = 0
a = 0

for s in S:
  if s=="p":
    if p+1<=g:
      a+=0
      p+=1
    else:
      a-=1
      g+=1
  else:
    if p+1<=g:
      a+=1
      p+=1
    else:
      a+=0
      g+=1

print(a)

Submission status: Accepted

Solution code:
s = input()
n = len(s)
ans = 0
for i in range(n):
    if i % 2 == 0:  # 自分はｇ
        if s[i] == "p":
            ans -= 1
    else:  # 自分はｐ
        if s[i] == "g":
            ans += 1
print(ans)

Submission status: Accepted

Solution code:
from math import ceil
s=input()
gu=s.count('g')
pa=s.count('p')

p=len(s)//2
g=int(ceil(len(s)/2))

gu,g=gu-min(gu,g),g-min(gu,g)
pa,p=pa-min(pa,p),p-min(pa,p)

if g==0 and gu==0 and p==0 and pa==0:
  print(0)
  exit()
  
if p==0 and gu==0:
  print(-g)
  exit()
  
if pa==0 and g==0:
  print(gu)
  exit()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
S = readline().decode().rstrip()
N = len(S)
p_cnt = S.count('p')
p = N//2
print(p-p_cnt)

Submission status: Accepted

Solution code:
s=input()
count=0
for i in range(len(s)):
  if i % 2 == 0:
    if s[i]=='p':
      count -= 1
  else:
    if s[i]=='g':
      count += 1

print(count)

Submission status: Accepted

Solution code:
s = input()
N = len(s)
D = {"g":0, "p":0}
for i in range(N):
    D[s[i]] += 1
my_p = N//2
score = my_p - D["p"]
print(score)

Submission status: Accepted

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

if n % 2 == 0:
    print(s[n//2:].count('g') - s[:n//2].count('p'))
else:
    print(s[n//2+1:].count('g') - s[:n//2+1].count('p'))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
s = input()
g_cnt, p_cnt = 0, 0
ans = 0
for c in s:
    if c == 'g':
        if g_cnt > p_cnt:
            ans   += 1
            p_cnt += 1
        else:
            g_cnt += 1
    else:
        if g_cnt > p_cnt:
            p_cnt += 1
        else:
            ans   -= 1
            g_cnt += 1
print(ans)

Submission status: Accepted

Solution code:
def janken(a,b):
  if a==b:
    return 0
  elif a=="g" and b=="p":
    return 1
  else:
    return -1
s=0
S=list(input())
for i in range(len(S)):
  if i%2==0:
    k="g"
    s+=janken(S[i],k)
  else:
    k="p"
    s+=janken(S[i],k)
print(s)

Submission status: Accepted

Solution code:
s = str(input())

n = len(s)

g_num = 0
p_num = 0
win = 0
lose = 0



for i in range(n):
    if s[i] == "g" and g_num >= p_num+1:
        p_num+=1
        win+=1
    elif s[i] == "g":
        g_num +=1
    elif s[i] == "p" and g_num >= p_num+1:
        p_num +=1
    else:
        g_num +=1
        lose+=1


print(win-lose)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
s = input()
p = s.count('p')
print(len(s)//2-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 abc046_d():
    s = str(input())
    n = len(s)
    if n == 1: return 0
    gc = [0] * n
    pc = [0] * n
    for i, c in enumerate(s):
        gc[i] = gc[i-1] + c.count('g')
        pc[i] = pc[i-1] + c.count('p')
    ans = (gc[-1] - pc[-1]) // 2
    return ans

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

Submission status: Accepted

Solution code:
from collections import Counter

s=input()
c=Counter(s)
if len(s)%2==0:
    print(len(s)//2-c["p"])
else:
    print((len(s)-1)//2-c["p"])

Submission status: Accepted

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

p = 0
ans = 0

for i in range(n):
    s1 = s[i]
    if s1 == 'g':
        p += 1
    else:
        p -= 1
    n -= 1
    if p >= n:
        break

for i in range(n):
    if s[-i-1] == 'g':
        ans += 1

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

s = input()

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

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    S = readline().strip()

    ans = len(S) // 2 - S.count('p')

    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    S = readline().strip()

    g, p = 0, 0
    ans = 0
    for c in S:
        if g > p:
            p += 1
            if c == 'g':
                ans += 1
        else:
            g += 1
            if c == 'p':
                ans -= 1

    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし

s = LS2()

a,b = 0,0
for i in s:
    if i == 'g':
        a += 1
    else:
        b += 1

print((a-b)//2)

Submission status: Accepted

Solution code:
s=input()
n=len(s)
pcnt,gcnt=0,0
ans=[""]*n
for i in range(n):
    if s[i]=="g":
        if gcnt>pcnt:
            ans[i]="p"
            pcnt+=1
        else:
            ans[i]="g"
            gcnt+=1
    if pcnt==n//2 or gcnt==-(-n//2):
        break
i,j=0,0
#print(gcnt,pcnt)
while -(-n//2)>gcnt:
    if ans[i]=="":
        ans[i]="g"
        gcnt+=1
    i+=1
while n//2>pcnt:
    if ans[j]=="":
        ans[j]="p"
        pcnt+=1
    j+=1
score=0
#print(ans)
for i in range(n):
    if ans[i]=="p" and s[i]=="g":
        score+=1
    elif ans[i]=="g" and s[i]=="p":
        score-=1
print(score)

Submission status: Accepted

Solution code:
#float型を許すな
#numpyはpythonで
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7
s=SI()
n=len(s)
count=0
for i in range(n):
    if s[i]=="p":
        count+=1
if n%2==0:
    pos=n//2
else:
    pos=(n-1)//2
ans=pos-count
print(ans)

Submission status: Accepted

Solution code:
def judge(mygp,yourgp):
  if mygp=='g' and yourgp=='p':
    return -1
  elif mygp=='p' and yourgp=='g':
    return 1
  else:
    return 0

s=[x for x in input()]
t=[['g','p'][x%2] for x in range(len(s))]
print(sum([judge(a,b) for a,b in zip(t,s)]))

Submission status: Accepted

Solution code:
S = input()
cp = 0
cg = 0
point = 0
for s in S:
    if s == 'g':
        if cp + 1 <= cg:
            point += 1
            cp += 1
        else:
            cg += 1
    else:
        if cp + 1 <= cg:
            cp += 1
        else:
            point -= 1
            cg += 1
print(point)

Submission status: Accepted

Solution code:
S = list(input())
N = len(S)
gp = ["g","p"]
out = 0
for i in range(N):
    if i%2==0:
        hand = "g"
    else:
        hand = "p"
    if hand==S[i]:
        out += 0
    elif hand=="p" and S[i]=="g":
        out += 1
    elif hand=="g" and S[i]=="p":
        out += -1
print(out)

Submission status: Accepted

Solution code:
def solve():
    opponent = input()
    p_amt = len(opponent) // 2
    me = "p" * p_amt + "g" * (len(opponent) - p_amt)

    ans = 0
    for i in range(len(opponent)):
        if opponent[i] == "g" and me[i] == "p":
            ans += 1
        
        if opponent[i] == "p" and me[i] == "g":
            ans -= 1
    
    print(ans)

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    s = input()
    ro = 0
    pa = 0
    score = 0

    for hand in s:
        if hand == "g":
            if pa < ro:
                pa += 1
                score += 1
            else:
                ro += 1
        else:
            if pa < ro:
                pa += 1
            else:
                ro += 1
                score -= 1

    print(score)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
p = 0
g = 0
S = list(input())
ans = 0
for i in range(len(S)):
    if S[i] == "g" and p < g:
        ans += 1
        p += 1
    elif S[i] == "g" and p == g:
        g += 1
    if S[i] == "p" and p < g:
        p += 1
    elif S[i] == "p" and p == g:
        ans -= 1
        g += 1
print(ans)

Submission status: Accepted

Solution code:
S=input()
P=0
for i in range(len(S)):
  if i&1:
    if S[i]=='g':
      P+=1
  else:
    if S[i]=='p':
      P-=1
print(P)