Problem:
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

Solution (Python):

class Stack:
    def __init__(self, n):
        self.A = [0 for i in range(n)]
        self.len = n
        self.top = 0

    def is_empty(self):
        return self.top == 0

    def is_full(self):
        return self.top == self.len - 1

    def push(self, x):
        if not self.is_full():
            self.top += 1
            self.A[self.top] = x

    def pop(self):
        if not self.is_empty():
            x = self.A[self.top]
            self.top -= 1
            return x

    def top_element(self):
        if not self.is_empty():
            return self.A[self.top]


if __name__ == '__main__':
    S1 = Stack(20005)  
    S2 = Stack(10005)  
    line = raw_input()
    for i in range(len(line)):
        if line[i] == '\\':
            S1.push(i)
        elif line[i] == '/':
            if S1.is_empty():
                continue
            j = S1.pop()
            cnt = 0  
            
            
            
            
            while not S2.is_empty() and S2.top_element()[0] > j:
                cnt += S2.pop()[1]
            S2.push((j, cnt + i - j))
        else:
            pass

    l = []
    cnt = 0
    while not S2.is_empty():
        x = S2.pop()
        cnt += x[1]
        l.append(x)
    l.reverse()
    print cnt
    print len(l),
    for x in l:
        print x[1],
    print

Solution (Python):
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)

Solution (Python):
from enum import Enum
from queue import Queue
import collections

import sys
import math

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

LOC=[]
POOL=[]

line = input()
loc = 0
sum_S = 0

for ch in line:
    if ch == '\\':
        LOC.append(loc)
    elif ch == '/':
        if len(LOC) ==0:
            continue
        tmp_start = int(LOC.pop())
        tmp_end = loc
        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

    loc += 1
print("%d"%(sum_S))
print("%d"%(len(POOL)),end = "")

while len(POOL) > 0:
    print(" %d"%(POOL[0].S),end = "") 
    POOL.pop(0)

print()

Solution (Python):
input_line = input()
stack = []
area = 0
pond_area = 0
pond_areas = []

for i,s in enumerate(input_line):
    if s == '\\':
        stack.append(i)
        if pond_area: 
            pond_areas.append((l, pond_area))
            pond_area = 0
    elif stack and s == '/':
        l = stack.pop()
        area += i - l
        while True:
            if not pond_areas or pond_areas[-1][0] < l: break
            else: 
                pond_area += pond_areas.pop()[1]
        pond_area += i-l

if pond_area > 0: pond_areas.append((l, pond_area))

print(area)
print( " ".join([str(len(pond_areas))] + [str(a[1]) for a in pond_areas]) )

Solution (Python):
sectional_view = input()

list_index_down = []
list_index_area_left = []
list_area = []


for index_now, mark in enumerate(sectional_view):
    if   mark == "\\":
        list_index_down += [index_now]
    elif mark == "/" and list_index_down:
        index_down_last = list_index_down.pop()
        area = index_now - index_down_last

        while ((list_index_area_left) and
               (list_index_area_left[-1] > index_down_last)):
            area += list_area.pop()
            list_index_area_left.pop()

        list_index_area_left.append(index_down_last)
        list_area.append(area)


print(sum(list_area))
print(len(list_area),*(list_area))

Solution (Python):
from collections import deque


def main():
    total = 0
    s1 = deque()
    s2 = deque()
    str = input()
    for i in range(len(str)):
        if str[i] == "\\":
            s1.append(i)
        elif len(s1) > 0 and str[i] == "/":
            old = s1.pop()
            tmp = 0
            while len(s2) > 0 and old < s2[-1][0]:
                tmp += s2.pop()[1]
            s2.append([old, tmp + i - old])

    for i in range(len(s2)):
        total += s2[i][1]
    print(total)
    if s2:
        print(len(s2), end="")
        for i in range(len(s2)):
            if i == len(s2) - 1:
               print(" {}".format(s2[i][1]))
            else:
               print(" {}".format(s2[i][1]), end="")
    else:
        print(len(s2))

if __name__ == '__main__':
    main()

Solution (Python):
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)

