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:
def main():
    cross_sections = input()
    s1 = []
    s2 = []
    total_surface = 0
    for i, cross_section in enumerate(cross_sections):
        if cross_section == '\\':
            s1.append(i)
        elif cross_section == '/' and s1:
            ip = s1.pop()
            # calc total surface
            sub_surface = i - ip
            total_surface += sub_surface
            # calc sub surface
            for s in reversed(s2):
                if s[0] > ip:
                    sub_surface += s2.pop()[1]
                else:
                    break
            s2.append((ip, sub_surface))

    print(total_surface)
    if s2:
        print(len(s2), ' '.join(map(lambda x: str(x[1]), s2)))
    else:
        print(len(s2))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
areaStr = list(input())
N = len(areaStr)
tmpArea = []
totalArea = 0
eachArea = []
"""
for i in range(N):
    if areaStr[i] == "\\":
        tmpArea.append(i)
    elif areaStr[i] == "/":
        if len(tmpArea) != 0:
            totalArea += (i - tmpArea.pop())
    else:
        pass
    
"""


tmpArea = []
totalArea = 0
for i in range(N):
    if areaStr[i] == "\\":
        tmpArea.append(i)
    elif areaStr[i] == "/":
        if len(tmpArea) != 0:
            j = tmpArea.pop()
            
            totalArea += (i - j)
            a = i - j
            while(len(eachArea) > 0 and eachArea[len(eachArea) - 1][0] > j):
                a +=  eachArea.pop()[1]
               
            eachArea.append([j, a])
    else:
        pass
    

print(totalArea)
print(len(eachArea), end = "")
if len(eachArea) > 1:
    for i in range(len(eachArea)-1):
        print("", end = " ")
        print(eachArea[i][1], end = "")
if len(eachArea) >= 1:
    print("", end = " ")
    print(eachArea[len(eachArea)-1][1])
    
else:
    print("")

Submission status: Accepted

Solution code:
S = input()
t = 0
H = [0]
for c in S:
    if c == '\\':
        t -= 1
        H.append(t)
    elif c == '_':
        H.append(t)
    elif c == '/':
        t += 1
        H.append(t)
L = [0 for _ in range(len(H))] 
for i in range(1, len(H)):
    L[i] = max(L[i-1], H[i])
R = [H[len(H)-1]]
for i in reversed(range(len(H)-1)):
    R.append(max(R[len(R)-1], H[i]))
