s_id stringlengths 10 10 | p_id stringlengths 6 6 | u_id stringlengths 10 10 | date stringlengths 10 10 | language stringclasses 1
value | original_language stringclasses 11
values | filename_ext stringclasses 1
value | status stringclasses 1
value | cpu_time stringlengths 1 5 | memory stringlengths 1 7 | code_size stringlengths 1 6 | code stringlengths 1 539k |
|---|---|---|---|---|---|---|---|---|---|---|---|
s888036852 | p03986 | u539517139 | 1562072891 | Python | Python (3.4.3) | py | Runtime Error | 59 | 3500 | 133 | x=input()
t=0
for i in range(len(x)-1,-1,-1):
if x[i]=='T':
t+=1
else:
if t>0:
t-=1
else:
s+=1
print(s+t) |
s599169645 | p03986 | u405256066 | 1560061653 | Python | Python (3.4.3) | py | Runtime Error | 54 | 4328 | 229 | from sys import stdin
X = (stdin.readline().rstrip())
stack = []
for i in X:
if i == "S":
stack.append(i)
elif i == "T" and stack[-1] == "S":
stack.pop()
else:
stack.append(i)
print(len(stack)) |
s904325486 | p03986 | u405256066 | 1560041967 | Python | Python (3.4.3) | py | Runtime Error | 18 | 3500 | 150 | from sys import stdin
X = (stdin.readline().rstrip())
X_l = X[:(len(X)/2)]
X_r = X[(len(X)/2):]
print(len(X) - min(X_l.count("S"),X_r.count("T")) * 2) |
s251452838 | p03986 | u623819879 | 1558585358 | Python | PyPy3 (2.4.0) | py | Runtime Error | 180 | 47856 | 188 | import bisect
n=int(input())
p=[0]*(n+2)
c=1
for i in input().split():
p[int(i)]=c
c+=1
q=[0,n+1]
for i in range(1,n+1):
l=bisect.bisect(q,a)
r=l+1
print()
print(p)
|
s286579994 | p03986 | u230549821 | 1557017478 | Python | Python (3.4.3) | py | Runtime Error | 17 | 2940 | 90 | n = 0
for x in X:
if x == "S":
n += 1
else:
if n > 0:
n -= 1
print(2*n) |
s774635019 | p03986 | u163320134 | 1556906512 | Python | Python (3.4.3) | py | Runtime Error | 126 | 4256 | 620 | import collections
s=input()
n=len(s)
slen=collections.deque()
tlen=collections.deque()
cnt=0
ans=0
for i in range(n):
if s[i]=='S':
tpos=i
break
else:
tpos=n
for i in range(n-1,-1,-1):
if s[i]=='T':
spos=i
break
else:
spos=-1
s=s[tpos:spos+1]+'x'
for i in range(len(s)-1):
cnt+=1
if s[i]!=s[i+1]:
if s[i]=='S':
slen.append(cnt)
cnt=0
else:
tlen.append(cnt)
cnt=0
for i in range(len(slen)):
stmp,ttmp=slen.popleft(),tlen.popleft()
if stmp>ttmp:
ans+=ttmp
tmp=slen.popleft()+(stmp-ttmp)
slen.appendleft(tmp)
else:
ans+=stmp
print(n-ans*2) |
s772682084 | p03986 | u163320134 | 1556906354 | Python | Python (3.4.3) | py | Runtime Error | 96 | 4260 | 620 | import collections
s=input()
n=len(s)
slen=collections.deque()
tlen=collections.deque()
cnt=0
ans=0
for i in range(n):
if s[i]=='S':
tpos=i
break
else:
tpos=n
for i in range(n-1,-1,-1):
if s[i]=='T':
spos=i
break
else:
spos=-1
s=s[tpos:spos+1]+'x'
for i in range(len(s)-1):
cnt+=1
if s[i]!=s[i+1]:
if s[i]=='S':
slen.append(cnt)
cnt=0
else:
tlen.append(cnt)
cnt=0
for i in range(len(slen)):
stmp,ttmp=slen.popleft(),tlen.popleft()
if stmp>ttmp:
ans+=ttmp
tmp=stmp.popleft()+(stmp-ttmp)
slen.appendleft(tmp)
else:
ans+=stmp
print(n-ans*2) |
s530990909 | p03986 | u063052907 | 1555861087 | Python | Python (3.4.3) | py | Runtime Error | 18 | 3500 | 195 | X = input()
cnt_S, cnt_T = 0, 0
for c in range(X):
if c == "S":
cnt_S += 1
else:
if cnt_S:
cnt_S -= 1
else:
cnt_T += 1
print(cnt_S, cnt_T) |
s730389770 | p03986 | u227082700 | 1555467478 | Python | Python (3.4.3) | py | Runtime Error | 18 | 3500 | 92 | x=input();a=0
for i in range(len(x)):
if x[l-i-1]=="T":a+=1
else:a=max(0,a-1)
print(a*2) |
s909052226 | p03986 | u802772880 | 1554700256 | Python | Python (3.4.3) | py | Runtime Error | 18 | 3500 | 130 | s=input()
ls=len(s)
c=0
for i in range(ls):
if s[i]=='S':
c+=1
elif c>0:
ans+=2
c-=1
print(ls-ans) |
s706574910 | p03986 | u089230684 | 1553561704 | Python | Python (2.7.6) | py | Runtime Error | 11 | 2948 | 207 | s = raw_input()
n = int(raw_input())
head = []
sub = 0
for i, v in enumerate(s):
if v == 'S':
head.append(i)
if v == 'T' and head:
head.pop(0)
sub += 2
print(len(s) - sub) |
s370890677 | p03986 | u089230684 | 1553560598 | Python | Python (2.7.6) | py | Runtime Error | 1026 | 199808 | 211 | s = raw_input()
def cal(s):
a= 0
for idx in range(len(s)/2):
if s[2*idx]==s[2*idx +1]:
continue
else:
a = 1
s = s[2*(idx+1):]
break
if a:
return cal(s)
else:
return s
print(len(cal(s))) |
s244545618 | p03986 | u816631826 | 1553541373 | Python | Python (2.7.6) | py | Runtime Error | 12 | 2692 | 621 | @parallel
@roles('allgame')
def _last_redis_save():
with cd(get_deploy_path()):
redisSet = set()
ret = run('supervisorctl status')
for line in ret.split('\n'):
line = line.strip()
if line.find('RUNNING') >= 0 and line.find('redis') >= 0:
name = line.split()[0].strip()
redisSet.add(name)
ret = []
with cd('db'):
for redis in sorted(list(redisSet)):
port = redis[5:]
ret.append(run('ls -l -h game%s.rdb' % port))
return '\n'.join(ret)
def last_redis_save():
result = execute(_last_redis_save)
for k in sorted(result.keys()):
print '-'*20
print k, ':'
v = result[k]
print v |
s873655214 | p03986 | u175034939 | 1553231619 | Python | Python (3.4.3) | py | Runtime Error | 161 | 4840 | 337 | s = list(input())
cnt = 0
while True:
if s[0] == 'T':
s.pop(0)
cnt += 1
else:
break
while True:
if s[-1] == 'S':
s.pop(-1)
cnt += 1
else:
break
cs = 0
ct = 0
for i in range(len(s)):
if s[i] == 'S':
cs += 1
else:
ct += 1
print(cnt + abs(cs-ct)) |
s471542316 | p03986 | u175034939 | 1553231379 | Python | Python (3.4.3) | py | Runtime Error | 178 | 4840 | 555 | s = list(input())
cnt = 0
while True:
if s[0] == 'T':
s.pop(0)
cnt += 1
else:
break
while True:
if s[-1] == 'S':
s.pop(-1)
cnt += 1
else:
break
i = 0
now = 'on'
ans = 0
cs = 0
while i < len(s):
if s[i] == 'S':
cs += 1
now = 'on'
i += 1
elif now == 'on' and s[i] == 'T':
i += cs
cs = 0
now = 'off'
elif now == 'off' and s[i] == 'T':
cnt += 1
i += 1
if i >= len(s):
break
print(cnt) |
s034283809 | p03986 | u033524082 | 1552181334 | Python | Python (3.4.3) | py | Runtime Error | 20 | 3500 | 170 | x=input()
ans=len(x)
r=len(x)
if "ST" in x:
x.remove("ST")
ans-=2
while r!=len(x):
r=len(x)
if "ST" in x:
x.remove("ST")
ans-=2
print(ans) |
s504974516 | p03986 | u595893956 | 1550816564 | Python | Python (3.4.3) | py | Runtime Error | 17 | 2940 | 104 | s=input()
sc=0
tc=0
for i in s:
if i=="S":
sc+=1
elif sc!=0:
sc-=1
else tc+=1
print(tc+sc) |
s957749775 | p03986 | u052347048 | 1550258859 | Python | Python (3.4.3) | py | Runtime Error | 1055 | 3560 | 136 | a = input()
b = a.replace("ST","")
if a[0] =="S" and b[-1] =="T":
print(0)
while "ST" in b:
b = b.replace("ST","")
print(len(b)) |
s770967839 | p03986 | u284854859 | 1549941807 | Python | Python (3.4.3) | py | Runtime Error | 19 | 3884 | 7341 | #root.search(x): ◯.data == x のものが存在するある場合それを出力、ない場合Noneを出力
#root.insert(x): ◯.data == xが存在する場合Falseを出力、ない場合◯.data == x なる頂点を作る
#y.to_s(): 頂点yのdataを出力
#y.left_s(): 頂点yのleftを出力(ない場合はNone)
#root.search_lower(x,None): ○.dataがxより小さいものの中で最も大きいものを出力、ない場合Noneを出力
#root.search_higher(x,None): xより大きいものの中で最も小さいものを出力、ない場合Noneを出力
################################################################################
class Avltree:
def __init__(self,key=None):
self.key = key
self.left = None
self.right = None
self.balance = "Even"
def search_lower(self,key,key_lower):
if self.key == None:
return key_lower
if self.key > key:
if self.left == None:
return key_lower
else:
return self.left.search_lower(key,key_lower)
if self.key < key:
key_lower = self.key
if self.right == None:
return key_lower
else:
return self.right.search_lower(key,key_lower)
#self.key == keyの場合
if self.left == None:
return key_lower
else:
if key_lower == None:
return self.left.end_higher(self.left.key)
else:
return max(key_lower,self.left.end_higher(self.left.key))
def search_higher(self,key,key_higher):
if self.key == None:
return key_higher
if self.key > key:
key_higher = self.key
if self.left == None:
return key_higher
else:
return self.left.search_higher(key,key_higher)
if self.key < key:
if self.right == None:
return key_higher
else:
return self.right.search_higher(key,key_higher)
#self.key == keyの場合
if self.right == None:
return key_higher
else:
if key_higher == None:
return self.right.end_lower(self.right.key)
else:
return min(key_higher,self.right.end_lower(self.right.key))
def end_lower(self,end_lower_key):
if self.left == None:
return end_lower_key
else:
end_lower_key = self.left.key
return self.left.end_lower(end_lower_key)
def end_higher(self,end_higher_key):
if self.right == None:
return end_higher_key
else:
end_higher_key = self.right.key
return self.right.end_higher(end_higher_key)
def DoubleRightRotation(self):
tl = self.left
self.left = tl.right.right
tl.right.right = self # selfはそのノード
tlr = tl.right
tl.right = tlr.left
tlr.left = tl
if tlr.balance == "Left":
tlr.right.balance = "Right"
tlr.left.balance = "Even"
elif tlr.balance == "Right":
tlr.right.balance = "Even"
tlr.left.balance = "Left"
elif tlr.balance == "Even":
tlr.right.balance = "Even"
tlr.left.balance = "Even"
tlr.balance = "Even"
return tlr
def DoubleLeftRotation(self):
tr = self.right
self.right = tr.left.left
tr.left.left = self
trl = tr.left
tr.left = trl.right
trl.right = tr
if trl.balance == "Right":
trl.left.balance = "Left"
trl.right.balance = "Even"
elif trl.balance == "Left":
trl.left.balance = "Even"
trl.right.balance = "Right"
elif trl.balance == "Even":
trl.left.balance = "Even"
trl.right.balance = "Even"
trl.balance = "Even"
return trl
def SingleLeftRotation(self):
tr = self.right
tr.balance = "Even"
self.balance = "Even"
self.right = tr.left
tr.left = self
return tr
def SingleRightRotation(self):
tl = self.left
tl.balance = "Even"
self.balance = "Even"
self.left = tl.right
tl.right = self
return tl
def replace(self,p,v): # 親ノードpの下にある自分(self)をvに置き換える。
if p.left == self:
p.left = v
else :
p.right = v
def insert(self,key): # rootでのみ呼ばれる挿入
if self.key == None: # rootを含むrotationはしないことにする。
self.key = key
return self
if key < self.key:
if self.left == None:
self.left = Avltree(key)
else:
self.left.insertx(self,key)
elif key > self.key:
if self.right == None:
self.right = Avltree(key)
else:
self.right.insertx(self,key)
else: # key == self.key:
pass # do not overwrite
def insertx(self,p,key): # replaceを呼ぶために一つ上の親を持っているinsert
if self.key > key:
if self.left == None:
self.left = Avltree(key)
else:
if not self.left.insertx(self, key): # 左の木が生長しなければ、
return False # 成長しない
if self.balance == "Right":
self.balance = "Even"
return False
elif self.balance == "Even":
self.balance = "Left"
return True # 成長した
elif self.balance == "Left":
if self.left.balance == "Right":
self.replace(p,self.DoubleRightRotation())
elif self.left.balance == "Left":
self.replace(p,self.SingleRightRotation())
return False # rotationを行うと成長しない
if self.key < key:
if self.right == None:
self.right = Avltree(key)
else:
if not self.right.insertx(self, key):
return False
if self.balance == "Left":
self.balance = "Even"
return False
elif self.balance == "Even":
self.balance = "Right"
return True
elif self.balance == "Right":
if self.right.balance == "Left":
self.replace(p,self.DoubleLeftRotation())
elif self.right.balance == "Right":
self.replace(p,self.SingleLeftRotation())
return False
return False # self.key == keyの時は何もしないので成長もしない
################################################################
def inpl(): return [int(i) for i in input().split()]
n = int(input())
a = inpl()
b = {a[i]: i for i in range(n)}
root = Avltree()
ass = 0
for i in range(1,n+1):
l = root.search_lower(b[i],None)
r = root.search_higher(b[i],None)
if l == None:
l = -1
if r == None:
r = n
ass += (b[i]-l)*(r-b[i])*i
root.insert(b[i])
print(0) |
s898839899 | p03986 | u426964396 | 1549051990 | Python | Python (3.4.3) | py | Runtime Error | 19 | 3500 | 241 | s=input();pd=0;n='';p=1
while(1):
if s[pd]!='S' and s[pd+1]!='T':
n=n+s[pd]
pd+=1
if pd==len(s)-2:
pd=0
s=n
n=''
p+=1
if len(s)==2:
break
if p>=1000:
break
print(len(s)) |
s492575072 | p03986 | u426964396 | 1549051777 | Python | Python (3.4.3) | py | Runtime Error | 25 | 3500 | 242 | s=input();pd=0;n='';p=1
while(1):
if s[pd]!='S' and s[pd+1]!='T':
n=n+s[pd]
pd+=1
if pd==len(s)-2:
pd=0
s=n
n=''
p+=1
if len(s)==2:
break
if p>=10000:
break
print(len(s)) |
s760266833 | p03986 | u943004959 | 1546399390 | Python | Python (3.4.3) | py | Runtime Error | 17 | 2940 | 633 | #include <bits/stdc++.h>
using namespace std;
#define uint unsigned int
#define llong long long int
#define ullong unsigned long long int
const static long long int MOD = 1000000000 + 7;
int main (int argc, char *argv[]) {
cin.tie(0);
ios::sync_with_stdio(false);
string S;
cin >> S;
stack<char> ST;
for (int i = 0; i < S.size(); ++i) {
if (S[i] == 'S') {
ST.push(S[i]);
} else if (S[i] == 'T') {
if (ST.top() == 'S') ST.pop();
else if (ST.empty() == true || ST.top() == 'T') ST.push(S[i]);
}
}
cout << ST.size() << endl;
return 0;
} |
s464426929 | p03986 | u371467115 | 1545877823 | Python | Python (3.4.3) | py | Runtime Error | 17 | 2940 | 172 | S = input()
s = t = 0
for c in S:
if c == 'S':
s += 1
else:
if s > 0:
s -= 1
else:
t += 1
print(s+t)
#コピペです
|
s736880248 | p03986 | u063052907 | 1544918404 | Python | Python (3.4.3) | py | Runtime Error | 18 | 3064 | 181 | # coding: utf-8
n_S, n_T = 0, 0
if c in input():
if c == "S":
n_S += 1
else:
if n_S:
n_S -= 1
else:
T += 1
print(n_S + n_T)
|
s882913126 | p03986 | u368780724 | 1543784328 | Python | Python (3.4.3) | py | Runtime Error | 330 | 21992 | 389 | import numpy as np
def inpl(): return [int(i) for i in input().split()]
def minisum(x):
mini = np.argmin(x)
d = len(x)
if d == 1:
return x[0]
result = 0
if mini != 0:
result += minisum(x[0:mini])
if mini != d-1:
result += minisum(x[mini+1:d])
return result + (d-mini)*(mini+1)*x[mini]
N = input()
a = np.array(inpl())
print(minisum(a))
|
s716779219 | p03986 | u397531548 | 1542867275 | Python | Python (3.4.3) | py | Runtime Error | 1056 | 4840 | 239 | S=list(input())
i=0
while 0<=i<=len(S)-2:
if S[i]=="S":
if S[i+1]=="T":
S.remove(S[i])
S.remove(S[i])
i=0
if S[i+1]=="S":
i+=1
if S[i]=="T":
i+=1
print(len(S)) |
s639829448 | p03986 | u397531548 | 1542867194 | Python | Python (3.4.3) | py | Runtime Error | 1056 | 4968 | 429 | S=list(input())
i=0
while 0<=i<=len(S)-2:
if S[i]=="S":
if S[i+1]=="T":
S.remove(S[i])
S.remove(S[i])
if S[i+1]=="S":
i+=1
if S[i]=="T":
i+=1
while 0<=i<=len(S)-2:
if S[i]=="S":
if S[i+1]=="T":
S.remove(S[i])
S.remove(S[i])
i=0
if S[i+1]=="S":
i+=1
if S[i]=="T":
i+=1
print(len(S)) |
s051358370 | p03986 | u397531548 | 1542866683 | Python | Python (3.4.3) | py | Runtime Error | 1056 | 4840 | 222 | S=list(input())
i=0
while 0<=i<=len(S)-1:
if S[i]=="S":
if S[i+1]=="T":
S.remove(S[i])
S.remove(S[i])
i-=1
else:
i+=1
else:
i+=1
print(len(S)) |
s302055052 | p03986 | u397531548 | 1542866573 | Python | Python (3.4.3) | py | Runtime Error | 1056 | 4840 | 234 | S=list(input())
i=0
while 0<=i<=len(S)-1:
if S[i]=="S":
if S[i+1]=="T":
S.remove(S[i])
S.remove(S[i])
i=0
else:
i+=1
else:
i+=1
print(len(S))
|
s608766512 | p03986 | u603234915 | 1538777514 | Python | Python (3.4.3) | py | Runtime Error | 61 | 5668 | 186 | s = list(input())
l = []
for i in range(len(s)):
if s[i] == 'S':
l.append('S')
elif l[-1] == 'T' or not l:
l.append('T')
else:
l.pop()
print(len(l))
|
s855923808 | p03986 | u136395536 | 1537101462 | Python | Python (3.4.3) | py | Runtime Error | 1055 | 3824 | 338 | #できなかった― えーんえーん
X = input()
for i in range(10**10000):
times = len(X) - 1
if times > 0:
for j in range(times):
if X[j] == "S" and X[j+1] == "T":
newX = X[0:j]+X[j+2:len(X)]
X = newX
else:
break
print(len(X))
|
s464958076 | p03986 | u536113865 | 1536440568 | Python | Python (3.4.3) | py | Runtime Error | 90 | 4864 | 204 | s = input()
stack = [s[0]]
for i in range(1,len(s)):
cur_str = stack[-1]
new_str = s[i]
if cur_str+new_str=="ST":
stack.pop()
else:
stack.append(new_str)
print(len(stack))
|
s221409042 | p03986 | u030726788 | 1522873566 | Python | Python (3.4.3) | py | Runtime Error | 18 | 3500 | 58 | s=input()
while("ST" in s):
s.remove("ST")
print(len(s)) |
s437605598 | p03986 | u817328209 | 1522451809 | Python | Python (3.4.3) | py | Runtime Error | 1056 | 4840 | 269 | x = list(input())
Lm = len(x)
L = len(x)
now = len(x) - 1
while now >= 0 and L >= 2 :
if now == Lm - 1 :
now -= 1
continue
if x[now] == 'S' and x[now+1] == 'T' :
x.pop(now+1)
x.pop(now)
L -= 2
now -= 1
print(len(x)) |
s646042760 | p03986 | u835482198 | 1500883357 | Python | Python (3.4.3) | py | Runtime Error | 86 | 10728 | 611 | X = input()
# X = 'SSTTST'
# X = 'TSSTTTSS'
# naive case
# len_prev = -1
# while len_prev != len(X):
# len_prev = len(X)
# X = X.replace('ST', '')
# print(len(X))
i = 0
cnt = []
X += " "
cur = 1
for i in range(len(X) - 1):
if X[i] == X[i + 1]:
cur += 1
else:
cnt.append((X[i], cur))
cur = 1
total = 0
for i in range(len(cnt) - 1):
if cnt[i][0] == 'S':
if cnt[i][1] > cnt[i + 1][1]:
if i + 2 < len(cnt) - 1:
cnt[i + 2][1] += cnt[i][1] - cnt[i + 1][1]
total += min(cnt[i][1], cnt[i + 1][1])
print(len(X) - 1 - 2 * total)
|
s436904736 | p03986 | u835482198 | 1500883227 | Python | Python (3.4.3) | py | Runtime Error | 86 | 10596 | 608 |
X = input()
# X = 'SSTTST'
# X = 'TSSTTTSS'
# naive case
# len_prev = -1
# while len_prev != len(X):
# len_prev = len(X)
# X = X.replace('ST', '')
# print(len(X))
i = 0
cnt = []
X += " "
cur = 1
for i in range(len(X) - 1):
if X[i] == X[i + 1]:
cur += 1
else:
cnt.append((X[i], cur))
cur = 1
total = 0
for i in range(len(cnt) - 1):
if cnt[i][0] == 'S':
if cnt[i][1] > cnt[i + 1][1]:
if i + 2 < len(cnt):
cnt[i + 2][1] += cnt[i][1] - cnt[i + 1][1]
total += min(cnt[i][1], cnt[i + 1][1])
print(len(X) - 1 - 2 * total)
|
s549822530 | p03986 | u619631862 | 1476014398 | Python | Python (3.4.3) | py | Runtime Error | 25 | 3756 | 317 | n = int(input())
a=[int(i) for i in input().split()]
s=[]
sa=n*(n+1)/2
s.append(a)
for i in range(1,n):
s.append([])
for j in range(len(s[i-1])-1):
if s[i-1][j]<s[i-1][j+1]:
s[i].append(s[i-1][j])
sa+=s[i-1][j]
else:
s[i].append(s[i-1][j+1])
sa+=s[i-1][j+1]
print(int(sa)) |
s507806115 | p03986 | u236080859 | 1475573200 | Python | Python (2.7.6) | py | Runtime Error | 19 | 3304 | 145 | s = input()
def AString(stringX):
while "ST" in stringX:
stringX = stringX.replace("ST", "", 1)
print len(stringX)
AString(s)
|
s501792177 | p03986 | u172200367 | 1475378739 | Python | Python (2.7.6) | py | Runtime Error | 16 | 2948 | 451 | N = int(raw_input())
n = map(int, raw_input().split())
n_min = min(n)
total = 0
for ind, num in enumerate(n):
if num == n_min:
total += num * (ind+1) * (N - ind)
continue
l, k = ind, ind
while l >= 0:
if num <= n[l]:
l -= 1
else:
break
while k < N:
if num <= n[k]:
k += 1
else:
break
total += num * (ind-l) * (k-ind)
print total |
s063336923 | p03986 | u429978706 | 1475378597 | Python | Python (2.7.6) | py | Runtime Error | 16 | 2568 | 180 | X = raw_input()
cnt = 0
cnt_max = cnt
for i in range(len(X)):
if X[i] = 'T':
cnt += 1
else:
cnt -= 1
if cnt > cnt_max:
cnt_max = cnt
print cnt_max * 2 |
s043657819 | p03986 | u429978706 | 1475378083 | Python | PyPy2 (5.6.0) | py | Runtime Error | 37 | 8816 | 183 | X = raw_input()
cnt = 0
cnt_max = cnt
for i in range(len(X)):
if X[i] = 'T':
cnt += 1
else:
cnt -= 1
if cnt > cnt_max:
cnt_max = cnt
return cnt_max * 2 |
s551890076 | p03986 | u854554545 | 1475377691 | Python | Python (3.4.3) | py | Runtime Error | 575 | 22412 | 216 | import sys
import numpy as np
N = int(sys.stdin.readline())
P = np.array([int(x) for x in sys.stdin.readline().split()])
SUM = np.sum([np.sum([min(P[l:r+1]) for r in range(l, N)]) for l in range(N)])
print(SUM) |
s294960024 | p03986 | u820351940 | 1475376615 | Python | Python (3.4.3) | py | Runtime Error | 26 | 3500 | 241 | N = int(input())
a = list(map(int, input().split()))
def resolve(a):
target = N
result = 0
for i in a:
if target > i: target = i
result += target
return result
print(sum([resolve(a[x:]) for x in range(N)]))
|
s863914684 | p03986 | u854554545 | 1475376193 | Python | Python (3.4.3) | py | Runtime Error | 663 | 19520 | 217 | import sys
import numpy as np
N = int(sys.stdin.readline())
P = np.array([int(x) for x in sys.stdin.readline().split()])
SUM = np.sum([np.sum([np.min(P[l:r+1]) for r in range(l, N)]) for l in range(N)])
print(SUM) |
s950623710 | p03986 | u854554545 | 1475376001 | Python | Python (3.4.3) | py | Runtime Error | 819 | 16300 | 214 | import sys
import numpy as np
N = int(sys.stdin.readline())
P = np.array([int(x) for x in sys.stdin.readline().split()])
SUM = np.sum([np.sum([min(P[l:r+1]) for r in range(l, N)]) for l in range(N)])
print(SUM) |
s035060945 | p03986 | u250209149 | 1475374574 | Python | Python (2.7.6) | py | Runtime Error | 17 | 2820 | 912 | N = int(raw_input())
a = [int(x) for x in raw_input().split(' ')]
sorteda = sorted(a)
maxlen = sorteda[-1]
numpathsoflen = {}
if(sorteda[0] < (maxlen+1)/2):
print 'Impossible'
elif(maxlen % 2 == 0
and sorteda[0] == maxlen/2
and sorteda[0] == sorteda[1]):
print 'Impossible'
else:
numnodes = maxlen + 1
for i in range(N):
if a[i] in numpathsoflen.keys():
if numpathsoflen[a[i]] >= 2:
numnodes += 1
numpathsoflen[a[i]] += 1
else:
numpathsoflen[a[i]] = 1
if(numnodes != N):
print 'Impossible'
else:
out= 'Possible'
starti = (maxlen+1)/2
if maxlen % 2 == 0:
starti += 1
for i in range(starti, maxlen+1):
if((not i in numpathsoflen.keys()) or numpathsoflen[i] < 2):
out = 'Impossible'
print out |
s308798948 | p03986 | u620944332 | 1475373993 | Python | Python (3.4.3) | py | Runtime Error | 25 | 3064 | 86 | s = input()
while 'ST' in s:
s = s.replace('ST', '', 1)
print(len(s))
|
s658120872 | p03986 | u433025875 | 1475373317 | Python | Python (2.7.6) | py | Runtime Error | 17 | 2948 | 104 | s = raw_input()
t = raw_input()
while s.find(t)>-1:
i = s.find(t)
s = s[:i]+s[i+4:]
print len(s) |
s830613389 | p03986 | u433025875 | 1475372995 | Python | Python (2.7.6) | py | Runtime Error | 17 | 2948 | 120 | s = raw_input()
t = raw_input()
print s.find(t)
while s.find(t)>-1:
i = s.find(t)
s = s[:i]+s[i+4:]
print len(s) |
s335567729 | p03986 | u112002050 | 1475372950 | Python | PyPy3 (2.4.0) | py | Runtime Error | 221 | 47984 | 123 | N = int(input())
a = [int(i) for i in input().split()]
print(sum([min(a[l:r + 1]) for l in range(N) for r in range(l, N)])) |
s310735416 | p03986 | u125205981 | 1475372484 | Python | Python (3.4.3) | py | Runtime Error | 22 | 3064 | 115 | ef st(x):
while 'ST' in x:
x = x.replace('ST', '', 1)
return x
X = str(input())
print(len(st(X)))
|
s776508301 | p03986 | u112002050 | 1475371390 | Python | Python (3.4.3) | py | Runtime Error | 739 | 202908 | 197 | X = input()
n = 10 ** 10000
def STring(X, n):
index = X.find("ST")
if index == -1 or n == 0:
return X
else:
return STring(X[0:index] + X[index + 2:], n - 1)
print(len(STring(X , n))) |
s133030192 | p03986 | u112002050 | 1475371126 | Python | Python (3.4.3) | py | Runtime Error | 731 | 198552 | 159 | X = input()
def STring(X):
index = X.find("ST")
if index == -1:
return X
else:
return STring(X[0:index] + X[index + 2:])
print(len(STring(X)))
|
s617707581 | p03986 | u010733367 | 1475370599 | Python | Python (3.4.3) | py | Runtime Error | 21 | 3068 | 8 | TSSTTTSS |
s376555006 | p03986 | u820351940 | 1475370490 | Python | Python (2.7.6) | py | Runtime Error | 19 | 3304 | 141 | s = input()
while 1:
result = s.replace("ST", "")
if result != s:
s = result
break
else: s = result
print len(s)
|
s276952553 | p03987 | u860546679 | 1600358242 | Python | Python (3.8.2) | py | Runtime Error | 25 | 8956 | 959 | #include<iostream>
#include<iomanip>
#include<cmath>
#include<string>
#include<cstring>
#include<vector>
#include<list>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;
#define fi first
#define se second
#define mp make_pair
#define mt make_tuple
#define pqueue priority_queue
const int inf=1e9+7;
const ll mod=1e9+7;
const ll mod1=998244353;
const ll big=1e18;
const double PI=2*asin(1);
int main() {
int N;
cin>>N;
int a[N];
int tmptmp;
for(int i=0;i<N;++i) {
cin>>tmptmp;
tmptmp--;
a[tmptmp] = i;
}
set<ll> st;
st.insert(-1);
st.insert(N);
auto tmp=st.begin(), tmp1=st.begin(), tmp2=st.begin();
ll ans = 0;
for(ll i=0;i<N;++i) {
st.insert(a[i]);
tmp = st.find(a[i]);
tmp1 = st.find(a[i]);
tmp1--;
tmp2 = st.find(a[i]);
tmp2++;
ans += (i+1)*(*tmp-*tmp1)%mod*(*tmp2-*tmp)%mod;
ans %= mod;
}
cout<<ans<<endl;
}
|
s956965116 | p03987 | u729133443 | 1599928758 | Python | Python (3.8.2) | py | Runtime Error | 297 | 24212 | 633 | import sys
if sys.argv[-1] == 'ONLINE_JUDGE':
import os, zlib, base64
open('solve.pyx', 'wb').write(zlib.decompress(base64.b85decode("c${rg?P`QD5d7~`ER=Fu@8pF3DAIcpIZBMHw=|bXvi9iPcTKFlmIf4eW_H|<JU~x@XC@OGFv^az8u6sdG8??Rf}u`NQx%Xw({*y5LB4-+AE?>+jZWc@q6*xT+vpKlUzFd&<jL}obo!Go&Q@+hukO8i^f<_4HG&E$Tr#mo?eU716Rb1c;{akPsWvabx{*wift-!$_MqVe$B5o8WDx2kSxzU^TASn_;Q3{vXb|=ljtz7k)%%8PC{OZwg8B$0bP@N+v$t?pkQL)t)E+3I#@X>(k*3uy&>56S?}6MF*&yQ}F#<2UK|vZ&ZEErW^;t4jS6Rzy69n9%ygk%=u;=2Bsv=&8P5jSKVl%{xQ)S!@{afc|+vln!vD&)N<4SVkrJBgeIHE}6#L0FRzK9ITpz4$#DzX7Rua@aL<hw`H?_^O$_66`A&C>")))
os.system('cythonize -i -3 -b solve.pyx')
import solve |
s881823439 | p03987 | u648212584 | 1591679943 | Python | PyPy3 (2.4.0) | py | Runtime Error | 923 | 74304 | 1409 | import sys
input = sys.stdin.buffer.readline
def main():
# SegmentTree Class
class SegmentTree:
# 初期化
def __init__(self, size, default):
self.size = 2**(size-1).bit_length()
self.default = default
self.seg = [default]*(2*self.size)
# function(max, min, plus, minus, etc...)
def segfunc(self,x,y):
return max(x,y)
# update
def update(self,k,x):
k += self.size
self.seg[k] = x
while k:
k = (k-1)//2
self.seg[k] = self.segfunc(self.seg[2*k+1],self.seg[2*k+2])
# query([p,q)のsegfunc)
def query(self,p,q):
if q <= p:
return self.default
p += self.size-1;q += self.size-2
ret = self.default
while q-p > 1:
if p&1 == 0:
ret = self.segfunc(ret,self.seg[p])
if q&1 == 1:
ret = self.segfunc(ret,self.seg[q])
q -= 1
p = p//2
q = (q-1)//2
ret = self.segfunc(self.segfunc(ret,self.seg[p]),self.seg[q])
return ret
# seg確認用
def seg_print(self):
print(self.seg)
N = int(input())
a = list(map(int,input().split()))
ans=[i+1 for i in range(N)]
left_seg = SegmentTree(N, 0)
for i, num in enumerate(a):
ans[num-1] *= i + 1 - left_seg.query(0,num)
left_seg.update(num-1, i+1)
right_seg = SegmentTree(N, 0)
for i, num in enumerate(a[::-1]):
ans[num-1] *= i + 1 - right_seg.query(0,num)
right_seg.update(num-1, i+1)
print(sum(ans))
if __name__ == "__main__":
main()
|
s067810977 | p03987 | u423585790 | 1590439738 | Python | PyPy3 (2.4.0) | py | Runtime Error | 299 | 82800 | 700 | from collections import deque
n=int(input())
a=list(map(int,input().split()))
A=[a[0]+a[0]<a[1]-a[0]>a[1]]+a+[a[-1]+a[-1]<a[-2]-a[-1]>a[-2]]
valley=0
peak=1
dp=deque()
for i in range(1,n+1):
if A[i-1]<A[i]>A[i+1]:
dp.append((i-1,peak))
elif A[i-1]>A[i]<A[i+1]:
dp.append((i-1,valley))
l,lf=dp.popleft()
r,rf=dp.popleft()
if lf == peak:
ans=a[0]
else:
ans=a[0]*(r+1)
for i in range(1,n-1):
if r == i:
t,tf=r,rf
r,rf=dp.popleft()
if tf == valley:
ans+=a[i]*(i-l+1)*(r-i+1)
else:
ans+=a[i]
l,lf=t,tf
else:
if lf == valley:
ans+=a[i]*(r-i+1)
else:
ans+=a[i]*(i-l+1)
if rf == valley:
ans+=a[-1]*(n-l)
else:
ans+=a[-1]
print(ans)
|
s740091738 | p03987 | u423585790 | 1590439684 | Python | PyPy3 (2.4.0) | py | Runtime Error | 303 | 82800 | 711 | from collections import deque
n=int(input())
a=list(map(int,input().split()))
A=[a[0]+a[0]<a[1]-a[0]>a[1]]+a+[a[-1]+a[-1]<a[-2]-a[-1]>a[-2]]
valley=0
peak=1
dp=deque()
for i in range(1,n+1):
if A[i-1]<A[i]>A[i+1]:
dp.append((i-1,peak))
elif A[i-1]>A[i]<A[i+1]:
dp.append((i-1,valley))
l,lf=dp.popleft()
r,rf=dp.popleft()
if lf == peak:
ans=a[0]
else:
ans=a[0]*(r+1)
print(ans)
for i in range(1,n-1):
if r == i:
t,tf=r,rf
r,rf=dp.popleft()
if tf == valley:
ans+=a[i]*(i-l+1)*(r-i+1)
else:
ans+=a[i]
l,lf=t,tf
else:
if lf == valley:
ans+=a[i]*(r-i+1)
else:
ans+=a[i]*(i-l+1)
if rf == valley:
ans+=a[-1]*(n-l)
else:
ans+=a[-1]
print(ans)
|
s801630189 | p03987 | u423585790 | 1590439414 | Python | PyPy3 (2.4.0) | py | Runtime Error | 181 | 38256 | 643 | from collections import deque
n=int(input())
a=list(map(int,input().split()))
A=[a[0]+a[0]<a[1]-a[0]>a[1]]+a+[a[-1]+a[-1]<a[-2]-a[-1]>a[-2]]
valley=0
peak=1
dp=deque()
for i in range(1,n+1):
if A[i-1]<A[i]>A[i+1]:
dp.append((i-1,peak))
elif A[i-1]>A[i]<A[i+1]:
dp.append((i-1,valley))
l,lf=dp.popleft()
r,rf=dp.popleft()
if lf == peak:
ans=a[0]
else:
ans=a[0]*(r+1)
for i in range(1,n-1):
if r == i:
t,tf=r,rf
r,rf=dp.popleft()
if rf == valley:
ans+=a[i]*(i-l+1)*(r-i+1)
else:
ans+=a[i]
l,lf=t,tf
else:
if lf == valley:
ans+=a[i]*(r-i+1)
else:
ans+=a[i]*(i-l+1)
print(ans) |
s882080515 | p03987 | u571867512 | 1589927932 | Python | Python (3.4.3) | py | Runtime Error | 2118 | 231972 | 1024 | from sys import setrecursionlimit
def cal(A):
if len(A) == 0:
return 0
else:
B = sorted(A)
C = [B[len(B)-1-i] for i in range(len(B))]
if A == B or A == C:
if A == B:
output = 0
for i in range(len(A)):
output += (A[i] * (len(A)-i))
return output
else:
output = 0
for i in range(len(A)):
output += (A[N-i-1] * (len(A)-i))
return output
else:
min_A = B[0]
for i in range(len(A)):
if A[i] == min_A: #最小
pt = i
break
A_left,A_right = A[:pt],A[pt+1:]
ans = min_A * (len(A_left)+1) * (len(A_right)+1)
return ans + cal(A_left) + cal(A_right)
def main():
N = int(input())
A = list(map(int,input().split()))
setrecursionlimit(10**7)
print(cal(A))
if __name__ == "__main__":
main()
|
s108607389 | p03987 | u144913062 | 1589654903 | Python | PyPy3 (2.4.0) | py | Runtime Error | 163 | 38384 | 1591 | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define ALL(x) (x).begin(), (x).end()
vector<vector<int>> lookup;
int L;
void build_sparse_table(int N, vector<ll>& a) {
int n = 1;
L = 0;
while (n <= N) {
n <<= 1;
L++;
}
lookup = vector<vector<int>>(N, vector<int>(L));
REP(i, N) {
lookup[i][0] = a[i];
}
for (int j = 1; j < L; j++) {
REP(i, N - (1 << j) + 1) {
lookup[i][j] = min(lookup[i][j-1], lookup[i + (1 << (j-1))][j-1]);
}
}
}
int query(int l, int r) {
int lb = 0, ub = L + 1;
while (ub - lb > 1) {
int m = (lb + ub) / 2;
if ((1 << m) < r - l) lb = m;
else ub = m;
}
return min(lookup[l][lb], lookup[r - (1 << lb)][lb]);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int N;
cin >> N;
vector<ll> a(N);
REP(i, N) cin >> a[i];
build_sparse_table(N, a);
vector<ll> left(N);
REP(i, N) {
int lb = -1, ub = i;
while (ub - lb > 1) {
int m = (lb + ub) / 2;
if (query(m, i) < a[i]) lb = m;
else ub = m;
}
left[i] = i - lb;
}
vector<int> right(N);
REP(i, N) {
int lb = i, ub = N+1;
while (ub - lb > 1) {
int m = (lb + ub) / 2;
if (query(i, m) < a[i]) ub = m;
else lb = m;
}
right[i] = lb - i;
}
ll ans = 0;
REP(i, N) ans += left[i] * right[i] * a[i];
cout << ans << endl;
} |
s455520529 | p03987 | u223904637 | 1583896948 | Python | PyPy3 (2.4.0) | py | Runtime Error | 180 | 38256 | 1555 | import sys
input=sys.stdin.readline
def segfunc(x,y):
return x+y
def init(init_val):
#set_val
for i in range(n):
seg[i+num-1]=init_val[i]
#built
for i in range(num-2,-1,-1):
seg[i]=segfunc(seg[2*i+1],seg[2*i+2])
def update(k,x):
k+=num-1
seg[k]=x
while k+1:
k=(k-1)//2
seg[k]=segfunc(seg[k*2+1],seg[k*2+2])
def query(p,q):
if q<=p:
return ide_ele
p+=num-1
q+=num-2
res=ide_ele
while q-p>1:
if p&1==0:
res=segfunc(res,seg[p])
if q&1==1:
res=segfunc(res,seg[q])
q-=1
p=p//2
q=(q-1)//2
if p==q:
res=segfunc(res,seg[p])
else:
res=segfunc(segfunc(res,seg[p]),seg[q])
return res
ide_ele=0
n=int(input())
n+=2
num=2**(n-1).bit_length()
seg=[ide_ele]*2*num
l=list(map(int,input().split()))
p=[]
n-=2
for i in range(n):
p.append([l[i],i+1])
p.sort(key=lambda x:x[0])
ans=0
update(0,1)
update(n+1,1)
for i in range(n):
update(p[i][1],1)
x=query(0,p[i][1])
ok=n+1
ng=-1
while ok-ng>1:
m=(ok+ng)//2
if query(0,m)<x-1:
ng=m
else:
ok=m
left=ok
ok=n+1
ng=-1
while ok-ng>1:
m=(ok+ng)//2
if query(0,m)<x-1:
ng=m
else:
ok=m
right=ok
ans+=(i+1)*(l[i][1]-left)*(right-l[i][1])
print(ans) |
s904522630 | p03987 | u476604182 | 1583093078 | Python | PyPy3 (2.4.0) | py | Runtime Error | 183 | 38512 | 841 | class BIT:
def __init__(self,n):
self.N = n
self.data = [0]*(N+1)
def bit_add(self,i,a):
j = i+1
while j<=N:
self.data[j] += a
j += j&-j
def bit_sum(self,i):
m = 0
j = i+1
while j>0:
m += self.data[j]
j -= j&-j
return m
def bit_search(self,x):
i = 0
m = 0
j = 1<<(self.N.bit_length()-1)
while j:
if i+j<=N and self.data[i+j]+m<=x:
i += j
m += self.data[i]
j >>= 1
return i
N, *A = map(int, open('0').read().split())
bit = BIT(N)
ntoi = [0]*(N+1)
ans = 0
for i, a in enumerate(A):
ntoi[a] = i
for i in range(1,N+1):
j = ntoi[i]
L = bit.bit_sum(j)
R = N-L-1
if L!=0:
a = bit.bit_search(L-1)
else:
a = -1
if R!=0:
b = bit.bit_search(L)
else:
b = N
ans += (j-a)*(b-j)*i
bit.bit_add(j,1)
print(ans) |
s655407338 | p03987 | u476604182 | 1583093015 | Python | Python (3.4.3) | py | Runtime Error | 18 | 3064 | 841 | class BIT:
def __init__(self,n):
self.N = n
self.data = [0]*(N+1)
def bit_add(self,i,a):
j = i+1
while j<=N:
self.data[j] += a
j += j&-j
def bit_sum(self,i):
m = 0
j = i+1
while j>0:
m += self.data[j]
j -= j&-j
return m
def bit_search(self,x):
i = 0
m = 0
j = 1<<(self.N.bit_length()-1)
while j:
if i+j<=N and self.data[i+j]+m<=x:
i += j
m += self.data[i]
j >>= 1
return i
N, *A = map(int, open('0').read().split())
bit = BIT(N)
ntoi = [0]*(N+1)
ans = 0
for i, a in enumerate(A):
ntoi[a] = i
for i in range(1,N+1):
j = ntoi[i]
L = bit.bit_sum(j)
R = N-L-1
if L!=0:
a = bit.bit_search(L-1)
else:
a = -1
if R!=0:
b = bit.bit_search(L)
else:
b = N
ans += (j-a)*(b-j)*i
bit.bit_add(j,1)
print(ans) |
s082190944 | p03987 | u532966492 | 1577165662 | Python | Python (3.4.3) | py | Runtime Error | 1808 | 182072 | 622 | def main():
n = int(input())
a = list(map(int, input().split()))
a = sorted(list(enumerate(a)), key=lambda x: -x[1])
L = [i for i in range(n+2)] # 連結成分のうち一番左のindex
R = [i for i in range(n+2)] # 連結成分のうち一番右のindex
ans = 0
for i, j in a: # 1-indexなので1ずれる
print(L, R)
M = R[i+1] # 連結成分の最大値
m = L[i+1] # 連結成分の最小値
ans += j*(M-i)*(i+2-m) # 計算
R[m-1] = M # 連結成分の左端の更新
L[M+1] = m # 連結成分の右端の更新
print(ans)
main() |
s750276203 | p03987 | u399721252 | 1575654630 | Python | PyPy3 (2.4.0) | py | Runtime Error | 165 | 38256 | 1077 | sys.setrecursionlimit(100000)
maxcost = 10**10
n = int(input())
num = [ int(v) for v in input().split() ]
pos = sorted([ (v, i) for i, v in enumerate(num,1) ])
pos = [ i[1] for i in pos ]
ln = len(bin(n-1))-1
ln2 = 2**(ln-1)
segtree = [ maxcost for i in range(2**ln-1) ]
#最小値用
def update_tomin(tree, p, q=1):
p += 2**(ln-1)-2
while p >= 0:
tree[p] = min(tree[p], q)
p = (p-1)//2
def getmin(tree,a,b,k=0,l=0,r=ln2):
if r <= a or b <= l:
return maxcost
elif a <= l and r <= b:
return tree[k]
else:
return min( getmin(tree,a,b,2*k+1,l,(l+r)//2), getmin(tree,a,b,2*k+2,(l+r)//2,r) )
for i, v in enumerate(num):
update_tomin(segtree,i+1,v)
def divconq(a, b):
if a == b:
return num[a-1]
else:
m = getmin(segtree,a-1,b)
k = pos[m-1]
s = m * (b-k+1) * (k-a+1)
if k == a:
return s + divconq(a+1, b)
elif k == b:
return s + divconq(a, b-1)
else:
return s + divconq(a, k-1) + divconq(k+1, b)
print(divconq(1,n)) |
s916022685 | p03987 | u399721252 | 1575654411 | Python | Python (3.4.3) | py | Runtime Error | 2106 | 40076 | 1047 | maxcost = 10**10
n = int(input())
num = [ int(v) for v in input().split() ]
pos = sorted([ (v, i) for i, v in enumerate(num,1) ])
pos = [ i[1] for i in pos ]
ln = len(bin(n-1))-1
ln2 = 2**(ln-1)
segtree = [ maxcost for i in range(2**ln-1) ]
#最小値用
def update_tomin(tree, p, q=1):
p += 2**(ln-1)-2
while p >= 0:
tree[p] = min(tree[p], q)
p = (p-1)//2
def getmin(tree,a,b,k=0,l=0,r=ln2):
if r <= a or b <= l:
return maxcost
elif a <= l and r <= b:
return tree[k]
else:
return min( getmin(tree,a,b,2*k+1,l,(l+r)//2), getmin(tree,a,b,2*k+2,(l+r)//2,r) )
for i, v in enumerate(num):
update_tomin(segtree,i+1,v)
def divconq(a, b):
if a == b:
return num[a-1]
else:
m = getmin(segtree,a-1,b)
k = pos[m-1]
s = m * (b-k+1) * (k-a+1)
if k == a:
return s + divconq(a+1, b)
elif k == b:
return s + divconq(a, b-1)
else:
return s + divconq(a, k-1) + divconq(k+1, b)
print(divconq(1,n)) |
s365642603 | p03987 | u017810624 | 1573889567 | Python | PyPy3 (2.4.0) | py | Runtime Error | 171 | 38256 | 6783 | def main():
class Avltree:
def __init__(self,key=None):
self.key = key
self.left = None
self.right = None
self.balance = "Even"
def search(self,key):
if self.key == None:
return None
if self.key > key:
if self.left == None:
return None
else:
return self.left.search(key)
if self.key < key:
if self.right == None:
return None
else:
return self.right.search(key)
return self
def search_lower(self,key,key_lower):
if self.key == None:
return key_lower
if self.key > key:
if self.left == None:
return key_lower
else:
return self.left.search_lower(key,key_lower)
if self.key < key:
key_lower = self.key
if self.right == None:
return key_lower
else:
return self.right.search_lower(key,key_lower)
if self.left == None:
return key_lower
else:
if key_lower == None:
return self.left.end_higher(self.left.key)
else:
return max(key_lower,self.left.end_higher(self.left.key))
def search_higher(self,key,key_higher):
if self.key == None:
return key_higher
if self.key > key:
key_higher = self.key
if self.left == None:
return key_higher
else:
return self.left.search_higher(key,key_higher)
if self.key < key:
if self.right == None:
return key_higher
else:
return self.right.search_higher(key,key_higher)
if self.right == None:
return key_higher
else:
if key_higher == None:
return self.right.end_lower(self.right.key)
else:
return min(key_higher,self.right.end_lower(self.right.key))
def end_lower(self,end_lower_key):
if self.left == None:
return end_lower_key
else:
end_lower_key = self.left.key
return self.left.end_lower(end_lower_key)
def end_higher(self,end_higher_key):
if self.right == None:
return end_higher_key
else:
end_higher_key = self.right.key
return self.right.end_higher(end_higher_key)
def DoubleRightRotation(self):
tl = self.left
self.left = tl.right.right
tl.right.right = self
tlr = tl.right
tl.right = tlr.left
tlr.left = tl
if tlr.balance == "Left":
tlr.right.balance = "Right"
tlr.left.balance = "Even"
elif tlr.balance == "Right":
tlr.right.balance = "Even"
tlr.left.balance = "Left"
elif tlr.balance == "Even":
tlr.right.balance = "Even"
tlr.left.balance = "Even"
tlr.balance = "Even"
return tlr
def DoubleLeftRotation(self):
tr = self.right
self.right = tr.left.left
tr.left.left = self
trl = tr.left
tr.left = trl.right
trl.right = tr
if trl.balance == "Right":
trl.left.balance = "Left"
trl.right.balance = "Even"
elif trl.balance == "Left":
trl.left.balance = "Even"
trl.right.balance = "Right"
elif trl.balance == "Even":
trl.left.balance = "Even"
trl.right.balance = "Even"
trl.balance = "Even"
return trl
def SingleLeftRotation(self):
tr = self.right
tr.balance = "Even"
self.balance = "Even"
self.right = tr.left
tr.left = self
return tr
def SingleRightRotation(self):
tl = self.left
tl.balance = "Even"
self.balance = "Even"
self.left = tl.right
tl.right = self
return tl
def replace(self,p,v):
if p.left == self:
p.left = v
else :
p.right = v
def insert(self,key):
if self.key == None:
self.key = key
return self
if key < self.key:
if self.left == None:
self.left = Avltree(key)
else:
self.left.insertx(self,key)
elif key > self.key:
if self.right == None:
self.right = Avltree(key)
else:
self.right.insertx(self,key)
else: # key == self.key:
pass # do not overwrite
def insertx(self,p,key):
if self.key > key:
if self.left == None:
self.left = Avltree(key)
else:
if not self.left.insertx(self, key):
return False
if self.balance == "Right":
self.balance = "Even"
return False
elif self.balance == "Even":
self.balance = "Left"
return True
elif self.balance == "Left":
if self.left.balance == "Right":
self.replace(p,self.DoubleRightRotation())
elif self.left.balance == "Left":
self.replace(p,self.SingleRightRotation())
return False
if self.key < key:
if self.right == None:
self.right = Avltree(key)
else:
if not self.right.insertx(self, key):
return False
if self.balance == "Left":
self.balance = "Even"
return False
elif self.balance == "Even":
self.balance = "Right"
return True
elif self.balance == "Right":
if self.right.balance == "Left":
self.replace(p,self.DoubleLeftRotation())
elif self.right.balance == "Right":
self.replace(p,self.SingleLeftRotation())
return False
return False
def to_s(self):
return self.key
def left_s(self):
if self.left == None:
return None
return (self.left).key
def right_s(self):
if self.right == None:
return None
return (self.right).key
n=int(input())
a=list(map(int,input().split()))
ans=0
l=[0]*n
for i in range(n):
l[a[i]-1]=i
root=Avltree()
root.insert(-1)
root.insert(n)
for i in range(n):
root.insert(l[i])
ans+=(i+1)*(l[i]-root.search_lower(l[i],None))*(root.search_higher(l[i],None)-l[i])
print(ans)
if __name__ == '__main__':
main() |
s808313117 | p03987 | u347640436 | 1568590264 | Python | Python (3.4.3) | py | Runtime Error | 1857 | 25736 | 655 | INF = float('inf')
def query(a, b, k, l, r, st):
if r <= a or b <= l:
return INF
if a <= l and r <= b:
return st[k]
else:
k *= 2
t = (l + r) // 2
vl = query(a, b, k + 1, l, t)
vr = query(a, b, k + 2, t, r)
return min(vl, vr)
def main():
N = int(input())
a = list(map(int, input().split()))
n = 1 << N.bit_length()
st = [INF] * (2 * n - 1)
for i in range(N):
k = i + n - 1
st[k] = a[i]
while k > 0:
k = (k - 1) // 2
st[k] = min(st[k * 2 + 1], st[k * 2 + 2])
result = 0
for l in range(N):
for r in range(l, N):
result += query(l, r + 1, 0, 0, n)
print(result)
main()
|
s809534025 | p03987 | u347640436 | 1568588926 | Python | Python (3.4.3) | py | Runtime Error | 776 | 25460 | 591 | INF = float('inf')
N = int(input())
a = list(map(int, input().split()))
st = [INF] * ((1 << N.bit_length()) - 1)
for i in range(N):
k = i + N - 1
st[k] = a[i]
while k > 0:
k = (k - 1) // 2
st[k] = min(st[k * 2 + 1], st[k * 2 + 2])
def query(a, b, k, l, r):
if r <= a or b <= l:
return INF
if a <= l and r <= b:
return st[k]
else:
vl = query(a, b, k * 2 + 1, l, (l + r) // 2)
vr = query(a, b, k * 2 + 2, (l + r) // 2, r)
return min(vl, vr)
result = 0
for l in range(N):
for r in range(l, N):
result += query(l, r + 1, 0, 0, N)
print(result)
|
s326643000 | p03987 | u729133443 | 1568337681 | Python | Python (3.4.3) | py | Runtime Error | 94 | 25884 | 2683 | import bisect
class BTreeNode:
def __init__(self):
self.key = []
self.child = []
class BTree:
def __init__(self):
self.root = BTreeNode()
def search_higher(self, key):
ptr = self.root
ret = None
while ptr.child:
i = bisect.bisect_right(ptr.key, key)
if i != len(ptr.key):
ret = ptr.key[i]
ptr = ptr.child[i]
i = bisect.bisect_right(ptr.key, key)
if i != len(ptr.key):
ret = ptr.key[i]
return ret
def search_lower(self, key):
ptr = self.root
ret = None
while ptr.child:
i = bisect.bisect_left(ptr.key, key)
if i != 0:
ret = ptr.key[i - 1]
ptr = ptr.child[i]
i = bisect.bisect_left(ptr.key, key)
if i != 0:
ret = ptr.key[i - 1]
return ret
def insert(self, key):
def insert_rec(ptr):
b_size = 512
if not ptr.child:
bisect.insort(ptr.key, key)
if len(ptr.key) == b_size * 2 - 1:
ret = BTreeNode()
ret.key = ptr.key[:b_size]
ptr.key = ptr.key[b_size:]
return ret
else:
i = bisect.bisect(ptr.key, key)
temp = insert_rec(ptr.child[i])
if temp is not None:
ptr.key.insert(i, temp.key.pop(-1))
ptr.child.insert(i, temp)
if len(ptr.child) == b_size * 2:
ret = BTreeNode()
ret.child = ptr.child[:b_size]
ptr.child = ptr.child[b_size:]
ret.key = ptr.key[:b_size]
ptr.key = ptr.key[b_size:]
return ret
return None
temp = insert_rec(self.root)
if temp is not None:
root = BTreeNode()
root.key = [temp.key.pop(-1)]
root.child = [temp, self.root]
self.root = root
def dump(self):
def dump_rec(ptr, dep):
for _ in range(0, dep):
print(" ", end="")
print(ptr.key)
for c in ptr.child:
dump_rec(c, dep + 1)
dump_rec(self.root, 0)
print("")
def main():
n,*a=map(int,open(0).read().split())
l=[0]*n
for i,v in enumerate(a,1):l[v-1]=i
t=BTree()
t.insert(0)
t.insert(n+1)
c=0
for i,v in enumerate(l,1):
c+=(t.search_higher(v)-v)*(v-t.search_lower(v))*i
insert(t.v)
print(c)
main() |
s263436003 | p03987 | u729133443 | 1568332110 | Python | Python (3.4.3) | py | Runtime Error | 97 | 25884 | 1617 | from bisect import*
def main():
root=[],[]
def search_higher(key):
ptr=root
ret=None
while ptr[1]:
i=bisect(ptr[0],key)
if i!=len(ptr[0]):ret=ptr[0][i]
ptr=ptr[1][i]
i=bisect(ptr[0],key)
if i!=len(ptr[0]):ret=ptr[0][i]
return ret
def search_lower(key):
ptr=root
ret=None
while ptr[1]:
i=bisect_left(ptr[0],key)
if i!=0:ret=ptr[0][i-1]
ptr=ptr[1][i]
i=bisect_left(ptr[0],key)
if i!=0:ret=ptr[0][i-1]
return ret
def insert_rec(ptr,key):
b_size=512
if not ptr[1]:
insort(ptr[0],key)
if len(ptr[0])==b_size*2-1:
ret=ptr[0][:b_size],[]
ptr[0]=ptr[0][b_size:]
return ret
else:
i=bisect(ptr[0],key)
tmp=insert_rec(ptr[1][i],key)
if tmp:
ptr[0].insert(i,tmp[0].pop())
ptr[1].insert(i,tmp)
if len(ptr[1])==b_size*2:
ret=[],[]
ret=ptr[0][:b_size],ptr[1][:b_size]
ptr[0],ptr[1]=ptr[0][b_size:],ptr[1][b_size:]
return ret
def insert(key):
tmp=insert_rec(root,key)
if tmp:root[0],root[1]=[tmp[0].pop()],[tmp,root]
n,*a=map(int,open(0).read().split())
l=[0]*n
for i,v in enumerate(a,1):l[v-1]=i
insert(0)
insert(n+1)
c=0
for i,v in enumerate(l,1):
c+=(search_higher(v)-v)*(v-search_lower(v))*i
insert(v)
print(c)
main() |
s403943162 | p03987 | u729133443 | 1568330875 | Python | Python (3.4.3) | py | Runtime Error | 2105 | 25884 | 1865 | from bisect import*
def main():
class BTreeNode:
def __init__(self):self.key,self.child=[],[]
root=BTreeNode()
def search_higher(key):
ptr=root
ret=None
while ptr.child:
i=bisect(ptr.key,key)
if i!=len(ptr.key):ret=ptr.key[i]
ptr=ptr.child[i]
i=bisect(ptr.key,key)
if i!=len(ptr.key):ret=ptr.key[i]
return ret
def search_lower(key):
ptr=root
ret=None
while ptr.child:
i=bisect_left(ptr.key,key)
if i!=0:ret=ptr.key[i-1]
ptr=ptr.child[i]
i=bisect_left(ptr.key,key)
if i!=0:ret=ptr.key[i-1]
return ret
def insert_rec(ptr,key):
b_size=512
if not ptr.child:
insort(ptr.key,key)
if len(ptr.key)==b_size*2-1:
ret=BTreeNode()
ret.key=ptr.key[:b_size]
ptr.key=ptr.key[b_size:]
return ret
else:
i=bisect(ptr.key,key)
tmp=insert_rec(ptr.child[i])
if tmp:
ptr.key.insert(i,tmp.key.pop(-1))
ptr.child.insert(i,tmp)
if len(ptr.child)==b_size*2:
ret=BTreeNode()
ret.child=ptr.child[:b_size]
ptr.child=ptr.child[b_size:]
ret.key=ptr.key[:b_size]
ptr.key=ptr.key[b_size:]
return ret
def insert(key):
tmp=insert_rec(root,key)
if tmp:root.key,root.child=[tmp.key.pop(-1)],[tmp,root]
n,*a=map(int,open(0).read().split())
l=[0]*n
for i,v in enumerate(a,1):l[v-1]=i
insert(0)
insert(n+1)
c=0
for i,v in enumerate(l,1):
c+=(search_higher(v)-v)*(v-search_lower(v))*i
insert(v)
print(c)
main() |
s647919817 | p03987 | u922901775 | 1563879632 | Python | PyPy3 (2.4.0) | py | Runtime Error | 176 | 38288 | 22180 | #!/usr/bin/env python3
import sys
from collections import deque
from bisect import bisect
# The possible Node colors
BLACK = 'BLACK'
RED = 'RED'
NIL = 'NIL'
class Node:
def __init__(self, value, color, parent, left=None, right=None):
self.value = value
self.color = color
self.parent = parent
self.left = left
self.right = right
def __repr__(self):
return '{color} {val} Node'.format(color=self.color, val=self.value)
def __iter__(self):
if self.left.color != NIL:
yield from self.left.__iter__()
yield self.value
if self.right.color != NIL:
yield from self.right.__iter__()
def __eq__(self, other):
if self.color == NIL and self.color == other.color:
return True
if self.parent is None or other.parent is None:
parents_are_same = self.parent is None and other.parent is None
else:
parents_are_same = self.parent.value == other.parent.value and self.parent.color == other.parent.color
return self.value == other.value and self.color == other.color and parents_are_same
def has_children(self) -> bool:
""" Returns a boolean indicating if the node has children """
return bool(self.get_children_count())
def get_children_count(self) -> int:
""" Returns the number of NOT NIL children the node has """
if self.color == NIL:
return 0
return sum([int(self.left.color != NIL), int(self.right.color != NIL)])
class RedBlackTree:
# every node has null nodes as children initially, create one such object for easy management
NIL_LEAF = Node(value=None, color=NIL, parent=None)
def __init__(self):
self.count = 0
self.root = None
self.ROTATIONS = {
# Used for deletion and uses the sibling's relationship with his parent as a guide to the rotation
'L': self._right_rotation,
'R': self._left_rotation
}
def __iter__(self):
if not self.root:
return list()
yield from self.root.__iter__()
def add(self, value):
if not self.root:
self.root = Node(value, color=BLACK, parent=None, left=self.NIL_LEAF, right=self.NIL_LEAF)
self.count += 1
return
parent, node_dir = self._find_parent(value)
if node_dir is None:
return # value is in the tree
new_node = Node(value=value, color=RED, parent=parent, left=self.NIL_LEAF, right=self.NIL_LEAF)
if node_dir == 'L':
parent.left = new_node
else:
parent.right = new_node
self._try_rebalance(new_node)
self.count += 1
def remove(self, value):
"""
Try to get a node with 0 or 1 children.
Either the node we're given has 0 or 1 children or we get its successor.
"""
node_to_remove = self.find_node(value)
if node_to_remove is None: # node is not in the tree
return
if node_to_remove.get_children_count() == 2:
# find the in-order successor and replace its value.
# then, remove the successor
successor = self._find_in_order_successor(node_to_remove)
node_to_remove.value = successor.value # switch the value
node_to_remove = successor
# has 0 or 1 children!
self._remove(node_to_remove)
self.count -= 1
def contains(self, value) -> bool:
""" Returns a boolean indicating if the given value is present in the tree """
return bool(self.find_node(value))
def ceil(self, value) -> int or None:
"""
Given a value, return the closest value that is equal or bigger than it,
returning None when no such exists
"""
if self.root is None: return None
last_found_val = None if self.root.value < value else self.root.value
def find_ceil(node):
nonlocal last_found_val
if node == self.NIL_LEAF:
return None
if node.value == value:
last_found_val = node.value
return node.value
elif node.value < value:
# go right
return find_ceil(node.right)
else:
# this node is bigger, save its value and go left
last_found_val = node.value
return find_ceil(node.left)
find_ceil(self.root)
return last_found_val
def floor(self, value) -> int or None:
"""
Given a value, return the closest value that is equal or less than it,
returning None when no such exists
"""
if self.root is None: return None
last_found_val = None if self.root.value > value else self.root.value
def find_floor(node):
nonlocal last_found_val
if node == self.NIL_LEAF:
return None
if node.value == value:
last_found_val = node.value
return node.value
elif node.value < value:
# this node is smaller, save its value and go right, trying to find a cloer one
last_found_val = node.value
return find_floor(node.right)
else:
return find_floor(node.left)
find_floor(self.root)
return last_found_val
def _remove(self, node):
"""
Receives a node with 0 or 1 children (typically some sort of successor)
and removes it according to its color/children
:param node: Node with 0 or 1 children
"""
left_child = node.left
right_child = node.right
not_nil_child = left_child if left_child != self.NIL_LEAF else right_child
if node == self.root:
if not_nil_child != self.NIL_LEAF:
# if we're removing the root and it has one valid child, simply make that child the root
self.root = not_nil_child
self.root.parent = None
self.root.color = BLACK
else:
self.root = None
elif node.color == RED:
if not node.has_children():
# Red node with no children, the simplest remove
self._remove_leaf(node)
else:
"""
Since the node is red he cannot have a child.
If he had a child, it'd need to be black, but that would mean that
the black height would be bigger on the one side and that would make our tree invalid
"""
raise Exception('Unexpected behavior')
else: # node is black!
if right_child.has_children() or left_child.has_children(): # sanity check
raise Exception('The red child of a black node with 0 or 1 children'
' cannot have children, otherwise the black height of the tree becomes invalid! ')
if not_nil_child.color == RED:
"""
Swap the values with the red child and remove it (basically un-link it)
Since we're a node with one child only, we can be sure that there are no nodes below the red child.
"""
node.value = not_nil_child.value
node.left = not_nil_child.left
node.right = not_nil_child.right
else: # BLACK child
# 6 cases :o
self._remove_black_node(node)
def _remove_leaf(self, leaf):
""" Simply removes a leaf node by making it's parent point to a NIL LEAF"""
if leaf.value >= leaf.parent.value:
# in those weird cases where they're equal due to the successor swap
leaf.parent.right = self.NIL_LEAF
else:
leaf.parent.left = self.NIL_LEAF
def _remove_black_node(self, node):
"""
Loop through each case recursively until we reach a terminating case.
What we're left with is a leaf node which is ready to be deleted without consequences
"""
self.__case_1(node)
self._remove_leaf(node)
def __case_1(self, node):
"""
Case 1 is when there's a double black node on the root
Because we're at the root, we can simply remove it
and reduce the black height of the whole tree.
__|10B|__ __10B__
/ \ ==> / \
9B 20B 9B 20B
"""
if self.root == node:
node.color = BLACK
return
self.__case_2(node)
def __case_2(self, node):
"""
Case 2 applies when
the parent is BLACK
the sibling is RED
the sibling's children are BLACK or NIL
It takes the sibling and rotates it
40B 60B
/ \ --CASE 2 ROTATE--> / \
|20B| 60R LEFT ROTATE 40R 80B
DBL BLACK IS 20----^ / \ SIBLING 60R / \
50B 80B |20B| 50B
(if the sibling's direction was left of it's parent, we would RIGHT ROTATE it)
Now the original node's parent is RED
and we can apply case 4 or case 6
"""
parent = node.parent
sibling, direction = self._get_sibling(node)
if sibling.color == RED and parent.color == BLACK and sibling.left.color != RED and sibling.right.color != RED:
self.ROTATIONS[direction](node=None, parent=sibling, grandfather=parent)
parent.color = RED
sibling.color = BLACK
return self.__case_1(node)
self.__case_3(node)
def __case_3(self, node):
"""
Case 3 deletion is when:
the parent is BLACK
the sibling is BLACK
the sibling's children are BLACK
Then, we make the sibling red and
pass the double black node upwards
Parent is black
___50B___ Sibling is black ___50B___
/ \ Sibling's children are black / \
30B 80B CASE 3 30B |80B| Continue with other cases
/ \ / \ ==> / \ / \
20B 35R 70B |90B|<---REMOVE 20B 35R 70R X
/ \ / \
34B 37B 34B 37B
"""
parent = node.parent
sibling, _ = self._get_sibling(node)
if (sibling.color == BLACK and parent.color == BLACK
and sibling.left.color != RED and sibling.right.color != RED):
# color the sibling red and forward the double black node upwards
# (call the cases again for the parent)
sibling.color = RED
return self.__case_1(parent) # start again
self.__case_4(node)
def __case_4(self, node):
"""
If the parent is red and the sibling is black with no red children,
simply swap their colors
DB-Double Black
__10R__ __10B__ The black height of the left subtree has been incremented
/ \ / \ And the one below stays the same
DB 15B ===> X 15R No consequences, we're done!
/ \ / \
12B 17B 12B 17B
"""
parent = node.parent
if parent.color == RED:
sibling, direction = self._get_sibling(node)
if sibling.color == BLACK and sibling.left.color != RED and sibling.right.color != RED:
parent.color, sibling.color = sibling.color, parent.color # switch colors
return # Terminating
self.__case_5(node)
def __case_5(self, node):
"""
Case 5 is a rotation that changes the circumstances so that we can do a case 6
If the closer node is red and the outer BLACK or NIL, we do a left/right rotation, depending on the orientation
This will showcase when the CLOSER NODE's direction is RIGHT
___50B___ __50B__
/ \ / \
30B |80B| <-- Double black 35B |80B| Case 6 is now
/ \ / \ Closer node is red (35R) / \ / applicable here,
20B 35R 70R X Outer is black (20B) 30R 37B 70R so we redirect the node
/ \ So we do a LEFT ROTATION / \ to it :)
34B 37B on 35R (closer node) 20B 34B
"""
sibling, direction = self._get_sibling(node)
closer_node = sibling.right if direction == 'L' else sibling.left
outer_node = sibling.left if direction == 'L' else sibling.right
if closer_node.color == RED and outer_node.color != RED and sibling.color == BLACK:
if direction == 'L':
self._left_rotation(node=None, parent=closer_node, grandfather=sibling)
else:
self._right_rotation(node=None, parent=closer_node, grandfather=sibling)
closer_node.color = BLACK
sibling.color = RED
self.__case_6(node)
def __case_6(self, node):
"""
Case 6 requires
SIBLING to be BLACK
OUTER NODE to be RED
Then, does a right/left rotation on the sibling
This will showcase when the SIBLING's direction is LEFT
Double Black
__50B__ | __35B__
/ \ | / \
SIBLING--> 35B |80B| <- 30R 50R
/ \ / / \ / \
30R 37B 70R Outer node is RED 20B 34B 37B 80B
/ \ Closer node doesn't /
20B 34B matter 70R
Parent doesn't
matter
So we do a right rotation on 35B!
"""
sibling, direction = self._get_sibling(node)
outer_node = sibling.left if direction == 'L' else sibling.right
def __case_6_rotation(direction):
parent_color = sibling.parent.color
self.ROTATIONS[direction](node=None, parent=sibling, grandfather=sibling.parent)
# new parent is sibling
sibling.color = parent_color
sibling.right.color = BLACK
sibling.left.color = BLACK
if sibling.color == BLACK and outer_node.color == RED:
return __case_6_rotation(direction) # terminating
raise Exception('We should have ended here, something is wrong')
def _try_rebalance(self, node):
"""
Given a red child node, determine if there is a need to rebalance (if the parent is red)
If there is, rebalance it
"""
parent = node.parent
value = node.value
if (parent is None # what the fuck? (should not happen)
or parent.parent is None # parent is the root
or (node.color != RED or parent.color != RED)): # no need to rebalance
return
grandfather = parent.parent
node_dir = 'L' if parent.value > value else 'R'
parent_dir = 'L' if grandfather.value > parent.value else 'R'
uncle = grandfather.right if parent_dir == 'L' else grandfather.left
general_direction = node_dir + parent_dir
if uncle == self.NIL_LEAF or uncle.color == BLACK:
# rotate
if general_direction == 'LL':
self._right_rotation(node, parent, grandfather, to_recolor=True)
elif general_direction == 'RR':
self._left_rotation(node, parent, grandfather, to_recolor=True)
elif general_direction == 'LR':
self._right_rotation(node=None, parent=node, grandfather=parent)
# due to the prev rotation, our node is now the parent
self._left_rotation(node=parent, parent=node, grandfather=grandfather, to_recolor=True)
elif general_direction == 'RL':
self._left_rotation(node=None, parent=node, grandfather=parent)
# due to the prev rotation, our node is now the parent
self._right_rotation(node=parent, parent=node, grandfather=grandfather, to_recolor=True)
else:
raise Exception("{} is not a valid direction!".format(general_direction))
else: # uncle is RED
self._recolor(grandfather)
def __update_parent(self, node, parent_old_child, new_parent):
"""
Our node 'switches' places with the old child
Assigns a new parent to the node.
If the new_parent is None, this means that our node becomes the root of the tree
"""
node.parent = new_parent
if new_parent:
# Determine the old child's position in order to put node there
if new_parent.value > parent_old_child.value:
new_parent.left = node
else:
new_parent.right = node
else:
self.root = node
def _right_rotation(self, node, parent, grandfather, to_recolor=False):
grand_grandfather = grandfather.parent
self.__update_parent(node=parent, parent_old_child=grandfather, new_parent=grand_grandfather)
old_right = parent.right
parent.right = grandfather
grandfather.parent = parent
grandfather.left = old_right # save the old right values
old_right.parent = grandfather
if to_recolor:
parent.color = BLACK
node.color = RED
grandfather.color = RED
def _left_rotation(self, node, parent, grandfather, to_recolor=False):
grand_grandfather = grandfather.parent
self.__update_parent(node=parent, parent_old_child=grandfather, new_parent=grand_grandfather)
old_left = parent.left
parent.left = grandfather
grandfather.parent = parent
grandfather.right = old_left # save the old left values
old_left.parent = grandfather
if to_recolor:
parent.color = BLACK
node.color = RED
grandfather.color = RED
def _recolor(self, grandfather):
grandfather.right.color = BLACK
grandfather.left.color = BLACK
if grandfather != self.root:
grandfather.color = RED
self._try_rebalance(grandfather)
def _find_parent(self, value):
""" Finds a place for the value in our binary tree"""
def inner_find(parent):
"""
Return the appropriate parent node for our new node as well as the side it should be on
"""
if value == parent.value:
return None, None
elif parent.value < value:
if parent.right.color == NIL: # no more to go
return parent, 'R'
return inner_find(parent.right)
elif value < parent.value:
if parent.left.color == NIL: # no more to go
return parent, 'L'
return inner_find(parent.left)
return inner_find(self.root)
def find_node(self, value):
def inner_find(root):
if root is None or root == self.NIL_LEAF:
return None
if value > root.value:
return inner_find(root.right)
elif value < root.value:
return inner_find(root.left)
else:
return root
found_node = inner_find(self.root)
return found_node
def _find_in_order_successor(self, node):
right_node = node.right
left_node = right_node.left
if left_node == self.NIL_LEAF:
return right_node
while left_node.left != self.NIL_LEAF:
left_node = left_node.left
return left_node
def _get_sibling(self, node):
"""
Returns the sibling of the node, as well as the side it is on
e.g
20 (A)
/ \
15(B) 25(C)
_get_sibling(25(C)) => 15(B), 'R'
"""
parent = node.parent
if node.value >= parent.value:
sibling = parent.left
direction = 'L'
else:
sibling = parent.right
direction = 'R'
return sibling, direction
def solve(N: int, a: "List[int]"):
sep = RedBlackTree()
sep.add(-1)
sep.add(N)
idx = {aa: i for i, aa in enumerate(a)}
res = 0
for n in range(1, N+1):
i = idx[n]
j = sep.floor(i)
k = sep.ceil(i)
res += n * (i - j) * (k - i)
sep.add(i)
print(res)
return
# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
a = [ int(next(tokens)) for _ in range(N) ] # type: "List[int]"
solve(N, a)
if __name__ == '__main__':
main()
|
s441079148 | p03987 | u627417051 | 1563736394 | Python | Python (3.4.3) | py | Runtime Error | 2106 | 45232 | 2032 | def getlist():
return list(map(int, input().split()))
class Node:
def __init__(self, key, parent=None, left=None, right=None):
self.key = key
self.p = parent
self.left = left
self.right = right
def __repr__(self):
return 'Node(%s)' % repr(self.key)
def search(self, k):
if self is None or k == self.key:
return self
if k < self.key:
return self.left.search(k)
else:
return self.right.search(k)
def minimum(self):
minimum = self
while minimum.left:
minimum = minimum.left
return minimum
def maximum(self):
while self.right:
self = self.right
return self
# 次節点
def successor(self):
if self.right:
return self.right.minimum()
y = self.p
while y and self == y.right:
self = y
y = y.p
return y
# 前節点
def predecessor(self):
if self.left:
return self.left.maximum()
y = self.p
while y and self == y.left:
self = y
y = y.p
return y
# 二分探索木のルートを返すメソッド
def root(self):
while self.p:
self = self.p
return self
# 挿入
def insert(self, value):
z = Node(value)
y = None
self = self.root()
while self:
y = self
if z.key < self.key:
self = self.left
else:
self = self.right
z.p = y
if y is None:
pass
elif z.key < y.key:
y.left = z
else:
y.right = z
N = int(input())
a = getlist()
l = [0] * (N + 1)
for i in range(1, N + 1):
l[a[i - 1]] = i
ans = 0
DD = Node(N + 1)
DD.insert(0)
for i in range(1, N + 1):
val = l[i]
DD.insert(val)
ans += i * (DD.search(val).successor().key - val) * (val - DD.search(val).predecessor().key)
print(ans) |
s094702251 | p03987 | u052499405 | 1560037557 | Python | Python (3.4.3) | py | Runtime Error | 2110 | 193428 | 1507 | import sys
sys.setrecursionlimit(10**6)
INF = 10**9
class RMQ:
def __init__(self, a):
self.n = len(aindex)
self.size = 2**(self.n - 1).bit_length()
self.data = [[INF, INF] for _ in range(2*self.size-1)]
self.initialize()
# Initialize data
def initialize(self):
for i in range(self.n):
self.data[self.size + i - 1] = aindex[i]
for i in range(self.n-2, -1, -1):
if self.data[i*2 + 1][0] < self.data[i*2 + 2][0]:
self.data[i] = self.data[i*2 + 1]
else:
self.data[i] = self.data[i*2 + 2]
# Min value in [l, r)
def query(self, l, r):
L = l + self.size; R = r + self.size
s = [INF, INF]
while L < R:
if R & 1:
R -= 1
s = min(s, self.data[R-1])
if L & 1:
s = min(s, self.data[L-1])
L += 1
L >>= 1; R >>= 1
return s
n = int(input())
a = [int(item) for item in input().split()]
aindex = []
for i, item in enumerate(a):
aindex.append([item, i])
rmq = RMQ(aindex)
def get_range_minsum(l, r):
if r - l == 1:
return a[l]
range_min, min_index = rmq.query(l,r)
val = 0
if min_index > l:
val += get_range_minsum(l, min_index)
if min_index < r-1:
val += get_range_minsum(min_index+1, r)
val += range_min * (min_index - l + 1) * (r - min_index)
return val
print(get_range_minsum(0, len(a))) |
s694118831 | p03987 | u077337864 | 1556337715 | Python | Python (3.4.3) | py | Runtime Error | 1500 | 166968 | 595 | import heapq
n = int(input())
alist = list(map(int, input().split()))
ad = {}
for i, a in enumerate(alist):
ad[a] = i
h = []
right = [n-1] * n
for i in range(n):
while h and -h[0] > alist[i]:
v = -heapq.heappop(h)
right[ad[v]] = i - 1
heapq.heappush(h, -alist[i])
print(right, h)
h = []
left = [0] * n
for i in reversed(range(n)):
while h and -h[0] > alist[i]:
v = -heapq.heappop(h)
left[ad[v]] = i + 1
heapq.heappush(h, -alist[i])
print(left, h)
ans = 0
for i in range(n):
ans += alist[i] * (i - left[i] + 1) * (right[i] - i + 1)
print(ans)
print(ans)
|
s833189331 | p03987 | u316386814 | 1553383811 | Python | Python (3.4.3) | py | Runtime Error | 2141 | 615860 | 779 | import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()
from collections import Counter
def main():
N = II()
A = LI()
idxs = [0] * (N + 1)
for i, a in enumerate(A):
idxs[a] = i
def func(arr):
if len(arr) == 0:
return 0
a = min(arr)
idx = idxs[a]
return (idx + 1) * (len(arr) - idx) * a + func(arr[:idx]) + func(arr[idx + 1:])
ans = func(A)
return ans
print(main())
|
s231781893 | p03987 | u316386814 | 1553383768 | Python | Python (3.4.3) | py | Runtime Error | 95 | 23956 | 773 | import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()
from collections import Counter
def main():
N = II()
A = LI()
idxs = [0] * N
for i, a in enumerate(A):
idxs[a] = i
def func(arr):
if len(arr) == 0:
return 0
a = min(arr)
idx = idxs[a]
return (idx + 1) * (len(arr) - idx) * a + func(arr[:idx]) + func(arr[idx + 1:])
ans = func(A)
return ans
print(main())
|
s608695954 | p03987 | u316386814 | 1553383747 | Python | Python (3.4.3) | py | Runtime Error | 96 | 24084 | 772 | import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()
from collections import Counter
def main():
N = II()
A = LI()
idxs = [0] * N
for i, a in enumerate(A):
idxs[a] = i
def func(arr):
if len(arr) == 0:
return 0
a = min(arr)
idx = idx[a]
return (idx + 1) * (len(arr) - idx) * a + func(arr[:idx]) + func(arr[idx + 1:])
ans = func(A)
return ans
print(main())
|
s126298807 | p03987 | u316386814 | 1553383594 | Python | Python (3.4.3) | py | Runtime Error | 2139 | 591604 | 782 | import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()
from collections import Counter
def main():
N = II()
A = LI()
idxs = [0] * (N + 1)
for i, a in enumerate(A, 1):
idxs[a] = i
def func(arr):
if len(arr) == 0:
return 0
a = min(arr)
idx = idxs[a]
return (idx + 1) * (len(arr) - idx) * a + func(arr[:idx]) + func(arr[idx + 1:])
ans = func(A)
return ans
print(main())
|
s186209616 | p03987 | u316386814 | 1553382679 | Python | PyPy3 (2.4.0) | py | Runtime Error | 243 | 70992 | 829 | import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()
from collections import Counter, deque
from bisect import bisect_right
def main():
N = II()
A = LI()
idxs = [0] * (N + 1)
for i, a in enumerate(A, 1):
idxs[a] = i
lowers = deque([0, N + 1])
ans = 0
for a, i in enumerate(idxs[1:], 1):
j = bisect_right(lowers, i)
l, r = lowers[j - 1], lowers[j]
lowers.insert(j, i)
ans += (i - l) * (r - i) * a
return ans
print(main()) |
s605938502 | p03987 | u543954314 | 1553362291 | Python | Python (3.4.3) | py | Runtime Error | 2104 | 24744 | 213 | n = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(n):
l,r = 1,1
while a[i-l] > a[i] and i-l > -1:
l += 1
while a[i+r] > a[i] and i+r < n:
r += 1
ans += l*r*a[i]
print(ans) |
s538541132 | p03987 | u729133443 | 1552377794 | Python | Python (3.4.3) | py | Runtime Error | 2021 | 27564 | 6207 | #AVL
##search(0,x):O(logN)
# xがある場合indexを、ない場合Noneを返す
def search(root,key):
if avl_key[root] > key:
if avl_left[root] == None:
return None
else:
return search(avl_left[root],key)
if avl_key[root] < key:
if avl_right[root] == None:
return None
else:
return search(avl_right[root],key)
return root
##end_lower/higher:search_lower/higherで使用
def end_lower(root):
if avl_left[root] == None:
return avl_key[root]
else:
return end_lower(avl_left[root])
def end_higher(root):
if avl_right[root] == None:
return avl_key[root]
else:
return end_higher(avl_right[root])
##search_lower(0,x,None):O(logN)
# xより小さいものの中で最も大きいものを出力。ない場合はNoneを出力
def search_lower(root,key,lower_key):
if avl_key[root] > key:
if avl_left[root] == None:
return lower_key
else:
return search_lower(avl_left[root],key,lower_key)
if avl_key[root] < key:
lower_key = avl_key[root]
if avl_right[root] == None:
return lower_key
else:
return search_lower(avl_right[root],key,lower_key)
# ==
if avl_left[root] == None:
return lower_key
else:
if lower_key == None:
return end_higher(avl_left[root])
else:
return max(lower_key,end_higher(avl_left[root]))
##search_higher(0,x,None):O(logN)
# xより大きいものの中で最も小さいものを出力。ない場合はNoneを出力
def search_higher(root,key,higher_key):
if avl_key[root] > key:
higher_key = avl_key[root]
if avl_left[root] == None:
return higher_key
else:
return search_higher(avl_left[root],key,higher_key)
if avl_key[root] < key:
if avl_right[root] == None:
return higher_key
else:
return search_higher(avl_right[root],key,higher_key)
# ==
if avl_right[root] == None:
return higher_key
else:
if higher_key == None:
return end_lower(avl_right[root])
else:
return min(higher_key,end_lower(avl_right[root]))
##Rotation,replace,insertx:insertで使用
def DoubleRightRotation(x):
tl = avl_left[x]
avl_left[x] = avl_right[avl_right[tl]]
avl_right[avl_right[tl]] = x
tlr = avl_right[tl]
avl_right[tl] = avl_left[tlr]
avl_left[tlr] = tl
if balance[tlr] == -1:
balance[avl_right[tlr]] = 1
balance[avl_left[tlr]] = 0
elif balance[tlr] == 1:
balance[avl_right[tlr]] = 0
balance[avl_left[tlr]] = -1
else:
balance[avl_right[tlr]] = 0
balance[avl_left[tlr]] = 0
balance[tlr] = 0
return tlr
def DoubleLeftRotation(x):
tr = avl_right[x]
avl_right[x] = avl_left[avl_left[tr]]
avl_left[avl_left[tr]] = x
trl = avl_left[tr]
avl_left[tr] = avl_right[trl]
avl_right[trl] = tr
if balance[trl] == 1:
balance[avl_right[trl]] = 0
balance[avl_left[trl]] = -1
elif balance[trl] == -1:
balance[avl_left[trl]] = 0
balance[avl_right[trl]] = 1
else:
balance[avl_right[trl]] = 0
balance[avl_left[trl]] = 0
balance[trl] = 0
return trl
def SingleLeftRotation(x):
tr = avl_right[x]
balance[tr] = 0
balance[x] = 0
avl_right[x] = avl_left[tr]
avl_left[tr] = x
return tr
def SingleRightRotation(x):
tl = avl_left[x]
balance[tl] = 0
balance[x] = 0
avl_left[x] = avl_right[tl]
avl_right[tl] = x
return tl
def replace(x,p,v):
if avl_left[p] == x:
avl_left[p] = v
else:
avl_right[p] = v
def insertx(root,p,key):
if avl_key[root] > key:
if avl_left[root] == None:
avl_key.append(key)
avl_left[root] = len(avl_key)-1
else:
if not insertx(avl_left[root],root,key):
return False
if balance[root] == 1:
balance[root] = 0
return False
elif balance[root] == 0:
balance[root] = -1
return True
else:
if balance[avl_left[root]] == 1:
replace(root,p,DoubleRightRotation(root))
elif balance[avl_left[root]] == -1:
replace(root,p,SingleRightRotation(root))
return False
if avl_key[root] < key:
if avl_right[root] == None:
avl_key.append(key)
avl_right[root] = len(avl_key)-1
else:
if not insertx(avl_right[root],root,key):
return False
if balance[root] == -1:
balance[root] = 0
return False
elif balance[root] == 0:
balance[root] = 1
return True
else:
if balance[avl_right[root]] == -1:
replace(root,p,DoubleLeftRotation(root))
elif balance[avl_right[root]] == 1:
replace(root,p,SingleLeftRotation(root))
return False
return False
##insert(0,x):O(logN)
#x追加
def insert(root,key):
if key < avl_key[root]:
if avl_left[root] == None:
avl_key.append(key)
avl_left[root] = len(avl_key)-1
else:
insertx(avl_left[root],root,key)
elif key > avl_key[root]:
if avl_right[root] == None:
avl_key.append(key)
avl_right[root] = len(avl_key)-1
else:
insertx(avl_right[root],root,key)
else:
pass
########################################################
##初期化(要素は一つ入れておく)
#avl_key:値,avl_left:左の子のindex,avl_right:右の子のindex
#balance[i]: {"Even":0,"Left":-1,"Right":1}
#avl_keyには初めに何か加えておく
n = 10**5
avl_key = [0]
avl_left = [None]*n
avl_right = [None]*n
balance = [0]*n
n,*a=map(int,open(0).read().split())
l=[0]*n
for i,v in enumerate(a,1):
l[v-1]=i
insert(0,0)
insert(0,n+1)
c=0
for i,v in enumerate(l,1):
c+=(search_higher(0,v,None)-v)*(v-search_lower(0,v,None))*i
insert(0,v)
print(c) |
s265551118 | p03987 | u334712262 | 1552021305 | Python | Python (3.4.3) | py | Runtime Error | 2106 | 33524 | 8642 | # -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub
sys.setrecursionlimit(10000)
def read_int():
return int(input())
def read_int_n():
return list(map(int, input().split()))
def read_float():
return float(input())
def read_float_n():
return list(map(float, input().split()))
def read_str():
return input().strip()
def read_str_n():
return list(map(str, input().split()))
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, 'sec')
return ret
return wrap
class Avltree:
""" Avl木を表現するクラス """
def __init__(self):
self.avl = [None,None,None,0]
def node(self,key):
return [None,key,None,0]
# search(x) xが存在するならTrueをしないならFalseを返す
# 使用法 Instance.search(x)
def search(self,key,avl=None):
if avl == None:
avl = self.avl
if key == avl[1]:
return True
elif key < avl[1]:
if avl[0] == None:
return False
else:
return self.search(key,avl[0])
elif avl[1] < key:
if avl[2] == None:
return False
else:
return self.search(key,avl[2])
# key未満で最大の要素を検索する。なければNoneを返す。
# 使用法 Instance.search_lower(x)
def search_lower(self,key,key_lower=None,avl=0):
if avl == 0:
avl = self.avl
# print(avl, key)
if avl == None:
return key_lower
elif key < avl[1]:
if avl[0] == None:
return key_lower
else:
return self.search_lower(key,key_lower,avl[0])
elif avl[1] < key:
key_lower = avl[1]
if avl[2] == None:
return key_lower
else:
return self.search_lower(key,key_lower,avl[2])
#avl[1] == keyの場合
if avl[0] == None:
return key_lower
else:
if key_lower == None:
return self.end_higher(avl[0][1],avl[0])
else:
return max(key_lower,self.end_higher(avl[0][1],avl[0]))
# keyより大きい最小の要素を検索する。なければNoneを返す。
# 使用法 Instance.search_higher(x)
def search_higher(self,key,key_higher=None,avl=0):
if avl == 0:
avl = self.avl
if avl == None:
return key_higher
if key < avl[1]:
key_higher = avl[1]
if avl[0] == None:
return key_higher
else:
return self.search_higher(key,key_higher,avl[0])
if avl[1] < key:
if avl[2] == None:
return key_higher
else:
return self.search_higher(key,key_higher,avl[2])
#self.key == keyの場合
if avl[2] == None:
return key_higher
else:
if key_higher == None:
return self.end_lower(avl[2][1],avl[2])
else:
return min(key_higher,self.end_lower(avl[2][1],avl[2]))
def end_lower(self,end_lower_key,avl=None):
if avl == None:
avl = self.avl
if avl[0] == None:
return end_lower_key
else:
end_lower_key = avl[0][1]
return self.end_lower(end_lower_key,avl[0])
def end_higher(self,end_higher_key,avl=None):
if avl == None:
avl = self.avl
if avl[2] == None:
return end_higher_key
else:
end_higher_key = avl[2][1]
return self.end_higher(end_higher_key,avl[2])
def DoubleRightRotation(self,avl):
tl = avl[0]
avl[0] = tl[2][2]
tl[2][2] = avl # selfはそのノード
tlr = tl[2]
tl[2] = tlr[0]
tlr[0] = tl
if tlr[3] == 1:
tlr[2][3] = 2
tlr[0][3] = 0
elif tlr[3] == 2:
tlr[2][3] = 0
tlr[0][3] = 1
elif tlr[3] == 0:
tlr[2][3] = 0
tlr[0][3] = 0
tlr[3] = 0
return tlr
def DoubleLeftRotation(self,avl):
tr = avl[2]
avl[2] = tr[0][0]
tr[0][0] = avl
trl = tr[0]
tr[0] = trl[2]
trl[2] = tr
if trl[3] == 2:
trl[0][3] = 1
trl[2][3] = 0
elif trl.balance == 1:
trl[0][3] = 0
trl[2][3] = 2
elif trl.balance == 0:
trl[0][3] = 0
trl[2][3] = 0
trl[3] = 0
return trl
def SingleLeftRotation(self,avl):
tr = avl[2]
tr[3] = 0
avl[3] = 0
avl[2] = tr[0]
tr[0] = avl
return tr
def SingleRightRotation(self,avl):
tl = avl[0]
tl[3] = 0
avl[3] = 0
avl[0] = tl[2]
tl[2] = avl
return tl
def replace(self,p,v,avl): # 親ノードpの下にある自分(avl)をvに置き換える。
if p[0] is avl:
p[0] = v
else :
p[2] = v
# 木に要素を追加する。
# 使用法 Instance.insert(x)
def insert(self,key): # rootでのみ呼ばれる挿入
if self.avl[1] == None: # rootを含むrotationはしないことにする。
self.avl[1] = key
return self.avl
if key < self.avl[1]:
if self.avl[0] == None:
self.avl[0] = self.node(key)
else:
self.insertx(self.avl,key,self.avl[0])
elif self.avl[1] < key:
if self.avl[2] == None:
self.avl[2] = self.node(key)
else:
self.insertx(self.avl,key,self.avl[2])
else: # key == self.avl[1]:
pass # do not overwrite
def insertx(self,p,key,avl): # replaceを呼ぶために一つ上の親を持っているinsert
if key < avl[1]:
if avl[0] == None:
avl[0] = self.node(key)
else:
if not self.insertx(avl,key,avl[0]): # 左の木が生長しなければ、
return False # 成長しない
balance = avl[3]
if balance == 2:
avl[3] = 0
return False
elif balance == 0:
avl[3] = 1
return True # 成長した
elif balance == 1:
if avl[0][3] == 2:
self.replace(p,self.DoubleRightRotation(avl),avl)
elif avl[0][3] == 1:
self.replace(p,self.SingleRightRotation(avl),avl)
return False # rotationを行うと成長しない
if avl[1] < key:
if avl[2] == None:
avl[2] = self.node(key)
else:
if not self.insertx(avl,key,avl[2]):
return False
balance = avl[3]
if balance == 1:
avl[3] = 0
return False
elif balance == 0:
avl[3] = 2
return True
elif balance == 2:
if avl[2][3] == 1:
self.replace(p,self.DoubleLeftRotation(avl),avl)
elif avl[2][3] == 2:
self.replace(p,self.SingleLeftRotation(avl),avl)
return False
return False # avl[1] == keyの時は何もしないので成長もしない
def debug(self):
print(self.avl)
@mt
def slv(N, A):
ans = 0
a2i = [0] * (N+1)
for i, a in enumerate(A):
a2i[A[i]] = i
at = Avltree()
at.insert(-1)
at.insert(N)
for a in range(1, N+1):
i = a2i[a]
l = at.search_lower(i)
r = at.search_higher(i)
# print(l, r, i, a)
ans += (i - l) * (r - i) * a
at.insert(i)
return ans
def main():
N = read_int()
A = read_int_n()
print(slv(N, A))
# A = list(range(1, 200000+1))
# for _ in range(100):
# random.shuffle(A)
# N = len(A)
# print(slv(N, A))
if __name__ == '__main__':
main()
|
s698287812 | p03987 | u025235255 | 1549941766 | Python | PyPy3 (2.4.0) | py | Runtime Error | 264 | 76408 | 8215 | #root.search(x): ◯.data == x のものが存在するある場合それを出力、ない場合Noneを出力
#root.insert(x): ◯.data == xが存在する場合Falseを出力、ない場合◯.data == x なる頂点を作る
#y.to_s(): 頂点yのdataを出力
#y.left_s(): 頂点yのleftを出力(ない場合はNone)
#root.search_lower(x,None): ○.dataがxより小さいものの中で最も大きいものを出力、ない場合Noneを出力
#root.search_higher(x,None): xより大きいものの中で最も小さいものを出力、ない場合Noneを出力
################################################################################
class Avltree:
def __init__(self,key=None):
self.key = key
self.left = None
self.right = None
self.balance = "Even"
def search(self,key):
if self.key == None:
return None
if self.key > key:
if self.left == None:
return None
else:
return self.left.search(key)
if self.key < key:
if self.right == None:
return None
else:
return self.right.search(key)
return self # self.key == keyの場合
def search_lower(self,key,key_lower):
if self.key == None:
return key_lower
if self.key > key:
if self.left == None:
return key_lower
else:
return self.left.search_lower(key,key_lower)
if self.key < key:
key_lower = self.key
if self.right == None:
return key_lower
else:
return self.right.search_lower(key,key_lower)
#self.key == keyの場合
if self.left == None:
return key_lower
else:
if key_lower == None:
return self.left.end_higher(self.left.key)
else:
return max(key_lower,self.left.end_higher(self.left.key))
def search_higher(self,key,key_higher):
if self.key == None:
return key_higher
if self.key > key:
key_higher = self.key
if self.left == None:
return key_higher
else:
return self.left.search_higher(key,key_higher)
if self.key < key:
if self.right == None:
return key_higher
else:
return self.right.search_higher(key,key_higher)
#self.key == keyの場合
if self.right == None:
return key_higher
else:
if key_higher == None:
return self.right.end_lower(self.right.key)
else:
return min(key_higher,self.right.end_lower(self.right.key))
def end_lower(self,end_lower_key):
if self.left == None:
return end_lower_key
else:
end_lower_key = self.left.key
return self.left.end_lower(end_lower_key)
def end_higher(self,end_higher_key):
if self.right == None:
return end_higher_key
else:
end_higher_key = self.right.key
return self.right.end_higher(end_higher_key)
def DoubleRightRotation(self):
tl = self.left
self.left = tl.right.right
tl.right.right = self # selfはそのノード
tlr = tl.right
tl.right = tlr.left
tlr.left = tl
if tlr.balance == "Left":
tlr.right.balance = "Right"
tlr.left.balance = "Even"
elif tlr.balance == "Right":
tlr.right.balance = "Even"
tlr.left.balance = "Left"
elif tlr.balance == "Even":
tlr.right.balance = "Even"
tlr.left.balance = "Even"
tlr.balance = "Even"
return tlr
def DoubleLeftRotation(self):
tr = self.right
self.right = tr.left.left
tr.left.left = self
trl = tr.left
tr.left = trl.right
trl.right = tr
if trl.balance == "Right":
trl.left.balance = "Left"
trl.right.balance = "Even"
elif trl.balance == "Left":
trl.left.balance = "Even"
trl.right.balance = "Right"
elif trl.balance == "Even":
trl.left.balance = "Even"
trl.right.balance = "Even"
trl.balance = "Even"
return trl
def SingleLeftRotation(self):
tr = self.right
tr.balance = "Even"
self.balance = "Even"
self.right = tr.left
tr.left = self
return tr
def SingleRightRotation(self):
tl = self.left
tl.balance = "Even"
self.balance = "Even"
self.left = tl.right
tl.right = self
return tl
def replace(self,p,v): # 親ノードpの下にある自分(self)をvに置き換える。
if p.left == self:
p.left = v
else :
p.right = v
def insert(self,key): # rootでのみ呼ばれる挿入
if self.key == None: # rootを含むrotationはしないことにする。
self.key = key
return self
if key < self.key:
if self.left == None:
self.left = Avltree(key)
else:
self.left.insertx(self,key)
elif key > self.key:
if self.right == None:
self.right = Avltree(key)
else:
self.right.insertx(self,key)
else: # key == self.key:
pass # do not overwrite
def insertx(self,p,key): # replaceを呼ぶために一つ上の親を持っているinsert
if self.key > key:
if self.left == None:
self.left = Avltree(key)
else:
if not self.left.insertx(self, key): # 左の木が生長しなければ、
return False # 成長しない
if self.balance == "Right":
self.balance = "Even"
return False
elif self.balance == "Even":
self.balance = "Left"
return True # 成長した
elif self.balance == "Left":
if self.left.balance == "Right":
self.replace(p,self.DoubleRightRotation())
elif self.left.balance == "Left":
self.replace(p,self.SingleRightRotation())
return False # rotationを行うと成長しない
if self.key < key:
if self.right == None:
self.right = Avltree(key)
else:
if not self.right.insertx(self, key):
return False
if self.balance == "Left":
self.balance = "Even"
return False
elif self.balance == "Even":
self.balance = "Right"
return True
elif self.balance == "Right":
if self.right.balance == "Left":
self.replace(p,self.DoubleLeftRotation())
elif self.right.balance == "Right":
self.replace(p,self.SingleLeftRotation())
return False
return False # self.key == keyの時は何もしないので成長もしない
def to_s(self):
return self.key
def left_s(self):
if self.left == None:
return None
return (self.left).key
def right_s(self):
if self.right == None:
return None
return (self.right).key
################################################################
'''
input = sys.stdin.readline
n = int(input())
a = [int(input()) for _ in range(n)]
#b[i]:iが何番目か
b = [None]*(n+1)
for i in range(n):
b[a[i]] = i
'''
def inpl(): return [int(i) for i in input().split()]
n = int(input())
a = inpl()
b = {a[i]: i for i in xrange(n)}
root = Avltree()
ass = 0
for i in xrange(1,n+1):
l = root.search_lower(b[i],None)
r = root.search_higher(b[i],None)
if l == None:
l = -1
if r == None:
r = n
ass += (b[i]-l)*(r-b[i])*i
root.insert(b[i])
print(ass) |
s275880173 | p03987 | u368780724 | 1543784345 | Python | Python (3.4.3) | py | Runtime Error | 1552 | 34004 | 389 | import numpy as np
def inpl(): return [int(i) for i in input().split()]
def minisum(x):
mini = np.argmin(x)
d = len(x)
if d == 1:
return x[0]
result = 0
if mini != 0:
result += minisum(x[0:mini])
if mini != d-1:
result += minisum(x[mini+1:d])
return result + (d-mini)*(mini+1)*x[mini]
N = input()
a = np.array(inpl())
print(minisum(a))
|
s632270747 | p03987 | u864197622 | 1543717727 | Python | Python (3.4.3) | py | Runtime Error | 74 | 25768 | 339 | N = int(input())
A = [int(a) for a in input().split()]
s = 0
for i in range(N):
l = i
while l>0:
if A[l-1] > a[i]:
l -= 1
else:
break
r = i
while r<N-1:
if A[r+1] > a[i]:
r += 1
else:
break
s += A[i] * (i-l+1) * (r-i+1)
print(s) |
s322866024 | p03987 | u368780724 | 1542109544 | Python | Python (3.4.3) | py | Runtime Error | 1576 | 34056 | 418 | import numpy as np
def inpl(): return [int(i) for i in input().split()]
def minisum(x):
mini = np.argmin(x)
d = len(x)
if d == 0:
return 0
if d == 1:
return x[0]
result = 0
if mini != 0:
result += minisum(x[:mini])
if mini != d-1:
result += minisum(x[mini+1:])
return result + (d-mini)*(mini+1)*x[mini]
N = input()
a = np.array(inpl())
print(minisum(a)) |
s908624424 | p03987 | u368780724 | 1542109378 | Python | Python (3.4.3) | py | Runtime Error | 1873 | 34008 | 353 | import numpy as np
def inpl(): return [int(i) for i in input().split()]
def minisum(x):
mini = np.argmin(x)
d = len(x)
result = 0
if mini != 0:
result += minisum(x[0:mini])
if mini != d-1:
result += minisum(x[mini+1:d])
return result + (d-mini)*(mini+1)*x[mini]
N = input()
a = np.array(inpl())
print(minisum(a)) |
s265501514 | p03987 | u368780724 | 1542108795 | Python | Python (3.4.3) | py | Runtime Error | 1605 | 34008 | 388 | import numpy as np
def inpl(): return [int(i) for i in input().split()]
def minisum(x):
mini = np.argmin(x)
d = len(x)
if d == 1:
return x[0]
result = 0
if mini != 0:
result += minisum(x[0:mini])
if mini != d-1:
result += minisum(x[mini+1:d])
return result + (d-mini)*(mini+1)*x[mini]
N = input()
a = np.array(inpl())
print(minisum(a)) |
s502693013 | p03987 | u996952235 | 1540245257 | Python | Python (3.4.3) | py | Runtime Error | 33 | 17780 | 226 | def min(li):
min = -1
for i in li:
if min > i:
min = i;
return min
n = int(input())
l = input().split(' ')
sum = 0;
for l in range(n):
for r in range(l,n):
sum += min(l[:r])
print(sum)
|
s011314353 | p03987 | u996952235 | 1540245079 | Python | Python (3.4.3) | py | Runtime Error | 32 | 17780 | 226 | def min(li):
min = -1
for i in li:
if min > i:
min = i;
return min
n = int(input())
l = input().split(' ')
sum = 0;
for l in range(n):
for r in range(r,n):
sum += min(l[:r])
print(sum)
|
s538998816 | p03987 | u334712262 | 1539670754 | Python | Python (3.4.3) | py | Runtime Error | 1723 | 36476 | 1385 | # -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub
sys.setrecursionlimit(10000)
def read_int():
return int(input())
def read_int_n():
return list(map(int, input().split()))
def read_float():
return float(input())
def read_float_n():
return list(map(float, input().split()))
def read_str():
return input().strip()
def read_str_n():
return list(map(str, input().split()))
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, 'sec')
return ret
return wrap
@mt
def slv(N, A):
import numpy as np
A = np.array(A)
def f(A):
n = len(A)
if not n:
return 0
if n == 1:
return A[0]
i = np.argmin(A)
return A[i]*(i+1)*(n-i) + f(A[:i]) + f(A[i+1:])
return f(A)
def main():
N = read_int()
A = read_int_n()
print(slv(N, A))
if __name__ == '__main__':
main()
|
s044811849 | p03987 | u098968285 | 1477235115 | Python | Python (3.4.3) | py | Runtime Error | 187 | 34344 | 748 | # def makelist(n, m):
# return [[0 for i in range(m)] for j in range(n)]
# a = int(input())
# b, c = map(int, input().split())
# s = input()
par = [0]*202020
size = [0]*202020
def find(x):
if par[x] == x:
return x
else:
par[x] = find(par[x])
return par[x]
def unite(x, y):
x = find(x)
y = find(y)
res = size[x] * size[y]
size[x] += size[y]
par[y] = x
return res
# main
n = int(input())
for i in range(202020):
par[i] = i
size[i] = 1
a = [0] + list(map(int, input().split()))
b = [0]*(n+1)
for i in range(1, n+1):
b[a[i]] = i
ans = 0
for j in reversed(1, n+1):
i = b[j]
ans += a[i]
if i - 1 >= 1 and a[i-1] > a[i]:
ans += unite(i-1, i) * a[i]
if i + 1 <= n and a[i+1] > a[i]:
ans += unite(i+1, i) * a[i]
print(ans)
|
s720642797 | p03987 | u108617242 | 1475527388 | Python | Python (3.4.3) | py | Runtime Error | 55 | 16916 | 132 | n = int(input())
a = input().split()
score = 0
for k in range(0,n):
for l in range(k,n):
score += min(int(a[k:l+1]))
print(score) |
s969449052 | p03987 | u108617242 | 1475527336 | Python | Python (3.4.3) | py | Runtime Error | 54 | 16916 | 137 | n = int(input())
a = input().split()
score = 0
for k in range(0,n):
for l in range(k,n):
score += int(min(int(a[k:l+1])))
print(score) |
s564658471 | p03987 | u108617242 | 1475527216 | Python | Python (3.4.3) | py | Runtime Error | 24 | 3064 | 136 | n = int(input())
a = input().split()
score = 0
for k in range(0,n):
for l in range(k,n):
score += int(min(int(a[k:l+1]))
print(score) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.