Problem:


  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Areas on the Cross-Section Diagram

  Your task is to simulate a flood damage.

  For a given cross-section diagram, reports areas of flooded sections.

  Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides.
For example, for the above cross-section diagram, the rain will create floods which have areas of 4, 2, 1, 19 and 9 respectively.

Input

  A string, which represents slopes and flatlands by '/', '\' and '_' respectively, is given in a line. For example, the region of the above example is given by a string "\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\".

output

  Report the areas of floods in the following format:

$A$

$k$ $L_1$ $L_2$ ... $L_k$

  In the first line, print the total area $A$ of created floods.

  In the second line, print the number of floods $k$ and areas $L_i (i = 1, 2, ..., k)$ for each flood from the left side of the cross-section diagram. Print a space character before $L_i$.

Constraints

$1 \leq$ length of the string $\leq 20,000$

Sample Input 1

\\//

Sample Output 1

4
1 4

Sample Input 2

\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\

Sample Output 2

35
5 4 2 1 19 9



Sample input:
\\//


Sample output:
4
1 4

Submission status: Accepted

Solution code:
import sys, collections
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    S = SS()
    stk = []
    pool_stk = []

    ans = 0
    for i, e in enumerate(S):
        if e=='\\':
            stk.append(i)
        elif e=='/':
            if stk:
                idx_d = stk.pop()
                pool_layer = i - idx_d
                ans += pool_layer
                if pool_stk and idx_d<pool_stk[-1][0]:
                    merged_pool = 0
                    while pool_stk and idx_d<pool_stk[-1][0]:
                        pool_tmp = pool_stk.pop()
                        merged_pool += pool_tmp[1]
                    pool_stk.append((idx_d, merged_pool+pool_layer))
                else:
                    pool_stk.append((idx_d, pool_layer))
    
    print(ans)
    print(len(pool_stk), *[i[1] for i in pool_stk])

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
dan = list(input())
wid = len(dan)
stack_s1 = list()
stack_s2 = list()

for i in range(wid):
    if dan[i] == '\\':
        stack_s1.append(i)
    if len(stack_s1) > 0 and dan[i] == '/':
        j = stack_s1.pop()
        men = i - j
        while len(stack_s2) > 0 and j < stack_s2[-1][0]:
            tmp = stack_s2.pop()
            men += tmp[1]
        stack_s2.append([j, men])

t_men = 0
k = list()
k.append(str(len(stack_s2)))
for i, j in stack_s2:
    t_men += j
    k.append(str(j))
print(t_men)
print(' '.join(k))

Submission status: Accepted

Solution code:
from collections import deque

input = input()

stack = deque()
area = deque()

for i, v in enumerate(input):
    if v == "\\":
        stack.append(i)
    elif v == "/" and stack:
        j = stack.pop()
        ans = i - j
        while area and j<area[-1][0]:
            ans += area.pop()[1]
        area.append([j, ans])

B = [len(area)]
A = [i[1] for i in area]
print(sum(A))
B.extend(A)
print(*B)

Submission status: Accepted

Solution code:
import collections

s = input()
s1 = collections.deque([])
s2 = collections.deque([])
sum_ = 0
for i,ch in enumerate(s):
    if ch == "\\":
        s1.append(i)
    elif ch == "/" and len(s1)>0:
        j = s1.pop()
        sum_ += i - j
        a = i - j
        while len(s2) > 0 and s2[-1][0]>j:
            a += s2.pop()[1]
        s2.append([j,a])
ans = []
while len(s2)>0:
    ans.append(s2.pop()[1])
ans.reverse()
print(sum(ans))
ans.insert(0,len(ans))
print(*ans)

Submission status: Accepted

Solution code:
def main():
    s = input()
    lst1 = []
    lst2 = []
    total_area = 0

    for i in range(len(s)):
        if s[i] == "\\":
            lst1.append(i)
        elif s[i] == "/" and len(lst1) > 0:
            j = lst1.pop()
            area = i - j
            total_area += area
            while len(lst2) > 0 and lst2[-1][0] > j:
                area += lst2.pop()[1]
            lst2.append([j, area])
    print(total_area)
    print(len(lst2), *[area for j, area in lst2])


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
inputString = input()
terrainWidth = len(inputString)+1