Solution (Python):
from collections import deque
s = input()
n = len(s)
stack1 = deque()
stack2 = deque()
A = 0
a = 0
for ni in range(n):
    if s[ni] == "\\":
        stack1.append(ni)
    elif s[ni] == "/" and len(stack1) > 0 :
        tmp = stack1.pop()
        A += ni - tmp
        while True:
            if len(stack2) > 0 and stack2[-1][0] > tmp:
                a += stack2.pop()[1]
            else:
                break
        a += ni - tmp
        stack2.append([ni,a])
        a = 0
print(A)
print(len(stack2),*[i[1] for i in stack2])

Solution (Python):
def _main():
  text = list(input())

  S1 = []
  S2 = []
  area = 0

  for i in range(len(text)):
    if text[i] == '\\':
      S1.append(i)
    elif text[i] == '/' and len(S1) > 0:
      j = S1.pop()
      section_area = i - j
      area += section_area
      while len(S2) > 0 and S2[-1][0] > j:
        section_area += S2[-1][1]
        S2.pop()
      S2.append([j, section_area])
  print(area)
  print(len(S2), *[n[1] for n in S2])




if __name__ == '__main__':
  _main()

Solution (Python):
lines = list(input())
total = 0
size = 0

stack = []
ponds = []
size = 0
for i in range(len(lines)):
    if lines[i] == "\\":
        stack.append(i)
    elif lines[i] == "/":
        if not stack == []:
            left_index = stack.pop()
            size = i - left_index
            target_index = left_index
            
            
            while not ponds == [] and ponds[-1][0] > left_index:
                direct = ponds.pop()
                target_index = direct[0]
                size += direct[1]
            ponds.append([target_index,size])




ans = []
ans.append(len(ponds))
for _ in ponds:
    ans.append(_[1])

print(sum(ans[1:]))
print(" ".join(map(str,ans)))

Solution (Python):
s = input()

sum = 0
process_stack = []
puddle_stack = []

length = len(s)

for i in range(length):
    if s[i] == "\\":
        process_stack.append(i)
    elif s[i] == "/":
        if process_stack:
            edge = process_stack.pop()
            sum += i - edge
            puddle_sum = 0
            while puddle_stack:
                if puddle_stack[len(puddle_stack) - 1][0] < edge:
                    break;
                puddle_sum += puddle_stack.pop()[1]
            puddle_stack.append((edge, puddle_sum + i - edge))

print(sum)

result_string = ""
puddle_num = len(puddle_stack)
result_string += str(puddle_num)
for i in range(len(puddle_stack)):
    result_string += " "
    result_string += str(puddle_stack.pop(0)[1])

print(result_string)

Solution (Python):
s=input()
stack=[]
tmpans=[]
ans=[]
for k,v in enumerate(s):
    if v=="\\":
        stack.append(k)
    elif v=="/" and len(stack)>0:
        p=stack.pop()
        a=k-p
        while len(tmpans)>0 and tmpans[-1][-1]>p:
            a+=tmpans[-1][0]
            tmpans.pop()
        tmpans.append([a,p])
x=[i[0] for i in tmpans]
print(sum(x))
print(len(x),*x)

Solution (Python):
from collections import deque
s = input()
S1 = deque()
S2 = deque()
total = 0
for i in range(len(s)):
    if s[i] == '\\':
        S1.append(i)
    elif s[i] == '/':
        if len(S1) != 0:
            a = S1.pop()
            total += i - a
            area = i - a
            if len(S2) != 0:
                while S2[-1][0] > a:
                    area += S2.pop()[1]
                    if len(S2) == 0:
                        break
                S2.append([a ,area])
            else:
                S2.append([a, area])
        else:
            pass
print(total)
if total == 0:
    print(0)
else:
    print(len(S2), ' '.join(map(lambda x: str(x[1]), S2)))

Solution (Python):
if __name__ == '__main__':
    import sys
    input = sys.stdin.readline

    from collections import deque

    s = input()
    s1 = deque([])
    s2 = 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(' '.join(map(str, ans)))

Solution (Python):
f = list(input())
s = []