R.reverse()
C = [min(L[i], R[i]) for i in range(len(H))]
D = 0
ans = []
for i in range(len(H)-1):
    D += (C[i] - H[i]) + (C[i+1] - H[i+1])
    if C[i+1] == H[i+1] and D != 0:
        ans.append(D // 2)
        D = 0
print(sum(ans))
ans.insert(0, len(ans))
print(' '.join(map(str, ans)))

Submission status: Accepted

Solution code:
s=input()


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

stack=[]
i=0
result=0
#みずたまりは、[左側の位置と、数量を表す]
mizutamari=[[-1,0]]
for item in s:
    #print(stack,mizutamari)
    if item=="\\":
        stack.append(i)
    elif item=="/":
        if len(stack)>0:
            temp=stack.pop()
            result+=i-temp
            left=mizutamari.pop()
            if left[0]>temp:
                vol=i-temp
                while 1:
                    vol=left[1]+vol
                    mizutamari.append([temp,vol])
                    if len(mizutamari)<=2:
                        break
                    bk=mizutamari.pop()
                    bkbk=mizutamari.pop()
                    if bkbk<bk:
                        mizutamari.append(bkbk)
                        mizutamari.append(bk)
                        break
                    else:
                        left=bkbk




                
            else:
                #print(left[0],"<",temp,":","naze",left,temp)
                mizutamari.append(left)
                mizutamari.append([temp,i-temp])
                #print(mizutamari)


    i+=1
print(result)
s=""
for item in mizutamari[1:]:
    s+=str(item[1])+" "

if result==0:
    print(0)
else:
    print(len(mizutamari)-1,s[:-1])

Submission status: Accepted

Solution code:
def cal_water(floods):
    fstack = []
    astack = []
    i = 0
    for flood in floods:
        if flood == '\\':
            fstack.append(i)
        elif flood == '/' and len(fstack) > 0:
            s = fstack.pop(-1)
            area = (i - s) * 1
            while len(astack) > 0 and astack[-1][0] > s:
                _, a = astack.pop(-1)
                area += a
            astack.append((s, area))   
        else:
            pass
        i += 1
    
    tot = 0
    tot_area = 0
    out = ''
    while len(astack) > 0:
        _, area = astack.pop()
        tot += 1
        tot_area += area
        out = ' ' + str(area) + out
    
    print(tot_area)
    print(str(tot) +  out)

if __name__ == '__main__':
    floods = input()
    cal_water(floods)

Submission status: Accepted

Solution code:
from collections import deque
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")

def main():
    inf = 10 ** 6
    s = input()
    n = len(s)
    land = [0] * (n + 1)
    for i, c in enumerate(s):
        if c == "/":
            land[i + 1] = land[i] + 1
        elif c == "_":
            land[i + 1] = land[i]
        else:
            land[i + 1] = land[i] - 1
    # print(land)

    water = [0] * (n + 1)
    w = -inf
    i = n
    for l in land[::-1]:
        if l > w: w = l
        water[i] = w
        i -= 1
    w = -inf
    for i, l in enumerate(land):
        if l > w: w = l
        water[i] = min(water[i], w)
    # print(water)

    mm = []
    sum_d = 0
    for w, l in zip(water, land):
        d = w - l
        if d == 0 and sum_d:
            mm.append(sum_d)
            sum_d = 0
        else:
            sum_d += d

    print(sum(mm))
    print(len(mm), *mm)

main()

Submission status: Accepted

Solution code:
from collections import deque


def calc_area(chars):
    s1 = deque()
    s2 = deque()
    area = 0

    for idx, char in enumerate(chars):
        if char == "\\":
            s1.append(idx)
        elif char == "/":
            if s1:
                left_idx = s1.pop()
                sub_area = idx - left_idx
                area = area + sub_area
                while s2 and left_idx < s2[-1][0]:
                    sub_area += s2.pop()[1]
                s2.append((left_idx, sub_area))
    return area, s2


def main():
    chars = input()
    area, s2 = calc_area(chars)
    print(area)
    text = ""
    count = 0
    while s2:
        text += " " + str(s2.popleft()[1])
        count += 1
    print(str(count) + text)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:

class Stack:
    def __init__(self, data=None):
        # Pythonではクラスのデフォルト引数は１度しか初期化されないため、
        # うっかりdata=[]としてしまうと、複数のインスタンスを生成したときに
        # 同じ配列を参照することになってしまう！！！
        # http://amacbee.hatenablog.com/entry/2016/12/07/004510
        if data is None:
            self.data = []
        else:
            self.data = data

    def push(self, x):
        self.data.append(x)

    def pop(self):
        if self.is_empty() is True:
            return None
        else:
            return self.data.pop(-1)

    def is_empty(self):
        if len(self.data) == 0:
            return True
        else:
            return False

    def get_length(self):
        return len(self.data)

    def reverse(self):
        self.data.reverse()


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

diagram = input()
A = 0  # 総面積
k = 0  # 水たまりの数
L = []  # 各水たまりの面積

s1 = Stack()
s2 = Stack()

new_flood = False

# s1.push(10)
# s1.push(20)
# s1.push(30)
# print(s2.data)

for i, vector in enumerate(diagram):
    # print('----------')
    # print(i, vector)

    if vector == '\\':
        # print('下り')
        # print('test')
        s1.push(i)

        # 個別
        # data = {'first_pos': i, 'area': 0}
        # s2.push(data)
        # grad = 'down'

        new_flood = True

    elif vector == '/':
        # print('上り')
        j = s1.pop()
        if j is not None:
            # print(i, j)
            A += i - j

            # current_flood = s2.pop()
            # if current_flood['first_pos'] =
            # Agenshidan88
            # = i:
            #     current_flood['area'] += i - j

            size = i - j

            if new_flood is True:
                s2.push({'first_pos': j, 'size': size})
                new_flood = False

            # if s2.is_empty() is True:
            #     s2.push({'first_pos': j, 'area': i-j})

            else:
                current_flood = s2.pop()
                current_flood['first_pos'] = j
                current_flood['size'] += size

                while True:
                    prev_flood = s2.pop()
                    if prev_flood is not None:
                        if prev_flood['first_pos'] > j:
                            current_flood['size'] += prev_flood['size']
                        else:
                            s2.push(prev_flood)
                            s2.push(current_flood)
                            break
                    else:
                        s2.push(current_flood)
                        break

    # print(s1.data)
    # print(s2.data)
    # print('----------')

print(A)

output = str(s2.get_length())
for elem in s2.data:
    output += ' ' + str(elem['size'])

print(output)

Submission status: Accepted

Solution code:
from collections import deque
input_list = list(input())

left_idx_stack = deque()
puddle_stack = deque()

for idx, s in enumerate(input_list):
    if s == "\\":
        left_idx_stack.append(idx)
    
    elif s == '/':
        if left_idx_stack:
            latest_left_idx = left_idx_stack.pop()
            area = idx - latest_left_idx
        
            if not puddle_stack:
                puddle_stack.append((latest_left_idx, area))
            
            elif latest_left_idx > puddle_stack[-1][0]:
                puddle_stack.append((latest_left_idx, area))
            else:
                
                while len(puddle_stack) != 0 and (latest_left_idx < puddle_stack[-1][0]):
                    latest_puddle = puddle_stack.pop()
                    area += latest_puddle[1]
                    
                puddle_stack.append((latest_left_idx, area))
        else:
            pass
areas = [p[1] for p in puddle_stack]
print(sum(areas))
print(len(areas), *areas)

Submission status: Accepted

Solution code:
S1 = []
S2= []
sum = 0
for i, s in enumerate(input()):
    if s == "\\":
        S1.append(i)
    elif s == "/" 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))