height = [0] # 土地の高さを求める (左端 = 0)
currentHeight = 0
for c in inputString:
    if c == '_':
        d = 0
    elif c == '/':
        d = 1
    elif c == '\\':
        d = -1
    else:
        pass
    currentHeight += d
    height.append(currentHeight)

leftMax = [] # 各地点における、その地点より左の最大高さを求める
currentMax = 0
for h in height:
    currentMax = max(h, currentMax)
    leftMax.append(currentMax)

rightMax = [0]*terrainWidth # 各地点における、その地点より右の最大高さを求める
currentMax = height[-1]
for i in range(len(height), 0, -1):
    currentMax = max(height[i-1], currentMax)
    rightMax[i-1] = currentMax

floodArea = 0
floodDepth = [0]*terrainWidth # 各地点の水位は leftMax と rightMax の最小値
for i in range(terrainWidth):
    floodDepth[i] = min(leftMax[i], rightMax[i]) - height[i]
    floodArea += floodDepth[i]

pools = []
inPool = False
for depth in floodDepth:
    if depth:
        if inPool:
            pools[-1] += depth
        else:
            inPool = True
            pools.append(depth)
    elif inPool:
        inPool = False

print(floodArea)
if pools:
    print(len(pools), ' '.join([str(p) for p in pools]))
else:
    print(0)

Submission status: Accepted

Solution code:
from collections import deque
from sys import stdin

A = input()
d = deque([])
e = deque([])
area = 0
areas = deque([])

for a,b in enumerate(A):
    if b == "\\":
        d.append(a)
    elif b == "/" and d != deque([]):
        x = d.pop()
        area += a - x
        areas.append([x,a,a-x])

menseki = 0
kaitou = []
prev_start,prev_end = 20000,0
while len(areas) > 0:
    temp = areas.pop()
    if temp[0] > prev_start and temp[1] < prev_end:
        menseki += temp[2]
    else:
        if menseki != 0:
            kaitou.append(menseki)
        menseki = temp[2]
        prev_start, prev_end = temp[0],temp[1]
    if len(areas) == 0:
        kaitou.append(menseki)

print(sum(kaitou))
kaitou.append(len(kaitou))
print(*kaitou[::-1])

Submission status: Accepted

Solution code:
from collections import deque
que = deque()
l = input()
S = 0
S2 = []
for j in range(len(l)):
    i = l[j]
    if i == '\\':
        que.append(j)
        continue
    elif i == '/':
        if len(que) == 0:
            continue
        k = que.pop()
        pond_sum = j-k
        S += pond_sum
        while S2 and S2[-1][0] > k:
            pond_sum += S2[-1][1]
            S2.pop()
        S2.append([k,pond_sum])
    elif i == '_':
        continue
data = [i for j,i in S2]
print(S)
print(len(S2),*data)

Submission status: Accepted

Solution code:
def area_cal(input_fig):
    stack = []
    # area = [[面積計算が始まった位置, 面積],・・・]
    area = []
    total = 0
    for i in range(len(input_fig)):
        fig = input_fig[i]
        if fig == "\\":
            stack.append(i)
        elif fig == "/" and stack:
            j = stack.pop()
            width = i - j
            total += width
            while area and area[-1][0] > j:
                width += area[-1][1]
                area.pop()
            area.append([i,width])
    return area, total
            
input_fig = input()
area, total = area_cal(input_fig)
print(total)
if area:
    print(len(area),*list(zip(*area))[1])
else:
    print(0)

Submission status: Accepted

Solution code:
s=[]
p=[]
a=i=0
for c in input():
    if"\\"==c:
        s+=[i]
    elif"/"==c and s:
        j=s.pop()
        t=i-j
        a+=t
        while p and p[-1][0]>j:
            t+=p[-1][1];p.pop()
        p+=[(j,t)]
    i+=1
print(a)
if p:
    print(len(p),*list(zip(*p))[1])
else:
    print(0)

Submission status: Accepted

Solution code:
import math
import sys
import itertools
from collections import deque
# import numpy as np