for i, v in enumerate(f):
    if v == '\\':
        s.append([v, i])
    elif v == '/' and len(s) > 0:
        n = s.pop()
        if n[0] == '\\':
            t = i-n[1]
            s.append(['.', t])
        elif len(s) > 0:
            j = len(s)-1
            n1 = n[1]
            while j >= 0 and s[j][0] == '.':
                
                n1 += s[j][1]
                j -= 1
            if j >= 0:
                m = s[j]
                
                n1 += i-m[1]
                s = s[:j]
                s.append(['.', n1])
            else:
                
                s.append(n)

        else:
            s.append(n)
    


a = [v[1] for v in s if v[0] == '.']
print(sum(a))
a.insert(0, len(a))
print(" ".join([str(v) for v in a]))

Solution (Python):
S = input()
lake_sum = 0
stack1 = []
stack2 = []
for i in range(len(S)):
    if S[i] == '\\':
        stack1.append(i)
    elif S[i] == '/':
        if stack1 == []:
            continue
        j = stack1.pop()
        area = i - j
        lake_sum += area
        while True:
            if stack2 == []:
                break
            k, l = stack2.pop()
            if k < j:
                stack2.append((k, l))
                break
            area += l
        stack2.append((j, area))
print(lake_sum)
if stack2 == []:
    print(0)
else:
    lakes = []
    lakes.append(str(len(stack2)))
    for lake in stack2:
        lakes.append(str(lake[1]))
    print(' '.join(lakes))

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline

def putsarray(array):
    if len(array) == 0:
        print()
        return
    for i in range(len(array) - 1):
        print(int(array[i]), end=' ')
    print(int(array[-1]))

def main():
    stack = deque([])
    instr = input()
    is_same_lake = False
    result = 0

    lakes = deque([])

    for i in range(len(instr)):
        char = instr[i]
        if char == "\\":
            stack.append(i)
        elif char == "_":
            pass
        elif char == "/":
            if len(stack) == 0:
                is_same_lake = False
                continue
            down = stack.pop()
            result += i - down
            lake_area = i - down
            index = len(lakes) -1
            while True:
                if index < 0:
                    break
                lake = lakes[index]
                if down < lake[0] and lake[1] < i:
                    lake_area += lakes.pop()[2]
                else:
                    break
                index -= 1
                    
            lakes.append((down, i, lake_area))

    print(int(result))
    putsarray([len(lakes),] + [l[2] for l in lakes])

    

main()

Solution (Python):
l = input()
l += "_"
stack1 = []
stack2 = []
A = 0
for i in range(len(l)):
    if l[i] == "\\":
        stack1.append(i)
    elif l[i] == "/" and stack1:
        b = stack1.pop()
        a = i - b
        A += a
        while stack2 and stack2[-1][0] > b:
            a += stack2.pop()[1]
        stack2.append([b, a])
print(A)
print(len(stack2), *(i[1] for i in stack2))

Solution (Python):
def hightMapGenerator(text):
    height_map = []
    current_height = 0
    for letter in text:
        if letter == '\\':
            current_height -= 1
        elif letter == '/':
            current_height += 1
        else :
            pass
        height_map.append(current_height)
    return height_map

def pondChecker(text, height_map):
    
    all_ponds = []
    pond = []
    for n, letter in enumerate(text):
        if pond == []: 
            if letter == '\\': 
                max_height = max(height_map[n:])
                if height_map[n] + 1 <= max_height: 
                    start_index = n
                    pond.append(start_index) 
                else :
                    pass
        else : 
            if height_map[start_index] + 1 == height_map[n]: 
                end_index = n
                pond.append(end_index)
                all_ponds.append(pond)
                pond = []
    return all_ponds
    
def squareCalc(text, pond_height_map):
    square = 0
    current_height = max(pond_height_map)
    for n, letter in enumerate(text):
        if letter == '\\':
            square += current_height - pond_height_map[n] - 0.5
        elif letter == '/':
            square += current_height - pond_height_map[n] + 0.5
        else :
            square += current_height - pond_height_map[n]
    return int(square)

