inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
---|---|
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are $n$ voters, and two ways to convince each of them to vote for you. The first way to convince the $i$-th voter is to pay him $p_i$ coins. The second way is to make $m_i$ other voters vote for you, and the $i$-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with $m_1 = 1$, $m_2 = 2$, $m_3 = 2$, $m_4 = 4$, $m_5 = 5$, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: ${5} \rightarrow {1, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 4, 5}$.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 2 \cdot 10^5$) β the number of test cases.
The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the number of voters.
The next $n$ lines contains the description of voters. $i$-th line contains two integers $m_i$ and $p_i$ ($1 \le p_i \le 10^9, 0 \le m_i < n$).
It is guaranteed that the sum of all $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case print one integer β the minimum number of coins you have to spend so that everyone votes for you.
-----Example-----
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
-----Note-----
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: ${3} \rightarrow {1, 3} \rightarrow {1, 2, 3}$.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: ${1} \rightarrow {1, 3, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 5, 6, 7} \rightarrow {1, 2, 3, 4, 5, 6, 7}$.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: ${2, 5} \rightarrow {1, 2, 3, 4, 5} \rightarrow {1, 2, 3, 4, 5, 6}$.
|
import sys
import heapq as hp
#sys.stdin = open('in', 'r')
t = int(sys.stdin.readline())
for ti in range(t):
n = int(sys.stdin.readline())
a = [tuple(map(int, sys.stdin.readline().split())) for i in range(n)]
a.sort(key = lambda x: (x[0], -x[1]))
c = 0
h = []
res = 0
for i in range(n-1,-1,-1):
hp.heappush(h, a[i][1])
while c + i < a[i][0]:
res += hp.heappop(h)
c += 1
print(res)
#sys.stdout.write('YES\n')
#sys.stdout.write(f'{res}\n')
#sys.stdout.write(f'{y1} {x1} {y2} {x2}\n')
|
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are $n$ voters, and two ways to convince each of them to vote for you. The first way to convince the $i$-th voter is to pay him $p_i$ coins. The second way is to make $m_i$ other voters vote for you, and the $i$-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with $m_1 = 1$, $m_2 = 2$, $m_3 = 2$, $m_4 = 4$, $m_5 = 5$, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: ${5} \rightarrow {1, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 4, 5}$.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 2 \cdot 10^5$) β the number of test cases.
The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the number of voters.
The next $n$ lines contains the description of voters. $i$-th line contains two integers $m_i$ and $p_i$ ($1 \le p_i \le 10^9, 0 \le m_i < n$).
It is guaranteed that the sum of all $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case print one integer β the minimum number of coins you have to spend so that everyone votes for you.
-----Example-----
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
-----Note-----
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: ${3} \rightarrow {1, 3} \rightarrow {1, 2, 3}$.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: ${1} \rightarrow {1, 3, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 5, 6, 7} \rightarrow {1, 2, 3, 4, 5, 6, 7}$.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: ${2, 5} \rightarrow {1, 2, 3, 4, 5} \rightarrow {1, 2, 3, 4, 5, 6}$.
|
import sys
from heapq import *
#sys.stdin = open('in', 'r')
t = int(sys.stdin.readline())
for ti in range(t):
n = int(sys.stdin.readline())
a = [tuple(map(int, sys.stdin.readline().split())) for i in range(n)]
a.sort(key = lambda x: (x[0], -x[1]))
c = 0
h = []
res = 0
for i in range(n-1,-1,-1):
heappush(h, a[i][1])
while c + i < a[i][0]:
res += heappop(h)
c += 1
print(res)
#sys.stdout.write('YES\n')
#sys.stdout.write(f'{res}\n')
#sys.stdout.write(f'{y1} {x1} {y2} {x2}\n')
|
You like playing chess tournaments online.
In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").
The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.
After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.
Compute the maximum score you can get by cheating in the optimal way.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) β the number of test cases. The description of the test cases follows.
The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) β the number of games played and the number of outcomes that you can change.
The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.
It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.
-----Output-----
For each testcase, print a single integer β the maximum score you can get by cheating in the optimal way.
-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW
Output
7
11
6
26
46
0
1
6
-----Note-----
Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game).
An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game.
Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game).
An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.
|
import sys
input = sys.stdin.readline
def main():
n, k = map(int, input().split())
string = input().strip()
if "W" not in string:
ans = min(n, k) * 2 - 1
print(max(ans, 0))
return
L_s = []
cnt = 0
bef = string[0]
ans = 0
for s in string:
if s == bef:
cnt += 1
else:
if bef == "L":
L_s.append(cnt)
else:
ans += cnt * 2 - 1
cnt = 1
bef = s
if bef == "W":
ans += cnt * 2 - 1
cnt = 0
if string[0] == "L" and L_s:
cnt += L_s[0]
L_s = L_s[1:]
L_s.sort()
for l in L_s:
if k >= l:
ans += l * 2 + 1
k -= l
else:
ans += k * 2
k = 0
ans += 2 * min(k, cnt)
print(ans)
for _ in range(int(input())):
main()
|
You like playing chess tournaments online.
In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").
The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.
After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.
Compute the maximum score you can get by cheating in the optimal way.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) β the number of test cases. The description of the test cases follows.
The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) β the number of games played and the number of outcomes that you can change.
The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.
It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.
-----Output-----
For each testcase, print a single integer β the maximum score you can get by cheating in the optimal way.
-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW
Output
7
11
6
26
46
0
1
6
-----Note-----
Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game).
An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game.
Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game).
An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.
|
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n,k = map(int,input().split())
s = input()
s = [s[i] for i in range(n)]
base = s.count("W")
if base == 0:
if k:
print(2*k-1)
else:
print(0)
elif base+k>=n:
print(2*n-1)
else:
interval = []
while s and s[-1]=="L":
s.pop()
s = s[::-1]
while s and s[-1]=="L":
s.pop()
while s:
if s[-1]=="W":
while s and s[-1]=="W":
s.pop()
else:
tmp = 0
while s and s[-1]=="L":
s.pop()
tmp += 1
interval.append(tmp)
interval.sort(reverse=True)
K = k
while interval and k:
if k>=interval[-1]:
k -= interval.pop()
else:
break
print(2*(base+K)-1-len(interval))
|
You like playing chess tournaments online.
In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").
The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.
After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.
Compute the maximum score you can get by cheating in the optimal way.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) β the number of test cases. The description of the test cases follows.
The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) β the number of games played and the number of outcomes that you can change.
The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.
It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.
-----Output-----
For each testcase, print a single integer β the maximum score you can get by cheating in the optimal way.
-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW
Output
7
11
6
26
46
0
1
6
-----Note-----
Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game).
An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game.
Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game).
An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.
|
import sys
input = sys.stdin.readline
def compress(string):
string = string + "#"
n = len(string)
begin, end, cnt = 0, 1, 1
ans = []
while end < n:
if string[begin] == string[end]:
end, cnt = end + 1, cnt + 1
else:
ans.append((string[begin], cnt))
begin, end, cnt = end, end + 1, 1
return ans
t = int(input())
for _ in range(t):
n, k = map(int, input().split())
s = input()[:-1]
s = compress(s)
w_groups = 0
w_cnt = 0
l_cnt = 0
li = []
for i, (char, cnt) in enumerate(s):
if char == "W":
w_groups += 1
w_cnt += cnt
if char == "L":
l_cnt += cnt
if 1 <= i < len(s) - 1:
li.append(cnt)
if w_cnt == 0:
print(max(min(k, l_cnt) * 2 - 1, 0))
continue
ans = w_cnt * 2 - w_groups
ans += min(k, l_cnt) * 2
li.sort()
for val in li:
if k >= val:
ans += 1
k -= val
print(ans)
|
You like playing chess tournaments online.
In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").
The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.
After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.
Compute the maximum score you can get by cheating in the optimal way.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) β the number of test cases. The description of the test cases follows.
The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) β the number of games played and the number of outcomes that you can change.
The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.
It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.
-----Output-----
For each testcase, print a single integer β the maximum score you can get by cheating in the optimal way.
-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW
Output
7
11
6
26
46
0
1
6
-----Note-----
Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game).
An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game.
Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game).
An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.
|
for _ in range(int(input())):
n, k = list(map(int, input().split()))
s = input()
k = min(k, s.count("L"))
arr = []
cur = 0
sc = 0
se = False
if s[0] == "W":
sc += 1
for e in s:
if e == "L":
cur += 1
else:
if cur > 0 and se:
arr.append(cur)
se = True
cur = 0
for i in range(1, n):
if s[i] == "W":
if s[i-1] == "W":
sc += 2
else:
sc += 1
arr.sort()
arr.reverse()
#print(arr, sc)
while len(arr) > 0 and arr[-1] <= k:
k -= arr[-1]
sc += arr[-1]*2+1
arr.pop()
#print(k)
sc += k*2
if k > 0 and s.count("W") == 0:
sc -= 1
print(sc)
|
You like playing chess tournaments online.
In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").
The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.
After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.
Compute the maximum score you can get by cheating in the optimal way.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) β the number of test cases. The description of the test cases follows.
The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) β the number of games played and the number of outcomes that you can change.
The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.
It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.
-----Output-----
For each testcase, print a single integer β the maximum score you can get by cheating in the optimal way.
-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW
Output
7
11
6
26
46
0
1
6
-----Note-----
Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game).
An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game.
Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game).
An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.
|
from sys import stdin
t = int(stdin.readline())
for i in range(t):
n, k = tuple(int(x) for x in stdin.readline().split())
line = 'L' * (k+1) + stdin.readline()[:-1] + 'L' * (k+1)
score = 0
flag = False
for char in line:
if char == 'W':
if flag:
score += 2
else:
score += 1
flag = True
else:
flag = False
seq = sorted(len(x) for x in line.split('W'))
if len(seq) == 1:
if k == 0:
print(0)
else:
print(2*k-1)
continue
for item in seq:
if item == 0:
continue
if k - item >= 0:
k -= item
score += 2 * (item-1) + 3
elif k > 0:
score += 2 * k
break
else:
break
print(min(score, 2*n-1))
|
You like playing chess tournaments online.
In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").
The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.
After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.
Compute the maximum score you can get by cheating in the optimal way.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) β the number of test cases. The description of the test cases follows.
The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) β the number of games played and the number of outcomes that you can change.
The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.
It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.
-----Output-----
For each testcase, print a single integer β the maximum score you can get by cheating in the optimal way.
-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW
Output
7
11
6
26
46
0
1
6
-----Note-----
Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game).
An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game.
Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game).
An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.
|
from sys import stdin
"""
n=int(stdin.readline().strip())
n,m=map(int,stdin.readline().strip().split())
s=list(map(int,stdin.readline().strip().split()))
s=stdin.readline().strip()
"""
T=int(stdin.readline().strip())
for caso in range(T):
n,k=list(map(int,stdin.readline().strip().split()))
s=list(stdin.readline().strip())
aux=[]
last=-1
for i in range(n):
if i>0 and s[i]=='L' and s[i-1]=='W':
last=i
if i<n-1 and s[i]=='L' and s[i+1]=='W' and last!=-1:
aux.append([i-last,last,i])
aux.sort()
for i in aux:
for j in range(i[1],i[2]+1):
if k>0:
s[j]='W'
k-=1
ini=-1
fin=n
for i in range(n):
if s[i]=='W':
ini=i-1
break
for i in range(n-1,-1,-1):
if s[i]=='W':
fin=i+1
break
for i in range(ini,-1,-1):
if k>0:
s[i]='W'
k-=1
for i in range(fin,n):
if k>0:
s[i]='W'
k-=1
ans=0
if ini==-1 and fin==n:
for i in range(n):
if k>0:
s[i]='W'
k-=1
for i in range(n):
if s[i]=='W':
if i>0 and s[i-1]=='W':
ans+=2
else:
ans+=1
print(ans)
|
You like playing chess tournaments online.
In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").
The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.
After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.
Compute the maximum score you can get by cheating in the optimal way.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) β the number of test cases. The description of the test cases follows.
The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) β the number of games played and the number of outcomes that you can change.
The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.
It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.
-----Output-----
For each testcase, print a single integer β the maximum score you can get by cheating in the optimal way.
-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW
Output
7
11
6
26
46
0
1
6
-----Note-----
Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game).
An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game.
Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game).
An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.
|
for _ in range(int(input())):
n, k = list(map(int, input().split()))
inp = input().lower()
k = min(k, inp.count('l'))
ans = inp.count('w') + tuple(zip(inp, 'l' + inp)).count('ww') + k * 2
if 'w' in inp:
inp2 = []
cur = -1
for c in inp:
if cur != -1:
if c == 'l':
cur += 1
else:
inp2.append(cur)
if c == 'w':
cur = 0
inp2.sort()
for inp2i in inp2:
if inp2i > k:
break
k -= inp2i
ans += 1
else:
ans = max(ans - 1, 0)
print(ans)
|
You like playing chess tournaments online.
In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").
The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.
After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.
Compute the maximum score you can get by cheating in the optimal way.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) β the number of test cases. The description of the test cases follows.
The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) β the number of games played and the number of outcomes that you can change.
The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.
It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.
-----Output-----
For each testcase, print a single integer β the maximum score you can get by cheating in the optimal way.
-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW
Output
7
11
6
26
46
0
1
6
-----Note-----
Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game).
An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game.
Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game).
An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.
|
import sys
readline = sys.stdin.readline
T = int(readline())
Ans = [None]*T
for qu in range(T):
N, K = list(map(int, readline().split()))
S = [1 if s == 'W' else 0 for s in readline().strip()]
if all(s == 0 for s in S):
Ans[qu] = max(0, 2*K-1)
continue
ans = 0
ctr = 0
st = []
L = []
res = 0
hh = False
for i in range(N):
s = S[i]
if s == 1:
if i == 0 or S[i-1] == 0:
ans += 1
else:
ans += 2
if ctr:
st.append(ctr)
ctr = 0
hh = True
else:
if hh:
ctr += 1
else:
res += 1
res += ctr
st.sort()
J = []
for s in st:
J.extend([2]*(s-1) + [3])
J.extend([2]*res)
Ans[qu] = ans + sum(J[:min(len(J), K)])
print('\n'.join(map(str, Ans)))
|
You like playing chess tournaments online.
In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").
The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.
After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.
Compute the maximum score you can get by cheating in the optimal way.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) β the number of test cases. The description of the test cases follows.
The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) β the number of games played and the number of outcomes that you can change.
The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.
It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.
-----Output-----
For each testcase, print a single integer β the maximum score you can get by cheating in the optimal way.
-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW
Output
7
11
6
26
46
0
1
6
-----Note-----
Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game).
An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game.
Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game).
An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.
|
def solve():
n, k = list(map(int, input().split()))
s = input()
ans = 0
prev = False
c = []
cc = 0
for i in range(n):
if s[i] == 'W':
if cc:
if cc != i:
c.append(cc)
cc = 0
if prev:
ans += 2
else:
ans += 1
prev = True
else:
prev = False
cc += 1
c.sort()
for i in range(len(c)):
if c[i] <= k:
k -= c[i]
ans += c[i] * 2 + 1
if 'W' in s:
ans += k * 2
else:
ans += max(k * 2 - 1, 0)
ans = min(ans, n * 2 - 1)
print(ans)
t = int(input())
for _ in range(t):
solve()
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for _ in range(int(input())):
s = input()
p = [i for i in s.split("0") if i!=""]
p.sort(reverse=True)
ans = 0
for i in range(0,len(p),2):
ans+=len(p[i])
print(ans)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for _ in range(int(input())):
s=[len(i)for i in input().split('0')]
s.sort()
print(sum(s[-1::-2]))
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for _ in range(int(input())):
s = input()
t = [i for i in s.split("0") if i!=""]
t.sort(reverse=True)
cnt=0
for i in range(0,len(t),2):
cnt+=len(t[i])
print(cnt)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for _ in range(int(input())):
s = input()
ar = []
cur = 0
for c in s:
if c == "1":
cur += 1
else:
ar.append(cur)
cur = 0
if cur != 0:
ar.append(cur)
ar.sort()
ar.reverse()
print(sum(ar[::2]))
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for nt in range(int(input())):
s = input()
n = len(s)
if s[0]=="1":
count = 1
else:
count = 0
groups = []
for i in range(1,n):
if s[i]=="1":
count += 1
else:
if count:
groups.append(count)
count = 0
if count:
groups.append(count)
groups.sort(reverse=True)
ans = 0
for i in range(0,len(groups),2):
ans += groups[i]
print (ans)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
def solv():
s=list(map(int,input()))
v=[]
sm=0
for n in s:
if n:
sm+=1
else:
v.append(sm)
sm=0
if sm:v.append(sm)
v.sort(reverse=True)
res=0
for n in range(0,len(v),2):res+=v[n]
print(res)
for _ in range(int(input())):solv()
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
import math
t=int(input())
for w in range(t):
s=sorted(input().split('0'),reverse=True)
c=0
for i in range(0,len(s),2):
c+=len(s[i])
print(c)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
from itertools import groupby
t = int(input())
for _ in range(t):
s = input()
l = []
for k, v in groupby(s):
if k == '1':
l.append(len(list(v)))
l.sort(reverse=True)
n = len(l)
res = 0
for i in range(0, n, 2):
res += l[i]
print(res)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for _ in range(int(input())):
s = input()
x = sorted(len(i) for i in s.split('0') if len(i) > 0)
print(max(sum(x[::2]), sum(x[1::2])))
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
from sys import stdin,stdout
from math import sqrt,gcd,ceil,floor,log2,log10,factorial,cos,acos,tan,atan,atan2,sin,asin,radians,degrees,hypot
from bisect import insort, insort_left, insort_right, bisect_left, bisect_right, bisect
from array import array
from functools import reduce
from itertools import combinations, combinations_with_replacement, permutations
from fractions import Fraction
from random import choice,getrandbits,randint,random,randrange,shuffle
from re import compile,findall,escape
from statistics import mean,median,mode
from heapq import heapify,heappop,heappush,heappushpop,heapreplace,merge,nlargest,nsmallest
for test in range(int(stdin.readline())):
s=input()
l=findall(r'1+',s)
lengths=[len(i) for i in l]
lengths.sort(reverse=True)
alice=0
for i in range(0,len(lengths),2):
alice+=lengths[i]
print(alice)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
import sys
input = sys.stdin.readline
T = int(input())
for t in range(T):
s = input()[:-1]
counts = []
current = 0
for c in s:
if c == '1':
current += 1
else:
counts.append(current)
current = 0
if current:
counts.append(current)
res = 0
counts = sorted(counts, reverse=True)
for i in range(len(counts)):
if 2*i >= len(counts):
break
res += counts[2*i]
print(res)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
import sys
import math
def II():
return int(sys.stdin.readline())
def LI():
return list(map(int, sys.stdin.readline().split()))
def MI():
return map(int, sys.stdin.readline().split())
def SI():
return sys.stdin.readline().strip()
t = II()
for q in range(t):
s = SI()
a = []
count = 0
for i in range(len(s)):
if s[i] == "1":
count+=1
else:
a.append(count)
count = 0
a.append(count)
a.sort(reverse=True)
print(sum(a[0:len(a):2]))
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
from math import *
from collections import *
from random import *
from decimal import Decimal
from heapq import *
from bisect import *
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**5)
def lis():
return list(map(int,input().split()))
def ma():
return list(map(int,input().split()))
def inp():
return int(input())
def st1():
return input().rstrip('\n')
t=inp()
while(t):
t-=1
#n=inp()
a=st1()
oe=[]
c=0
for i in a:
if(i=='1'):
c+=1
else:
if(c!=0):
oe.append(c)
c=0
if(c):
oe.append(c)
s=0
oe.sort(reverse=True)
for i in range(len(oe)):
if(i%2==0):
s+=oe[i]
print(s)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for _ in range(int(input())):
s = input() + '0'
A = []
tr = False
x = 0
for i in range(len(s)):
if s[i] == '1':
if tr:
x += 1
else:
tr = True
x = 1
else:
if tr:
tr = False
A.append(x)
A.sort(reverse=True)
Ans = 0
for i in range(len(A)):
if i % 2 == 0:
Ans += A[i]
print(Ans)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
t = int(input())
while t:
s = input()
arr = []
k = 0
for i in s:
if i == '1':
k += 1
else:
arr.append(k)
k = 0
if k:
arr.append(k)
arr.sort(reverse=True)
ans = 0
for i in range(0, len(arr), 2):
ans += arr[i]
print(ans)
t -= 1
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
x = input().rstrip()
arr = []
c = 0
for char in x:
if char=='1':
c+=1
else:
arr.append(c)
c = 0
arr.append(c)
arr.sort()
arr.reverse()
ans = 0
for i in range(0,len(arr),2):
ans += arr[i]
print(ans)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
import sys
input = sys.stdin.readline
t=int(input())
for tests in range(t):
S=input().strip()+"0"
L=[]
NOW=0
for s in S:
if s=="0":
L.append(NOW)
NOW=0
else:
NOW+=1
L.sort(reverse=True)
ANS=0
for i in range(0,len(L),2):
ANS+=L[i]
print(ANS)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for _ in range (int(input())):
s=input()
a = []
flag = 0
count = 0
for i in range (len(s)):
if s[i]=='1':
count+=1
else:
a.append(count)
count=0
if i==len(s)-1 and count!=0:
a.append(count)
a.sort(reverse=True)
ans = 0
for i in range(len(a)):
if i%2==0:
ans+=a[i]
print(ans)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for t in range(int(input())):
s = input()
last = -1
num = []
n = len(s)
for i in range(n):
if (s[i] == "0"):
if (i - last - 1 > 0):
num.append(i - last - 1)
last = i
if (n - last - 1 > 0):
num.append(n - last - 1)
num = sorted(num)[::-1]
ans = 0
for i in range(0, len(num), 2):
ans += num[i]
print(ans)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for test in range(int(input())):
s = input()
a = []
now = 0
n = len(s)
for i in range(n):
if s[i] == "0":
if now > 0:
a.append(now)
now = 0
else:
now += 1
if now > 0:
a.append(now)
a.sort(reverse=True)
ans = 0
for i in range(0, len(a), 2):
ans += a[i]
print(ans)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for _ in range(int(input())):
s = input()
ones = []
cnt = 0
for i in s:
if i == '1':
cnt += 1
else:
if cnt != 0:
ones.append(cnt)
cnt = 0
if cnt != 0:
ones.append(cnt)
ones.sort(reverse=True)
print(sum(ones[::2]))
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
from collections import defaultdict as dd
import math
import sys
input=sys.stdin.readline
def nn():
return int(input())
def li():
return list(input())
def mi():
return list(map(int, input().split()))
def lm():
return list(map(int, input().split()))
def solve():
s = input()
sets = []
streak = 0
for i in range(len(s)):
if s[i]=='1':
streak+=1
else:
if streak>0:
sets.append(streak)
streak=0
if streak>0:
sets.append(streak)
streak=0
sets.sort(reverse=True)
print(sum(sets[::2]))
q=nn()
for _ in range(q):
solve()
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
t = int(input())
for _ in range(t):
s = [int(i) for i in input().strip()]
n = len(s)
bckt = []
ct = 0
for i in range(n):
if s[i]:
ct += 1
else:
if ct:
bckt.append(ct)
ct = 0
if ct:
bckt.append(ct)
bckt.sort(reverse=True)
print(sum(bckt[::2]))
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for i in range(int(input())):
ip=list(map(int,input()))
ones=[]
tot=0
for i in ip:
if i==1:
tot+=1
else:
ones.append(tot)
tot=0
if tot:ones.append(tot)
ones.sort(reverse=True)
ans=0
for i in range(0,len(ones),2):
ans+=ones[i]
print(ans)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
#BINOD
import math
test = int(input())
for t in range(test):
s = input()
n = len(s)
A = []
o=0
for i in range(n):
if(s[i]=='1'):
o+=1
else:
A.append(o)
o=0
if(s[n-1]=='1'):
A.append(o)
A.sort(reverse = True)
ans = 0
for i in range(0,len(A),2):
ans += A[i]
print(ans)
#Binod
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
for _ in range(int(input())):
data = list(map(int,list(input())))
fl = False
data.append("&")
l = 0
st = []
for i in range(len(data)):
if fl and data[i] == 1:
l+=1
continue
if fl and data[i]!=1:
st.append(l)
l = 0
fl = False
continue
if not fl and data[i] == 1:
l = 1
fl = True
st.sort(reverse=True)
c1 = 0
for i in range(0,len(st),2):
c1+=st[i]
print(c1)
|
Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in $s$ and delete them.
For example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold): $\textbf{1}0110 \to 0110$; $1\textbf{0}110 \to 1110$; $10\textbf{1}10 \to 1010$; $101\textbf{1}0 \to 1010$; $10\textbf{11}0 \to 100$; $1011\textbf{0} \to 1011$.
After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\textbf{11}0 \to 1\textbf{00} \to 1$.
The game ends when the string becomes empty, and the score of each player is the number of $1$-characters deleted by them.
Each player wants to maximize their score. Calculate the resulting score of Alice.
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 500$) β the number of test cases.
Each test case contains exactly one line containing a binary string $s$ ($1 \le |s| \le 100$).
-----Output-----
For each test case, print one integer β the resulting score of Alice (the number of $1$-characters deleted by her).
-----Example-----
Input
5
01111001
0000
111111
101010101
011011110111
Output
4
0
6
3
6
-----Note-----
Questions about the optimal strategy will be ignored.
|
import math
from collections import deque
from sys import stdin, stdout
from string import ascii_letters
input = stdin.readline
#print = stdout.write
letters = ascii_letters[:26]
for _ in range(int(input())):
arr = list(map(int, input().strip()))
lens = []
count = 0
for i in arr:
if i == 0:
if count > 0:
lens.append(count)
count = 0
else:
count += 1
if count > 0:
lens.append(count)
lens.sort(reverse=True)
res = 0
for i in range(0, len(lens), 2):
res += lens[i]
print(res)
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
for _ in range(int(input())):
# n, x = map(int, input().split())
n = int(input())
arr = list(map(int, input().split()))
ans = [arr[0]]
for i in range(1, n - 1):
if arr[i - 1] < arr[i] and arr[i] > arr[i + 1]:
ans.append(arr[i])
elif arr[i - 1] > arr[i] and arr[i] < arr[i + 1]:
ans.append(arr[i])
ans.append(arr[-1])
print(len(ans))
print(*ans)
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
t = int(input())
for loop in range(t):
n = int(input())
p = list(map(int,input().split()))
a = p
ans = []
for i in range(n):
if i == 0 or i == n-1:
ans.append(p[i])
elif a[i-1] <= a[i] <= a[i+1]:
continue
elif a[i-1] >= a[i] >= a[i+1]:
continue
else:
ans.append(p[i])
print(len(ans))
print(*ans)
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
for t in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
b = [a[0]] + [a[i] for i in range(1, n - 1) if not(a[i - 1] < a[i] < a[i + 1] or
a[i - 1] > a[i] > a[i + 1])] + [a[-1]]
print(len(b))
print(*b)
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
for _ in range(int(input())):
n = int(input())
p = list(map(int, input().split()))
ans = [str(p[0])]
for i in range(1,n-1):
if p[i-1] < p[i] < p[i+1]:
continue
if p[i-1] > p[i] > p[i+1]:
continue
ans.append(str(p[i]))
ans.append(str(p[-1]))
print(len(ans))
print(" ".join(ans))
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
for _ in range(int(input())):
n = int(input())
p = tuple(map(int, input().split()))
ans = [p[i] for i in range(n) if i in (0, n - 1) or p[i] != sorted(p[i - 1:i + 2])[1]]
print(len(ans))
print(*ans)
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
t = int(input())
for test in range(t):
n = int(input())
l = list(map(int, input().rstrip().split()))
i = 0
arr = list()
arr.append(str(l[0]))
while i+1 < n:
if i+1 == n-1 or (l[i] < l[i+1] and l[i+1] > l[i+2]) or (l[i] > l[i+1] and l[i+1] < l[i+2]):
arr.append(str(l[i+1]))
i += 1
print(len(arr))
print(" ".join(arr))
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
from collections import *
from sys import stdin,stderr
def rl():
return [int(w) for w in stdin.readline().split()]
t, = rl()
for _ in range(t):
n, = rl()
p = rl()
s = [p[0]]
for i in range(1, n-1):
if p[i-1] < p[i] > p[i+1] or p[i-1] > p[i] < p[i+1]:
s.append(p[i])
s.append(p[-1])
print(len(s))
print(*s)
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
import sys
input = sys.stdin.readline
for nt in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
if n==2:
print (2)
print (*a)
continue
ans = [a[0]]
if a[1]>a[0]:
turn = 1
else:
turn = 0
s = abs(a[1]-a[0])
for i in range(2,n):
if turn:
if a[i]>a[i-1]:
continue
ans.append(a[i-1])
turn = 0
else:
if a[i]<a[i-1]:
continue
ans.append(a[i-1])
turn = 1
ans.append(a[-1])
print (len(ans))
print (*ans)
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
from collections import defaultdict as dd
import math
import sys
input=sys.stdin.readline
def nn():
return int(input())
def li():
return list(input())
def mi():
return list(map(int, input().split()))
def lm():
return list(map(int, input().split()))
q=nn()
for _ in range(q):
n = nn()
per = lm()
best =[per[0]]
for i in range(len(per)-2):
minper = min(per[i], per[i+1], per[i+2])
maxper = max(per[i], per[i+1], per[i+2])
if minper==per[i+1] or maxper==per[i+1]:
best.append(per[i+1])
best.append(per[-1])
print(len(best))
print(*best)
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
import sys
def ii():
return sys.stdin.readline().strip()
def idata():
return [int(x) for x in ii().split()]
def solve_of_problem():
n = int(ii())
data = idata()
ans = [data[0]]
for i in range(1, n - 1):
if data[i - 1] < data[i] > data[i + 1] or data[i - 1] > data[i] < data[i + 1]:
ans += [data[i]]
print(len(ans) + 1)
print(*ans, data[-1])
return
for ______ in range(int(ii())):
solve_of_problem()
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
def main():
n = int(input())
lst = list(map(int, input().split()))
take = [lst[0]]
sign = 0
for i in range(1, n):
if i == n - 1:
take.append(lst[i])
else:
if lst[i] > take[-1]:
if lst[i + 1] < lst[i]:
take.append(lst[i])
elif lst[i] < take[-1]:
if lst[i + 1] > lst[i]:
take.append(lst[i])
line = str(len(take)) + '\n'
for i in take:
line += str(i) + ' '
print(line)
def __starting_point():
t = int(input())
for i in range(t):
main()
__starting_point()
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
p = list(map(int, input().split()))
ans = [p[0]]
for i in range(n-2):
if (p[i]-p[i+1])*(p[i+1]-p[i+2])<0:
ans.append(p[i+1])
ans.append(p[-1])
print(len(ans))
print(*ans)
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
T = int(input())
for t in range(T):
N = int(input())
P = [int(_) for _ in input().split()]
up = P[1] > P[0]
res = [P[0]]
for i in range(1, N-1):
if up and P[i+1] < P[i]:
res.append(P[i])
up = False
elif not up and P[i+1] > P[i]:
res.append(P[i])
up = True
if P[N-1] != P[N-2]:
res.append(P[N-1])
print(len(res))
print(' '.join(map(str, res)))
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
def f(n,l):
output = [l[0]]
for i in range(1,n-1):
if (l[i]-l[i-1])*(l[i+1]-l[i]) < 0:
output.append(l[i])
output.append(l[-1])
return str(len(output))+'\n'+' '.join([str(x) for x in output])
numberofcases = int(input())
for _ in range(numberofcases):
n = int(input())
l = [int(t) for t in input().split()]
print(f(n,l))
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
def help():
n = int(input())
arr = list(map(int,input().split(" ")))
peak = [False]*n
down = [False]*n
for i in range(n):
if(i==0):
if(arr[0]<arr[1]):
down[0]=True
if(arr[0]>arr[1]):
peak[i]=True
elif(i==n-1):
if(arr[n-1]<arr[n-2]):
down[i]=True
if(arr[n-1]>arr[n-2]):
peak[i]=True
else:
if(arr[i-1]<arr[i] and arr[i]>arr[i+1]):
peak[i]=True
elif(arr[i-1]>arr[i] and arr[i]<arr[i+1]):
down[i]=True
series = []
for i in range(n):
if(peak[i]==True or down[i]==True):
series.append(i)
ans = 0
for i in range(len(series)-1):
ans += abs(series[i]-series[i+1])
print(len(series))
for i in range(len(series)):
print(arr[series[i]],end=" ")
print()
for _ in range(int(input())):
help()
|
Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that: $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$. Among all such subsequences, choose the one whose length, $k$, is as small as possible.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.
A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$)Β β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$)Β β the length of the permutation $p$.
The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct)Β β the elements of the permutation $p$.
The sum of $n$ across the test cases doesn't exceed $10^5$.
-----Output-----
For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$Β β its elements.
If multiple subsequences satisfy these conditions, you are allowed to find any of them.
-----Example-----
Input
2
3
3 2 1
4
1 3 4 2
Output
2
3 1
3
1 4 2
-----Note-----
In the first test case, there are $4$ subsequences of length at least $2$: $[3,2]$ which gives us $|3-2|=1$. $[3,1]$ which gives us $|3-1|=2$. $[2,1]$ which gives us $|2-1|=1$. $[3,2,1]$ which gives us $|3-2|+|2-1|=2$.
So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.
|
import sys
T = int(sys.stdin.readline().strip())
for t in range (0, T):
n = int(sys.stdin.readline().strip())
p = list(map(int, sys.stdin.readline().strip().split()))
ans = [p[0]]
for i in range(1, n):
if p[i] != ans[-1]:
if len(ans) == 1:
ans.append(p[i])
else:
if (ans[-2] - ans[-1]) * (ans[-1] - p[i]) > 0:
ans.pop()
ans.append(p[i])
print(len(ans))
print(" ".join(list(map(str, ans))))
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
n = int(input())
def area(width, height) :
return (width+1) * (height+1)
def calcul(s1, c, s2) :
maxx, maxy, minx, miny = 0, 0, 0, 0
x, y = 0, 0
for k in range(len(s1)) :
if s1[k] == "W" :
y += 1
if s1[k] == "S" :
y -= 1
if s1[k] == "A" :
x -= 1
if s1[k] == "D" :
x += 1
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
if c == "W" :
y += 1
elif c == "S" :
y -= 1
elif c == "A" :
x -= 1
elif c == "D" :
x += 1
else :
print(c, "ok")
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
for k in range(len(s2)) :
if s2[k] == "W" :
y += 1
if s2[k] == "S" :
y -= 1
if s2[k] == "A" :
x -= 1
if s2[k] == "D" :
x += 1
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
diffx = maxx - minx
diffy = maxy - miny
tmp = area(diffx, diffy)
return tmp
def pre_calcul(s, moment, pre_avant, date_debut) :
x, y, maxx, minx, maxy, miny = pre_avant
for k in range(date_debut, moment) :
if s[k] == "W" :
y += 1
if s[k] == "S" :
y -= 1
if s[k] == "A" :
x -= 1
if s[k] == "D" :
x += 1
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
return (x, y, maxx, minx, maxy, miny)
def calcul2(s, c, moment, precalcul) :
x, y, maxx, minx, maxy, miny = precalcul
if c == "W" :
y += 1
elif c == "S" :
y -= 1
elif c == "A" :
x -= 1
elif c == "D" :
x += 1
else :
print(c, "ok")
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
for k in range(moment, len(s)) :
if s[k] == "W" :
y += 1
if s[k] == "S" :
y -= 1
if s[k] == "A" :
x -= 1
if s[k] == "D" :
x += 1
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
diffx = maxx - minx
diffy = maxy - miny
tmp = area(diffx, diffy)
return tmp
for _ in range(n) :
s = input()
maxx, maxy, minx, miny = 0, 0, 0, 0
x, y = 0, 0
momentminx, momentmaxx, momentminy, momentmaxy = -1, -1, -1, -1
for k in range(len(s)) :
if s[k] == "W" :
y += 1
if s[k] == "S" :
y -= 1
if s[k] == "A" :
x -= 1
if s[k] == "D" :
x += 1
if x > maxx :
momentmaxx = k
if y > maxy :
momentmaxy = k
if x < minx :
momentminx = k
if y < miny :
momentminy = k
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
diffx = maxx - minx
diffy = maxy - miny
tmp = 999999999999999999999999999999999999
l = [momentmaxx, momentmaxy, momentminx, momentminy]
l = list(set(l))
l = [i for i in l if i != -1]
l.sort()
if l != [] :
precalcul = pre_calcul(s, l[0], (0, 0, 0, 0, 0, 0), 0)
avant = l[0]
for moment in l :
precalcul = pre_calcul(s, moment, precalcul, avant)
avant = moment
tmp = min(tmp, calcul2(s, 'W', moment, precalcul))
tmp = min(tmp, calcul2(s, 'S', moment, precalcul))
tmp = min(tmp, calcul2(s, 'A', moment, precalcul))
tmp = min(tmp, calcul2(s, 'D', moment, precalcul))
print(tmp)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
import sys
input = sys.stdin.readline
Q=int(input())
for testcases in range(Q):
S=input().strip()
X=Y=0
MAXX=MINX=MAXY=MINY=0
for s in S:
if s=="D":
X+=1
MAXX=max(MAXX,X)
elif s=="A":
X-=1
MINX=min(MINX,X)
elif s=="W":
Y+=1
MAXY=max(MAXY,Y)
else:
Y-=1
MINY=min(MINY,Y)
#print(MAXX,MINX,MAXY,MINY)
MAXXLIST=[]
MINXLIST=[]
MAXYLIST=[]
MINYLIST=[]
if MAXX==0:
MAXXLIST.append(0)
if MAXY==0:
MAXYLIST.append(0)
if MINX==0:
MINXLIST.append(0)
if MINY==0:
MINYLIST.append(0)
X=Y=0
for i in range(len(S)):
s=S[i]
if s=="D":
X+=1
if X==MAXX:
MAXXLIST.append(i+1)
elif s=="A":
X-=1
if X==MINX:
MINXLIST.append(i+1)
elif s=="W":
Y+=1
if Y==MAXY:
MAXYLIST.append(i+1)
else:
Y-=1
if Y==MINY:
MINYLIST.append(i+1)
#print(MAXXLIST)
#print(MAXYLIST)
#print(MINXLIST)
#print(MINYLIST)
ANS=(MAXX-MINX+1)*(MAXY-MINY+1)
#print(ANS)
if MAXX-MINX>1:
if MAXXLIST[0]>MINXLIST[-1] or MINXLIST[0]>MAXXLIST[-1]:
ANS=min(ANS,(MAXX-MINX)*(MAXY-MINY+1))
if MAXY-MINY>1:
if MAXYLIST[0]>MINYLIST[-1] or MINYLIST[0]>MAXYLIST[-1]:
ANS=min(ANS,(MAXX-MINX+1)*(MAXY-MINY))
print(ANS)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
T = int(input())
for _ in range(T):
s = input()
cleft=cup=cdown=cright=0
left=up=down=right=0
fleft=lleft=0
fright=lright=0
fup=lup=0
fdown=ldown=0
x=y=0
for i, c in enumerate(s):
if c=="W":
y -= 1
cup += 1
elif c=="S":
y += 1
cdown += 1
elif c=="A":
x -= 1
cleft += 1
elif c=="D":
x += 1
cright += 1
if x == left:
lleft = i
if x == right:
lright = i
if y == down:
ldown = i
if y == up:
lup = i
if x < left:
left = x
fleft=i
lleft=i
if x > right:
right = x
fright=i
lright=i
if y < up:
up = y
fup=i
lup=i
if y > down:
down = y
fdown=i
ldown=i
width = right - left + 1
height = down - up + 1
best = width * height
if height > 2:
if ldown < fup or lup < fdown:
best = min(best, width * (height-1))
if width > 2:
if lleft < fright or lright < fleft:
best = min(best, (width-1) * height)
print(best)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
t = int(input())
for _ in range(t):
s = input()
n = len(s)
fa, fd, fs, fw = [0], [0], [0], [0]
ba, bd, bs, bw = [0], [0], [0], [0]
cur = [0, 0]
for i in range(n):
if s[i] == "A":
cur[0] -= 1
elif s[i] == "D":
cur[0] += 1
elif s[i] == "S":
cur[1] -= 1
elif s[i] == "W":
cur[1] += 1
fa.append(min(fa[-1], cur[0]))
fd.append(max(fd[-1], cur[0]))
fs.append(min(fs[-1], cur[1]))
fw.append(max(fw[-1], cur[1]))
h = fd[-1]-fa[-1]
v = fw[-1]-fs[-1]
area = (h+1)*(v+1)
cur = [0, 0]
for i in range(n-1, -1, -1):
if s[i] == "D":
cur[0] -= 1
elif s[i] == "A":
cur[0] += 1
elif s[i] == "W":
cur[1] -= 1
elif s[i] == "S":
cur[1] += 1
ba.append(min(ba[-1], cur[0]))
bd.append(max(bd[-1], cur[0]))
bs.append(min(bs[-1], cur[1]))
bw.append(max(bw[-1], cur[1]))
ba.reverse()
bd.reverse()
bs.reverse()
bw.reverse()
#print(fa, fd, fs, fw)
#print(ba, bd, bs, bw)
hok, vok = False, False
for i in range(1, n):
#print(n, i)
if fd[i]-fa[i] < h and abs(bd[i]-ba[i]) < h:
hok = True
if fw[i]-fs[i] < v and abs(bw[i]-bs[i]) < v:
vok = True
if hok:
area = min(area, h*(v+1))
if vok:
area = min(area, v*(h+1))
print(area)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
for q in range(int(input())):
data = input()
# if data in ["WW", "AA", "SS", "DD"]:
# print(2)
# continue
mx = [0,0,0,0]
x = 0
y = 0
pos = [[-1],[-1],[-1],[-1]]
for i in range(len(data)):
# print(x,y)
d = data[i]
if d == "W":
y += 1
if y > mx[0]:
mx[0] = y
pos[0] = []
elif d == "S":
y -= 1
if y < mx[2]:
mx[2] = y
pos[2] = []
elif d == "A":
x -= 1
if x < mx[1]:
mx[1] = x
pos[1] = []
else:
x += 1
if x > mx[3]:
mx[3] = x
pos[3] = []
if x == mx[3]:
pos[3].append(i)
if x == mx[1]:
pos[1].append(i)
if y == mx[0]:
pos[0].append(i)
if y == mx[2]:
pos[2].append(i)
# print(mx)
# print(pos)
wid = mx[3] - mx[1] + 1
hei = mx[0] - mx[2] + 1
ans = wid * hei
if pos[3][0] > pos[1][-1] + 1 or pos[1][0] > pos[3][-1] + 1:
ans -= hei
if pos[0][0] > pos[2][-1] + 1 or pos[2][0] > pos[0][-1] + 1:
ans = min((hei-1)*(wid), ans)
print(ans)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
T = int(input())
w = [[-1, 0], [1, 0], [0, 1], [0, -1]]
mp = {'A':0, 'D':1, 'W':2, 'S':3}
while T > 0:
T-=1
s = input()
l = [0]; r = [0];
u = [0]; d = [0];
for dir in s[::-1]:
l.append(l[-1])
r.append(r[-1])
u.append(u[-1])
d.append(d[-1])
if dir == 'A':
l[-1]+=1
if r[-1] > 0: r[-1]-=1
elif dir == 'D':
r[-1]+=1
if l[-1] > 0: l[-1]-=1
elif dir == 'S':
d[-1]+=1
if u[-1] > 0: u[-1]-=1
else:
u[-1]+=1
if d[-1] > 0: d[-1]-=1
l = l[::-1]; r = r[::-1]; u = u[::-1]; d = d[::-1];
x = 0; y = 0
ml = 0; mr = 0; mu = 0; md = 0;
ans = (l[0] + r[0] + 1) * (u[0] + d[0] + 1)
for i in range(len(s)+1):
mml=ml;mmr=mr;mmu=mu;mmd=md;
for j in range(4):
xx=x+w[j][0]
yy=y+w[j][1]
if xx<0: ml=max(ml,-xx)
if xx>0: mr=max(mr,xx)
if yy>0: mu=max(mu,yy)
if yy<0: md=max(md,-yy)
xx-=l[i]
if xx<0: ml=max(ml,-xx)
xx+=r[i]+l[i];
if xx>0: mr=max(mr,xx)
yy-=d[i]
if yy<0: md=max(md,-yy)
yy+=u[i]+d[i]
if yy>0: mu=max(mu,yy)
ans = min(ans, (ml+mr+1)*(mu+md+1))
ml=mml;mr=mmr;mu=mmu;md=mmd;
if i < len(s):
x+=w[mp[s[i]]][0]
y+=w[mp[s[i]]][1]
if x<0: ml=max(ml,-x)
if x>0: mr=max(mr,x)
if y>0: mu=max(mu,y)
if y<0: md=max(md,-y)
print(ans)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
import sys
from collections import defaultdict
input = sys.stdin.readline
import math
def main():
t = int(input())
for _ in range(t):
s = input().rstrip()
a1 = []
a2 = []
ws = {'W': 1, 'S': -1}
ad = {'A': 1, 'D': -1}
for c in s:
if c in ('W', 'S'):
a1.append(ws[c])
else:
a2.append(ad[c])
pref_a1 = [0] + a1.copy()
pref_a2 = [0] + a2.copy()
for i in range(1, len(pref_a1)):
pref_a1[i] += pref_a1[i-1]
for i in range(1, len(pref_a2)):
pref_a2[i] += pref_a2[i-1]
def canDecrease(a):
_min = min(a)
_max = max(a)
# decrease max
_min_rindex = a.index(_min)
for i in range(_min_rindex, len(a)):
if a[i] == _min:
_min_rindex = i
_max_index = a.index(_max)
if _max_index > _min_rindex:
return True
# increase min
_max_rindex = a.index(_max)
for i in range(_max_rindex, len(a)):
if a[i] == _max:
_max_rindex = i
_min_index = a.index(_min)
if _max_rindex < _min_index:
return True
return False
x = max(pref_a1)-min(pref_a1)
y = max(pref_a2)-min(pref_a2)
res = (x+1) * (y+1)
if x > 1 and canDecrease(pref_a1):
res = min(res, x * (y+1))
if y > 1 and canDecrease(pref_a2):
res = min(res, (x+1) * y)
print(res)
def __starting_point():
main()
__starting_point()
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
for i in range(int(input())):
s = input()
lm, rm, um, dm = 0, 0, 0, 0
xp, yp = 0, 0
for ch in s:
if ch == 'W':
yp += 1
elif ch == 'A':
xp -= 1
elif ch == 'S':
yp -= 1
else:
xp += 1
lm = min(lm, xp)
rm = max(rm, xp)
um = max(um, yp)
dm = min(dm, yp)
xp, yp = 0, 0
lmfSet, rmfSet, umfSet, dmfSet = 0, 0, 0, 0
if lm == 0:
lml = 0
lmf = 0
lmfSet = 1
if rm == 0:
rml = 0
rmf = 0
rmfSet = 1
if um == 0:
uml = 0
umf = 0
umfSet = 1
if dm == 0:
dml = 0
dmf = 0
dmfSet = 1
for i, ch in zip(list(range(1, len(s) + 1)), s):
if ch == 'W':
yp += 1
elif ch == 'A':
xp -= 1
elif ch == 'S':
yp -= 1
else:
xp += 1
if xp == lm:
lml = i
if not lmfSet:
lmf = i
lmfSet = 1
if xp == rm:
rml = i
if not rmfSet:
rmf = i
rmfSet = 1
if yp == um:
uml = i
if not umfSet:
umf = i
umfSet = 1
if yp == dm:
dml = i
if not dmfSet:
dmf = i
dmfSet = 1
canx, cany = 0, 0
if dml + 1 < umf or uml + 1 < dmf:
cany = 1
if lml + 1 < rmf or rml + 1 < lmf:
canx = 1
if canx:
if cany:
print(min((um - dm) * (rm - lm + 1), (um - dm + 1) * (rm - lm)))
else:
print((rm - lm) * (um - dm + 1))
else:
if cany:
print((um - dm) * (rm - lm + 1))
else:
print((rm - lm + 1) * (um - dm + 1))
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
t=int(input())
def possible(presum):
l=len(presum)
lastmax=-1
firstmin=l
mx=max(presum)
mn=min(presum)
for i in range(l):
if(mx==presum[i]):
lastmax=max(lastmax,i)
if(mn==presum[i]):
firstmin=min(i,firstmin)
if lastmax<firstmin:
return True
return False
for i in range(t):
s=input()
l1=[0]
l2=[0]
for i in s:
if i=='S':
l1.append(l1[-1]-1)
elif i=='W':
l1.append(l1[-1]+1)
elif i=="D":
l2.append(l2[-1]+1)
else:
l2.append(l2[-1]-1)
length=max(l1)-min(l1)+1
breadth=max(l2)-min(l2)+1
ans=length*breadth
if length>2 and possible(l1):
ans=min(ans,(length-1)*breadth)
for i in range(len(l1)):
l1[i]*=-1
if length>2 and possible(l1):
ans=min(ans,(length-1)*breadth)
if breadth>2 and possible(l2):
ans=min(ans,(length)*(breadth-1))
for i in range(len(l2)):
l2[i]*=-1
if breadth>2 and possible(l2):
ans=min(ans,(length)*(breadth-1))
print(ans)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
def lim(s):
now = 0
up, down = 0, 0
for i in s:
now += i
up = max(up, now)
down = min(down, now)
return up, down
def f(a):
return a[0] - a[1] + 1
def upg(s):
t = lim(s)
up, down = t[0], t[1]
arr = [1, 1]
now = 0
for i in range(len(s) - 1):
if now == up - 1 and s[i + 1] == 1 and arr[0] == 1:
arr[0] = 0
if f(lim(s[:(i + 1)] + [-1] + s[(i + 1):])) < f(t):
return 1
if now == down + 1 and s[i + 1] == -1 and arr[1] == 1:
arr[1] = 0
if f(lim(s[:(i + 1)] + [1] + s[(i + 1):])) < f(t):
return 1
now += s[i + 1]
return 0
for q in range(int(input())):
s = input()
s1, s2 = [0], [0]
for i in s:
if i == 'W': s1.append(1)
if i == 'S': s1.append(-1)
if i == 'A': s2.append(1)
if i == 'D': s2.append(-1)
u1 = upg(s1)
u2 = upg(s2)
res1, res2 = f(lim(s1)), f(lim(s2))
ans = min((res1 - u1) * res2, (res2 - u2) * res1)
print(ans)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
t= int(input())
for _ in range(0,t):
a= list(input())
nowx=0
nowy=0
maxx=0
minx=0
maxy=0
miny=0
tmaxx=0
tminx=0
tmaxy=0
tminy=0
highw=0
highs=0
widthd=0
widtha=0
for i in range (0,len(a)):
if a[i] == 'W':
nowy += 1
if nowy >= maxy:
maxy=nowy
tmaxy=i
elif a[i] == 'S':
nowy -= 1
if nowy <=miny:
miny=nowy
tminy=i
elif a[i] == 'D':
nowx += 1
if nowx >= maxx:
maxx=nowx
tmaxx=i
elif a[i] == 'A':
nowx -= 1
if nowx <=minx:
minx=nowx
tminx=i
highw= max(highw,nowy-miny)
highs= max(highs,maxy-nowy)
widthd=max(widthd,nowx-minx)
widtha=max(widtha,maxx-nowx)
y1= max(highw,highs)
y2= max(highw!=0 or highs!=0, y1- ((highw!=highs)))
x1= max(widthd,widtha)
x2= max(widthd!=0 or widtha!=0, x1-((widthd!=widtha)))
print(min((y1+1)*(x2+1),(1+y2)*(x1+1)))
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
t = int(input())
for _ in range(t):
ss = input()
minx=0
fminxpos = -1
lminxpos = -1
maxx=0
fmaxxpos = -1
lmaxxpos = -1
miny=0
fminypos = -1
lminypos = -1
maxy=0
fmaxypos = -1
lmaxypos = -1
x = 0
y = 0
for i,s in enumerate(ss):
if s == 'W':
y +=1
if y > maxy:
maxy=y
fmaxypos=i
if y == maxy:
lmaxypos=i
elif s == 'S':
y -= 1
if y < miny:
miny = y
fminypos = i
if y == miny:
lminypos = i
elif s == 'D':
lastd = i
x += 1
if x > maxx:
maxx = x
fmaxxpos = i
if x == maxx:
lmaxxpos = i
elif s == 'A':
lasta = i
x -= 1
if x < minx:
minx = x
fminxpos = i
if x == minx:
lminxpos = i
xsize = maxx - minx + 1
ysize = maxy - miny + 1
if xsize > 2 and (fmaxxpos > lminxpos or fminxpos > lmaxxpos):
xmin = xsize - 1
else:
xmin = xsize
if ysize > 2 and (fmaxypos > lminypos or fminypos > lmaxypos):
ymin = ysize - 1
else:
ymin = ysize
print(min(xmin*ysize, xsize*ymin))
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
T = int(input())
for _ in range(T):
cmd = input()
mostL, mostR, mostB, mostT = 0, 0, 0, 0
mostLs, mostRs, mostBs, mostTs = [0],[0],[0],[0]
x,y=0,0
i = 0
for c in cmd:
i += 1
if c == "W":
y += 1
if y>mostT:
mostT = y
mostTs = [i]
elif y == mostT:
mostTs.append(i)
elif c == "S":
y -= 1
if y<mostB:
mostB = y
mostBs = [i]
elif y == mostB:
mostBs.append(i)
elif c == "A":
x -= 1
if x < mostL:
mostL = x
mostLs = [i]
elif x == mostL:
mostLs.append(i)
elif c == "D":
x += 1
if x > mostR:
mostR = x
mostRs = [i]
elif x == mostR:
mostRs.append(i)
LR = mostR - mostL + 1
if LR >= 3:
firstL, lastL = mostLs[0], mostLs[-1]
firstR, lastR = mostRs[0], mostRs[-1]
cross = lastR > firstL and lastL > firstR
LR_extra = not cross
else:
LR_extra = False
BT = mostT - mostB + 1
if BT >= 3:
firstB, lastB = mostBs[0], mostBs[-1]
firstT, lastT = mostTs[0], mostTs[-1]
cross = lastB > firstT and lastT > firstB
BT_extra = not cross
else:
BT_extra = False
if LR_extra and BT_extra:
area = min((LR-1)*BT,LR*(BT-1))
elif LR_extra:
area = (LR-1)*BT
elif BT_extra:
area = LR*(BT-1)
else:
area = LR*BT
print(area)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
def main():
hh, vv, r = [0], [0], []
f = {'W': (vv, -1), 'S': (vv, 1), 'A': (hh, -1), 'D': (hh, 1)}.get
for _ in range(int(input())):
del vv[1:], hh[1:], r[:]
for l, d in map(f, input()):
l.append(l[-1] + d)
for l in hh, vv:
mi, ma = min(l), max(l)
a, tmp = mi - 1, []
for b in filter((mi, ma).__contains__, l):
if a != b:
a = b
tmp.append(a)
ma -= mi - 1
r.append(ma)
if len(tmp) < 3 <= ma:
ma -= 1
r.append(ma)
print(min((r[0] * r[3], r[1] * r[2])))
def __starting_point():
main()
__starting_point()
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
def main():
h, v = hv = ([0], [0])
f = {'W': (v, -1), 'S': (v, 1), 'A': (h, -1), 'D': (h, 1)}.get
for _ in range(int(input())):
del h[1:], v[1:]
for l, d in map(f, input()):
l.append(l[-1] + d)
x = y = 1
for l in hv:
lh, a, n = (min(l), max(l)), 200001, 0
for b in filter(lh.__contains__, l):
if a != b:
a = b
n += 1
le = lh[1] - lh[0] + 1
x, y = y * le, x * (le - (n < 3 <= le))
print(x if x < y else y)
def __starting_point():
main()
__starting_point()
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
t = int(input())
for c in range(t):
s = input()
up_max = down_max = right_max = left_max = 0
first_up = last_up = first_down = last_down = first_left = last_left = first_right = last_right = 0
current_x = current_y = 0
horizontal_count = vertical_count = 0
for i in range(len(s)):
if s[i] == 'W':
current_y += 1
vertical_count += 1
if current_y > up_max:
up_max = current_y
first_up = last_up = i + 1
elif current_y == up_max:
last_up = i + 1
elif s[i] == 'S':
current_y -= 1
vertical_count += 1
if current_y < down_max:
down_max = current_y
first_down = last_down = i + 1
elif current_y == down_max:
last_down = i + 1
elif s[i] == 'D':
current_x += 1
horizontal_count += 1
if current_x > right_max:
right_max = current_x
first_right = last_right = i + 1
elif current_x == right_max:
last_right = i + 1
else:
current_x -= 1
horizontal_count += 1
if current_x < left_max:
left_max = current_x
first_left = last_left = i + 1
elif current_x == left_max:
last_left = i + 1
h = up_max - down_max + 1
w = right_max - left_max + 1
ans = h * w
if vertical_count > 1 and last_up < first_down:
ans = min(ans, (h - 1) * w)
if vertical_count > 1 and last_down < first_up:
ans = min(ans, (h - 1) * w)
if horizontal_count > 1 and last_right < first_left:
ans = min(ans, h * (w - 1))
if horizontal_count > 1 and last_left < first_right:
ans = min(ans, h * (w - 1))
print(ans)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
q = int(input())
for _ in range(q):
d = [x for x in list(input())]
x, y = 0, 0
minX, maxX, minY, maxY = 0, 0 ,0 ,0
allowW, allowS, allowA, allowD = True, True, True, True
for v in d:
if v == 'W':
y += 1
if y > maxY:
maxY = y
allowS = True
allowW = False
elif y == maxY:
allowW = False
elif v == 'S':
y -= 1
if y < minY:
minY = y
allowW = True
allowS = False
elif y == minY:
allowS = False
elif v == 'A':
x -= 1
if x < minX:
minX = x
allowA = False
allowD = True
elif x == minX:
allowA = False
else:#if v == 'D':
x += 1
if x > maxX:
maxX = x
allowA = True
allowD = False
elif x == maxX:
allowD = False
val = (maxX-minX+1)*(maxY-minY+1)
if (maxX-minX) > 1 and (allowD or allowA):
val = min(val, (maxX-minX)*(maxY-minY+1))
if (maxY-minY) > 1 and (allowW or allowS):
val = min(val, (maxX-minX+1)*(maxY-minY))
print(val)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
# coding=utf-8
INF = 1e11
# move = {'W': (0, 0), 'A': (0, 0), 'S': (0, 0), 'D': (0, 0)}
move = {'W': (0, 1), 'A': (-1, 0), 'S': (0, -1), 'D': (1, 0)}
def getExtremes(positions):
minX, minY, maxX, maxY = [positions[0][0]], [positions[0][1]], [positions[0][0]], [positions[0][1]]
for p in positions[1:]:
minX.append(min(minX[-1], p[0]))
minY.append(min(minY[-1], p[1]))
maxX.append(max(maxX[-1], p[0]))
maxY.append(max(maxY[-1], p[1]))
return minX, minY, maxX, maxY
t = int(input())
while t > 0:
t -= 1
s = input()
x, y = 0, 0
positions = [(0, 0)]
for c in s:
x, y = x + move[c][0], y + move[c][1]
positions.append((x, y))
# print(positions)
# print()
minXBeg, minYBeg, maxXBeg, maxYBeg = getExtremes(positions)
# print(minXBeg, minYBeg, maxXBeg, maxYBeg, sep="\n")
# print()
positions.reverse()
minXEnd, minYEnd, maxXEnd, maxYEnd = getExtremes(positions)
minXEnd.reverse()
minYEnd.reverse()
maxXEnd.reverse()
maxYEnd.reverse()
# print(minXEnd, minYEnd, maxXEnd, maxYEnd, sep="\n")
# print()
positions.reverse()
ans = INF
for i in range(len(s)):
for c in move:
minX = min(minXBeg[i], positions[i][0] + move[c][0], minXEnd[i + 1] + move[c][0])
maxX = max(maxXBeg[i], positions[i][0] + move[c][0], maxXEnd[i + 1] + move[c][0])
minY = min(minYBeg[i], positions[i][1] + move[c][1], minYEnd[i + 1] + move[c][1])
maxY = max(maxYBeg[i], positions[i][1] + move[c][1], maxYEnd[i + 1] + move[c][1])
area = (maxX - minX + 1) * (maxY - minY + 1)
# print(i, c, minX, maxX, minY, maxY, area)
ans = min(ans, area)
print(ans)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
def solve():
i = 0
j = 0
imax = imin = 0
jmax = jmin = 0
fjmin = ljmin = fjmax = ljmax = fimax = limax = fimin = limin = -1
for ind, e in enumerate(input()):
if e == 'W':
i += 1
if i > imax:
imax = i
fimax = ind
limax = ind
elif e == 'S':
i -= 1
if i < imin:
imin = i
fimin = ind
limin = ind
elif e == "A":
j -= 1
if j < jmin:
jmin = j
fjmin = ind
ljmin = ind
elif e == 'D':
j += 1
if j > jmax:
jmax = j
fjmax = ind
ljmax = ind
if j == jmin:
ljmin = ind
if j == jmax:
ljmax = ind
if i == imin:
limin = ind
if i == imax:
limax = ind
ans = 0
if fjmax > ljmin + 1 or fjmin > ljmax + 1:
ans = imax - imin + 1
if fimax > limin + 1 or fimin > limax + 1:
ans = max(ans, jmax - jmin + 1)
print((imax - imin + 1) * (jmax - jmin + 1) - ans)
for _ in range(int(input())):
solve()
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
import sys
input = sys.stdin.readline
Q = int(input())
Query = [list(input().rstrip()) for _ in range(Q)]
for S in Query:
L = len(S)
T = [(0, 0)]
for s in S:
x, y = T[-1]
if s == "W":
T.append((x, y+1))
elif s == "S":
T.append((x, y-1))
elif s == "A":
T.append((x-1, y))
else:
T.append((x+1, y))
# up, down, left, right
dp1 = [[0, 0, 0, 0] for _ in range(L+1)]
for i, (x, y) in enumerate(T):
if i == 0: continue
dp1[i][0] = max(y, dp1[i-1][0])
dp1[i][1] = min(y, dp1[i-1][1])
dp1[i][2] = min(x, dp1[i-1][2])
dp1[i][3] = max(x, dp1[i-1][3])
lx, ly = T[-1]
dp2 = [[ly, ly, lx, lx] for _ in range(L+1)]
for i in reversed(range(L)):
x, y = T[i]
dp2[i][0] = max(y, dp2[i+1][0])
dp2[i][1] = min(y, dp2[i+1][1])
dp2[i][2] = min(x, dp2[i+1][2])
dp2[i][3] = max(x, dp2[i+1][3])
Y, X = dp1[L][0]-dp1[L][1]+1, dp1[L][3]-dp1[L][2]+1
ans = 0
for i in range(L):
if dp1[i][0] < dp2[i][0] and dp1[i][1] < dp2[i][1]:
ans = max(ans, X)
if dp1[i][0] > dp2[i][0] and dp1[i][1] > dp2[i][1]:
ans = max(ans, X)
if dp1[i][2] < dp2[i][2] and dp1[i][3] < dp2[i][3]:
ans = max(ans, Y)
if dp1[i][2] > dp2[i][2] and dp1[i][3] > dp2[i][3]:
ans = max(ans, Y)
print(X*Y-ans)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
def read_int():
return int(input())
def read_ints():
return list(map(int, input().split(' ')))
t = read_int()
INF = int(1e7)
for case_num in range(t):
s = input()
x = 0
y = 0
xlist = [0]
ylist = [0]
for c in s:
if c == 'W':
y += 1
elif c == 'S':
y -= 1
elif c == 'A':
x -= 1
else:
x += 1
xlist.append(x)
ylist.append(y)
n = len(s)
l = [0]
r = [0]
u = [0]
d = [0]
for i in range(1, n + 1):
l.append(min(l[-1], xlist[i]))
r.append(max(r[-1], xlist[i]))
u.append(max(u[-1], ylist[i]))
d.append(min(d[-1], ylist[i]))
lr = [xlist[n]]
rr = [xlist[n]]
ur = [ylist[n]]
dr = [ylist[n]]
for i in range(1, n + 1):
lr.append(min(lr[-1], xlist[n - i]))
rr.append(max(rr[-1], xlist[n - i]))
ur.append(max(ur[-1], ylist[n - i]))
dr.append(min(dr[-1], ylist[n - i]))
ans = INF * INF
coeff = [[-1, 0], [1, 0], [0, -1], [0, 1]]
for k in range(4):
for i in range(n):
nl = min(l[i], lr[n - i] + coeff[k][0])
nr = max(r[i], rr[n - i] + coeff[k][0])
nu = max(u[i], ur[n - i] + coeff[k][1])
nd = min(d[i], dr[n - i] + coeff[k][1])
area = (nr - nl + 1) * (nu - nd + 1)
ans = min(ans, area)
print(ans)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
import sys
input = sys.stdin.readline
for _ in range(int(input())):
s = input()
l, r, u, d, fl, fr, fu, fd, x, y = [0] * 10
for i in range(len(s)):
if s[i] == 'W':
y += 1
if y > u:
u = y
fd = 0
fu = 1
if y == u:
fu = 1
elif s[i] == 'A':
x -= 1
if x < l:
l = x
fl = 1
fr = 0
if x == l:
fl = 1
elif s[i] == 'S':
y -= 1
if y < d:
d = y
fd = 1
fu = 0
if y == d:
fd = 1
elif s[i] == 'D':
x += 1
if x > r:
r = x
fr = 1
fl = 0
if x == r:
fr = 1
#bless Ctrl+C Ctrl+V
x, y = r - l + 1, u - d + 1
s, k = x * y, x * y
if x > 2 and not fl * fr:
s = k - y
if y > 2 and not fu * fd and k - x < s:
s = k - x
print(s)
|
You have a string $s$ β a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β move one cell up; 'S' β move one cell down; 'A' β move one cell left; 'D' β move one cell right.
Let $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \text{DSAWWAW}$ then $Grid(s)$ is the $4 \times 3$ grid: you can place the robot in the cell $(3, 2)$; the robot performs the command 'D' and moves to $(3, 3)$; the robot performs the command 'S' and moves to $(4, 3)$; the robot performs the command 'A' and moves to $(4, 2)$; the robot performs the command 'W' and moves to $(3, 2)$; the robot performs the command 'W' and moves to $(2, 2)$; the robot performs the command 'A' and moves to $(2, 1)$; the robot performs the command 'W' and moves to $(1, 1)$. [Image]
You have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $s$ to minimize the area of $Grid(s)$.
What is the minimum area of $Grid(s)$ you can achieve?
-----Input-----
The first line contains one integer $T$ ($1 \le T \le 1000$) β the number of queries.
Next $T$ lines contain queries: one per line. This line contains single string $s$ ($1 \le |s| \le 2 \cdot 10^5$, $s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$) β the sequence of commands.
It's guaranteed that the total length of $s$ over all queries doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers: one per query. For each query print the minimum area of $Grid(s)$ you can achieve.
-----Example-----
Input
3
DSAWWAW
D
WA
Output
8
2
4
-----Note-----
In the first query you have to get string $\text{DSAWW}\underline{D}\text{AW}$.
In second and third queries you can not decrease the area of $Grid(s)$.
|
import sys
def work(c,c1, s):
maxlast, maxfirst,minlast,minfirst = 0,0,0,0
max = 0
min = 0
y = 0
for i in range(len(s)):
if s[i] == c:
y += 1
elif s[i] == c1:
y -=1
if max < y:
maxfirst,maxlast = i,i
max = y
elif max ==y :
maxlast = i
if y < min:
minlast,minfirst =i,i
min = y
elif min == y:
minlast = i
flag = 0
if (maxlast<minfirst or maxfirst>minlast) and max-min > 1:
flag = 1
return max-min+1,flag
count = 0
for line in sys.stdin:
if count == 0:
n = int(line.strip().split(' ')[0])
#k = int(line.strip().split(' ')[1])
#m = int(line.strip().split(' ')[2])
count += 1
continue
s = line.strip()
flag,flag1 =0,0
n,flag = work('W','S', s)
m,flag1 = work('A', 'D', s)
res = n * m
if flag1 and flag:
res = min(n*(m-1),m*(n-1))
elif flag:
res = m*(n-1)
elif flag1:
res = (m-1)*n
print(res)
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.
Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.
For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.
Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) Β β the length of arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$) Β β elements of array $a$. There can be duplicates among elements.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) Β β elements of array $b$. There can be duplicates among elements.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible.
You can print each letter in any case (upper or lower).
-----Example-----
Input
5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
Output
YES
NO
YES
YES
NO
-----Note-----
In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$
In the second test case we can't make equal numbers on the second position.
In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case.
In the last lest case, it is impossible to make array $a$ equal to the array $b$.
|
from math import *
mod = 1000000007
for zz in range(int(input())):
n = int(input())
a = [ int(i) for i in input().split()]
b = [int(i) for i in input().split()]
ha = True
hp = False
hm = False
for i in range(n):
if b[i] != a[i]:
if b[i] > a[i]:
if (hp):
pass
else:
ha = False
break
else:
if (hm):
pass
else:
ha = False
break
if a[i] > 0:
hp = True
elif a[i] < 0:
hm = True
if ha:
print('YES')
else:
print('NO')
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.
Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.
For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.
Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) Β β the length of arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$) Β β elements of array $a$. There can be duplicates among elements.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) Β β elements of array $b$. There can be duplicates among elements.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible.
You can print each letter in any case (upper or lower).
-----Example-----
Input
5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
Output
YES
NO
YES
YES
NO
-----Note-----
In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$
In the second test case we can't make equal numbers on the second position.
In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case.
In the last lest case, it is impossible to make array $a$ equal to the array $b$.
|
t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
d1 = False
d2 = False
ans = True
for j in range(n):
if a[j] > b[j]:
if not d1:
ans = False
if a[j] < b[j]:
if not d2:
ans = False
if a[j] == -1:
d1 = True
elif a[j] == 1:
d2 = True
if ans:
print("YES")
else:
print("NO")
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.
Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.
For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.
Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) Β β the length of arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$) Β β elements of array $a$. There can be duplicates among elements.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) Β β elements of array $b$. There can be duplicates among elements.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible.
You can print each letter in any case (upper or lower).
-----Example-----
Input
5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
Output
YES
NO
YES
YES
NO
-----Note-----
In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$
In the second test case we can't make equal numbers on the second position.
In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case.
In the last lest case, it is impossible to make array $a$ equal to the array $b$.
|
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
pos = neg = False
ok = True
for i in range(n):
if a[i] > b[i] and not neg:
ok = False
break
if a[i] < b[i] and not pos:
ok = False
break
if a[i] == -1:
neg = True
if a[i] == 1:
pos = True
print('YES' if ok else 'NO')
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.
Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.
For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.
Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) Β β the length of arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$) Β β elements of array $a$. There can be duplicates among elements.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) Β β elements of array $b$. There can be duplicates among elements.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible.
You can print each letter in any case (upper or lower).
-----Example-----
Input
5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
Output
YES
NO
YES
YES
NO
-----Note-----
In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$
In the second test case we can't make equal numbers on the second position.
In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case.
In the last lest case, it is impossible to make array $a$ equal to the array $b$.
|
from math import *
for t in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
cnt1 = 0
cnt0 = 0
cntotr = 0
f = True
for i in range(n):
if a[i] > b[i]:
if cntotr == 0:
f = False
break
if a[i] < b[i]:
if cnt1 == 0:
f = False
break
if a[i] == 0:
cnt0 += 1
elif a[i] == 1:
cnt1 += 1
else:
cntotr += 1
if f:
print("YES")
else:
print("NO")
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.
Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.
For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.
Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) Β β the length of arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$) Β β elements of array $a$. There can be duplicates among elements.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) Β β elements of array $b$. There can be duplicates among elements.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible.
You can print each letter in any case (upper or lower).
-----Example-----
Input
5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
Output
YES
NO
YES
YES
NO
-----Note-----
In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$
In the second test case we can't make equal numbers on the second position.
In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case.
In the last lest case, it is impossible to make array $a$ equal to the array $b$.
|
t = int(input())
for _ in range(t):
n = int(input())
A = map(int, input().split())
B = map(int, input().split())
seen_pos = seen_neg = False
for a, b in zip(A, B):
if (b > a and not seen_pos) or (b < a and not seen_neg):
print('NO')
break
if a > 0:
seen_pos = True
elif a < 0:
seen_neg = True
else:
print('YES')
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.
Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.
For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.
Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) Β β the length of arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$) Β β elements of array $a$. There can be duplicates among elements.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) Β β elements of array $b$. There can be duplicates among elements.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible.
You can print each letter in any case (upper or lower).
-----Example-----
Input
5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
Output
YES
NO
YES
YES
NO
-----Note-----
In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$
In the second test case we can't make equal numbers on the second position.
In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case.
In the last lest case, it is impossible to make array $a$ equal to the array $b$.
|
import math
from collections import defaultdict
ml=lambda:map(int,input().split())
ll=lambda:list(map(int,input().split()))
ii=lambda:int(input())
ip=lambda:input()
"""========main code==============="""
t=ii()
for _ in range(t):
x=ii()
a=ll()
b=ll()
one=-1
minus=-1
f=0
for i in range(x):
if(b[i]>a[i]):
if(one==-1):
f=1
break
elif (b[i]<a[i]):
if(minus==-1):
f=1
break
if(a[i]==1):
one=1
elif(a[i]==-1):
minus=1
if(f):
print("NO")
else:
print("YES")
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.
Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.
For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.
Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) Β β the length of arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$) Β β elements of array $a$. There can be duplicates among elements.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) Β β elements of array $b$. There can be duplicates among elements.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible.
You can print each letter in any case (upper or lower).
-----Example-----
Input
5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
Output
YES
NO
YES
YES
NO
-----Note-----
In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$
In the second test case we can't make equal numbers on the second position.
In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case.
In the last lest case, it is impossible to make array $a$ equal to the array $b$.
|
t=int(input())
for _ in range(t):
n=int(input())
a=list(map(int, input().split()))
b=list(map(int, input().split()))
grow = shrink = False
for ai, bi in zip(a,b):
if bi < ai:
if not shrink:
print('NO')
break
elif bi > ai and not grow:
print('NO')
break
if ai == 1:
grow = True
elif ai == -1:
shrink = True
else:
print('YES')
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.
Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.
For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.
Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) Β β the length of arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$) Β β elements of array $a$. There can be duplicates among elements.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) Β β elements of array $b$. There can be duplicates among elements.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible.
You can print each letter in any case (upper or lower).
-----Example-----
Input
5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
Output
YES
NO
YES
YES
NO
-----Note-----
In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$
In the second test case we can't make equal numbers on the second position.
In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case.
In the last lest case, it is impossible to make array $a$ equal to the array $b$.
|
t = int(input())
for case_num in range(t):
n = int(input())
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))
pos = False
neg = False
ok = True
for i in range(n):
if (not pos) and (not neg) and (a[i] != b[i]):
ok = False
break
if (not pos) and (a[i] < b[i]):
ok = False
break
if (not neg) and (a[i] > b[i]):
ok = False
break
if a[i] < 0:
neg = True
if a[i] > 0:
pos = True
print('YES' if ok else 'NO')
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.
Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.
For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.
Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) Β β the length of arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$) Β β elements of array $a$. There can be duplicates among elements.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) Β β elements of array $b$. There can be duplicates among elements.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible.
You can print each letter in any case (upper or lower).
-----Example-----
Input
5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
Output
YES
NO
YES
YES
NO
-----Note-----
In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$
In the second test case we can't make equal numbers on the second position.
In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case.
In the last lest case, it is impossible to make array $a$ equal to the array $b$.
|
import math
def main():
was = set()
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(n):
if a[i] - b[i] > 0:
if not -1 in was:
print("NO")
return
elif a[i] - b[i] < 0:
if not 1 in was:
print("NO")
return
was.add(a[i])
print("YES")
def __starting_point():
t = int(input())
for i in range(t):
main()
__starting_point()
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.
Anton can perform the following sequence of operations any number of times: Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once. Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.
For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.
Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) Β β the length of arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$) Β β elements of array $a$. There can be duplicates among elements.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) Β β elements of array $b$. There can be duplicates among elements.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible.
You can print each letter in any case (upper or lower).
-----Example-----
Input
5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
Output
YES
NO
YES
YES
NO
-----Note-----
In the first test-case we can choose $(i, j)=(2, 3)$ twice and after that choose $(i, j)=(1, 2)$ twice too. These operations will transform $[1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]$
In the second test case we can't make equal numbers on the second position.
In the third test case we can choose $(i, j)=(1, 2)$ $41$ times. The same about the fourth test case.
In the last lest case, it is impossible to make array $a$ equal to the array $b$.
|
from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
from fractions import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 300010
MOD = 10**9+7
spf = [i for i in range(MAXN)]
spf[0]=spf[1] = -1
def sieve():
for i in range(2,MAXN,2):
spf[i] = 2
for i in range(3,int(MAXN**0.5)+1):
if spf[i]==i:
for j in range(i*i,MAXN,i):
if spf[j]==j:
spf[j]=i
def fib(n,m):
if n == 0:
return [0, 1]
else:
a, b = fib(n // 2)
c = ((a%m) * ((b%m) * 2 - (a%m)))%m
d = ((a%m) * (a%m))%m + ((b)%m * (b)%m)%m
if n % 2 == 0:
return [c, d]
else:
return [d, c + d]
def charIN(x= ' '):
return(sys.stdin.readline().strip().split(x))
def arrIN(x = ' '):
return list(map(int,sys.stdin.readline().strip().split(x)))
def ncr(n,r):
num=den=1
for i in range(r):
num = (num*(n-i))%MOD
den = (den*(i+1))%MOD
return (num*(pow(den,MOD-2,MOD)))%MOD
def flush():
return sys.stdout.flush()
'''*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*'''
def solve():
n = int(input())
a = arrIN()
b = arrIN()
x = [[0,0,0] for i in range(n)]
for i in range(n):
x[i][0] = int(a[i]==-1)
x[i][1] = int(a[i]==0)
x[i][2] = int(a[i]==1)
x[i][0]|=x[i-1][0]
x[i][1]|=x[i-1][1]
x[i][2]|=x[i-1][2]
if a[0]!=b[0]:
print('NO')
else:
for i in range(1,n):
if a[i]!=b[i]:
if a[i]>b[i]:
if not x[i-1][0]:
print('NO')
break
else:
if not x[i-1][2]:
print('NO')
break
else:
print('YES')
t = int(input())
for i in range(t):
solve()
|
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 10^4$) β the number of test cases.
Next $T$ lines contain test cases β one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) β the length of the highway and the number of good and bad days respectively.
-----Output-----
Print $T$ integers β one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
-----Example-----
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
-----Note-----
In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good.
In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.
|
for i in range(int(input())):
n,g,b=map(int,input().split())
nn=(n+1)//2
print(max(nn+(nn-1)//g*b,n))
|
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 10^4$) β the number of test cases.
Next $T$ lines contain test cases β one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) β the length of the highway and the number of good and bad days respectively.
-----Output-----
Print $T$ integers β one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
-----Example-----
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
-----Note-----
In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good.
In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.
|
for _ in range(int(input())):
n, g, b = list(map(int, input().split()))
half = (n - 1) // 2 + 1
ans = (g + b) * (half // g) - b # + (half % g)
if half % g != 0:
ans += b + half % g
print(max(ans, n))
|
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 10^4$) β the number of test cases.
Next $T$ lines contain test cases β one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) β the length of the highway and the number of good and bad days respectively.
-----Output-----
Print $T$ integers β one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
-----Example-----
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
-----Note-----
In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good.
In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.
|
# import sys
#
# input = lambda: sys.stdin.readline().strip()
for i in range(int(input())):
n,g, b = list(map(int, input().split()))
n1 = n
n = (n+1)//2
k = n//g
if n%g:
print(max(n1,k*(g+b)+n%g))
else:
print(max(n1,g*k+b*(k-1)))
|
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 10^4$) β the number of test cases.
Next $T$ lines contain test cases β one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) β the length of the highway and the number of good and bad days respectively.
-----Output-----
Print $T$ integers β one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
-----Example-----
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
-----Note-----
In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good.
In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.
|
def iinput():
return [int(x) for x in input().split()]
def main():
n, g, b = iinput()
z = (n + 1) // 2
d = (z - 1) // g
return max(d * b + z, n)
for i in range(int(input())):
print(main())
|
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 10^4$) β the number of test cases.
Next $T$ lines contain test cases β one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) β the length of the highway and the number of good and bad days respectively.
-----Output-----
Print $T$ integers β one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
-----Example-----
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
-----Note-----
In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good.
In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.
|
import sys
input = sys.stdin.readline
t=int(input())
for tests in range(t):
n,g,b=list(map(int,input().split()))
ALL=(n+1)//2
ANS=n
week=-(-ALL//g)-1
ANS=max(ANS,week*(g+b)+(ALL-week*g))
print(ANS)
|
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 10^4$) β the number of test cases.
Next $T$ lines contain test cases β one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) β the length of the highway and the number of good and bad days respectively.
-----Output-----
Print $T$ integers β one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
-----Example-----
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
-----Note-----
In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good.
In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.
|
t = int(input())
for q in range(t):
n, g, b = [int(i) for i in input().split()]
num = n
n = n // 2 + n % 2
val = n // g
d = 0
if n % g == 0:
d = (val - 1) * (b + g) + g
else:
d = val * (b + g) + n % g
if d < num:
print(num)
else:
print(d)
|
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 10^4$) β the number of test cases.
Next $T$ lines contain test cases β one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) β the length of the highway and the number of good and bad days respectively.
-----Output-----
Print $T$ integers β one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
-----Example-----
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
-----Note-----
In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good.
In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.
|
t = int(input())
def check(n, h, g, b, m):
if m < n:
return False
loop, rest = divmod(m, g + b)
ok = min(rest, g) + loop * g
return ok >= h
for _ in range(t):
n,g,b = list(map(int,input().split()))
high = (n + 1) // 2
ok, ng = 10 ** 20, 0
while ok - ng > 1:
mid = (ok + ng) // 2
if check(n, high, g, b, mid):
ok = mid
else:
ng = mid
print(ok)
|
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 10^4$) β the number of test cases.
Next $T$ lines contain test cases β one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) β the length of the highway and the number of good and bad days respectively.
-----Output-----
Print $T$ integers β one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
-----Example-----
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
-----Note-----
In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good.
In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.
|
def solve():
n, g, b = [int(x) for x in input().split()]
l = 0
r = int(1e30)
while r-l > 1:
m = (l+r)//2
blk = m // (g + b)
cnt = blk * g + min(g, m % (g + b))
if cnt >= (n+1)//2:
r = m
else:
l = m
print(max(r, n))
t = int(input())
for _ in range(t):
solve()
|
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 10^4$) β the number of test cases.
Next $T$ lines contain test cases β one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) β the length of the highway and the number of good and bad days respectively.
-----Output-----
Print $T$ integers β one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
-----Example-----
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
-----Note-----
In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good.
In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.
|
import sys
import math
from collections import defaultdict
from collections import deque
from itertools import combinations
from itertools import permutations
input = lambda : sys.stdin.readline().rstrip()
read = lambda : list(map(int, input().split()))
go = lambda : 1/0
def write(*args, sep="\n"):
for i in args:
sys.stdout.write("{}{}".format(i, sep))
INF = float('inf')
MOD = int(1e9 + 7)
YES = "YES"
NO = "NO"
for _ in range(int(input())):
try:
n, g, b = read()
total = math.ceil(n / 2)
s = 0
e = 1 << 63
while s <= e:
m = (s + e) // 2
good = 0
bad = 0
x = m // (g + b)
good += x * g
bad += x * b
y = m - (m // (g + b)) * (g + b)
good += min(y, g)
bad += max(0, y - g)
if good + bad >= n and good >= total:
e = m - 1
else:
s = m + 1
print(s)
except ZeroDivisionError:
continue
except Exception as e:
print(e)
continue
|
Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.
You can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \dots, g$ are good.
You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.
What is the minimum number of days is needed to finish the repair of the whole highway?
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 10^4$) β the number of test cases.
Next $T$ lines contain test cases β one per line. Each line contains three integers $n$, $g$ and $b$ ($1 \le n, g, b \le 10^9$) β the length of the highway and the number of good and bad days respectively.
-----Output-----
Print $T$ integers β one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.
-----Example-----
Input
3
5 1 1
8 10 10
1000000 1 1000000
Output
5
8
499999500000
-----Note-----
In the first test case, you can just lay new asphalt each day, since days $1, 3, 5$ are good.
In the second test case, you can also lay new asphalt each day, since days $1$-$8$ are good.
|
for _ in range(int(input())):
n,g,b = map(int,input().split())
orign = n
n = (n+1)//2
com = ((n-1)//g)
ans = com*(g+b)
n -= com*g
ans += n
print(max(ans,orign))
|
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 10^4$) β the number of test cases in the input. Then $t$ test cases follow.
Each test case is given in two lines.
The first line contains two integers $a_1$ and $b_1$ ($1 \le a_1, b_1 \le 100$) β the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).
The second line contains two integers $a_2$ and $b_2$ ($1 \le a_2, b_2 \le 100$) β the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).
-----Output-----
Print $t$ answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower).
-----Example-----
Input
3
2 3
3 1
3 2
1 3
3 3
1 3
Output
Yes
Yes
No
|
for _ in range(int(input())):
a1, b1 = list(map(int, input().split()))
a2, b2 = list(map(int, input().split()))
if a1 > b1:
a1, b1 = b1, a1
if a2 > b2:
a2, b2 = b2, a2
flag = False
if a1 == a2 and a1 == b1 + b2:
flag = True
if b1 == b2 and b1 == a1 + a2:
flag = True
print('Yes' if flag else 'No')
|
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 10^4$) β the number of test cases in the input. Then $t$ test cases follow.
Each test case is given in two lines.
The first line contains two integers $a_1$ and $b_1$ ($1 \le a_1, b_1 \le 100$) β the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).
The second line contains two integers $a_2$ and $b_2$ ($1 \le a_2, b_2 \le 100$) β the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).
-----Output-----
Print $t$ answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower).
-----Example-----
Input
3
2 3
3 1
3 2
1 3
3 3
1 3
Output
Yes
Yes
No
|
t = int(input())
for _ in range(t):
a1, b1 = map(int, input().split())
a2, b2 = map(int, input().split())
if a1 > b1:
a1, b1 = b1, a1
if a2 > b2:
a2, b2 = b2, a2
if b1 == b2 and a1 + a2 == b1:
print("Yes")
else:
print("No")
|
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 10^4$) β the number of test cases in the input. Then $t$ test cases follow.
Each test case is given in two lines.
The first line contains two integers $a_1$ and $b_1$ ($1 \le a_1, b_1 \le 100$) β the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).
The second line contains two integers $a_2$ and $b_2$ ($1 \le a_2, b_2 \le 100$) β the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).
-----Output-----
Print $t$ answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower).
-----Example-----
Input
3
2 3
3 1
3 2
1 3
3 3
1 3
Output
Yes
Yes
No
|
t = int(input())
for case in range(t):
a, b = list(map(int, input().split()))
c, d = list(map(int, input().split()))
if a == c and b + d == a:
print('Yes')
elif b == d and a + c == b:
print('Yes')
elif a == d and b + c == a:
print('Yes')
elif b == c and a + d == b:
print('Yes')
else:
print('No')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.