def main():
  S = sys.stdin.readline()
  len_S = len(S)

  index = 0 # 操作しているSのインデックス
  DOWN = [] # 下り文字をスタック
  POOL = [] # 水たまりごとの面積
  area = 0 # 総面積

  for s in S:
    if s == '\\':
      DOWN.append(index)

    elif s == '/' and len(DOWN) > 0:
      pool_start = DOWN.pop()
      pool_end = index
      tmp_area = pool_end - pool_start
      area += tmp_area

      while True:
        if len(POOL) == 0:
          break
        if POOL[-1]['start'] > pool_start and POOL[-1]['end'] < pool_end:
          tmp_area += POOL[-1]['area']
          POOL.pop()
        else:
          break

      POOL.append({'start': pool_start, 'end': pool_end, 'area': tmp_area})

    index += 1

  print(area)
  if len(POOL) > 0:
    print(len(POOL), end=" ")
    for i in range(len(POOL)-1):
      print(POOL[i]['area'], end=" ")
    print(POOL[-1]['area'])
  else:
    print(0)

if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
import queue

inpstr = input()
stack = queue.LifoQueue()
stack_areas = queue.LifoQueue()

cnt = 0  # 位置
area = 0  # 総面積
for s in inpstr:
	if s == '\\':
		stack.put(cnt)
	elif s == '/':
		if not stack.empty():
			i = stack.get()
			area = area + cnt - i
			# 個々の面積の再計算
			temp = [i, cnt - i]  # 今回の面積と開始位置
			if stack_areas.empty():
				stack_areas.put(temp)
			else:
				for j in range(0, stack_areas.qsize()):
					temp2 = stack_areas.get()
					if i > temp2[0]:
						stack_areas.put(temp2)
						break
					else:
						temp[1] = temp[1] + temp2[1]
				stack_areas.put(temp)
	elif s == '_':
		pass  # 何もしない、結果cntだけ増える
	cnt = cnt + 1

print(area)
# stackから出力用のリストに変換
areas = []
while not stack_areas.empty():
	areas.append(stack_areas.get()[1])
#print(areas)
areas.append(len(areas))
areas.reverse()
print(' '.join([str(n) for n in areas]))

Submission status: Accepted

Solution code:
from collections import deque
import sys


def func(S):
    i = 0
    water = 0
    stack = []
    waters = []
    while i < len(S):
        for inc, s in enumerate(S[i:]):
            if s == '\\':
                stack.append(s)
                water += len(stack)

            if not stack:
                break

            if s == '/':
                stack.pop()
                water += len(stack)

            if s == '_':
                water += len(stack)

            if not stack:
                break
        if water != 0 and not stack:
            waters.append(water)
        water = 0

        if inc == len(S[i:]) - 1:
            if not stack:
                i = len(S)
            break

        i += inc if inc else 1

    return waters, S[i:]


if __name__ == '__main__':
    S = [c for c in input()]

    waters, S = func(S)

    rev_S = []
    for s in S[::-1]:
        if s == '\\':
            rev_S.append('/')
        elif s == '/':
            rev_S.append('\\')
        else:
            rev_S.append('_')

    new_waters, _ = func(rev_S)
    waters += new_waters[::-1]

print(sum(waters))
print(len(waters), *waters)

Submission status: Accepted

Solution code:
current_l = 0
stack_s = []
stack_each_area = []
areas = []
for s in input():
#     print(stack_each_area)
    if(s == '\\'):
        stack_s.append(current_l)
    elif(s == '/'):
        if(len(stack_s)==0):
            continue
        left_edge = stack_s.pop(-1)
        area = current_l - left_edge
        areas.append(area)
        
        merged_area = area
        merged_j = []
        for j in range(len(stack_each_area)):
            if( left_edge < stack_each_area[j][0] and stack_each_area[j][0] < current_l):
                merged_area += stack_each_area[j][1]
                merged_j.append(j)
        for del_j in merged_j[::-1]:
            del stack_each_area[del_j]
        stack_each_area.append((current_l, merged_area))
    current_l += 1
print(sum(areas))
if(len(stack_each_area) != 0):
    print(len(stack_each_area), " ".join([ str(lm[1]) for lm in stack_each_area]))
else:
    print(0)