def slicedPondsGenerator(text, height_map, all_ponds):
    sliced_ponds_str = []
    sliced_height_map = []
    for pond in all_ponds:
        start = pond[0]
        end = pond[1] + 1
        sliced_pond_str = text[start:end]
        sliced_height = height_map[start:end]
        sliced_ponds_str.append(sliced_pond_str)
        sliced_height_map.append(sliced_height)
    return sliced_ponds_str, sliced_height_map

text = input()

if '/' not in text:
    print(0)
    print(0)
elif '\\' not in text:
    print(0)
    print(0)
else :
    height_map = hightMapGenerator(text)
    
    all_ponds = pondChecker(text, height_map)
    if all_ponds == []:
        print(0)
        print(0)
    else :
        
        sliced_ponds_str, sliced_height_map = slicedPondsGenerator(text, height_map, all_ponds)
        
        
        squares = []
        for n, pond_str in enumerate(sliced_ponds_str):
            square = squareCalc(pond_str, sliced_height_map[n])
            squares.append(square)

        size_of_ponds = sum(squares)
        num_of_ponds = len(squares)
        output = ' '.join([str(n) for n in squares])
        print(size_of_ponds)
        print(num_of_ponds,output)

Solution (Python):

s = list(input().rstrip())
ht = []
ponds=[]
for i, ch in enumerate(s):
    if ch == "\\":
        ht.append(i)
    elif ch == "/":
        if ht:
            b = ht.pop()
            ap = i - b
            if not ponds:
                ponds.append([b, ap])
            else:
                while ponds:
                    p = ponds.pop()
                    if p[0] > b:
                        ap += p[1]
                    else:
                        ponds.append([p[0],p[1]])
                        break
                ponds.append([b,ap])
    else:
        pass

ans = ""
area = 0
for point, ar in ponds:
    area += ar
    ans += " "
    ans += str(ar)
print(area)
print(str(len(ponds)) + ans)

Solution (Python):
from collections import defaultdict




BS, SL = '\\', '/'

diagram = list(input())

flood = defaultdict(int)
total = 0
stack = []

for cur, terrain in enumerate(diagram):
    if terrain == BS:
        stack.append(cur)
    elif terrain == SL and stack:
        first = stack.pop()
        water = cur-first
        total += water
        for (f_first, f_last) in list(flood):
            if first < f_first < cur:
                flood[(first, cur)] += flood.pop((f_first, f_last))
        flood[(first, cur)] += water

print(total)
print(' '.join(map(str, [len(flood)] + list(flood.values()))))

Solution (Python):
from collections import deque

list = list(input())

queue = deque([]) 
queue2 = []
total = 0

for i in range(len(list)):
        if list[i] == '\\':
                queue.append(i)
        elif list[i] == '/' and len(queue) > 0:
                j = queue.pop()
                total += (i - j)
                temp = i - j
                while len(queue2) > 0 and queue2[len(queue2) - 1][0] > j:
                        temp += queue2[len(queue2) - 1][1]
                        queue2.pop()
                queue2.append([j, temp])
strResult = [str(len(queue2))]
for i in range(len(queue2)):
        strResult.append(str(queue2[i][1]))

print(total)
print(" ".join(strResult))

Solution (Python):
class Pond:
    def __init__(self, arg_left, arg_area):
        self.left = arg_left
        self.area = arg_area

form = input()
stack = []
stack2 = []
totalArea = 0
for i in range(len(form)):
    
    tmpForm = form[i]
    if tmpForm == '\\':
        stack.append(i)
    
    elif tmpForm == '/' and len(stack) > 0:
        xLeft = stack.pop()
        xRight = i
        tmpArea = xRight - xLeft
        totalArea += tmpArea

        
        while len(stack2) > 0 and stack2[-1].left > xLeft:
            tmpArea += stack2.pop().area

        stack2.append(Pond(xLeft, tmpArea)) 

print(totalArea)
ans = []
ans.append(len(stack2))
for pond in stack2:
    ans.append(pond.area)
print(' '.join(map(str, ans)))

Solution (Python):
import sys,itertools
from collections import deque

input = sys.stdin.readline