print(sum)
sum2 = [str(len(S2))]
for s in S2:
    sum2.append(str(s[1]))
print(" ".join(sum2))

Submission status: Accepted

Solution code:
s = input()
stack1 = []
stack2 = []
for i in range(len(s)):
    if s[i] == '\\':
        stack1.append(i)
    elif s[i] == '/' and stack1:
        j = stack1.pop()
        area = i-j
        while stack2:
            if stack2[-1][0] < j:
                break
            else:
                area += stack2.pop()[1]
        stack2.append((j,area))
ans = list(stack2[i][1] for i in range(len(stack2)))
print(sum(ans))
if ans:
    print(len(ans),' '.join(map(str,ans)))
else:
    print(0)

Submission status: Accepted

Solution code:
#https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/3/ALDS1_3_D

s = str(input())
l = len(s)

h = [0]
for i in range(l):
    if s[i] == '\\':
        h.append(h[i]-1)
    elif s[i] == '/':
        h.append(h[i]+1)
    else:
        h.append(h[i])

a = []
m = -200000
n = 0
for i in range(l+1):
    if m == h[i] and i != 0:
        a.append([n,i,m])
        m = -200000
    if m < h[i] or i == 0:
        m = h[i]
        n = i
    if (m in h[i+1:]) == False:
        m = -200000

b = []
tmp = 0
for i in range(len(a)):
    for j in range(a[i][0],a[i][1]):
        tmp += a[i][2] - h[j]
        if s[j] == '/':
            tmp += 1 / 2
        elif s[j] == '\\':
            tmp -= 1 / 2
    b.append(int(tmp))
    tmp = 0

if len(b) != 0:
    i=0
    while True:
        if b[i] == 0:
            del b[i]
            i -= 1
        i += 1
        if i == len(b):
            break


A = sum(b)
k = len(b)

print(A)
print(k,end = '')
if k != 0:
    print(' ',end='')
    for i in range(k-1):
        print(b[i],end=' ')
    print(b[len(b)-1])
else:
    print('')

Submission status: Accepted

Solution code:
s=[]
p=[]
a=i=0
for cur in input():
 if"\\"==cur:s+=[i]
 elif"/"==cur 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:
inp = input()


lst = list(inp)
stk = []
stk2 = []

for i in range(len(lst)):
    if lst[i] == '\\':
        stk.append(i)
    if lst[i] == '/' and len(stk)>0:
        idx = stk.pop()
        a = i - idx
        if len(stk2) > 0:
            while(len(stk2) > 0):
                tmp = stk2.pop()
                if idx < tmp[0]:
                    a += tmp[1]
                else:
                    stk2.append(tmp)
                    break
        stk2.append([idx, a])

s = 0
l = []

for i in stk2:
    l.append((i[1]))
    s += i[1]
print(s)
if(len(stk2) > 0):
    print(len(stk2), end=' ')
    print(*l)
else:
    print("0")