Submission status: Accepted

Solution code:

if __name__ == "__main__":
    line = input()

    S1 = []
    S2 = []
    total = 0

    for k, v in enumerate(line):
        if v == '\\':
            S1.append(k)
        elif v == '/' and len(S1) > 0:
            left_pos = S1.pop()
            area = k - left_pos
            total += area

            while True:
                if len(S2) < 1 or S2[-1][0] < left_pos:
                    S2.append([left_pos, area])
                    break
                else:
                    btm_area = S2.pop()
                    area += btm_area[1]

    print(total)
    indiv = [str(v[1]) for v in S2]
    indiv.insert(0, str(len(S2)))
    print(' '.join(indiv))

Submission status: Accepted

Solution code:
from sys import stdin
from collections import deque

def main():
    point = 0
    watermarks = []
    ponds = []

    for mark in list(stdin.readline()):
        point += 1
        if mark == "\\":
            watermarks.append(point)
        elif mark == "/":
            if watermarks:
                start_point = watermarks.pop()
                area = point - start_point
                while ponds and ponds[-1][0] > start_point:
                    area += ponds.pop()[1]
                ponds.append((start_point, area))

    pond_list = [pond[1] for pond in ponds]
    print(sum(pond_list))
    print(len(pond_list), *pond_list)

main()

Submission status: Accepted

Solution code:
from collections import deque
x = input()
A = 0
S1 = deque()
S2 = deque()

for i in range(len(x)):
    if x[i] == "\\":
        S1.append(i)
    elif x[i] == "/" and len(S1) > 0 :
        j = S1.pop()
        A += i - j
        a  = i - j
        while  len(S2) > 0 and S2[-1][0] > j:
            a += S2[-1][1]
            S2.pop()
        S2.append([j,a])
print(A)

if len(S2)== 0:
    print(0)
else:
    print(len(S2),"",end="")
    for i in range(len(S2)):
        if i == len(S2) - 1:
            print(S2[i][1])
        else:
            print(S2[i][1],"",end="")

Submission status: Accepted

Solution code:
field = input()

#%%
idxes = [] # \の位置を管理。一個/が追加されるたびに、その部分は水たまりになれるので、後ろからpopされる
v_lakes = [] # （その水たまりの最も左の\の位置、その水たまりの現時点での面積）の組を格納

for i, f in enumerate(field):
    if f == '\\':
        idxes.append(i) # \の位置を記録
    elif f == '/' and len(idxes) > 0:
        j = idxes.pop() # 最後尾の\の位置を抜き出す
        v = i - j   # \/間の長さがテンポラリの面積vに対応
        # 可能であるなら面積を統合する処理。螺旋本の19の面積みたいに、内側に2つ水たまりができるけどもっと大きく統合できるパターンがある
        # 今回新しく積み上げたj が すでに格納されてる水溜りの左端（v_lakes[-1][0]）よりも、小さい（より左側にある）場合は水溜りを統合してもよい
        while len(v_lakes) > 0 and v_lakes[-1][0] > j:
            v += v_lakes.pop()[1] # 統合する水溜りをpopして加える
        v_lakes.append((j, v))

ans = [v[1] for v in v_lakes]
print(sum(ans))
print(len(ans), *ans)

Submission status: Accepted

Solution code:
from collections import deque

data = input()
tmp = deque()
se = list()
ase = list()
lakes = list()

x = 0
#check start - end
for a in data:
  if a == '\\':
    tmp.append(x)
  if a == '/' and len(tmp) > 0 :
    s = tmp.pop()
    se.append([s,x])
  x += 1
se.sort()

# analyse s -e
if len(se) > 0 :
  ase.append(se[0])
  for i in range(1,len(se)) :
    s,e = ase[len(ase)-1]
    if e < se[i][0]:
      ase.append(se[i])

#calc lakes
for a in ase:
  lsize = 0
  deep = 0
  lx = a[0]
  for m in data[a[0]:a[1] + 1] :
    if m == '\\':
      lsize += 1 + deep
      deep += 1
    elif m == '/':
      deep -= 1
      lsize += deep
      if lx == a[1]:
        lakes.append(lsize)
    else: # '_'
      lsize += deep
    lx += 1