def _main():
    IN = input()
    area = 0
    all_area_stack = deque([])
    local_spot_stack = deque([])
    for i, op in enumerate(IN):
        if(op == '\\'):
            all_area_stack.append(i)
        elif(op == '/' and len(all_area_stack) > 0):
            i_p = all_area_stack.pop()
            area += (i - i_p)
            local_area = i - i_p
            while(len(local_spot_stack) > 0 and local_spot_stack[-1][0] > i_p):
                top_i, top_area = local_spot_stack.pop()
                local_area += top_area
            local_spot_stack.append((i, local_area))
    
    spots = [str(spot[1]) for spot in local_spot_stack]
    str_spots = ' '.join(spots)
    print(area)
    if(len(local_spot_stack) > 0):
        print('{} {}'.format(len(local_spot_stack), str_spots))
    else:
        print(0)





if __name__ == "__main__":
    _main()

Solution (Python):
import sys
input = sys.stdin.readline

cs_view = input().rstrip('\r\n')
list_v = list(cs_view)

stack1 = []
all_sum = 0
sum_stack = []
for i, elem in enumerate(list_v):
    if elem == '\\':
        stack1.append(i)
    elif len(stack1) > 0 and elem == '/':
        j = stack1.pop()
        all_sum += i - j
        a = i - j
        while len(sum_stack) > 0 and sum_stack[-1][0] > j:
            a += sum_stack.pop()[1]
        sum_stack.append([j, a])

print(all_sum)
esum = []
for a in sum_stack:
    esum.append(a[1])
esum.insert(0, len(esum))
maped_esum = map(str, esum)
str_esum = ' '.join(maped_esum)
print(str_esum)

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

Solution (Python):
from sys import stdin
from collections import deque

sect = stdin.readline().lstrip("/_").rstrip("\n\\_")
stack = deque()
res = deque()

for i in range(len(sect)):
    if sect[i] == "\\":
        stack.append(i)
    elif sect[i] == "/":
        if len(stack) != 0:
            b = stack.pop()
            if len(res) == 0:
                res.append( (b, i-b) )
            elif b > res[-1][0]:
                res.append( (b, i-b) )
            else: 
                sum_L = i-b
                while len(res) != 0:
                    if res[-1][0] > b:
                    	sum_L += res[-1][1]
                    	res.pop()
                    else:
                    	break

                res.append((b, sum_L))

res = [x[1] for x in res]
print(sum(res))
print(len(res), *res)

Solution (Python):
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))

Solution (Python):


"""
stackの応用(水たまりの面積)
"""

from collections import deque

S = list(input())


ans = 0

stack1 = deque()

stack2 = deque()
for i in range(len(S)):
    if S[i] == '\\':
        stack1.append(i)
    
    elif S[i] == '/' and stack1:
        
        
        j = stack1.pop()
        ans += i - j

        
        
        
        pond = i - j
        while stack2 and stack2[-1][0] >= j:
            pond += stack2.pop()[1]
        
        stack2.append([j, pond])
print(ans)

print(len(stack2), *[pond for j, pond in stack2])

Solution (Python):
import sys


def read_heights():
    current = 0
    heights = [current]
    for c in sys.stdin.read().strip():
        current += {
            '/': 1,
            '\\': -1,
            '_': 0
        }[c]
        heights.append(current)
    return heights


heights = read_heights()

height_index = {}
for i, h in enumerate(heights):
    height_index.setdefault(h, []).append(i)

flooded = [False] * len(heights)
floods = []


for h in sorted(height_index.keys(), reverse=True):
    indexes = height_index[h]
    for i in range(len(indexes) - 1):
        start = indexes[i]
        stop = indexes[i + 1]
        if start + 1 == stop or flooded[start] or flooded[stop]:
            continue
        if any(heights[j] >= h for j in range(start + 1, stop)):
            continue
        
        floods.append((start, stop))
        for j in range(start, stop):
            flooded[j] = True

floods.sort()

areas = []
for start, stop in floods:
    area = 0
    top = heights[start]
    for i in range(start + 1, stop + 1):
        h = heights[i]
        area += top - h + (heights[i - 1] - h) * 0.5
    areas.append(int(area))

print(sum(areas))
print(' '.join([str(v) for v in [len(areas)] + areas]))