Submission status: Accepted

Solution code:
class Info:
    def __init__(self,arg_start,arg_end,arg_S):
        self.start = arg_start
        self.end = arg_end
        self.S = arg_S

POOL = []
LOC = []
cnt = 0
sum_S = 0

line = input()

for c in line:
    if c == "\\":
        LOC.append(cnt)
    elif c == "/":
        if len(LOC) == 0:
            continue
        tmp_start = LOC.pop()
        tmp_end = cnt
        tmp_S = tmp_end - tmp_start
        sum_S += tmp_S
        while len(POOL) > 0:
            if POOL[-1].start > tmp_start and POOL[-1].end < tmp_end:
                tmp_S += POOL[-1].S
                POOL.pop()
            else:
                break
        POOL.append(Info(tmp_start,tmp_end,tmp_S))
    else:
        pass
    cnt += 1

lst = [len(POOL)]
for i in range(len(POOL)):
    lst.append(POOL[i].S)
print(sum_S)
print(*lst)

Submission status: Accepted

Solution code:
def main():
    S = input()

    def an_area(S):
        ans = 0
        stack_in = []
        stack_out = []
        for i,ch in enumerate(S):
            if ch == '\\':
                stack_in.append(i)
            elif stack_in and ch == '/':
                j = stack_in.pop()
                cur =  i - j
                stack_out.append((j,i,cur))
                ans += cur
        return ans,stack_out

    ans, l = an_area(S)
    if ans == 0:
        print(ans)
        print(len(l))
        return

    l.sort()
    pre_le, pre_ri = l[0][0], l[0][1]
    pre_ar = 0
    areas = []
    for le,ri,ar in l:
        if pre_le <= ri <= pre_ri:
            pre_ar += ar
        else:
            areas.append(pre_ar)
            pre_ar = ar
            pre_le, pre_ri = le, ri
    else:
        areas.append(pre_ar)
    
    print(ans)
    print(len(areas),*areas)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
value = input();

j = 0
s = 0
n = len(value)
stack1 = list()
stack2 = []#[[[] for i in range(2)] for j in range(n)]
while(j < n):
    if value[j] == '\\':
        stack1.append(j)
    if value[j] == '/' :
        if len(stack1) != 0:
            idx1 = stack1[-1]
            idx2 = j
            stack2.append([idx1,idx2 - idx1])
            stack1.pop(-1)
            s += 1
    if s - 2 >= 0:
        if stack2[s-1][0] < stack2[s-2][0]:
            stack2[s-2][0] = stack2[s-1][0]
            stack2[s-2][1] += stack2[s-1][1]
            s -= 1
            stack2.pop(-1)
        
    j += 1

if s - 2 >= 0:
    for i in reversed(range(2, s+1)):
        if stack2[i-1][0] < stack2[i-2][0]:
            stack2[i-2][0] = stack2[i-1][0]
            stack2[i-2][1] += stack2[i-1][1]
            #s -= 1
            stack2.pop(i-1)


sumi = 0
s = len(stack2)
for i in range(0, s):
    sumi += stack2[i][1]
    
print(sumi)
if sumi == 0:
    print(s)
else:
    print(s, end = " ")

for i in range(0, s):
    if i != s - 1:
        print(stack2[i][1], end=" ")
    else:
        print(stack2[i][1])

Submission status: Accepted

Solution code:
s = input()
left_index = []
puddles = []

for i in range(len(s)):
    if s[i] == "\\":
        left_index.append(i)

    elif s[i] == "/" and len(left_index) > 0:
        left = left_index.pop()
        puddle = i - left

        while len(puddles) > 0 and puddles[-1][0] > left:
            puddle += puddles.pop()[1]

        puddles.append([left, puddle])

ans = [p[1] for p in puddles]
print(sum(ans))
if len(ans): print(len(ans), " ".join(map(str, ans)))
else : print(len(ans))

Submission status: Accepted

Solution code:
s = input()
n = len(s)
St = []
St2 = []
h = 0
area = 0

for i in range(n):
    if s[i] == "\\":
        St.append(i)
        h -= 1
    elif s[i] == "/":
        h += 1
        if St:
            left = St.pop()
            area += i - left
            
            area2 = 0
            while St2:
                left2 = St2.pop()
                j = left2[0]
                if left < left2[0]:
                    area_add = left2[1]
                    area2 += area_add
                else:
                    St2.append(left2)
                    break
            St2.append([left, area2 + i-left])