print(sum(lakes))
print(len(lakes),end="")
for lake in lakes:
  print(" {}".format(lake),end="")
print()

Submission status: Accepted

Solution code:
landform = [c for c in input()]
down = []
areas = []

for i in range(len(landform)):
    if landform[i] == '\\':
        down.append(i)
    if landform[i] == '/':
        if down:
            pair = down.pop()
            area = i - pair
            while areas and areas[-1][0] > pair:
                area += areas.pop()[1]
            areas.append([pair, area])

sum_area = 0
for area in areas:
    sum_area += area[1]
print(sum_area)

ans = []
ans.append(str(len(areas)))
ans += [str(area[1]) for area in areas]

print(' '.join(ans))

Submission status: Accepted

Solution code:
l = input()

stack1 = []
stack2 = []

all_area = 0

for val in range(len(l)):
    if l[val] == "\\":
        stack1.append(val)
    elif l[val] == "/" and stack1 != []:
        temp = stack1.pop(-1)
        all_area = all_area + (val - temp)
        each_area = val - temp
        while stack2 != [] and stack2[-1][0] > temp:
            each_area = each_area + stack2.pop(-1)[1]

        stack2.append([temp, each_area])
    else:
        pass

print(all_area)
print(len(stack2), end="")

for i in range(len(stack2)):
    print(" ", end="")
    print(stack2[i][1],end="")

print("")

Submission status: Accepted

Solution code:
S = input()
st = [(0, 0, -1)]
cur = 0; ma = 0
for i, c in enumerate(S):
    if c == '/':
        cur += 1
        s = 0
        while st and st[-1][0] == cur-1 and cur <= ma:
            lev, su, j = st.pop()
            s += su
        if st and st[-1][0] == cur:
            s += i - st[-1][2] - 1
        ma = max(ma, cur)
        st.append((cur, s, i))
    elif c == '\\':
        cur -= 1
        st.append((cur, 0, i))
    elif c == '_':
        st.append((cur, 0, i))
ans = []
for lev, su, j in st:
    if su > 0:
        ans.append(su)
print(sum(ans))
print(len(ans), *ans)

Submission status: Accepted

Solution code:
s = input()
stack = []
stack1 = []
tot = 0
rs = []
for i in range(len(s)):
    if s[i] == '\\':
        stack.append(i)
    elif s[i] == '/':
        if len(stack) > 0:
            tmp = i - stack[-1]
            tot += tmp
            while len(stack1) > 0 and stack1[-1][0] > stack[-1]:
                tmp += stack1[-1][1]
                stack1.pop()
            stack1.append((stack[-1], tmp))
            stack.pop()
print(tot)
print(len(stack1), *(y for x,y in stack1))

Submission status: Accepted

Solution code:
from collections import deque

S = input()

pool_q=deque()
slope_q=deque()

for i,s in enumerate(S):
    if s=="\\":
        slope_q.append(i)
        pool_q.append((i,0))
    elif s=="/":
        if len(slope_q) > 0:
            pre_down=slope_q.pop()
            plus=i-pre_down
            while 1:
                pre_pool=pool_q.pop()
                if pre_pool[0] == pre_down:
                    pool_q.append((pre_down,plus))
                    break
                else:
                    plus+=pre_pool[1]
SUM = 0
ans=[0]
cnt=0
for i in range(len(pool_q)):
    pool=pool_q.popleft()[1]
    if pool > 0:
        ans.append(pool)
        SUM+=pool
        cnt+=1
ans[0]=cnt
print(SUM)
print(*ans)

Submission status: Accepted

Solution code:
S = [s for s in input()]

stack1 = []
stack2 = []

for i in range(len(S)):
    if S[i] == '\\':
        stack1.append(i)
    elif S[i] == '/':
        if len(stack1) != 0:
            pos = stack1.pop()
            area = i - pos
            while len(stack2) != 0:
                pair = stack2.pop()
                if pos < pair[0]:
                    area += pair[1]
                else:
                    stack2.append(pair)
                    break
            stack2.append((pos, area))

print(sum([s[1] for s in stack2]))
print(len(stack2), *[s[1] for s in stack2])

Submission status: Accepted