Solution (Python):
from collections import deque


def main():
    stack = deque()
    diagram = input()
    square = []

    for index, value in enumerate(diagram):
        if value == '\\':
            stack.append(-index)
        elif value == '/':
            if len(stack) > 0:
                tmp = []
                while True:
                    tmp.append(stack.pop())
                    if tmp[-1] <= 0:
                        stack.append(sum(tmp[:-1]) + index + tmp[-1])
                        break
                if len(stack) == 1:
                    square.append(stack.pop())
    square.extend([i for i in stack if i > 0])

    print(sum(square))
    if sum(square) == 0:
        print(0)
    else:
        print('{} {}'.format(len(square), ' '.join([str(i) for i in square])))


if __name__ == '__main__':
    main()

Solution (Python):

s=j=0  
a=[]
b=[]  
d=[]
for i,x in enumerate(input()):  
    if x == '\\':
        a+=[i]
    elif x == '/' and a:
        j = a.pop()
        c = i-j
        s += c
        while b and b[-1]>j:  
            c+=d.pop()
            b.pop()

        b += [j]  
        d += [c]

print(s)
print(len(b), *(d))

Solution (Python):
from collections import deque

slope = input()
down_slope   = deque()
total_slopes = deque()

for i in range(len(slope)):
    if slope[i] == '\\':
        down_slope.append(i)
    elif slope[i] == '/':
        area = 0
        if len(down_slope) > 0:
            while len(total_slopes) > 0 and total_slopes[-1][0] > down_slope[-1]:
                area += total_slopes[-1][1]
                total_slopes.pop()
            area += i-down_slope[-1]
            total_slopes.append([down_slope[-1],area])
            down_slope.pop()

if len(total_slopes) > 0:
    total_slopes = [i[1] for i in total_slopes]
    print(sum(total_slopes))
    print(len(total_slopes),end=' ')
    print(' '.join(map(str,total_slopes)))
else:
    print(0)
    print(0)

Solution (Python):





from collections import deque
import heapq
import sys
input = sys.stdin.readline


def main():
    q = deque()
    m = str(input()).strip()
    dq = []
    count = 0
    for i in range(len(m)):
        if (m[i] == "\\" ):
            q.append(i)
            continue
        if (m[i] == "/" and len(q) > 0):
            j = q.pop()
            count += i - j
            
            dq.append((j,i))
    print (count)
    if (len(dq) == 0):
        print (0)
        return

    l = []
    dq.sort()
    dq.reverse()
    (a,b) = dq.pop()
    
    score = b - a
    while len(dq) > 0:
        (i,n) = dq.pop()
        if ( b > i ):
            score += n - i
        else:
            l.append(score)
            score = n - i
            a = i
            b = n
    else:
        l.append(score)

    print (len(l),*l)

if __name__ == '__main__':
    main()

Solution (Python):
inpu = input()
back = list(r"\\")[0]

stack = []
area = 0
area_sub = []
for i,symbol in enumerate(inpu):
    if symbol == back:
        stack.append(i)
        
    elif symbol == "/":
        
        if len(stack)>0:
            a = stack.pop()
            area += i-a
            
            area2 = 0
            while len(area_sub) and a<area_sub[-1][0]:
                pre = area_sub.pop()
                area2 += pre[1]
            area2 += i-a 
            area_sub.append([a,area2])
print(area)


if len(area_sub) > 0: 
    print(len(area_sub), end=" ")
    ar = [a[1] for a in area_sub]
    print(*ar)
else:
    print(len(area_sub))

Solution (Python):
n=input()
a=[]
area=[]
x1=[]
x2=[]

x=1
for i in n:
	if i=='\\':
		a.append(x)
		
	elif i=='/' and len(a)>=1:
		area.append(x-a[len(a)-1])
		x1.append(a[len(a)-1])
		x2.append(x)
		a.pop()		
		
		for i in range(len(x1)-2,-1,-1):	
			if x1[len(x1)-1]<x1[i] and x2[len(x2)-1]>x2[i]:
				x1.pop(i)
				x2.pop(i)
				area[i]=area[i]+area[len(area)-1]
				area.pop()
	x+=1