print(area)
ans = [t[1] for t in St2]
if St2:
    print(len(St2), end = " ")
    print(*ans)

else:
    print(0)

Submission status: Accepted

Solution code:
x = input()
S1 = []
S2 = []
current_position = 0
total_area = 0

for i in x:
    if i == '\\':
        S1.append(current_position)

    elif i == '/':
        try:
            start_position = S1.pop()
            distance = current_position - start_position
            total_area += distance
            S2.append([start_position, distance])

        except:
            continue

    current_position += 1

print(total_area)

S2.insert(0, [-1, -1])
S3 = []
if len(S2) == 1:print(0)
else:
    for i in range(len(S2)-1, -1, -1):
        x, y = S2[i]
        px, py = S2[i-1]
        if x < px:
            S2[i-1] = [x, y + py]
        else:
            S3.append(S2[i])

    print(len(S3), *[j for i, j in S3[::-1]])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

area_data = input()
total_area = 0
temp_area = 0

stack1 = []
stack2 = []

now_position = 0
for c in area_data:
    if c == '\\':
        stack1.append(now_position)
    elif c == '/':
        if len(stack1) > 0:
            last_potision = stack1.pop()
            temp_area = (now_position - last_potision)
            total_area += temp_area  # 前の\からの距離が、そのまま面積になる

            # print("before stack:{}".format(stack2))
            while len(stack2) > 0:
                prev_spot = stack2.pop()
                # print("prev spot:{}".format(prev_spot))
                # print("last_potision:{}".format(last_potision))
                if prev_spot[0] > last_potision:
                    temp_area += prev_spot[1]
                else:
                    stack2.append(prev_spot)
                    break

            stack2.append((last_potision, temp_area))

        # print("stack2:{}".format(stack2))

    now_position += 1

print(total_area)
print(len(stack2), end="")
for s in stack2:
    print(" ", end="")
    print(s[1], end="")
print()

Submission status: Accepted

Solution code:
from typing import Generic, List, TypeVar

T = TypeVar('T')

class Stack(Generic[T]):
	def __init__(self) -> None:
		self._container: List[T] = []
					
	@property
	def empty(self) -> bool:
		return not self._container # コンテナが空ならば真となる
	
	def push(self, item: T) -> None:
		self._container.append(item)

	def pop(self) -> T:
		return self._container.pop() # LIFO
	
	def __repr__(self) -> str:
		return repr(self._container)


if __name__ == "__main__":
	stack1 = Stack()
	stack2 = Stack()
	string = input()
	sum = 0
	for i in range(len(string)):
		if string[i] == "\\":
			stack1.push(i)
		elif string[i] == "_":
			pass
		elif string[i] == "/":
			if not stack1.empty:
				j = stack1.pop()
				sum += i - j
				a = i - j
				while not stack2.empty:
					item = stack2.pop()
					if item[0] <= j:
						stack2.push(item)
						break
					else:
						a += item[1]
				stack2.push((j, a))
	print(sum)
	b = []
	while not stack2.empty:
		b.append(str(stack2.pop()[1]))
	b.append(str(len(b)))
	b.reverse()
	print(' '.join(b))

Submission status: Accepted

Solution code:
# https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/3/ALDS1_3_D
# これは少し難しい
# stackをうまく利用して個々の湖の面積を出せるかが重要
# 条件を満たしたら面積mergeをするにはどうしたら良いのか考えよう。

chikei = input()
v_lakes = []  # 個々の湖の面積管理用のstack # (面積の始まりのidx, 面積)
idx_stack = []  # 地形のindex管理用の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
        # 可能であるならば面積merge
        # 今のjがv_lakesのj_preよりも小さかったら面積mergeができるということ
        while v_lakes and j < v_lakes[-1][0]:
            # すべての面積をmerge
            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:
n = input()

s1 = []
s2 = []

for i in range(len(n)):
    if n[i] == '\\':
        s1.append(i)
    elif n[i] == '/' and len(s1) > 0:
        a = s1.pop(-1)
        s2.append([a, i - a])

i = 0
while len(s2) > 1:
    if i == len(s2) - 1:
        break
    elif s2[i][0] > s2[i + 1][0]:
        s2[i + 1][1] += s2.pop(i)[1]
        i = 0
    else:
        i += 1