Solution code:
from collections import deque
S = input()
d = deque()
d2 = deque()
r = []
r_l = 0
buf = 0
for i, s in enumerate(S):
    i += 1
    if s == '\\':
        d.append(i)
    elif s == '/' and len(d) > 0:
        k = d.pop()
        r_l += i - k
        buf = i - k
        while(len(d2) > 0 and d2[-1][0] > k):
            _d = d2.pop()
            buf += _d[1]
        l = [k, buf]
        d2.append(l)

r = []
for i in d2:
    r.append(i[1])
print(r_l)
print(len(r), *r)

Submission status: Accepted

Solution code:
def main():
    s = input()
    stack = []#¥をためるstack
    stack_sum = []#現状できている池のstack
    for i in range(len(s)):
        
        if s[i] == "\\":
            stack.append(i)#池の左側をためる
        elif s[i] == "/":
            if len(stack) != 0:#対応する左側がなかったらskip
                sum_t = 0
                last = stack.pop(-1)#lastからiまでの池を下では考える
                sum_t += (i-last-1)+1#[last,i]の池の計算
                if len(stack_sum) != 0:
                    for j in reversed(range(len(stack_sum))):#後ろからみる
                        if stack_sum[j][0] > last:#[last,i]ではった池でマージできるところをマージ
                            sum_t += stack_sum[j][1]
                            stack_sum.pop(j)
                stack_sum.append((last, sum_t))
    sum_ans = 0#全ての池の合計
    ans = []
    for i in range(len(stack_sum)):
        sum_ans +=stack_sum[i][1]
        ans.append(stack_sum[i][1])#池の容量だけ取り出す

    #print(sum_ans)
    #print(ans)
    print(sum(ans))
    print(len(ans),*ans)

if __name__ == "__main__":
    main()
#O(n^2)なのでO(n)でやるべき

Submission status: Accepted

Solution code:
from collections import deque

line = input()

s1 = deque()
s2 = deque()

n = len(line)
total_area = 0

for i in range(n):
    if line[i] == "\\":
        s1.append(i)
    elif line[i] == "/":
        if s1: # if s1 is not empty
            j = s1.pop()
            area = i - j
            total_area += area
            if s2 and j < s2[-1][0]: # integrate the area of ponds
                while s2 and j < s2[-1][0]:
                    pre_pond = s2.pop()[1]
                    area += pre_pond
            s2.append([j,area])

print(total_area) 
if total_area!=0:
    print("{} ".format(len(s2)) + " ".join([str(x[1]) for x in s2]))
else:
    print(0)

Submission status: Accepted

Solution code:
#input
A = list(input())
#print(A)
##    print(A[i],end = "")
#print(len(A))
sum = 0
#Stack
Stack1 = [] #各水たまりの面積
Stack2 = [] #
for i in range(len(A)):
    if A[i] == "\\":
        Stack1.append(i)
    elif A[i] == "/":
        if Stack1 != []:
            ip = Stack1.pop()
            tmp_sum = i-ip
            sum += i-ip

            xp, yp = ip,tmp_sum

            #-----------------------#
            if Stack2 == []:
                Stack2.append((i, tmp_sum))
            #-----------------------
            else:

                x, y = Stack2.pop()
                # x < ip(xp)
                while ( x- xp >= 0):
                    yp = y + yp
                    if Stack2 == []:
                        xp = x
                        Stack2.append((xp, yp))
                        break
                    else:
                        x, y = Stack2.pop()
                    #Stack2.append((xp, y + yp))
                else:
                    Stack2.append((x, y))
                    Stack2.append((xp, yp))

#print(Stack2)
print(sum)
if sum == 0:
    print(0)
else:
    print(len(Stack2), end=' ') #k
    for i in range(len(Stack2)):
        x, y = Stack2[i]
        if i < len(Stack2)-1:
            print(y, end=' ')
        else:
            print(y)

Submission status: Accepted

Solution code:
chikei = input()
v_lakes = []
idx_stack = []

for i, c in enumerate(chikei):
	if c is "\\":
		idx_stack.append(i)
	elif c is "/" and idx_stack:
		j = idx_stack.pop()
		v = i - j
		while v_lakes and j < v_lakes[-1][0]:
			v += v_lakes.pop()[1]
		v_lakes.append((j, v))