print(sum(area))
print(len(area),*area)

Solution (Python):
s = input()
stack = []
n = len(s)

ans = 0
prev = 0
each = []
for i in range(n):
    if s[i] == '\\':
        stack.append(i)
    elif s[i] == '_':
        pass
    else:
        if len(stack) != 0:
            idx = stack.pop()
            ans += (i - idx)
            if len(stack) == 0:
                each.append(ans - prev)
                prev = ans

each2 = []
stack2 = []
ans2 = 0
prev2 = 0
if len(stack) >= 1:
    for i in range(n-1,stack[0],-1):
        if s[i] == '/':
            stack2.append(i)
        elif s[i] == '_':
            pass
        else:
            if len(stack2) != 0:
                idx = stack2.pop()
                ans2 += (idx - i)
                if len(stack2) == 0:
                    each2.append(ans2 - prev2)
                    prev2 = ans2
each2.reverse()
each.extend(each2)
print(ans)
if len(each) == 0:
    print(len(each))
else:
    print(len(each),end=" ")
    print(*each)

Solution (Python):
def flood(region_data,flood_data):
    height = 0
    water_num=0
    top=0
    i=-1
    for data in region_data:
        i+=1
        if(data=="\\"):
            if(height==0):
                top=i
            water_num+=height +0.5
            height+=1


        elif(data=="/"):
            if(height>=2):
                water_num+=height-0.5
                height-=1
            elif(height==1):
                water_num+=0.5
                flood_data.append(water_num)
                water_num=0
                height=0


        elif(data=="_"):
            water_num+=height
    if(height==0):
        top=-1
    return top







def flood2(region_data,flood_data):
    height = 0
    water_num=0
    top=0
    i=-1
    for data in region_data:
        i+=1
        if(data=="/"):
            if(height==0):
                top=i
            water_num+=height +0.5
            height+=1


        elif(data=="\\"):
            if(height>=2):
                water_num+=height-0.5
                height-=1
            elif(height==1):
                water_num+=0.5
                flood_data.append(water_num)
                water_num=0
                height=0


        elif(data=="_"):
            water_num+=height
    if(height==0):
        top=-1
    return top


region_data=list(input())
flood_data=[]
top=flood(region_data,flood_data)


if(top!=-1):
    region_data2=region_data[top:len(region_data)]
    region_data2.reverse()
    flood_data2=[]
    flood2(region_data2,flood_data2)
    flood_data2.reverse()
    flood_data_final=flood_data + flood_data2
else:
    flood_data_final=flood_data

flood_data_final=list(map(int,flood_data_final))
total=sum(flood_data_final)
num=[len(flood_data_final)]
flood_data_final=" ".join(list(map(str,num+flood_data_final)))

print(total)
print(f"{flood_data_final}")

Solution (Python):


S1 = []

S2 = []
tmp_total = 0
counter = 0
upper = 0

total_layer = 0

for i,symbol in enumerate(input()):
    if (symbol == '\\'):
        S1.append(i)
    elif (symbol == '/') and S1:
        i_p = S1.pop()
        total_layer = i - i_p
        if S2 :
            while S2 and S2[-1][0] > i_p:
                cal = S2.pop()
                total_layer += cal[1]
        S2.append((i, total_layer))
print(sum([j[1] for j in S2]))
if (len(S2) != 0):
    print(str(len(S2)) + ' ' + ' '.join([str(i[1]) for i in S2]))
else:
    print(str(len(S2)))

Solution (Python):
import sys

s = sys.stdin.readline().rstrip()
h = [0] * len(s)

start={}
d=0
for i,c in enumerate(s):
    if c=='\\':
        start[d] = i
        d -= 1;
    if c=='/':
        d += 1
        if start.get(d, -1)>=0:
            for j in range(start[d],i):
                h[j] += 1

print(sum(h))
narea=0
areas=''
ssum=0
for i in h:
    ssum += i
    if i==0:
        if ssum>0:
            narea+=1
            areas += ' ' + str(ssum)
            ssum=0

if narea>0: print(narea,areas,sep='')
else:       print(narea)