s = []
total = 0
for i in s2:
    s.append(str(int(i[1])))
    total += int(i[1])
print(total)
if len(s2) == 0:
    print('0')
else:
    print('{} {}'.format(len(s2), ' '.join(s)))

Submission status: Accepted

Solution code:
"""
スタックのデータ構造の定義
"""

class Stack:
    def __init__(self):
        self.stack = []

    def push(self, num):
        self.stack.append(num)

    def individual_push(self, num):
        self.stack.append(num)

    def pop(self):
        if len(self.stack) > 0:
            return True, self.stack.pop(-1)
        else:
            return False, 0
    
    def push_individual(self, left_index, current_index):
        sum_a = 0
        for pair in reversed(self.stack):
            if pair[0] > left_index:
                _, a = self.pop()
                sum_a += a[1]
            else:
                break
        self.push((left_index, sum_a + (current_index - left_index)))

    def print_individual_volume(self):
        volume_list = [str(s[1]) for s in self.stack]
        if len(volume_list) == 0:
            print(0)
        else:
            print("{} ".format(len(volume_list)) + " ".join(volume_list))


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

    stack1 = Stack()
    stack2 = Stack()
    area_sum = 0

    for i, v in enumerate(input_values):
        # print(i)

        if v == "\\":
            stack1.push(i)
        elif v == "/":
            result, pop_value = stack1.pop()
            if result:
                area = i - pop_value
                stack2.push_individual(pop_value, i)
            else:
                area = 0
            area_sum += area

    print(area_sum)
    stack2.print_individual_volume()

Submission status: Accepted

Solution code:
from collections import deque

if __name__ == '__main__':
    s = input()
    s1 = deque()
    s2 = deque()
    summ = 0
    for i, c in enumerate(s):
        if c == '\\':
            s1.append(i)
        elif s[i] == '/' and len(s1) > 0:
            j = s1.pop()
            summ += 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))
    counter = len(ans)
    ans.insert(0, counter)
    a = list(map(str, ans))
    print(' '.join(a))

Submission status: Accepted

Solution code:
# ALDS1_3_D Areas on the Cross-Section Diagram

s = input()
s = list(s)  # 地形リスト

s1 = []  # \ リスト


class S2:
    # 池の位置と大きさのリスト
    def __init__(self):
        self.point = []
        self.size = []

    def append(self, x, y):
        lake_size = y
        if not self.point:  # 一番最初の池の処理
            self.point.append(x)
            self.size.append(lake_size)
        else:
            if self.point[-1] < x:
                self.point.append(x)
                self.size.append(lake_size)
            else:
                while self.point[-1] > x:
                    # print('w self.point:{} x:{}'.format(self.point[-1], x))
                    self.point.pop()
                    lake_size += self.size[-1]
                    self.size.pop()
                    if not self.point:
                        break
                self.point.append(x)
                self.size.append(lake_size)
        # print('append point:{} append size:{}'.format(self.point, self.size))
        return self

    def pop(self):
        x = self.point.pop()
        y = self.size.pop()
        return x, y

    def sum_size(self):
        sum_size = sum(self.size)
        return sum_size


s2 = S2()

for i in range(len(s)):
    if s[i] is '\\':
        s1.append(i)
    elif s[i] is '/':
        if s1:  # S1が空ではない場合
            lake_point = s1.pop()
            lake_size = i - lake_point
            # print('point : {} size : {}'.format(lake_point, lake_size))

            s2.append(lake_point, lake_size)

total = s2.sum_size()
lake_num = len(s2.size)

# print('total size : {} number of lakes : {}\nlake size\n{}'.format(total, lake_num, s2.size))
print(total)
print(lake_num, end='')
for i in range(len(s2.size)):
    print('', s2.size[i], end='')
print('')

Submission status: Accepted

Solution code:
s=input()
stack_all=[]
stack_A=[]
point=0
#stack_allで全体の面積をはじめに求める
for i,j in enumerate(s):
    if j=="\\":
        stack_all.append(i)
    elif j=="/":
        try:
            left=stack_all.pop()
            po=i-left
            point +=po
            stack_A.append([left,po])
        except:continue
print(point)