ans = [len(v_lakes)]
v = [v[1] for v in v_lakes]
ans.extend(v)
print(sum(v))
print(*ans)

Submission status: Accepted

Solution code:
def Main():
    cross = input().replace("\n", "")

    S = list()
    V = list()
    ans = list()

    for i in range(len(cross)):
        r = cross[i]

        if r == "\\":
            S.append(i)
        elif r == "/":
            if len(S) > 0:
                j = S.pop()
                v = i - j
                V.append([v, j])

    while len(V) > 0 :
        total = 0
        [v, j] = V.pop()
        total += v

        while True:
            if len(V) > 0:
                [vv, jj] = V.pop()

                if jj > j:
                    total += vv
                else:
                    V.append([vv, jj])
                    ans.append(total)
                    break
            else:
                ans.append(total)
                break

    print("{}".format(sum(ans)))
    print(len(ans), *reversed(ans))

Main()

Submission status: Accepted

Solution code:
s=input()
s1=[]
s2=[]
ans=0
for i in range(len(s)):
    if(s[i]=="\\"):
        s1.append(i)
    elif(s[i]=="/" and s1):
        j = s1.pop()
        a=i-j
        ans+=a

        while(s2 and s2[-1][0]>j):
            a+=s2.pop()[1]
        s2.append([j,a])

print(ans)
print(len(s2),*(a for j, a in s2))

Submission status: Accepted

Solution code:
from sys import stdin
class Stack():
    def __init__(self):
        self.top=0
        self.top2=0
        self.S=[None]*1000
        self.S2= [None] * 1000
        self.total=0
        self.count=0
        self.haihun=0
        self.arealist=[]
        self.N=0
        self.part=0
        self.compt=False
        self.calc_flag=False
        self.up=0
    def isEmpty(self):
        return self.top==0
    def push(self,fig,finish=0):

        if fig=='\\':
            self.count += 1
            self.S.insert(self.top,self.count)
            self.top += 1


        elif fig=='/':
            self.count += 1
            it=self.pop()
            if self.top > 0: self.top -= 1#0=空

            if it is not None:

                # self.total = self.count - it + self.total  # 合計を図る
                self.S2.insert(self.top2, ([self.count - it, it]))
                self.top2+=1

                while(True):
                    if self.S2[self.top2 - 2] is None:break
                    if self.S2[self.top2-2][1]> it:#中に囲まれている
                        i=self.pop2()
                        if self.top2 > 0: self.top2 -= 1  # 0=空
                        j = self.pop2()
                        if self.top2> 0: self.top2 -= 1  # 0=空
                        self.S2.insert(self.top2,([i[0]+j[0],i[1]]))
                        self.top2 += 1
                    else:break
                if self.pop(flag=1) is None:  # 次がないとき
                    self.N += 1  # 池の数
                    while (True):
                        vari = self.pop2(flag=1)
                        if vari is not None:
                            if it <= vari[1]:
                                self.total += vari[0]
                            else:
                                break
                            self.pop2()
                            if self.top2 > 0: self.top2 -= 1  # 0=空
                        else:
                            break
                    self.part = self.total - self.part
                    self.arealist.append(self.part)
                    self.part = self.total


        elif fig=='_':
            self.count+=1
        if finish==1:
            if self.pop(flag=1) is not  None:  # 途中で終わってしまった
                rest=[]
                while(True):
                    part=self.popup()
                    self.up+=1
                    self.top2-=1
                    if  part is not None:
                        self.arealist.append(part[0])
                        self.N += 1  # 池の数
                        self.total+=part[0]
                    else:break





    def pop(self,flag=0):
        vari=self.S[self.top-1]
        if flag==0:
          self.S[self.top-1]=None
        return vari
    def pop2(self,flag=0):
        vari=self.S2[self.top2-1]
        if flag==0:
          self.S2[self.top2-1]=None
        return vari
    def popup(self):
        vari = self.S2[self.up]
        return vari
    def print(self):#終了
        self.push(None,finish=1)
        self.arealist=self.arealist[::-1]
        self.arealist.append(self.N)
        return self.total,self.arealist
