code
stringlengths 46
24k
| language
stringclasses 6
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.75
| max_line_length
int64 13
399
| avg_line_length
float64 5.01
139
| num_lines
int64 7
299
| task
stringlengths 151
14k
| source
stringclasses 3
values |
---|---|---|---|---|---|---|---|---|
class Solution:
def findSubString(self, s):
n = len(s)
distinct_chars = len(set(s))
freq = [0] * 256
left = 0
right = 0
count = 0
min_len = n
while right < n:
ch = ord(s[right])
if freq[ch] == 0:
count += 1
freq[ch] += 1
right += 1
while count == distinct_chars:
min_len = min(min_len, right - left)
ch = ord(s[left])
freq[ch] -= 1
if freq[ch] == 0:
count -= 1
left += 1
return min_len
| python | 14 | 0.526667 | 40 | 17.75 | 24 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, str):
nd = len(set(str))
i = 0
j = 0
res = len(str)
dic = {}
while i < len(str):
if str[i] in dic:
dic[str[i]] = dic[str[i]] + 1
else:
dic[str[i]] = 1
if len(dic) == nd:
while dic[str[j]] > 1:
dic[str[j]] = dic[str[j]] - 1
j = j + 1
res = min(res, i - j + 1)
i = i + 1
return res
| python | 16 | 0.475936 | 34 | 17.7 | 20 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
from collections import Counter
class Solution:
def findSubString(self, str1):
dict1 = dict()
count = 0
distinct = len(Counter(str1))
n = len(str1)
j = 0
minimum = n
for i in range(n):
if count < distinct:
while j < n:
if str1[j] not in dict1:
dict1[str1[j]] = 1
count += 1
else:
dict1[str1[j]] += 1
if count == distinct:
j += 1
break
j += 1
if count == distinct:
minimum = min(minimum, j - i)
dict1[str1[i]] -= 1
if dict1[str1[i]] == 0:
dict1.pop(str1[i])
count -= 1
return minimum
| python | 18 | 0.546552 | 33 | 18.333333 | 30 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, a):
s = ''
a1 = {}
for i in a:
a1[i] = 1
c1 = len(a1)
i = 0
j = 0
a2 = {}
c = 0
res = len(a)
while j < len(a):
if a[j] not in a2:
a2[a[j]] = 0
c += 1
a2[a[j]] += 1
while i <= j and c == c1:
res = min(res, j - i + 1)
a2[a[i]] -= 1
if a2[a[i]] == 0:
del a2[a[i]]
c -= 1
i += 1
j += 1
return res
| python | 15 | 0.399015 | 29 | 14.037037 | 27 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, str):
ans_len = len(set(str))
d = {}
ws = 0
ans = 10 ** 6
for we in range(0, len(str)):
d[str[we]] = d.get(str[we], 0) + 1
if len(d) == ans_len:
while d[str[ws]] > 1:
d[str[ws]] -= 1
ws += 1
ans = min(ans, we - ws + 1)
return ans
| python | 15 | 0.5 | 37 | 19.533333 | 15 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, str):
unique = set(str)
res = len(str)
j = 0
map = dict()
for i in range(0, len(str)):
if str[i] in map.keys():
map[str[i]] += 1
else:
map[str[i]] = 1
if len(unique) == len(map):
while map[str[j]] > 1:
map[str[j]] -= 1
j += 1
res = min(res, i - j + 1)
return res
| python | 15 | 0.511364 | 30 | 18.555556 | 18 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, str):
l = len(str)
s = set()
for i in range(len(str)):
s.add(str[i])
n = len(s)
head = 0
tail = 0
hmap = {}
ans = l
while head < l:
if str[head] in hmap:
hmap[str[head]] += 1
else:
hmap[str[head]] = 1
if len(hmap) == n:
while hmap[str[tail]] > 1:
hmap[str[tail]] -= 1
tail += 1
ans = min(ans, head - tail + 1)
head += 1
return ans
| python | 15 | 0.516129 | 35 | 17.083333 | 24 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
from collections import defaultdict, Counter
from sys import maxsize
class Solution:
def findSubString(self, str):
cnt = Counter(str)
cur = defaultdict(int)
k = 0
ans = maxsize
i = 0
for (j, ch) in enumerate(str):
cur[ch] += 1
if cur[ch] == 1:
k += 1
if k == len(cnt):
while i < j:
if cur[str[i]] == 1:
break
cur[str[i]] -= 1
i += 1
ans = min(ans, j - i + 1)
return ans
| python | 15 | 0.552448 | 44 | 17.652174 | 23 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, str):
res = float('inf')
(i, j) = (0, 0)
maxLen = len(set(list(str)))
hashmap = {}
while j < len(str):
if str[j] not in hashmap:
hashmap[str[j]] = 1
else:
hashmap[str[j]] += 1
j += 1
if len(hashmap) == maxLen:
while i < j and hashmap[str[i]] > 1:
hashmap[str[i]] -= 1
i += 1
res = min(res, j - i)
return res
| python | 15 | 0.5275 | 40 | 20.052632 | 19 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, str):
d = {}
for ch in str:
if ch not in d:
d[ch] = 1
n = len(d)
d.clear()
i = 0
j = 0
count = 0
mini = len(str)
while j < len(str):
if str[j] not in d:
d[str[j]] = 1
count = count + 1
else:
d[str[j]] = d[str[j]] + 1
if count == n:
while d[str[i]] != 1:
d[str[i]] = d[str[i]] - 1
i = i + 1
mini = min(mini, j - i + 1)
j = j + 1
return mini
| python | 16 | 0.461197 | 31 | 16.346154 | 26 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, s):
n = len(s)
d = {}
count = 0
for i in range(n):
d[s[i]] = 0
i = 0
j = 0
ans = n
while i < n:
if d[s[i]] == 0:
count += 1
d[s[i]] += 1
if count == len(d):
while j < n and d[s[j]] > 1:
d[s[j]] -= 1
j += 1
if ans > i - j + 1:
ans = i - j + 1
i += 1
return ans
| python | 15 | 0.411602 | 32 | 14.73913 | 23 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, str):
p = len(set(str))
j = 0
i = 0
d = {}
mn = 100000
while j < len(str):
if str[j] in d:
d[str[j]] += 1
else:
d[str[j]] = 1
if len(d) == p:
while len(d) == p:
mn = min(mn, j - i + 1)
d[str[i]] -= 1
if d[str[i]] == 0:
del d[str[i]]
i += 1
j += 1
return mn
| python | 17 | 0.432507 | 30 | 15.5 | 22 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, str):
d = {}
i = 0
j = 0
sw = 100000000
n = len(set(str))
while j < len(str):
if str[j] not in d:
d[str[j]] = 1
else:
d[str[j]] += 1
if len(d) == n:
while len(d) == n:
sw = min(sw, j - i + 1)
d[str[i]] -= 1
if d[str[i]] == 0:
del d[str[i]]
i += 1
j += 1
return sw
| python | 17 | 0.440541 | 30 | 15.818182 | 22 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, str):
dict = {}
for i in str:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
count = len(list(dict.keys()))
i = j = 0
ans = len(str)
c = 0
dict = {}
for i in range(len(str)):
if str[i] in dict:
dict[str[i]] += 1
else:
dict[str[i]] = 1
c += 1
if c == count:
ans = min(ans, i - j + 1)
while c == count and j <= i:
dict[str[j]] -= 1
if dict[str[j]] == 0:
del dict[str[j]]
c -= 1
ans = min(ans, i - j + 1)
j += 1
return ans
| python | 17 | 0.464738 | 32 | 17.433333 | 30 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
class Solution:
def findSubString(self, str):
s = set(str)
n = len(s)
ss = set()
ind = 0
d = {}
mini = 10 ** 9
for i in range(len(str)):
if str[i] not in ss:
ss.add(str[i])
d[str[i]] = d.get(str[i], 0) + 1
if len(ss) == n:
ind = i + 1
mini = min(mini, i + 1)
break
index = 0
while d[str[index]] > 1:
d[str[index]] -= 1
index += 1
mini = min(mini, i - index + 1)
for i in range(ind, len(str)):
d[str[i]] = d.get(str[i], 0) + 1
while d[str[index]] > 1:
d[str[index]] -= 1
index += 1
mini = min(mini, i - index + 1)
while d[str[index]] > 1:
d[str[index]] -= 1
index += 1
mini = min(mini, i - index + 1)
return mini
| python | 15 | 0.497854 | 35 | 20.181818 | 33 | Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Example 2:
Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Example 3:
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string S as input and returns the length of the smallest such window of the string.
Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
Constraints:
1 β€ |S| β€ 10^{5}
String may contain both type of English Alphabets. | taco |
from math import ceil, log, floor, sqrt, gcd
for _ in range(int(input())):
n = int(input())
l = list(map(int, input().split()))
f = {}
for i in l:
try:
f[i] += 1
except:
f[i] = 1
if max(f.values()) > n // 2 or len(set(l)) <= 2:
print('NO')
else:
print('YES')
l.sort()
print(*l)
print(*l[n // 2:] + l[:n // 2])
| python | 14 | 0.502976 | 49 | 18.764706 | 17 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
import math
import bisect
import heapq
from math import gcd, floor, sqrt, log
from collections import defaultdict as ddc
from collections import Counter
def intin():
return int(input())
def mapin():
return map(int, input().split())
def strin():
return input().split()
INF = 10 ** 20
mod = 1000000007
def exponentiation(bas, exp, mod=1000000007):
t = 1
while exp > 0:
if exp % 2 != 0:
t = t * bas % mod
bas = bas * bas % mod
exp //= 2
return t % mod
def MOD(p, q=1, mod=1000000007):
expo = 0
expo = mod - 2
while expo:
if expo & 1:
p = p * q % mod
q = q * q % mod
expo >>= 1
return p
def process(arr, n):
C = Counter(arr)
edge = 0
for val in C.values():
if val > n // 2:
print('NO')
return
elif val == n // 2:
edge += 1
if len(C.keys()) == edge == 2:
print('NO')
return
print('YES')
arr.sort()
(B, C) = (arr, arr[(n + 1) // 2:] + arr[:(n + 1) // 2])
r = n - 1
for i in range(n):
if i >= r:
break
if B[i] == C[i]:
(C[i], C[r]) = (C[r], C[i])
r -= 1
print(*B)
print(*C)
def main():
for _ in range(int(input())):
n = intin()
arr = list(mapin())
process(arr, n)
main()
| python | 12 | 0.553618 | 56 | 15.867647 | 68 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
tt = int(input())
for _ in range(tt):
n = int(input())
a = list(map(int, input().split()))
d = {}
for i in a:
try:
d[i] += 1
except KeyError:
d[i] = 1
m = max(list(d.values()))
k = len(list(d.keys()))
if m > n // 2 or k <= 2:
print('NO')
continue
else:
print('YES')
a.sort()
print(*a)
print(*a[m:] + a[:m])
| python | 13 | 0.495549 | 36 | 15.85 | 20 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
from bisect import bisect_left
from re import sub
import re
from typing import DefaultDict
import math
from collections import defaultdict
from math import sqrt
import collections
from sys import maxsize
from itertools import combinations_with_replacement
import sys
import copy
def sieve_erasthones(n):
cnt = 0
prime = [True for i in range(n + 1)]
p = 2
while p * p <= n:
if prime[p] == True:
for i in range(p ** 2, n + 1, p):
prime[i] = False
p += 1
prime[0] = False
prime[1] = False
for p in range(n + 1):
if prime[p]:
cnt += 1
return cnt
def calculate(p, q):
mod = 998244353
expo = 0
expo = mod - 2
while expo:
if expo & 1:
p = p * q % mod
q = q * q % mod
expo >>= 1
return p
def count_factors(n):
i = 1
c = 0
while i <= math.sqrt(n):
if n % i == 0:
if n // i == i:
c += 1
else:
c += 2
i += 1
return c
def ncr_modulo(n, r, p):
num = den = 1
for i in range(r):
num = num * (n - i) % p
den = den * (i + 1) % p
return num * pow(den, p - 2, p) % p
def isprime(n):
prime_flag = 0
if n > 1:
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
prime_flag = 1
break
if prime_flag == 0:
return True
else:
return False
else:
return True
def smallestDivisor(n):
if n % 2 == 0:
return 2
i = 3
while i * i <= n:
if n % i == 0:
return i
i += 2
return n
def dict_ele_count(l):
d = DefaultDict(lambda : 0)
for ele in l:
d[ele] += 1
return d
def max_in_dict(d):
maxi = 0
for ele in d:
if d[ele] > maxi:
maxi = d[ele]
return maxi
def element_count(s):
l = []
k = s[0]
c = 0
for ele in s:
if ele == k:
c += 1
else:
l.append([k, c])
k = ele
c = 1
l.append([k, c])
return l
def modular_exponentiation(x, y, p):
res = 1
x = x % p
if x == 0:
return 0
while y > 0:
if y & 1 != 0:
res = res * x % p
y = y >> 1
x = x * x % p
return res
def number_of_primefactor(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
l.append(i)
n = n / i
if n > 2:
l.append(n)
return len(set(l))
def twosum(a, n, x):
rem = []
for i in range(x):
rem.append(0)
for i in range(n):
if a[i] < x:
rem[a[i] % x] += 1
for i in range(1, x // 2):
if rem[i] > 0 and rem[x - i] > 0:
return True
if i >= x // 2:
if x % 2 == 0:
if rem[x // 2] > 1:
return True
else:
return False
elif rem[x // 2] > 0 and rem[x - x // 2] > 0:
return True
else:
return False
def divSum(num):
result = 0
i = 2
while i <= math.sqrt(num):
if num % i == 0:
if i == num / i:
result = result + i
else:
result = result + (i + num / i)
i = i + 1
return result + 1 + num
def subsequence(str1, str2):
m = len(str1)
n = len(str2)
j = 0
i = 0
while j < m and i < n:
if str1[j] == str2[i]:
j = j + 1
i = i + 1
return j == m
def primeFactors(n):
d = defaultdict(lambda : 0)
while n % 2 == 0:
d[2] += 1
n = n / 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
d[int(i)] += 1
n = n / i
if n > 2:
d[int(n)] += 1
return d
def calc(s):
ans = 0
for ele in s:
ans += ord(ele) - 96
return ans
def modInverse(b, m):
g = math.gcd(b, m)
if g != 1:
return -1
else:
return pow(b, m - 2, m)
def modDivide(a, b, m):
a = a % m
inv = modInverse(b, m)
return inv * a % m
def solve():
n = int(input())
d = defaultdict(lambda : 0)
l = list(map(int, input().split()))
ans = []
for ele in l:
d[ele] += 1
if len(d) <= 2:
print('NO')
return
l = sorted(d.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)
for ele in l:
if ele[1] > n // 2:
print('NO')
return
else:
break
ans1 = [l[0][0] for _ in range(l[0][1])]
ans2 = [l[0][0] for _ in range(l[0][1])]
temp1 = []
for i in range(1, len(l)):
temp1 += [l[i][0] for _ in range(l[i][1])]
ans1 += temp1
ans2 = temp1 + ans2
print('YES')
print(*ans1)
print(*ans2)
for _ in range(int(input())):
solve()
| python | 16 | 0.532189 | 67 | 15.573222 | 239 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
def go():
for i in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
b = a
b.sort()
f = 0
for j in range((n + 1) // 2):
if b[j] == b[j + n // 2]:
print('NO')
f = 1
break
if f == 1:
continue
if n % 2 == 0 and b[0] == b[n // 2 - 1] and (b[n // 2] == b[n - 1]):
print('NO')
continue
c = []
c.extend(b[int(n / 2):])
c.extend(b[:int(n / 2)])
print('YES')
print(*b)
print(*c)
go()
| python | 15 | 0.438053 | 70 | 17.833333 | 24 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
from collections import defaultdict
def solve():
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
cnt = defaultdict(int)
for i in a:
cnt[i] += 1
if cnt[i] > n // 2:
print('NO')
return
if n % 2 == 0 and (a[0] == a[n // 2 - 1] and a[n // 2] == a[n - 1]):
print('NO')
else:
print(f"YES\n{' '.join(map(str, a))}\n{' '.join(map(str, a[n // 2:]))} {' '.join(map(str, a[:n // 2]))}")
for _ in range(int(input())):
solve()
| python | 18 | 0.507726 | 107 | 24.166667 | 18 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, input().split()))
arr.sort()
x = list(set(arr))
flag = True
for i in x:
if arr.count(i) > n // 2:
flag = False
break
if flag == True:
if len(x) == 2 and arr.count(x[0]) == arr.count(x[1]):
print('NO')
else:
print('YES')
print(*arr)
x1 = n // 2
print(*arr[x1:] + arr[:x1])
else:
print('NO')
| python | 15 | 0.5225 | 56 | 18.047619 | 21 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
def solution():
N = int(input())
A = list(map(int, input().split()))
A.sort()
stat = 1
for i in range((N + 1) // 2):
if A[i] == A[i + N // 2]:
print('NO')
stat = 0
return
if stat and N % 2 == 0 and (A[0] == A[N // 2 - 1]) and (A[N // 2] == A[N - 1]):
print('NO')
else:
print('YES')
print(' '.join(map(str, A)))
print(' '.join(map(str, A[(N + 1) // 2:])), end=' ')
print(' '.join(map(str, A[:(N + 1) // 2])))
for _ in range(int(input())):
solution()
| python | 18 | 0.466527 | 80 | 24.157895 | 19 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
from collections import Counter
test = int(input())
for _ in range(test):
n = int(input())
A = list(map(int, input().split()))
c = Counter(A)
m = max(c.values())
if m > n // 2 or len(c) <= 2:
print('NO')
else:
print('YES')
A.sort()
print(*A)
p = n // 2
print(*A[p:] + A[:p])
| python | 13 | 0.539249 | 36 | 18.533333 | 15 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
t = int(input())
for _ in range(t):
n = int(input())
l = list(map(int, input().split()))
d = {}
for i in l:
d[i] = d.get(i, 0) + 1
mx = 0
for i in d.values():
if i >= mx:
mx = i
if len(d) == 2:
print('NO')
elif n % 2 == 0:
if mx <= n // 2:
print('YES')
l.sort()
for i in range(n):
print(l[i], end=' ')
print()
for i in range(n // 2, n):
print(l[i], end=' ')
print(end='')
for i in range(0, n // 2):
print(l[i], end=' ')
print()
else:
print('NO')
elif mx < n // 2 + 1:
print('YES')
l.sort()
for i in range(n):
print(l[i], end=' ')
print()
for i in range(n // 2 + 1, n):
print(l[i], end=' ')
print(end='')
for i in range(0, n // 2 + 1):
print(l[i], end=' ')
print()
else:
print('NO')
| python | 15 | 0.457847 | 36 | 17.357143 | 42 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
tc = int(input())
for t in range(0, tc):
length = int(input())
nums = list(map(int, input().split()))
Map = {}
for n in nums:
Map[n] = Map.setdefault(n, 0) + 1
if Map[n] > length // 2:
print('NO')
break
else:
if len(Map) == 2 and length % 2 == 0:
print('NO')
else:
freqs = sorted(set(Map.values()), reverse=True)
ans = []
for freq in freqs:
for (key, value) in Map.items():
if value == freq:
ans += [str(key)] * value
print('YES')
print(' '.join(ans))
print(' '.join(ans[Map[int(ans[0])]:] + ans[:Map[int(ans[0])]]))
| python | 21 | 0.536713 | 67 | 23.869565 | 23 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
t = int(input())
for test in range(t):
n = int(input())
lst = list(map(int, input().split()))
lst.sort()
lst2 = lst[n // 2:] + lst[:n // 2]
ans = 'YES'
for i in range(n):
if lst[i] == lst2[i]:
ans = 'NO'
break
p1 = 1
p2 = n - 2
while p1 < p2:
temp1 = sorted(lst[p1:p2 + 1])
temp2 = sorted(lst2[p1:p2 + 1])
if temp1 == temp2:
ans = 'NO'
break
p1 += 1
p2 -= 1
print(ans)
if ans == 'YES':
print(*lst)
print(*lst2)
| python | 13 | 0.515556 | 38 | 17 | 25 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
from math import inf
from collections import *
import math, os, sys, heapq, bisect, random, threading
from functools import lru_cache
from itertools import *
def inp():
return sys.stdin.readline().rstrip('\r\n')
def out(var):
sys.stdout.write(str(var))
def inpu():
return int(inp())
def lis():
return list(map(int, inp().split()))
def stringlis():
return list(map(str, inp().split()))
def sep():
return map(int, inp().split())
def strsep():
return map(str, inp().split())
def fsep():
return map(float, inp().split())
(M, M1) = (1000000007, 998244353)
def main():
how_much_noob_I_am = 1
how_much_noob_I_am = inpu()
for _ in range(1, how_much_noob_I_am + 1):
n = inpu()
arr = lis()
c = Counter(arr)
p = sum(c.values())
m = max(c.values())
if p - m < m or (m == n // 2 and len(set(arr)) == 2):
print('NO')
continue
arr.sort()
res = arr[(len(arr) + 1) // 2:] + arr[:(len(arr) + 1) // 2]
print('YES')
print(*arr)
print(*res)
main()
| python | 15 | 0.604103 | 61 | 18.897959 | 49 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
for _ in range(int(input())):
n = int(input())
l = input().split()
d = {}
for i in l:
i = int(i)
if i in d:
d[i] += 1
else:
d[i] = 1
l = []
for i in d:
l.append([i, d[i]])
if len(l) == 1:
print('NO')
elif len(l) == 2:
if l[0][0] == l[1][0] and (l[0][1] == 1 or l[0][1] == 2):
print('YES')
s = str(l[0][0]) * l[0][1] + str(l[1][0]) * l[0][1]
else:
print('NO')
else:
le = n // 2
ma = l[0][1]
s = []
for i in l:
s[len(s):] = [i[0]] * i[1]
if i[1] > ma:
ma = i[1]
if ma > le:
print('NO')
else:
print('YES')
for i in s:
print(i, end=' ')
print()
s = s[le:] + s[0:le]
for i in s:
print(i, end=' ')
print()
| python | 16 | 0.409289 | 59 | 16.225 | 40 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
import sys
import math
from collections import defaultdict, Counter, deque
from bisect import *
from string import ascii_lowercase
from heapq import *
def readInts():
x = list(map(int, sys.stdin.readline().rstrip().split()))
return x[0] if len(x) == 1 else x
def readList(type=int):
x = sys.stdin.readline()
x = list(map(type, x.rstrip('\n\r').split()))
return x
def readStr():
x = sys.stdin.readline().rstrip('\r\n')
return x
write = sys.stdout.write
read = sys.stdin.readline
def dist(x1, x2, y1, y2):
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def mergeSort(arr, check=lambda a, b: a < b, reverse=False):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
mergeSort(L, check, reverse)
mergeSort(R, check, reverse)
i = j = k = 0
while i < len(L) and j < len(R):
if check(L[i], R[j]):
if not reverse:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
elif not reverse:
arr[k] = R[j]
j += 1
else:
arr[k] = L[i]
i += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
def maxSum(arr):
max_sum = float('-inf')
max_cur = 0
for num in ar:
max_cur = max(max_cur + num, num)
if max_cur > max_sum:
max_sum = max_cur
return max_sum
def hcf(a, b):
if b == 0:
return a
else:
return hcf(b, b % a)
def get_power(n, m):
i = 1
p = -1
while i <= n:
i = i * m
p += 1
return p
def fact(n):
f = 1
for i in range(2, n + 1):
f *= i
return f
def find_closest(num, ar):
min_d = float('inf')
for num2 in ar:
d = abs(num2 - num)
if d < min_d:
min_d = d
return min_d
def check_pal(n):
s = str(n)
j = len(s) - 1
i = 0
while j > i:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
def solve(t):
n = readInts()
ar = readList()
cnt = 0
mx_ele = ar[0]
if len(set(ar)) < 3:
print('NO')
return None
for num in ar:
if num == mx_ele:
cnt += 1
else:
cnt -= 1
if cnt == 0:
mx_ele = num
cnt = 1
if cnt > 0:
cnt = 0
for num in ar:
if num == mx_ele:
cnt += 1
if cnt > n // 2:
print('NO')
return None
res = []
ar.sort()
res = ar[n // 2:] + ar[:n // 2]
print('YES')
print(*ar)
print(*res)
def main():
t = 1
sys.setrecursionlimit(12000)
t = readInts()
for i in range(t):
solve(i + 1)
main()
| python | 16 | 0.539737 | 60 | 15.454545 | 143 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
count = {}
for i in range(n):
if a[i] in count:
count[a[i]] += 1
else:
count[a[i]] = 1
if len(count.keys()) <= 2:
print('NO')
elif max(count.values()) > n // 2:
print('NO')
else:
print('YES')
pairs = list(count.items())
pairs.sort(key=lambda x: x[1], reverse=True)
array1 = []
for pair in pairs:
for j in range(pair[1]):
array1.append(pair[0])
array2 = []
shift = pairs[0][1]
for i in range(n - shift, n):
array2.append(array1[i])
for i in range(n - shift):
array2.append(array1[i])
print(*array1)
print(*array2)
| python | 14 | 0.571429 | 46 | 20.933333 | 30 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
from collections import Counter
for tcase in range(int(input())):
n = int(input())
a = Counter(map(int, input().split())).most_common()
b = []
for (k, v) in a:
b.extend([k] * v)
ans = False
i = 1
while not ans and i * 2 < len(a):
c = []
for (k, v) in a[i:]:
c.extend([k] * v)
for (k, v) in a[:i]:
c.extend([k] * v)
ans = all((bi != ci for (bi, ci) in zip(b, c)))
i += 1
if ans:
print('YES')
print(' '.join(map(str, b)))
print(' '.join(map(str, c)))
else:
print('NO')
| python | 15 | 0.51992 | 53 | 20.826087 | 23 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
def Print(arr):
for ele in arr:
print(ele, end=' ')
print()
t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, input().split()))
arr.sort()
ar = arr[n // 2:]
for i in range(n // 2):
ar.append(arr[i])
ans = True
for i in range(n):
if arr[i] == ar[i]:
ans = False
break
d = {}
for ele in arr:
d[ele] = d.get(ele, 0) + 1
if len(d) == 2:
tm = []
for ele in d:
tm.append(d[ele])
if tm[0] == tm[1]:
ans = False
if ans:
print('YES')
Print(arr)
Print(ar)
else:
print('NO')
| python | 13 | 0.523364 | 38 | 15.71875 | 32 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
for _ in range(int(input())):
size = int(input())
L = list(map(int, input().split()))
L.sort()
s = set(L)
c = 0
for i in s:
if L.count(i) > size // 2:
print('NO')
c = 1
break
if c == 1:
continue
if len(s) == 2:
print('NO')
continue
print('YES')
print(*L)
temp = L[(size + 1) // 2:] + L[:(size + 1) // 2]
print(*temp)
| python | 13 | 0.5 | 49 | 16.3 | 20 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
from math import *
a = int(input())
for x in range(a):
b = int(input())
c = list(map(int, input().split()))
h = {}
for y in range(b):
if h.get(c[y]) == None:
h[c[y]] = 1
else:
h[c[y]] += 1
o = b // 2
l = 0
for y in h:
if h[y] > o:
l = -1
break
if len(h) <= 2:
print('NO')
elif l == -1:
print('NO')
else:
print('YES')
c.sort()
print(*c)
j = c[o:] + c[:o]
print(*j)
| python | 13 | 0.460591 | 36 | 14.037037 | 27 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
from collections import Counter
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
arr.sort()
dit = Counter(arr)
f = max(dit.values())
if f > n // 2 or len(dit) == 2:
print('NO')
continue
new = arr[n // 2:] + arr[:n // 2]
print('YES')
print(*arr)
print(*new)
| python | 13 | 0.576547 | 38 | 20.928571 | 14 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
d = {}
for i in a:
if i in d:
d[i] += 1
else:
d[i] = 1
if max(d.values()) > n // 2:
print('NO')
continue
if len(d) == 2:
print('NO')
continue
print('YES')
c = []
a.sort()
c = a[n // 2:] + a[:n // 2]
print(*a)
print(*c)
| python | 13 | 0.46988 | 36 | 14.809524 | 21 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
arr.sort()
flag = False
mp = {}
for i in arr:
if i not in mp:
mp[i] = 1
else:
mp[i] += 1
if mp[i] > n // 2:
flag = True
if flag:
print('NO')
continue
if len(mp) == 2:
print('NO')
continue
arr.sort()
maxxx = 0
for k in mp:
if mp[k] > maxxx:
maxxx = mp[k]
num = []
num = arr
k = maxxx
num = num[::-1]
xx = num[:k - 1:-1]
yy = num[k - 1::-1]
num = yy + xx
print('YES')
print(*arr)
print(*num)
| python | 13 | 0.507634 | 38 | 14.411765 | 34 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
import math
t = int(input())
while t > 0:
n = int(input())
a = list(map(int, input().split()))
m = 0
d = {}
for x in range(n):
if a[x] in d:
d[a[x]] = d[a[x]] + 1
else:
d[a[x]] = 1
m = max(d[a[x]], m)
if m > n / 2:
print('NO')
else:
d = list(d.items())
if len(d) <= 2:
print('NO')
t -= 1
continue
print('YES')
d = sorted(d, key=lambda x: x[1], reverse=True)
for x in d:
for y in range(x[1]):
print(x[0], end=' ')
print()
for x in range(1, len(d)):
for y in range(d[x][1]):
print(d[x][0], end=' ')
for y in range(d[0][1]):
print(d[0][0], end=' ')
print()
t -= 1
| python | 15 | 0.476874 | 49 | 17.441176 | 34 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
for i in range(int(input())):
n = int(input())
l = list(map(int, input().split()))
lc = []
l.sort()
for i in set(l):
lc.append(l.count(i))
lc.sort(reverse=True)
if lc[0] > n // 2:
print('NO')
continue
if lc[0] + lc[1] == n:
print('NO')
continue
e = lc[0]
lans = []
for j in range(n):
lans.append(l[(j + e) % n])
print('YES')
for j in l:
print(j, end=' ')
print()
for j in lans:
print(j, end=' ')
print()
| python | 13 | 0.529817 | 36 | 16.44 | 25 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
from collections import Counter
tc = int(input())
for case in range(tc):
n = int(input())
a = list(map(int, input().split()))
c = Counter(a)
nb2 = n // 2
mx = max(c.values())
if mx > nb2 or len(set(a)) == 2:
print('NO')
continue
else:
print('YES')
a.sort()
print(*a, sep=' ')
print(*a[mx:] + a[:mx], sep=' ')
| python | 13 | 0.554878 | 36 | 19.5 | 16 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
import math
T = int(input())
for _ in range(T):
N = int(input())
l = list(map(int, input().split()))
flag = 'Yes'
l.sort()
a = 1
m = 0
for i in range(1, N):
if l[i - 1] == l[i]:
a += 1
else:
if m < a:
m = a
a = 1
if m < a:
m = a
if m > N // 2:
print('NO')
continue
k = m
i = 0
B = l[k:] + l[:k]
if l[0] == B[-1] and l[-1] == B[0]:
print('NO')
continue
print('YES')
for i in l:
print(i, end=' ')
print()
for i in B:
print(i, end=' ')
print()
| python | 13 | 0.455102 | 36 | 13.411765 | 34 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
from collections import Counter
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
c = Counter(arr)
m = max(c.values())
if m >= (n + 1) / 2 or len(set(arr)) <= 2:
print('NO')
else:
for el in c:
if c[el] == m:
break
a = [el] * m
b = []
for el in c:
if el != a[0]:
b += [el] * c[el]
print('YES')
print(*a + b)
print(*b + a)
| python | 14 | 0.497449 | 43 | 18.6 | 20 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
for cas in range(int(input())):
n = int(input())
l = list(map(int, input().split()))
l.sort()
if len(set(l)) == 1:
print('NO')
continue
if len(set(l)) == 2 and n % 2 == 0:
i = 0
j = n - 1
flag = 0
while i < j:
if l[i] == l[j]:
flag = 1
break
i += 1
j -= 1
if not flag:
print('NO')
continue
d = {}
flag = 0
for i in l:
if i not in d:
d[i] = 1
else:
d[i] += 1
mx = 0
for i in d:
if d[i] > mx:
mx = d[i]
if mx > n // 2:
print('NO')
continue
else:
print('YES')
print(*l)
print(*l[mx:] + l[:mx])
| python | 13 | 0.460177 | 36 | 13.868421 | 38 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
for _ in range(int(input())):
n = int(input())
l = list(map(int, input().split()))
l.sort()
pre = 0
xx = 0
d = dict()
flag = False
c = 0
for x in set(l):
d[x] = l.count(x)
if d[x] > pre:
xx = x
pre = d[x]
if d[x] > n - d[x]:
flag = True
break
if d[x] == n // 2 and n % 2 == 0:
c += 1
if c == 2:
flag = True
break
if flag:
print('NO')
else:
print('YES')
index = l.index(xx)
while index + 1 < n:
if l[index + 1] == xx:
index += 1
else:
break
print(*l)
l = l[n // 2:] + l[:n // 2]
print(*l)
| python | 13 | 0.458781 | 36 | 14.942857 | 35 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
T = int(input())
for _ in range(T):
N = int(input())
A = list(map(int, input().split()))
A.sort()
L = A[N // 2:]
L.extend(A[:N // 2])
f = False
for i in range(N - 1):
if A[i] == L[i]:
f = True
break
if A[i] == L[i + 1] and A[i + 1] == L[i]:
f = True
break
if A[N - 1] == L[N - 1]:
f = True
if f:
print('NO')
else:
print('YES')
print(*A)
print(*L)
| python | 13 | 0.45953 | 43 | 15.652174 | 23 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
import sys
from math import sqrt, gcd, factorial, ceil, floor
from collections import deque, Counter, OrderedDict
from heapq import heapify, heappush, heappop
input = lambda : sys.stdin.readline()
I = lambda : int(input())
S = lambda : input().strip()
M = lambda : map(int, input().strip().split())
L = lambda : list(map(int, input().strip().split()))
mod = 1000000007
for _ in range(I()):
n = I()
a = L()
a.sort()
c = a[n // 2:] + a[:n // 2]
if any((a[i] == c[i] for i in range(n))) or any((a[i] == c[i + 1] and a[i + 1] == c[i] for i in range(n - 1))):
print('NO')
continue
print('YES')
print(*a)
print(*c)
| python | 14 | 0.603865 | 112 | 28.571429 | 21 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
T = int(input())
for ts in range(T):
N = int(input())
A = list(map(int, input().split(' ')))
A.sort()
C = A.copy()
C = C[(N + 1) // 2:N] + C[:(N + 1) // 2]
check = True
for i in range(N):
if A[i] == C[i]:
check = False
break
if N % 2 == 0 and A[N // 2 - 1] == C[N // 2] and (A[N // 2] == C[N // 2 - 1]):
check = False
if check:
print('YES')
print(' '.join(map(str, A)))
print(' '.join(map(str, C)))
else:
print('NO')
| python | 13 | 0.467416 | 79 | 21.25 | 20 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
t = int(input())
for _ in range(t):
n = int(input())
line = input()
a = list(map(int, line.split()))
a.sort()
counts = [[a[0], 1]]
curr_value = a[0]
for i in range(1, n):
if a[i] == curr_value:
counts[-1][1] += 1
else:
curr_value = a[i]
counts.append([a[i], 1])
counts.sort(key=lambda x: x[1], reverse=True)
highest_count = counts[0][1]
if highest_count > n / 2 or len(counts) == 2:
print('NO')
else:
print('YES')
for item in a:
print(item, end=' ')
print()
for i in range(n):
index = (i + highest_count) % n
print(a[index], end=' ')
print()
| python | 13 | 0.553663 | 46 | 20.740741 | 27 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
def fi():
return int(input())
def li():
return list(map(int, input().split()))
t = fi()
for i in range(t):
n = fi()
a = li()
m = {}
for e in a:
if e not in m:
m[e] = 1
else:
m[e] += 1
pos = True
firstrot = 0
m = dict(sorted(m.items(), key=lambda x: x[1], reverse=True))
for (key, value) in m.items():
if value > n / 2 or (value == n / 2 and len(m.keys()) == 2):
pos = False
firstrot = value
break
if not pos:
print('NO')
else:
print('YES')
templist = []
for (key, value) in m.items():
for j in range(value):
templist.append(key)
print(*templist)
templist = templist[firstrot:] + templist[:firstrot]
print(*templist)
| python | 14 | 0.571001 | 62 | 18.676471 | 34 | You are given an array A of N integers A_{1}, A_{2}, \ldots, A_{N}. Determine if there are two [permutations] B and C of this array, for which the following condition is satisfied:
* There doesn't exist a pair of integers (i, j) such that 1 β€ i β€ j β€ N and (i, j) \neq (1, N), for which the subarray B[i:j] is a permutation of subarray C[i:j].
If there exist such permutations, find any of them.
As a reminder, B[i:j] refers to the subarray [B_{i}, B_{i+1}, \ldots, B_{j}]
------ Input Format ------
- The first line of the input contains a single integer T, the number of test cases. The description of the test cases follows.
- The first line of each test case contains a single integer N β the number of integers.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, if there are no such permutations B and C, output NO.
Otherwise, on the first line output YES. In the next line, output N integers B_{1}, B_{2}, \ldots, B_{N}. In the next line, output N integers C_{1}, C_{2}, \ldots, C_{N}.
You may print each character of YES/NO in either uppercase or lowercase (for example, the strings YES, yeS, YeS, and yEs will all be treated as identical).
------ Constraints ------
$1 β€T β€100$
$3 β€N β€1000$
$0 β€A_{i} β€10^{9}$
- The sum of $N$ over all test cases doesn't exceed $2000$.
----- Sample Input 1 ------
3
3
1 1 2
4
19 39 19 84
6
1 2 3 1 2 3
----- Sample Output 1 ------
NO
YES
19 19 39 84
39 84 19 19
YES
1 1 2 2 3 3
2 3 3 1 1 2
----- explanation 1 ------
Test case $1$: There are $3 \times 3 = 9$ pairs of permutations of the given array. Here's why they're all bad:
- If $B = [1, 1, 2]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 1, 2]$ and $C = [2, 1, 1]$, $B[2:2] = C[2:2]$
- If $B = [1, 2, 1]$ and $C = [1, 1, 2]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [1, 2, 1]$, $B[1:1] = C[1:1]$
- If $B = [1, 2, 1]$ and $C = [2, 1, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [1, 1, 2]$, $B[2:2] = C[2:2]$
- If $B = [2, 1, 1]$ and $C = [1, 2, 1]$, $B[3:3] = C[3:3]$
- If $B = [2, 1, 1]$ and $C = [2, 1, 1]$, $B[1:1] = C[1:1]$ | taco |
t = int(input())
for _ in range(t):
(a, b) = map(int, input().split())
if a == 0 and b == 0:
print(1)
elif a == 0:
print(0.5)
elif b == 0:
print(1)
elif a > 4 * b:
print('%.10f' % ((a - b) / a))
else:
print('%.10f' % (a / 16 / b + 0.5))
| python | 14 | 0.450593 | 37 | 18.461538 | 13 | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 β€ t β€ 10000) β amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 β€ a, b β€ 106).
Pretests contain all the tests with 0 < a < 10, 0 β€ b < 10.
Output
Print t lines β the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000 | taco |
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
threading.stack_size(10 ** 8)
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
(self.buffer.truncate(0), self.buffer.seek(0))
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda : self.buffer.read().decode('ascii')
self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print('Invalid argument to calculate n!')
print('n must be non-negative value. But the argument was ' + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print('Invalid argument to calculate n^(-1)')
print('n must be non-negative value. But the argument was ' + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print('Invalid argument to calculate (n^(-1))!')
print('n must be non-negative value. But the argument was ' + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n)
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
t = int(input())
for i in range(t):
(a, b) = list(map(int, input().split()))
if a == 0 and b == 0:
print(1)
elif a == 0:
print(0.5)
elif b == 0:
print(1)
else:
if a < 4 * b:
ans = (b * a + a * a / 8) / (2 * a * b)
else:
ans = 1 - b / a
print(ans)
| python | 17 | 0.642193 | 93 | 26.811189 | 143 | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 β€ t β€ 10000) β amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 β€ a, b β€ 106).
Pretests contain all the tests with 0 < a < 10, 0 β€ b < 10.
Output
Print t lines β the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000 | taco |
from fractions import Fraction
t = int(input())
for _ in range(t):
(a, b) = map(lambda x: Fraction(x), input().split(' '))
if b == 0:
print(1)
continue
elif a == 0:
print(0.5)
continue
up = a * (b + b + a / 4) / 2 - max(0, a - 4 * b) * (a / 4 - b) / 2
down = a * 2 * b
print(float(up / down))
| python | 12 | 0.517915 | 67 | 22.615385 | 13 | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 β€ t β€ 10000) β amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 β€ a, b β€ 106).
Pretests contain all the tests with 0 < a < 10, 0 β€ b < 10.
Output
Print t lines β the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000 | taco |
t = int(input())
for i in range(t):
(a, b) = [int(i) for i in input().split()]
b *= 4
if a == 0 and b == 0:
print(1)
elif a == 0:
print(0.5)
else:
ans = 0.5
if a > b:
ans += (a - b) / a / 2 + b / a / 4
else:
ans += a / b / 4
print(ans)
| python | 15 | 0.440154 | 43 | 16.266667 | 15 | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 β€ t β€ 10000) β amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 β€ a, b β€ 106).
Pretests contain all the tests with 0 < a < 10, 0 β€ b < 10.
Output
Print t lines β the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000 | taco |
T = int(input())
for _ in range(T):
(a, b) = map(int, input().split())
if b == 0:
print(1)
elif a == 0:
print(0.5)
else:
m = 2 * a * b
t = 1 / 8 * a * a + a * b
if b < a / 4:
delta = a / 4 - b
base = a * (delta / (delta + b))
t -= 1 / 2 * (delta * base)
ans = t / m
print(round(ans, 8))
| python | 15 | 0.433121 | 35 | 18.625 | 16 | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 β€ t β€ 10000) β amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 β€ a, b β€ 106).
Pretests contain all the tests with 0 < a < 10, 0 β€ b < 10.
Output
Print t lines β the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000 | taco |
t = int(input())
while t > 0:
(a, b) = map(int, input().split())
if a == 0 and b == 0:
print(1)
elif a == 0:
print(0.5)
elif b == 0:
print(1)
else:
ans = a * b + a * a / 8.0
if 4 * b <= a:
ans = 2.0 * b * b + (a - 4.0 * b) * b + a * b
ans /= 2.0 * a * b
print('%.10f' % ans)
t -= 1
| python | 16 | 0.413115 | 48 | 18.0625 | 16 | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 β€ t β€ 10000) β amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 β€ a, b β€ 106).
Pretests contain all the tests with 0 < a < 10, 0 β€ b < 10.
Output
Print t lines β the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000 | taco |
def li():
return list(map(int, input().split(' ')))
for _ in range(int(input())):
(a, b) = li()
if b != 0 and a != 0:
s = (max(0, a - 4 * b) + a) / 2
s *= min(a / 4, b)
ans = 1 / 2 + s / (2 * a * b)
print('{:.8f}'.format(ans))
elif b == 0:
print(1)
else:
print(0.5)
| python | 14 | 0.448763 | 42 | 20.769231 | 13 | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 β€ t β€ 10000) β amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 β€ a, b β€ 106).
Pretests contain all the tests with 0 < a < 10, 0 β€ b < 10.
Output
Print t lines β the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000 | taco |
t = int(input())
for _ in range(t):
(a, b) = map(float, input().split())
if b == 0.0:
print(1.0)
elif a == 0.0:
print(0.5)
elif a / 4.0 <= b:
print((a + 8.0 * b) / 16.0 / b)
else:
print(1.0 - b / a)
| python | 14 | 0.471698 | 37 | 18.272727 | 11 | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 β€ t β€ 10000) β amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 β€ a, b β€ 106).
Pretests contain all the tests with 0 < a < 10, 0 β€ b < 10.
Output
Print t lines β the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000 | taco |
import sys
lines = int(sys.stdin.readline())
for _ in range(lines):
(a, b) = map(float, sys.stdin.readline().split(' '))
if b == 0.0:
print(1)
elif a <= 4 * b:
print((0.125 * a + b) / (2.0 * b))
else:
print((a - b) / a)
| python | 13 | 0.534783 | 53 | 22 | 10 | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 β€ t β€ 10000) β amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 β€ a, b β€ 106).
Pretests contain all the tests with 0 < a < 10, 0 β€ b < 10.
Output
Print t lines β the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000 | taco |
T = int(input())
while T > 0:
T -= 1
(a, b) = map(int, input().split())
if a == 0 and b == 0:
print(1)
elif a == 0:
print(0.5)
elif b == 0:
print(1)
else:
check1 = a / 4
if check1 <= b:
ans = a * b + a * check1 / 2
else:
ans = 2 * a * b - 2 * b * b
ans = ans / (2 * a * b)
print(ans)
| python | 14 | 0.448718 | 35 | 16.333333 | 18 | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 β€ t β€ 10000) β amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 β€ a, b β€ 106).
Pretests contain all the tests with 0 < a < 10, 0 β€ b < 10.
Output
Print t lines β the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000 | taco |
def f(p, q):
if p == 0 and q == 0:
return 1
if p == 0:
return 0.5
if q == 0:
return 1
if q * 4 <= p:
return 1 - q * 2 * q / (2 * p * q)
else:
return 1 - (q - p / 4 + q) * p / (4 * p * q)
for i in range(int(input())):
(p, q) = map(int, input().split(' '))
print(f(p, q))
| python | 14 | 0.442509 | 46 | 19.5 | 14 | For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 β€ t β€ 10000) β amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 β€ a, b β€ 106).
Pretests contain all the tests with 0 < a < 10, 0 β€ b < 10.
Output
Print t lines β the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000 | taco |
def interpreter(code, iterations, width, height):
code = ''.join((c for c in code if c in '[news]*'))
canvas = [[0] * width for _ in range(height)]
row = col = step = count = loop = 0
while step < len(code) and count < iterations:
command = code[step]
if loop:
if command == '[':
loop += 1
elif command == ']':
loop -= 1
elif command == 'n':
row = (row - 1) % height
elif command == 's':
row = (row + 1) % height
elif command == 'w':
col = (col - 1) % width
elif command == 'e':
col = (col + 1) % width
elif command == '*':
canvas[row][col] ^= 1
elif command == '[' and canvas[row][col] == 0:
loop += 1
elif command == ']' and canvas[row][col] != 0:
loop -= 1
step += 1 if not loop else loop // abs(loop)
count += 1 if not loop else 0
return '\r\n'.join((''.join(map(str, row)) for row in canvas))
| python | 13 | 0.551163 | 63 | 29.714286 | 28 | # Esolang Interpreters #3 - Custom Paintfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series.
This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.
## The Language
Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape.
Valid commands in Paintfuck include:
- `n` - Move data pointer north (up)
- `e` - Move data pointer east (right)
- `s` - Move data pointer south (down)
- `w` - Move data pointer west (left)
- `*` - Flip the bit at the current cell (same as in Smallfuck)
- `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck)
- `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck)
The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task).
In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape.
Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine.
More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck).
## The Task
Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order:
1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid.
2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid.
3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer.
4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer.
A few things to note:
- Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters
- Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid
- In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid.
- One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.**
- Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`).
- Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument.
- The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is
```
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
```
... then your return string should be `"100\r\n010\r\n001"`.
Good luck :D
## Kata in this Series
1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck)
2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter)
3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter**
4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter) | taco |
def interpreter(code, iterations, width, height):
grid = [[0] * width for _ in range(height)]
code = [c for c in code if c in '[]nesw*']
(jumps, stack) = ({}, [])
for (i, c) in enumerate(code):
if c == '[':
stack.append(i)
if c == ']':
jumps[i] = stack.pop()
jumps[jumps[i]] = i
(ptr, x, y) = (-1, 0, 0)
while iterations > 0 and ptr < len(code) - 1:
ptr += 1
iterations -= 1
c = code[ptr]
if c == 'n':
y = (y - 1) % height
if c == 's':
y = (y + 1) % height
if c == 'w':
x = (x - 1) % width
if c == 'e':
x = (x + 1) % width
if c == '*':
grid[y][x] = 1 - grid[y][x]
if c == '[' and (not grid[y][x]):
ptr = jumps[ptr]
if c == ']' and grid[y][x]:
ptr = jumps[ptr]
return '\r\n'.join((''.join(map(str, row)) for row in grid))
| python | 12 | 0.480818 | 61 | 25.066667 | 30 | # Esolang Interpreters #3 - Custom Paintfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series.
This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.
## The Language
Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape.
Valid commands in Paintfuck include:
- `n` - Move data pointer north (up)
- `e` - Move data pointer east (right)
- `s` - Move data pointer south (down)
- `w` - Move data pointer west (left)
- `*` - Flip the bit at the current cell (same as in Smallfuck)
- `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck)
- `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck)
The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task).
In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape.
Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine.
More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck).
## The Task
Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order:
1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid.
2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid.
3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer.
4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer.
A few things to note:
- Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters
- Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid
- In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid.
- One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.**
- Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`).
- Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument.
- The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is
```
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
```
... then your return string should be `"100\r\n010\r\n001"`.
Good luck :D
## Kata in this Series
1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck)
2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter)
3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter**
4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter) | taco |
from collections import defaultdict
def interpreter(code, iterations, w, h):
(cp, r, c, p, stk, brackets, grid) = (0, 0, 0, 0, [], {}, [[0] * w for _ in range(h)])
for (i, cc) in enumerate(code):
if cc == '[':
stk.append(i)
elif cc is ']':
brackets[i] = stk.pop()
brackets[brackets[i]] = i
while p < iterations and cp < len(code):
if code[cp] == '*':
grid[r][c] = 0 if grid[r][c] else 1
elif code[cp] == '[' and grid[r][c] == 0:
cp = brackets[cp]
elif code[cp] == ']' and grid[r][c] == 1:
cp = brackets[cp]
elif code[cp] == 'n':
r = r - 1 if r else h - 1
elif code[cp] == 'w':
c = c - 1 if c else w - 1
elif code[cp] == 's':
r = r + 1 if r < h - 1 else 0
elif code[cp] == 'e':
c = c + 1 if c < w - 1 else 0
(cp, p) = (cp + 1, p + 1 if code[cp] in '[]nsew*' else p)
return '\r\n'.join([''.join((str(e) for e in r)) for r in grid])
| python | 13 | 0.511864 | 87 | 31.777778 | 27 | # Esolang Interpreters #3 - Custom Paintfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series.
This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.
## The Language
Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape.
Valid commands in Paintfuck include:
- `n` - Move data pointer north (up)
- `e` - Move data pointer east (right)
- `s` - Move data pointer south (down)
- `w` - Move data pointer west (left)
- `*` - Flip the bit at the current cell (same as in Smallfuck)
- `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck)
- `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck)
The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task).
In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape.
Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine.
More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck).
## The Task
Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order:
1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid.
2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid.
3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer.
4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer.
A few things to note:
- Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters
- Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid
- In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid.
- One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.**
- Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`).
- Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument.
- The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is
```
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
```
... then your return string should be `"100\r\n010\r\n001"`.
Good luck :D
## Kata in this Series
1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck)
2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter)
3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter**
4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter) | taco |
def interpreter(code, iterations, width, height):
inter = Inter(code, width, height)
inter.run(iterations)
return '\r\n'.join((''.join(map(str, e)) for e in inter.grid))
class Inter:
_instruct = {'w': 'moveW', 'e': 'moveE', 'n': 'moveN', 's': 'moveS', '*': 'flip', '[': 'jumpP', ']': 'jumpB'}
_nonC = lambda x: None
def __init__(self, code, w, h):
self.grid = [[0] * w for e in range(h)]
self.com = code
(self.w, self.h) = (w, h)
(self.x, self.y) = (0, 0)
(self.i, self.it) = (0, 0)
def countIteration(f):
def wrap(cls):
cls.it += 1
return f(cls)
return wrap
def run(self, iterat):
while self.it < iterat and self.i < len(self.com):
getattr(self, self._instruct.get(self.com[self.i], '_nonC'))()
self.i += 1
@countIteration
def moveE(self):
self.x = (self.x + 1) % self.w
@countIteration
def moveW(self):
self.x = (self.x - 1) % self.w
@countIteration
def moveN(self):
self.y = (self.y - 1) % self.h
@countIteration
def moveS(self):
self.y = (self.y + 1) % self.h
@countIteration
def flip(self):
self.grid[self.y][self.x] = int(not self.grid[self.y][self.x])
@countIteration
def jumpP(self):
if self.grid[self.y][self.x] == 0:
self._jump(1, ']', '[')
@countIteration
def jumpB(self):
if self.grid[self.y][self.x] == 1:
self._jump(-1, '[', ']')
def _jump(self, way, need, past, nest=0):
while way:
self.i += way
if self.com[self.i] == need and (not nest):
break
if self.com[self.i] == need and nest:
nest -= 1
if self.com[self.i] == past:
nest += 1
| python | 15 | 0.582157 | 110 | 22.253731 | 67 | # Esolang Interpreters #3 - Custom Paintfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series.
This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.
## The Language
Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape.
Valid commands in Paintfuck include:
- `n` - Move data pointer north (up)
- `e` - Move data pointer east (right)
- `s` - Move data pointer south (down)
- `w` - Move data pointer west (left)
- `*` - Flip the bit at the current cell (same as in Smallfuck)
- `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck)
- `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck)
The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task).
In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape.
Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine.
More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck).
## The Task
Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order:
1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid.
2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid.
3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer.
4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer.
A few things to note:
- Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters
- Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid
- In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid.
- One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.**
- Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`).
- Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument.
- The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is
```
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
```
... then your return string should be `"100\r\n010\r\n001"`.
Good luck :D
## Kata in this Series
1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck)
2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter)
3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter**
4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter) | taco |
def pairs(code):
opening = []
matching = {}
for (i, c) in enumerate(code):
if c == '[':
opening.append(i)
elif c == ']':
j = opening.pop()
matching[i] = j
matching[j] = i
assert not opening
return matching
def interpreter(code, iterations, width, height):
matching = pairs(code)
x = 0
y = 0
canvas = [[0 for _ in range(width)] for _ in range(height)]
index = 0
iterations_done = 0
while iterations_done < iterations:
try:
c = code[index]
except IndexError:
break
iterations_done += 1
if c == 'n':
y -= 1
y %= height
index += 1
elif c == 's':
y += 1
y %= height
index += 1
elif c == 'w':
x -= 1
x %= width
index += 1
elif c == 'e':
x += 1
x %= width
index += 1
elif c == '*':
canvas[y][x] ^= 1
index += 1
elif c == '[':
if canvas[y][x] == 0:
index = matching[index]
index += 1
elif c == ']':
if canvas[y][x] != 0:
index = matching[index]
index += 1
else:
iterations_done -= 1
index += 1
return '\r\n'.join((''.join(map(str, row)) for row in canvas))
| python | 13 | 0.531163 | 63 | 17.859649 | 57 | # Esolang Interpreters #3 - Custom Paintfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series.
This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.
## The Language
Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape.
Valid commands in Paintfuck include:
- `n` - Move data pointer north (up)
- `e` - Move data pointer east (right)
- `s` - Move data pointer south (down)
- `w` - Move data pointer west (left)
- `*` - Flip the bit at the current cell (same as in Smallfuck)
- `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck)
- `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck)
The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task).
In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape.
Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine.
More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck).
## The Task
Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order:
1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid.
2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid.
3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer.
4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer.
A few things to note:
- Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters
- Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid
- In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid.
- One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.**
- Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`).
- Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument.
- The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is
```
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
```
... then your return string should be `"100\r\n010\r\n001"`.
Good luck :D
## Kata in this Series
1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck)
2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter)
3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter**
4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter) | taco |
def build_jump_table(code):
jumps = {}
stack = []
for (i, c) in enumerate(code):
if c == '[':
stack.append(i)
elif c == ']':
j = stack.pop()
jumps[i] = j
jumps[j] = i
return jumps
class Interpreter:
def __init__(self, code, width, height):
self.code = code
self.jumps = build_jump_table(code)
self.cells = [[0] * width for _ in range(height)]
self.width = width
self.height = height
self.r = 0
self.c = 0
@property
def value(self):
return self.cells[self.r][self.c]
@value.setter
def value(self, val):
self.cells[self.r][self.c] = val
def run(self, iterations):
pc = 0
while pc < len(self.code) and iterations > 0:
op = self.code[pc]
if op == '*':
self.value = 1 - self.value
elif op == 'n':
self.r = (self.r - 1) % self.height
elif op == 's':
self.r = (self.r + 1) % self.height
elif op == 'w':
self.c = (self.c - 1) % self.width
elif op == 'e':
self.c = (self.c + 1) % self.width
elif op == '[' and self.value == 0:
pc = self.jumps[pc]
elif op == ']' and self.value == 1:
pc = self.jumps[pc]
pc += 1
iterations -= op in '*nswe[]'
return '\r\n'.join((''.join(map(str, row)) for row in self.cells))
def interpreter(code, iterations, width, height):
ip = Interpreter(code, width, height)
return ip.run(iterations)
| python | 16 | 0.577126 | 68 | 22.732143 | 56 | # Esolang Interpreters #3 - Custom Paintfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series.
This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.
## The Language
Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape.
Valid commands in Paintfuck include:
- `n` - Move data pointer north (up)
- `e` - Move data pointer east (right)
- `s` - Move data pointer south (down)
- `w` - Move data pointer west (left)
- `*` - Flip the bit at the current cell (same as in Smallfuck)
- `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck)
- `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck)
The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task).
In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape.
Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine.
More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck).
## The Task
Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order:
1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid.
2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid.
3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer.
4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer.
A few things to note:
- Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters
- Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid
- In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid.
- One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.**
- Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`).
- Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument.
- The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is
```
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
```
... then your return string should be `"100\r\n010\r\n001"`.
Good luck :D
## Kata in this Series
1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck)
2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter)
3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter**
4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter) | taco |
class Memory:
def __init__(self, width, height):
self.__x = 0
self.__y = 0
self.width = width
self.height = height
self.mem = [[0] * width for _ in range(height)]
def flip(self):
self.mem[self.y][self.x] = (self.get() + 1) % 2
def get(self):
return self.mem[self.y][self.x]
def to_string(self):
return '\r\n'.join((''.join(map(str, row)) for row in self.mem))
@property
def x(self):
return self.__x
@x.setter
def x(self, val):
self.__x = val % self.width
@property
def y(self):
return self.__y
@y.setter
def y(self, val):
self.__y = val % self.height
def interpreter(code, iterations, width, height):
op_ptr = 0
mem = Memory(width, height)
jumps = {}
bracket = []
for (i, op) in enumerate(code):
if op == '[':
bracket.append(i)
elif op == ']':
jumps[bracket[-1]] = i
jumps[i] = bracket.pop()
while iterations and op_ptr < len(code):
op = code[op_ptr]
if op in 'nesw*[]':
iterations -= 1
if op == 'n':
mem.y -= 1
elif op == 'e':
mem.x += 1
elif op == 's':
mem.y += 1
elif op == 'w':
mem.x -= 1
elif op == '*':
mem.flip()
elif op == '[' and mem.get() == 0:
op_ptr = jumps[op_ptr]
elif op == ']' and mem.get() != 0:
op_ptr = jumps[op_ptr]
op_ptr += 1
return mem.to_string()
| python | 13 | 0.55625 | 66 | 18.692308 | 65 | # Esolang Interpreters #3 - Custom Paintfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series.
This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.
## The Language
Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape.
Valid commands in Paintfuck include:
- `n` - Move data pointer north (up)
- `e` - Move data pointer east (right)
- `s` - Move data pointer south (down)
- `w` - Move data pointer west (left)
- `*` - Flip the bit at the current cell (same as in Smallfuck)
- `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck)
- `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck)
The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task).
In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape.
Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine.
More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck).
## The Task
Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order:
1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid.
2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid.
3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer.
4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer.
A few things to note:
- Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters
- Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid
- In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid.
- One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.**
- Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`).
- Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument.
- The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is
```
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
```
... then your return string should be `"100\r\n010\r\n001"`.
Good luck :D
## Kata in this Series
1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck)
2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter)
3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter**
4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter) | taco |
def interpreter(code, iterations, width, height):
grid = [[0 for r in range(width)] for c in range(height)]
t = iterations
(w, h) = (width, height)
(stack, bracket_pos) = ([], {})
for (i, c) in enumerate(code):
if c == '[':
stack.append(i)
elif c == ']':
bracket_pos[i] = stack[-1]
bracket_pos[stack.pop()] = i
(a, b, p) = (0, 0, 0)
while t > 0 and p < len(code):
if code[p] == 'e':
b += 1
elif code[p] == 'w':
b -= 1
elif code[p] == 's':
a += 1
elif code[p] == 'n':
a -= 1
elif code[p] == '*':
grid[a % h][b % w] ^= 1
elif code[p] == '[':
if grid[a % h][b % w] == 0:
p = bracket_pos[p]
elif code[p] == ']':
if grid[a % h][b % w] == 1:
p = bracket_pos[p]
else:
t += 1
t -= 1
p += 1
return '\r\n'.join((''.join(map(str, g)) for g in grid))
| python | 13 | 0.476601 | 58 | 22.882353 | 34 | # Esolang Interpreters #3 - Custom Paintfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series.
This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.
## The Language
Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape.
Valid commands in Paintfuck include:
- `n` - Move data pointer north (up)
- `e` - Move data pointer east (right)
- `s` - Move data pointer south (down)
- `w` - Move data pointer west (left)
- `*` - Flip the bit at the current cell (same as in Smallfuck)
- `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck)
- `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck)
The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task).
In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape.
Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine.
More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck).
## The Task
Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order:
1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid.
2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid.
3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer.
4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer.
A few things to note:
- Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters
- Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid
- In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid.
- One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.**
- Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`).
- Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument.
- The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is
```
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
```
... then your return string should be `"100\r\n010\r\n001"`.
Good luck :D
## Kata in this Series
1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck)
2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter)
3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter**
4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter) | taco |
def interpreter(code, iterations, width, height):
matrix = [[0 for i in range(width)] for i in range(height)]
i = 0
iteration = 0
p = [0, 0]
s = []
mate = {}
for k in range(len(code)):
c = code[k]
if c == '[':
s.append(k)
if c == ']':
m = s.pop()
mate[m] = k
mate[k] = m
while iteration < iterations and i < len(code):
c = code[i]
if c == '*':
matrix[p[1]][p[0]] ^= 1
elif c == 'n':
p[1] = (p[1] - 1) % height
elif c == 'e':
p[0] = (p[0] + 1) % width
elif c == 's':
p[1] = (p[1] + 1) % height
elif c == 'w':
p[0] = (p[0] - 1) % width
elif c == '[':
if not matrix[p[1]][p[0]]:
i = mate[i]
elif c == ']':
if matrix[p[1]][p[0]]:
i = mate[i]
else:
iteration -= 1
i += 1
iteration += 1
return '\r\n'.join([''.join([str(matrix[y][x]) for x in range(width)]) for y in range(height)])
| python | 14 | 0.477855 | 96 | 21.578947 | 38 | # Esolang Interpreters #3 - Custom Paintfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewhat inter-related. Under the influence of [a fellow Codewarrior](https://www.codewars.com/users/nickkwest), these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series.
This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various [esoteric programming languages/Esolangs](http://esolangs.org), mainly [Brainfuck](http://esolangs.org/wiki/Brainfuck) derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them.
## The Language
Paintfuck is a [borderline-esoteric programming language/Esolang](http://esolangs.org) which is a derivative of [Smallfuck](http://esolangs.org/wiki/Smallfuck) (itself a derivative of the famous [Brainfuck](http://esolangs.org/wiki/Brainfuck)) that uses a two-dimensional data grid instead of a one-dimensional tape.
Valid commands in Paintfuck include:
- `n` - Move data pointer north (up)
- `e` - Move data pointer east (right)
- `s` - Move data pointer south (down)
- `w` - Move data pointer west (left)
- `*` - Flip the bit at the current cell (same as in Smallfuck)
- `[` - Jump past matching `]` if bit under current pointer is `0` (same as in Smallfuck)
- `]` - Jump back to the matching `[` (if bit under current pointer is nonzero) (same as in Smallfuck)
The specification states that any non-command character (i.e. any character other than those mentioned above) should simply be ignored. The output of the interpreter is the two-dimensional data grid itself, best as animation as the interpreter is running, but at least a representation of the data grid itself after a certain number of iterations (explained later in task).
In current implementations, the 2D datagrid is finite in size with toroidal (wrapping) behaviour. This is one of the few major differences of Paintfuck from Smallfuck as Smallfuck terminates (normally) whenever the pointer exceeds the bounds of the tape.
Similar to Smallfuck, Paintfuck is Turing-complete **if and only if** the 2D data grid/canvas were unlimited in size. However, since the size of the data grid is defined to be finite, it acts like a finite state machine.
More info on this Esolang can be found [here](http://esolangs.org/wiki/Paintfuck).
## The Task
Your task is to implement a custom Paintfuck interpreter `interpreter()`/`Interpret` which accepts the following arguments in the specified order:
1. `code` - **Required**. The Paintfuck code to be executed, passed in as a string. May contain comments (non-command characters), in which case your interpreter should simply ignore them. If empty, simply return the initial state of the data grid.
2. `iterations` - **Required**. A non-negative integer specifying the number of iterations to be performed before the final state of the data grid is returned. See notes for definition of 1 iteration. If equal to zero, simply return the initial state of the data grid.
3. `width` - **Required**. The width of the data grid in terms of the number of data cells in each row, passed in as a positive integer.
4. `height` - **Required**. The height of the data grid in cells (i.e. number of rows) passed in as a positive integer.
A few things to note:
- Your interpreter should treat all command characters as **case-sensitive** so `N`, `E`, `S` and `W` are **not** valid command characters
- Your interpreter should initialize all cells within the data grid to a value of `0` regardless of the width and height of the grid
- In this implementation, your pointer must always start at the **top-left hand corner** of the data grid (i.e. first row, first column). This is important as some implementations have the data pointer starting at the middle of the grid.
- One iteration is defined as one step in the program, i.e. the number of command characters evaluated. For example, given a program `nessewnnnewwwsswse` and an iteration count of `5`, your interpreter should evaluate `nesse` before returning the final state of the data grid. **Non-command characters should not count towards the number of iterations.**
- Regarding iterations, the act of skipping to the matching `]` when a `[` is encountered (or vice versa) is considered to be **one** iteration regardless of the number of command characters in between. The next iteration then commences at the command **right after** the matching `]` (or `[`).
- Your interpreter should terminate normally and return the final state of the 2D data grid whenever **any** of the mentioned conditions become true: (1) All commands have been considered left to right, or (2) Your interpreter has already performed the number of iterations specified in the second argument.
- The return value of your interpreter should be a representation of the final state of the 2D data grid where each row is separated from the next by a CRLF (`\r\n`). For example, if the final state of your datagrid is
```
[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
]
```
... then your return string should be `"100\r\n010\r\n001"`.
Good luck :D
## Kata in this Series
1. [Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck)
2. [Esolang Interpreters #2 - Custom Smallfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-2-custom-smallfuck-interpreter)
3. **Esolang Interpreters #3 - Custom Paintfuck Interpreter**
4. [Esolang Interpreters #4 - Boolfuck Interpreter](http://codewars.com/kata/esolang-interpreters-number-4-boolfuck-interpreter) | taco |
n = int(input())
arr = list(map(int, input().split()))
tracker = [[-1] * (n + 1) for _ in range(2024)]
d = [[] for _ in range(n)]
for (j, v) in enumerate(arr):
tracker[v][j] = j
d[j].append(j)
for v in range(1, 2024):
for i in range(n):
j = tracker[v][i]
h = tracker[v][j + 1] if j != -1 else -1
if j != -1 and h != -1:
tracker[v + 1][i] = h
d[i].append(h)
a = [_ for _ in range(1, n + 1)]
for s in range(n):
for tracker in d[s]:
a[tracker] = min(a[tracker], a[s - 1] + 1 if s > 0 else 1)
print(a[n - 1])
| python | 13 | 0.521989 | 60 | 26.526316 | 19 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
INF = 10 ** 9
dp = [[INF] * (n + 1) for i in range(n + 1)]
val = [[-1] * (n + 1) for i in range(n + 1)]
for i in range(n):
dp[i][i + 1] = 1
val[i][i + 1] = a[i]
for l in range(2, n + 1):
for i in range(n - l + 1):
j = i + l
for k in range(i + 1, j):
if dp[i][k] == dp[k][j] == 1 and val[i][k] == val[k][j]:
dp[i][j] = 1
val[i][j] = val[i][k] + 1
else:
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])
print(dp[0][n])
| python | 17 | 0.467925 | 59 | 25.5 | 20 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
import sys
readline = sys.stdin.buffer.readline
N = int(readline())
A = list(map(int, readline().split()))
dp = [[0] * N for _ in range(N)]
for j in range(N):
dp[j][0] = A[j]
for l in range(1, N):
for j in range(l, N):
for k in range(j - l, j):
if dp[k][k - j + l] == dp[j][j - k - 1] > 0:
dp[j][l] = 1 + dp[j][j - k - 1]
break
dp = [None] + dp
Dp = [0] * (N + 1)
for j in range(1, N + 1):
res = N
for l in range(j):
if dp[j][l]:
res = min(res, 1 + Dp[j - l - 1])
Dp[j] = res
print(Dp[N])
| python | 15 | 0.501953 | 47 | 22.272727 | 22 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
n = int(input())
A = list(map(int, input().split()))
INF = 10 ** 3
dp = [[INF] * (n + 1) for _ in range(n + 1)]
val = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n):
dp[i][i + 1] = 1
for i in range(n):
val[i][i + 1] = A[i]
for d in range(2, n + 1):
for i in range(n + 1 - d):
j = i + d
for k in range(i + 1, j):
if dp[i][k] == 1 and dp[k][j] == 1 and (val[i][k] == val[k][j]):
dp[i][j] = min(dp[i][j], 1)
val[i][j] = val[i][k] + 1
else:
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])
print(dp[0][n])
| python | 17 | 0.448405 | 67 | 27.052632 | 19 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
from collections import defaultdict, deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, itertools, math
sys.setrecursionlimit(10 ** 5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI():
return list(map(int, input().split()))
def LF():
return list(map(float, input().split()))
def LI_():
return list(map(lambda x: int(x) - 1, input().split()))
def II():
return int(input())
def IF():
return float(input())
def S():
return input().rstrip()
def LS():
return S().split()
def IR(n):
res = [None] * n
for i in range(n):
res[i] = II()
return res
def LIR(n):
res = [None] * n
for i in range(n):
res[i] = LI()
return res
def FR(n):
res = [None] * n
for i in range(n):
res[i] = IF()
return res
def LIR(n):
res = [None] * n
for i in range(n):
res[i] = IF()
return res
def LIR_(n):
res = [None] * n
for i in range(n):
res[i] = LI_()
return res
def SR(n):
res = [None] * n
for i in range(n):
res[i] = S()
return res
def LSR(n):
res = [None] * n
for i in range(n):
res[i] = LS()
return res
mod = 1000000007
inf = float('INF')
def solve():
n = II()
a = LI()
dp = [[None for i in range(n + 1)] for i in range(n + 1)]
for i in range(n):
dp[i][i + 1] = [a[i], a[i], 1]
dp[i + 1][i] = [a[i], a[i], 1]
for i in range(2, n + 1):
for l in range(n - i + 1):
tmp = [-inf, inf, inf]
r = l + i
dpl = dp[l]
dpr = dp[r]
for m in range(l + 1, r):
lm = dpl[m]
mr = dpr[m]
lr = lm[2] + mr[2] - (lm[1] == mr[0])
if lr < tmp[2]:
tmp[2] = lr
if lm[1] == mr[0]:
if lm[2] == 1:
tmp[0] = lm[0] + 1
else:
tmp[0] = lm[0]
if mr[2] == 1:
tmp[1] = mr[1] + 1
else:
tmp[1] = mr[1]
else:
tmp[0] = lm[0]
tmp[1] = mr[1]
dp[l][r] = tmp
dp[r][l] = tmp
print(dp[0][n][2])
return
solve()
| python | 19 | 0.520811 | 58 | 16.192661 | 109 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
import io
import os
import sys
from functools import lru_cache
from collections import defaultdict
sys.setrecursionlimit(10 ** 5)
def solve(N, A):
valToLeftRight = defaultdict(lambda : defaultdict(set))
valToRightLeft = defaultdict(lambda : defaultdict(set))
for (i, x) in enumerate(A):
valToLeftRight[x][i].add(i)
valToRightLeft[x][i].add(i)
maxVal = 1000 + 10
for val in range(maxVal):
for (l, rights) in valToLeftRight[val - 1].items():
for r in rights:
l2 = r + 1
if l2 in valToLeftRight[val - 1]:
for r2 in valToLeftRight[val - 1][l2]:
assert l <= r
assert r + 1 == l2
assert l2 <= r2
valToLeftRight[val][l].add(r2)
valToRightLeft[val][r2].add(l)
r2 = l - 1
if r2 in valToRightLeft[val - 1]:
for l2 in valToRightLeft[val - 1][r2]:
assert l2 <= r2
assert r2 == l - 1
assert l <= r
valToLeftRight[val][l2].add(r)
valToRightLeft[val][r].add(l2)
intervals = defaultdict(list)
for val in range(maxVal):
for (l, rights) in valToLeftRight[val].items():
for r in rights:
intervals[l].append(r)
@lru_cache(maxsize=None)
def getBest(left):
if left == N:
return 0
best = float('inf')
for right in intervals[left]:
best = min(best, 1 + getBest(right + 1))
return best
return getBest(0)
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N,) = list(map(int, input().split()))
A = list(map(int, input().split()))
ans = solve(N, A)
print(ans)
| python | 18 | 0.63772 | 60 | 26.811321 | 53 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
import sys
input = sys.stdin.readline
n = int(input())
A = list(map(int, input().split()))
DP = [[-1] * (n + 1) for i in range(n + 1)]
for i in range(n):
DP[i][i] = A[i]
for mid in range(1, n):
for i in range(n):
j = i + mid
if j == n:
break
for k in range(i, j + 1):
if DP[i][k] == DP[k + 1][j] and DP[i][k] != -1:
DP[i][j] = DP[i][k] + 1
ANS = [2000] * (n + 1)
ANS.append(0)
for i in range(n):
ANS[i] = min(ANS[i], ANS[i - 1] + 1)
for j in range(i, n):
if DP[i][j] != -1:
ANS[j] = min(ANS[j], ANS[i - 1] + 1)
print(ANS[n - 1])
| python | 14 | 0.494585 | 50 | 23.086957 | 23 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
n = int(input())
b = [int(_) for _ in input().split()]
e = [[-1] * (n + 1) for _ in range(2024)]
d = [[] for _ in range(n)]
for (j, v) in enumerate(b):
e[v][j] = j
d[j].append(j)
for v in range(1, 2024):
for i in range(n):
j = e[v][i]
h = e[v][j + 1] if j != -1 else -1
if j != -1 and h != -1:
e[v + 1][i] = h
d[i].append(h)
a = [_ for _ in range(1, n + 1)]
for s in range(n):
for e in d[s]:
a[e] = min(a[e], a[s - 1] + 1 if s > 0 else 1)
print(a[n - 1])
| python | 13 | 0.463002 | 48 | 23.894737 | 19 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
n = int(input())
a = list(map(int, input().split()))
dp = [[505] * n for _ in range(n)]
Max = [[0] * n for _ in range(n)]
for i in range(n):
dp[i][i] = 1
Max[i][i] = a[i]
for len in range(1, n + 1):
for i in range(n - len + 1):
j = i + len - 1
for k in range(i, j):
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j])
if dp[i][k] == 1 and dp[k + 1][j] == 1 and (Max[i][k] == Max[k + 1][j]):
dp[i][j] = 1
Max[i][j] = Max[i][k] + 1
print(dp[0][n - 1])
| python | 15 | 0.45629 | 75 | 28.3125 | 16 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from collections import defaultdict as dd, deque, Counter
def data():
return sys.stdin.readline().strip()
def mdata():
return list(map(int, data().split()))
def outl(var):
sys.stdout.write(' '.join(map(str, var)) + '\n')
def out(var):
sys.stdout.write(str(var) + '\n')
from decimal import Decimal
INF = float('inf')
mod = int(1000000000.0) + 7
def cal(l, r):
if l == r:
dp1[l][r] = 1
dp2[l][r] = a[l]
if dp1[l][r]:
return dp1[l][r]
for i in range(l, r):
if cal(l, i) == 1 and cal(i + 1, r) == 1 and (dp2[l][i] == dp2[i + 1][r]):
dp1[l][r] = 1
dp2[l][r] = dp2[l][i] + 1
if not dp2[l][r]:
dp1[l][r] = 2
return dp1[l][r]
def cal2(l, r):
if dp1[l][r] == 1:
dp3[l][r] = 1
return 1
elif dp3[l][r]:
return dp3[l][r]
ans = INF
for i in range(l, r):
ans = min(cal2(l, i) + cal2(i + 1, r), ans)
dp3[l][r] = ans
return ans
n = int(data())
a = mdata()
ans = [n]
dp1 = [[0] * n for i in range(n)]
dp2 = [[0] * n for i in range(n)]
dp3 = [[0] * n for i in range(n)]
cal(0, n - 1)
cal2(0, n - 1)
out(dp3[0][n - 1])
| python | 13 | 0.561788 | 76 | 20.12963 | 54 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
n = int(input())
b = list(map(int, input().split(' ')))
e = [[-1] * (n + 1) for _ in range(2048)]
d = [[] for _ in range(n)]
for (i, v) in enumerate(b):
e[v][i] = i
d[i].append(i)
for v in range(1, 2048):
for i in range(n):
j = e[v][i]
if j != -1:
h = e[v][j + 1]
else:
h = -1
if j != -1 and h != -1:
e[v + 1][i] = h
d[i].append(h)
a = [_ for _ in range(1, n + 1)]
for s in range(n):
for e in d[s]:
if s > 0:
temp = a[s - 1] + 1
else:
temp = 1
a[e] = min(a[e], temp)
print(a[n - 1])
| python | 12 | 0.450867 | 41 | 18.961538 | 26 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
N = int(input())
X = list(map(int, input().split()))
from collections import defaultdict
dp1 = defaultdict(lambda : -1)
M = 1001
def ec(i, j):
return i * M + j
for i in range(N):
dp1[ec(i, i + 1)] = X[i]
for i in range(2, N + 1):
for j in range(N - i + 1):
for k in range(1, i):
(u, v) = (dp1[ec(j, j + k)], dp1[ec(j + k, j + i)])
if u != -1 and v != -1 and (u == v):
dp1[ec(j, j + i)] = u + 1
break
dp2 = [0] * (N + 1)
for i in range(N):
dp2[i + 1] = dp2[i] + 1
for j in range(i + 1):
if dp1[ec(j, i + 1)] == -1:
continue
dp2[i + 1] = min(dp2[i + 1], dp2[j] + 1)
print(dp2[-1])
| python | 15 | 0.496711 | 54 | 23.32 | 25 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
import sys
input = lambda : sys.stdin.readline().rstrip()
import copy
n = int(input())
A = [int(i) for i in input().split()]
inf = float('inf')
DP = [[inf] * (n + 1) for _ in range(n + 1)]
for j in range(1, n + 1):
for i in range(n):
if i + j > n:
continue
elif j == 1:
DP[i][i + 1] = A[i]
else:
for k in range(i + 1, i + j):
if DP[i][k] < 10000 and DP[k][i + j] < 10000:
if DP[i][k] == DP[k][i + j]:
DP[i][i + j] = DP[i][k] + 1
else:
DP[i][i + j] = 20000
elif DP[i][k] < 10000:
DP[i][i + j] = min(DP[i][i + j], 10000 + DP[k][i + j])
elif DP[k][i + j] < 10000:
DP[i][i + j] = min(DP[i][i + j], DP[i][k] + 10000)
else:
DP[i][i + j] = min(DP[i][i + j], DP[i][k] + DP[k][i + j])
print(DP[0][n] // 10000 if DP[0][n] >= 10000 else 1)
| python | 20 | 0.463659 | 62 | 28.555556 | 27 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
N = int(input())
X = list(map(int, input().split()))
from collections import defaultdict
dp = defaultdict(lambda : -1)
M = 1000001
for i in range(N):
dp[i + M] = X[i]
for i in range(2, N + 1):
for j in range(N - i + 1):
for k in range(1, i):
(u, v) = (dp[j + M * k], dp[j + k + M * (i - k)])
if u == -1 or v == -1 or u != v:
continue
dp[j + M * i] = u + 1
break
dp2 = [0] * (N + 1)
for i in range(N):
dp2[i + 1] = dp2[i] + 1
for j in range(i + 1):
if dp[j + (i + 1 - j) * M] == -1:
continue
dp2[i + 1] = min(dp2[i + 1], dp2[j] + 1)
print(dp2[-1])
| python | 15 | 0.487847 | 52 | 24.043478 | 23 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
N = int(input())
L = list(map(int, input().split()))
DP = [[-1] * N for i in range(N)]
for d in range(N):
for s in range(N - d):
e = s + d
if s == e:
DP[s][e] = L[s]
continue
for m in range(s, e):
l = DP[s][m]
r = DP[m + 1][e]
if l == r and l != -1:
DP[s][e] = max(DP[s][e], l + 1)
DP2 = [i + 1 for i in range(N)]
for i in range(N):
if DP[0][i] != -1:
DP2[i] = 1
continue
for j in range(i):
if DP[j + 1][i] != -1:
DP2[i] = min(DP2[i], DP2[j] + 1)
print(DP2[N - 1])
| python | 15 | 0.464143 | 35 | 20.826087 | 23 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
printn = lambda x: print(x, end='')
inn = lambda : int(input())
inl = lambda : list(map(int, input().split()))
inm = lambda : map(int, input().split())
ins = lambda : input().strip()
DBG = True and False
BIG = 10 ** 18
R = 10 ** 9 + 7
def ddprint(x):
if DBG:
print(x)
def dp(l, r):
if dpa[l][r] >= 0:
return dpa[l][r]
elif l == r:
dpa[l][r] = a[l]
else:
dpa[l][r] = 0
for j in range(l, r):
x = dp(l, j)
y = dp(j + 1, r)
if 0 < x == y:
dpa[l][r] = x + 1
return dpa[l][r]
n = inn()
a = inl()
dpa = [[-1] * (n + 1) for i in range(n + 1)]
dp2 = [BIG] * (n + 1)
dp2[0] = 1
for i in range(n):
if dp(0, i) > 0:
dp2[i] = 1
else:
mn = i + 1
for j in range(i):
x = dp(j + 1, i)
if 0 < x:
mn = min(mn, dp2[j] + 1)
dp2[i] = mn
for i in range(n):
ddprint(dpa[i])
ddprint(dp2)
print(dp2[n - 1])
| python | 16 | 0.495192 | 46 | 17.488889 | 45 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
dp = [[1000] * (n + 1) for i in range(n + 1)]
val = [[0] * (n + 1) for i in range(n + 1)]
for i in range(n):
dp[i][i + 1] = 1
val[i][i + 1] = a[i]
for p in range(2, n + 1):
for i in range(n - p + 1):
j = i + p
for k in range(i + 1, j):
if dp[i][k] == dp[k][j] == 1 and val[i][k] == val[k][j]:
dp[i][j] = 1
val[i][j] = val[i][k] + 1
else:
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])
print(dp[0][n])
| python | 17 | 0.47093 | 59 | 26.157895 | 19 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
rr = lambda : input().rstrip()
rri = lambda : int(rr())
rrm = lambda : list(map(int, rr().split()))
from functools import lru_cache
memo = lru_cache(None)
from sys import setrecursionlimit as srl
srl(10 ** 5)
def solve(N, A):
@memo
def dp(i, j, left=0):
if i == j:
if left == 0:
return 1
if A[i] == left:
return 1
return 2
if i > j:
return 0 if left == 0 else 1
ans = 1 + dp(i + 1, j, A[i])
if left >= 1:
stack = []
for k in range(i, j + 1):
stack.append(A[k])
while len(stack) >= 2 and stack[-1] == stack[-2]:
stack.pop()
stack[-1] += 1
if len(stack) == 1 and left == stack[-1]:
cand = dp(k + 1, j, left + 1)
if cand < ans:
ans = cand
return ans
return dp(1, N - 1, A[0])
print(solve(rri(), rrm()))
| python | 17 | 0.536585 | 53 | 21.257143 | 35 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
n = int(input())
a = list(map(int, input().split()))
grip = [[-1] * (n - i) for i in range(n)]
grip[0] = a.copy()
for level in range(1, n):
for left in range(n - level):
for split in range(level):
pl = grip[level - split - 1][left]
pr = grip[split][left + level - split]
if pl == pr != -1:
grip[level][left] = pl + 1
pref = [0] * (n + 1)
for p in range(1, n + 1):
x = n
for j in range(p):
l = pref[j]
r = grip[p - j - 1][j]
if r == -1:
r = p - j
else:
r = 1
x = min(x, l + r)
pref[p] = x
print(pref[-1])
| python | 13 | 0.502783 | 41 | 21.458333 | 24 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
import sys
dp = []
a = []
def calcdp(l, r):
global dp, a
if l + 1 == r:
dp[l][r] = a[l]
return dp[l][r]
if dp[l][r] != 0:
return dp[l][r]
dp[l][r] = -1
for k in range(l + 1, r):
la = calcdp(l, k)
ra = calcdp(k, r)
if la > 0 and la == ra:
dp[l][r] = la + 1
return dp[l][r]
def solve(n):
dp2 = [float('inf')] * (n + 1)
dp2[0] = 0
for i in range(n):
for j in range(i + 1, n + 1):
if calcdp(i, j) > 0:
dp2[j] = min(dp2[j], dp2[i] + 1)
return dp2[n]
def ip():
global dp, a
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))
a.append(0)
dp = []
ll = [0] * (n + 1)
for _ in range(n + 1):
dp.append(list(ll))
print(solve(n))
ip()
| python | 15 | 0.500717 | 49 | 16.871795 | 39 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
N = int(input())
arr = list(map(int, input().split()))
dp = [[-1 for x in range(N)] for y in range(N)]
for size in range(1, N + 1):
for i in range(N - size + 1):
j = i + size - 1
if i == j:
dp[i][j] = arr[i]
else:
for k in range(i, j):
if dp[i][k] != -1 and dp[i][k] == dp[k + 1][j]:
dp[i][j] = dp[i][k] + 1
dp2 = [x + 1 for x in range(N)]
for i in range(N):
for k in range(i + 1):
if dp[k][i] != -1:
if k == 0:
dp2[i] = 1
else:
dp2[i] = min(dp2[i], dp2[k - 1] + 1)
print(dp2[N - 1])
| python | 17 | 0.470363 | 51 | 23.904762 | 21 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
n = int(input())
a = list(map(int, input().split()))
dp = [[False] * (n + 1) for i in range(n + 1)]
def solve(l, r):
if dp[l][r]:
return dp[l][r]
if r - l == 1:
dp[l][r] = (a[l], 1)
return dp[l][r]
tmp = 10 ** 9
for i in range(l + 1, r):
if solve(l, i)[0] == -1 or solve(i, r)[0] == -1:
tmp = min(tmp, dp[l][i][1] + dp[i][r][1])
elif solve(l, i) == solve(i, r):
tmp = solve(l, i)[0] + 1
dp[l][r] = (tmp, 1)
return dp[l][r]
else:
tmp = min(tmp, 2)
dp[l][r] = (-1, tmp)
return dp[l][r]
solve(0, n)
print(dp[0][n][1])
| python | 15 | 0.469945 | 50 | 21.875 | 24 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
dp = [[-1] * (N + 1) for _ in range(N + 1)]
for l in range(N):
dp[l][l + 1] = A[l]
for d in range(2, N + 1):
for l in range(N - d + 1):
for t in range(1, d):
if dp[l][l + t] == dp[l + t][l + d] and dp[l][l + t] != -1:
dp[l][l + d] = dp[l][l + t] + 1
break
dp2 = [i for i in range(N + 1)]
for r in range(1, N + 1):
if dp[0][r] != -1:
dp2[r] = 1
for l in range(N):
for r in range(l + 2, N + 1):
if dp[l + 1][r] != -1:
dp2[r] = min(dp2[l + 1] + 1, dp2[r])
else:
dp2[r] = min(dp2[l + 1] + (r - l - 1), dp2[r])
print(dp2[N])
| python | 16 | 0.471875 | 62 | 25.666667 | 24 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
from collections import Counter
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce
def input():
return sys.stdin.readline().strip()
def iinput():
return int(input())
def tinput():
return input().split()
def rinput():
return map(int, tinput())
def rlinput():
return list(rinput())
mod = int(1000000000.0) + 7
def factors(n):
return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
n = iinput()
a = rlinput()
dp = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
dp[i][i] = a[i]
for l in range(n - 2, -1, -1):
for r in range(l + 1, n):
for k in range(l, r):
if dp[l][k] == dp[k + 1][r] and dp[l][k] != 0:
dp[l][r] = dp[l][k] + 1
squeeze = [float('inf')] * (n + 1)
squeeze[0] = 0
for i in range(1, n + 1):
for j in range(i):
if dp[j][i - 1] != 0:
squeeze[i] = min(squeeze[i], squeeze[j] + 1)
print(squeeze[n])
| python | 16 | 0.604273 | 99 | 21.340909 | 44 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
from sys import stdin, gettrace
if not gettrace():
def input():
return next(stdin)[:-1]
INF = 10000
def main():
n = int(input())
aa = [int(a) for a in input().split()]
dp = [[0] * (n + 1) for _ in range(n)]
def calc_dp(i, j):
if i + 1 == j:
dp[i][j] = aa[i]
if dp[i][j] != 0:
return dp[i][j]
dp[i][j] = -1
for k in range(i + 1, j):
lf = calc_dp(i, k)
rg = calc_dp(k, j)
if lf > 0 and lf == rg:
dp[i][j] = lf + 1
break
return dp[i][j]
dp2 = list(range(0, n + 1))
for i in range(n):
for j in range(i + 1, n + 1):
if calc_dp(i, j) > 0:
dp2[j] = min(dp2[j], dp2[i] + 1)
print(dp2[n])
main()
| python | 15 | 0.498442 | 39 | 19.0625 | 32 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
n = int(input())
a = list(map(int, input().split(' ')))
new_a = [[0] * 600 for i in range(600)]
dp = [[2147483647] * 600 for i in range(600)]
for i in range(n):
new_a[i + 1][i + 1] = a[i]
dp[i + 1][i + 1] = 1
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
dp[i][j] = j - i + 1
for llen in range(2, n + 1):
for left in range(1, n - llen + 2):
right = left + llen - 1
for middle in range(left, right):
dp[left][right] = min(dp[left][right], dp[left][middle] + dp[middle + 1][right])
if dp[left][middle] == 1 and dp[middle + 1][right] == 1 and (new_a[left][middle] == new_a[middle + 1][right]):
dp[left][right] = 1
new_a[left][right] = new_a[left][middle] + 1
print(dp[1][n])
| python | 15 | 0.550992 | 113 | 36.157895 | 19 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
(self.buffer.truncate(0), self.buffer.seek(0))
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda : self.buffer.read().decode('ascii')
self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd, deque as dq
import math, string
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
MOD = 998244353
def solve():
N = getInt()
A = getInts()
dp = [[-1 for j in range(N)] for i in range(N)]
for i in range(N):
dp[i][i] = A[i]
for X in range(2, N + 1):
for i in range(N - X + 1):
j = i + X - 1
for k in range(i, j):
if dp[i][k] == dp[k + 1][j] and dp[i][k] != -1:
dp[i][j] = dp[i][k] + 1
break
ans = [10 ** 9 + 1] * (N + 1)
ans[0] = 0
for i in range(1, N + 1):
for k in range(1, i + 1):
if dp[k - 1][i - 1] != -1:
ans[i] = min(ans[i], ans[k - 1] + 1)
return ans[N]
print(solve())
| python | 17 | 0.633523 | 76 | 25.212766 | 94 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
def f():
n = int(input())
A = [int(s) for s in input().split()]
memo = [[None for j in range(n + 1)] for i in range(n + 1)]
for i in range(n):
memo[i][i] = [A[i], A[i], 1]
for l in range(2, n + 1):
for left in range(0, n - l + 1):
right = left + l - 1
minLen = l
shortestMid = right
for mid in range(left + 1, right + 1):
pre = memo[left][mid - 1]
post = memo[mid][right]
combLen = pre[2] + post[2]
if pre[1] == post[0]:
combLen -= 1
if combLen < minLen:
minLen = combLen
shortestMid = mid
pre = memo[left][shortestMid - 1]
post = memo[shortestMid][right]
startEle = pre[0]
endEle = post[1]
if pre[2] == 1:
if pre[0] == post[0]:
startEle = pre[0] + 1
if post[2] == 1:
if pre[1] == post[0]:
endEle = post[0] + 1
memo[left][right] = [startEle, endEle, minLen]
print(memo[0][n - 1][2])
f()
| python | 15 | 0.530011 | 60 | 25.757576 | 33 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
import sys
import bisect
import heapq
from collections import defaultdict as dd
from collections import deque
from collections import Counter as c
from itertools import combinations as comb
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353
def data():
return sys.stdin.readline().strip()
def out(var):
sys.stdout.write(var)
def l():
return list(map(int, data().split()))
def sl():
return list(map(str, data().split()))
def sp():
return map(int, data().split())
def ssp():
return map(str, data().split())
def l1d(n, val=0):
return [val for i in range(n)]
def l2d(n, m, val=0):
return [[val for i in range(n)] for j in range(m)]
n = int(data())
arr = l()
dp = [[0 for j in range(500)] for i in range(500)]
dp2 = [0 for i in range(501)]
for i in range(n):
dp[i][i] = arr[i]
i = n - 2
while ~i:
j = i + 1
while j < n:
dp[i][j] = -1
for k in range(i, j):
if (~dp[i][k] and dp[i][k]) == dp[k + 1][j]:
dp[i][j] = dp[i][k] + 1
j += 1
i -= 1
for i in range(1, n + 1):
dp2[i] = pow(10, 9)
for j in range(i):
if ~dp[j][i - 1]:
dp2[i] = min(dp2[i], dp2[j] + 1)
out(str(dp2[n]))
| python | 14 | 0.606557 | 64 | 19.696429 | 56 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
from heapq import *
import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')
def II():
return int(sys.stdin.readline())
def MI():
return map(int, sys.stdin.readline().split())
def LI():
return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number):
return [LI() for _ in range(rows_number)]
def SI():
return sys.stdin.readline()[:-1]
def main():
inf = 10 ** 9
n = II()
aa = LI()
dp1 = [[-1] * (n + 1) for _ in range(n)]
to = [[i + 1] for i in range(n)]
for i in range(n):
dp1[i][i + 1] = aa[i]
for w in range(2, n + 1):
for l in range(n - w + 1):
r = l + w
for m in range(l + 1, r):
if dp1[l][m] != -1 and dp1[l][m] == dp1[m][r]:
dp1[l][r] = dp1[l][m] + 1
to[l].append(r)
hp = []
heappush(hp, (0, 0))
dist = [-1] * (n + 1)
while hp:
(d, i) = heappop(hp)
if i == n:
print(d)
break
if dist[i] != -1:
continue
dist[i] = d
for j in to[i]:
if dist[j] != -1:
continue
heappush(hp, (d + 1, j))
main()
| python | 16 | 0.522044 | 52 | 18.568627 | 51 | You are given an array $a_1, a_2, \dots, a_n$. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair). Replace them by one element with value $a_i + 1$.
After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?
-----Input-----
The first line contains the single integer $n$ ($1 \le n \le 500$) β the initial length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) β the initial array $a$.
-----Output-----
Print the only integer β the minimum possible length you can get after performing the operation described above any number of times.
-----Examples-----
Input
5
4 3 2 2 3
Output
2
Input
7
3 3 4 4 4 3 3
Output
2
Input
3
1 3 5
Output
3
Input
1
1000
Output
1
-----Note-----
In the first test, this is one of the optimal sequences of operations: $4$ $3$ $2$ $2$ $3$ $\rightarrow$ $4$ $3$ $3$ $3$ $\rightarrow$ $4$ $4$ $3$ $\rightarrow$ $5$ $3$.
In the second test, this is one of the optimal sequences of operations: $3$ $3$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $3$ $3$ $\rightarrow$ $4$ $4$ $4$ $4$ $4$ $\rightarrow$ $5$ $4$ $4$ $4$ $\rightarrow$ $5$ $5$ $4$ $\rightarrow$ $6$ $4$.
In the third and fourth tests, you can't perform the operation at all. | taco |
Subsets and Splits