#stack_Aに水が溜まっていくのをスタックしておく
#この過程で数字の小さいものは大きいものの上にきていることがわかるから重ねていく
stack_A.insert(0,[-1,-1])
stack_B=[]
if len(stack_A)==1:print(0)
else:
    for i in range(len(stack_A)-1,-1,-1):
        x,y=stack_A[i]
        px,py=stack_A[i-1]
        if x<px:
            stack_A[i-1]=[x,y+py]
        else:
            stack_B.append(stack_A[i])
    print(len(stack_B),*[j for i,j in stack_B[::-1]])

Submission status: Accepted

Solution code:
s = input()

length = len(s)

a = [0] * (length + 1)
b = [0] * length
y = 0
for i in range(length):
    if s[i] == '/':
        y += 1
    elif s[i] == '\\':
        y -= 1
    a[i + 1] = y

m = -30000
for i in range(length, 0, -1):
    m = max(m, a[i])
    b[i - 1] = m

i = 0
memory = []
while i < length:
    if a[i] > b[i]:
        i += 1
        continue

    start = a[i]
    i += 1
    base = 1
    d_from = s[i - 1]
    ws_part = 0
    while i < length + 1 and a[i] < start:
        d_to = s[i]
        ws_part += base
        if d_from == '\\' and d_to == '\\':
            base += 2
        if d_from == '\\' and d_to == '_':
            base += 1
        if d_from == '/' and d_to == '/':
            base -= 2
        if d_from == '/' and d_to == '_':
            base -= 1
        if d_from == '_' and d_to == '\\':
            base += 1
        if d_from == '_' and d_to == '/':
            base -= 1
        d_from = d_to
        i += 1

    if ws_part > 0:
        ws_part += 1
        memory.append(ws_part // 2)

print(sum(memory))
if memory:
    print(len(memory), ' '.join(map(str, memory)))
else:
    print(len(memory))

Submission status: Accepted

Solution code:
# coding: utf-8

def areas_calc(strings):
    stack1 = []
    stack2 = []
    total_m = 0
    for i, s in enumerate(strings):
        if s == "\\":
            stack1.append(i)
        elif s == "_":
            continue
        elif s == '/':
            if len(stack1) > 0:
                previous_i = stack1.pop()
                m = i - previous_i
                total_m += m

                while len(stack2) > 0:
                    stacked_i, stacked_m = stack2.pop()
                    if previous_i < stacked_i:
                        m += stacked_m
                    else:
                        stack2.append((stacked_i, stacked_m))
                        stack2.append((previous_i, m))
                        break

                else:
                    stack2.append((previous_i, m))
    print(total_m)
    k = len(stack2)
    for_output = [str(k)] + [str(m) for i, m in stack2]
    print(' '.join(for_output))
    

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

Submission status: Accepted

Solution code:
import sys
from collections import deque

def test():

	EleList = deque()
	sublist = []
	output = []
	areas_from_left = list(sys.stdin.readline())
	sum = 0
	depth = 0

	for element in areas_from_left:

		if element == '\\':
			depth += 1
			EleList.append(element)

		elif element == '_':
			if EleList:
				EleList.append(element)

		elif element == '/':
			depth -= 1
			if EleList:
				for pop_count in range(len(EleList)):
				
					pop_ele = EleList.pop()
					if pop_ele == '\\' and EleList:
						for i in range(pop_count+2):
							EleList.append('_')
						break
				lake = pop_count + 1
				sum += lake

				if len(EleList) == 0:
					if len(sublist) == 0:
						output.append(lake)
					else:
						tmp = 0
						for i in sublist:
							tmp += i[0]
						output.append(tmp + lake)
						sublist.clear()
				else:
					
					if not sublist or sublist[len(sublist)-1][1] < depth:
						sublist_element = [0,0]
						sublist_element[0] = lake
						sublist_element[1] = depth
						sublist.append(sublist_element)
					
					else:

						sublist_element = [lake,depth]

						while True:
							
							if not sublist:
								break

							tmp = sublist.pop()
							if tmp[1] > depth:
								sublist_element[0] += tmp[0]
							else:
								sublist.append(tmp)
								break

						sublist.append(sublist_element)
				#print(f"{output}{sublist}")

	output_sublist = []
	for tmp in sublist:
		output_sublist.append(tmp[0])

	output = output + output_sublist
	length = len(output)

	print(sum)
	if length != 0:
		print(f"{length} ",end='')
	else:
		print(length)
	

	for i in range(length - 1):
		print(f"{output[i]} ",end='')
	if output:
		print(output[length-1])

if __name__ == "__main__":
	test()