cmd =list(stdin.readline())
Stck=Stack()
for str in cmd:
    Stck.push(str)
total,area=Stck.print()
print(total,end='\n')
print(*area[::-1])

Submission status: Accepted

Solution code:
sum = 0
stack  = []
stack2 = []

str_inpt = input()

for i in range(len(str_inpt)):
  if str_inpt[i] == '\\':
    stack.append(i)
  elif str_inpt[i] == '/':
    if len(stack) < 1: continue
    pop_index = stack.pop(-1)
    area = i - pop_index
    sum += area
    while True:
      if len(stack2) < 1: break
      if stack2[-1][0] < pop_index: break
      if pop_index < stack2[-1][0]:
        pop_stack2 = stack2.pop(-1)
        area += pop_stack2[-1]

    stack2.append([pop_index, area])

print(sum)

if len(stack2) == 0:
  print('0')
else:
  print(str(len(stack2)) + ' ' + ' '.join([str(e[1]) for e in stack2]))

Submission status: Accepted

Solution code:
if __name__ == '__main__':

	l = input()
	S1, S2 = [], []
	
	sum = 0
	n = len(l)
	for i in range(n):
		if l[i] == "\\":
			S1.append(i)
		elif l[i] == "/" and S1:
			j = S1.pop()
			a = i - j
			sum += a
	
			while S2 and S2[-1][0] > j:
				a += S2.pop()[1]
			S2.append([j, a])
	
	print(sum)
	print(len(S2), *(a for j, a in S2))

Submission status: Accepted

Solution code:
import sys,bisect
sys.setrecursionlimit(15000)
s = sys.stdin.readline().rstrip()
st = []
ars = []
ar = 0
for i,c in enumerate(s):
  if c == "\\":
    st.append(i)
  elif c == "/":
    if st:
      j = st.pop()
      ar += i-j
      while ars and j < ars[-1][1]:
        ar0,_ = ars.pop()
        ar += ar0
      ars.append([ar,j])
      ar = 0
print(sum([ar for ar,_ in ars]))
if len(ars)==0:
  print(0)
else:
  print(len(ars)," ".join(map(str,[ar for ar,_ in ars])))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

x = input()
lst = list(x)
pt = []
rst = []
k = 0

# point get
cnt = 0
tmp = ""
for s in lst:
    if s == "/":
        if tmp == "_" or tmp == "/":
            cnt += 1
    elif s == "\\":
        if tmp == "\\":
            cnt -= 1
    else:
        if tmp == "\\":
            cnt -= 1

    pt += [cnt]
    tmp = s

#メンセキ
i,xs,m2 = 0,0,0
for s in lst:
    if s == "/":
        if i == xs and xs > 0:
            rst += [m2]
            k += 1
            xs,m2 = 0,0
    elif s == "_":
        pass
    else:
        try:
            x = pt[i+1:].index(pt[i])+i+1
            m2 += x-i
            if xs < x:
                xs = x
        except:
            pass
    i += 1
           
print(sum(rst))
print(k,*rst)

Submission status: Accepted

Solution code:
str = list(input())

a = []
all = 0
areas = []
for i in range(len(str)):
    if str[i] == "\\":
        a.append(i)
    elif str[i] == "/" and len(a) > 0:
        j = a.pop()
        b = i - j
        all += b
        while(len(areas) > 0 and areas[-1][0] > j):
            b += areas.pop()[1]
        areas.append([j, b])

print(int(all))
if len(areas) > 0:
    print(len(areas), *[areas[i][1] for i in range(len(areas))])
else:
    print(0)

Submission status: Accepted

Solution code:
mountains = list(input())
stack1, stack2 = [], []

for i, grad in enumerate(mountains):
    if grad == '\\':
        stack1.append(i)
    elif grad == '/':
        if stack1:
          left = stack1.pop(-1)
          right = i
          space = right - left
          while stack2 and stack2[-1][0] > left:
            space += stack2.pop(-1)[1]
          stack2.append([left, space])
    else:
        pass
#print(stack2)
space_list = [space for index, space in stack2]
print(sum(space_list))
print(len(space_list), *space_list)