text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Tags: *special, brute force, constructive algorithms, dsu, implementation
Correct Solution:
```
print(sum( [int (x) for x in input().strip().split()]))
```
| 87,000 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Tags: *special, brute force, constructive algorithms, dsu, implementation
Correct Solution:
```
a,b=map(int,input().split())
print(a+b )
```
| 87,001 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Tags: *special, brute force, constructive algorithms, dsu, implementation
Correct Solution:
```
a, b = map(int, input().split(" "))
print(a + b)
#
#
#
#
#
#
#
#
```
| 87,002 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Tags: *special, brute force, constructive algorithms, dsu, implementation
Correct Solution:
```
#This should work, stupid contest!!!
a,b = map(int, input().split())
print(a + b)
```
| 87,003 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Tags: *special, brute force, constructive algorithms, dsu, implementation
Correct Solution:
```
from sys import stdin,stdout
def main():
inp = [int (i) for i in input().split(" ")]
print(inp[0]+inp[1])
if __name__ == "__main__":
main()
```
| 87,004 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Tags: *special, brute force, constructive algorithms, dsu, implementation
Correct Solution:
```
n,m = map(int,input().split())
r=0
print(int(n)+int(m))
```
| 87,005 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Tags: *special, brute force, constructive algorithms, dsu, implementation
Correct Solution:
```
x,y = map(int,input().split())
print(x+y)
```
| 87,006 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Tags: *special, brute force, constructive algorithms, dsu, implementation
Correct Solution:
```
a, b = map(int, input().split())
print((a&b)+(a|b)) #6
```
| 87,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Submitted Solution:
```
a, b = [int(i) for i in input().split()]
print(a+b)
```
Yes
| 87,008 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Submitted Solution:
```
a,b=map(int,input().split(" "))
b+=a
print(b)
```
Yes
| 87,009 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Submitted Solution:
```
print(sum(map(int,input().split(' '))))
```
Yes
| 87,010 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Submitted Solution:
```
a, b = map(int, input().split())
print(a+b)
#6
```
Yes
| 87,011 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Submitted Solution:
```
#ddd]1111
a, b = map(int, input().split())
print(a + b)
```
No
| 87,012 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Submitted Solution:
```
a,b=map(int,input().split())
print(a+b&1023)
```
No
| 87,013 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Submitted Solution:
```
a,b = map(int,input().split())
print(0+a+b)
```
No
| 87,014 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
Input
The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space.
Output
Output the sum of the given integers.
Examples
Input
5 14
Output
19
Input
381 492
Output
873
Submitted Solution:
```
a,b=int(input()).split()
sum=a+b
print(sum)
```
No
| 87,015 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Tags: graphs, greedy, sortings
Correct Solution:
```
n, m = map(int, input().split())
cs = [0] + list(map(int, input().split()))
mls = [0 for i in range(n+1)]
for i in range(m):
x, y = map(int, input().split())
if cs[y] < cs[x]:
x, y = y, x
mls[x] += 1
print(sum([cs[i]*mls[i] for i in range(n+1)]))
```
| 87,016 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Tags: graphs, greedy, sortings
Correct Solution:
```
l2=input().split()
n=int(l2[0])
m=int(l2[1])
l=[int(y) for y in input().split()]
sum=0
for i in range(m):
l1=[int(x) for x in input().split()]
sum = sum + min(l[l1[0]-1],l[l1[1]-1])
print(sum)
```
| 87,017 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Tags: graphs, greedy, sortings
Correct Solution:
```
from collections import *
from sys import stdin
def arr_enu():
return [[i + 1, int(x)] for i, x in enumerate(stdin.readline().split())]
def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return [str(x) for x in stdin.readline().split()]
def calulate_cost():
cost = {}
for i in range(1, n + 1):
tem = 0
for j in toy.gdict[i]:
tem += energy[j - 1][1]
cost[i] = tem
return cost
def change(v):
for i in toy.gdict[v]:
try:
cost[i] -= dic[v]
except:
continue
class graph:
# initialize graph
def __init__(self, gdict=None):
if gdict is None:
gdict = defaultdict(list)
self.gdict, self.edges = gdict, []
# Get verticies
def get_vertices(self):
return list(self.gdict.keys())
# add edge
def add_edge(self, node1, node2):
self.gdict[node1].append(node2)
self.gdict[node2].append(node1)
self.edges.append([node1, node2])
n, m = arr_inp(1)
toy, energy = graph(), arr_enu()
for i in range(m):
u, v = arr_inp(1)
toy.add_edge(u, v)
cost, ans, dic = calulate_cost(), 0, {i: j for i, j in energy}
energy.sort(key=lambda x: x[1])
for i in range(n):
ma = energy[-1][0]
ans += cost[ma]
change(ma)
del cost[ma]
energy.pop()
print(ans)
```
| 87,018 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Tags: graphs, greedy, sortings
Correct Solution:
```
import math
n,m=map(int,input().split())
v=list(map(int,input().split()))
res=0
for i in range(m):
x,y=map(int,input().split())
x-=1;y-=1
res+=min(v[x],v[y])
print(res)
```
| 87,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Tags: graphs, greedy, sortings
Correct Solution:
```
n,k = map(int, input().split())
arr = list(map(int, input().split()))
ans=0
for _ in range(k):
u,v = map(int, input().split())
ans+=min(arr[u-1],arr[v-1])
print(ans)
```
| 87,020 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Tags: graphs, greedy, sortings
Correct Solution:
```
#! /usr/bin/env python
n, m = [int(x) for x in input().split()]
v = [int(x) for x in input().split()]
sv = [(x + 1, v[x]) for x in range(n)]
v = [0] + v
edges = {i:set() for i in range(1, n+1)}
for i in range(m):
f, t = [int(x) for x in input().split()]
edges[f].add(t)
edges[t].add(f)
ans = 0
sv.sort(key=lambda x: -x[1])
removed = [False] * (n + 1)
for i, vi in sv:
removed[i] = True
for f in edges[i]:
if not removed[f]:
ans += v[f]
print(ans)
```
| 87,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Tags: graphs, greedy, sortings
Correct Solution:
```
n, m = map(int, input().split())
u = list(map(int, input().split()))
v = list(enumerate(u, 1))
v.sort(key = lambda x: x[1], reverse = True)
s, u = 0, [0] + u
p = [[] for i in range(n + 1)]
for i in range(m):
x, y = map(int, input().split())
p[x].append(y)
p[y].append(x)
for x, f in v:
for y in p[x]: s += u[y]
u[x] = 0
print(s)
```
| 87,022 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Tags: graphs, greedy, sortings
Correct Solution:
```
n, m = map(int,input().split())
e = list(map(int, input().split()))
res = 0
for _ in range(m):
u,v = map(int, input().split())
res+= min(e[u-1], e[v-1])
print(res)
```
| 87,023 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Submitted Solution:
```
def main():
n,m = map(int,input().split())
l = [int(i) for i in input().split()]
ans = 0
for i in range(m):
a,b = map(int,input().split())
ans += min(l[a-1],l[b-1])
print(ans)
if __name__ == "__main__":
main()
```
Yes
| 87,024 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Submitted Solution:
```
n, m = map(int, input().split())
v = [0] + list(map(int, input().split()))
en = 0
for i in range(m):
a, b = map(int, input().split())
en += min(v[a], v[b])
print(en)
```
Yes
| 87,025 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Submitted Solution:
```
def Sol2(cost,cost2,G):
mk = [0 for _ in range(len(cost)) ]
sum = 0
for node in cost:
for i in G[node[1]]:
mk[i]+=1
c = len(G[node[1]]) - mk[node[1]]
sum += c*node[0]
return sum
if __name__ == '__main__':
n,m = map(int,input().split())
cost2 = [int(x) for x in input().split()]
cost = [(cost2[i],i) for i in range(len(cost2))]
arist = []
graf = [[]for i in range(n)]
for i in range(m):
x,y = map(int,input().split())
arist.append((x-1,y-1))
graf[x-1].append(y-1)
graf[y-1].append(x-1)
sort = sorted(cost,key=lambda parameter_list: parameter_list[0], reverse=False)
a = Sol2(sort,cost2,graf)
print(a)
```
Yes
| 87,026 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Submitted Solution:
```
def main():
n,m = map(int,input().split())
cur = list(map(int,input().split()))
tab = []
graph = [[] for x in range(n)]
for x in range(n):
tab.append((cur[x],x))
for x in range(m):
a,b = map(int,input().split())
a-=1
b-=1
graph[a].append(b)
graph[b].append(a)
tab.sort()
tab = tab[::-1]
v = [0]*n
s = 0
for x in range(n):
for nei in graph[tab[x][1]]:
if not v[nei]:
s += cur[nei]
v[tab[x][1]] = 1
print(s)
main()
```
Yes
| 87,027 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Submitted Solution:
```
def dfs(edges,energy,node,visited):
stack = [node]
cost = 0
while stack:
curr = stack.pop()
if curr not in visited:
visited.add(curr)
if curr in edges.keys():
for kid in edges[curr]:
if kid not in visited:
cost += min(energy[curr-1],energy[kid-1])
stack.append(kid)
return cost
def Solve(edges,energy):
n = len(edges)
cost = 0
visited = set()
for i in range(1,n+1):
if i not in visited:
cost += dfs(edges,energy,i,visited)
print(cost)
def main():
n,m = map(int,input().split())
energy = list(map(int,input().split()))
edges = {}
for i in range(m):
a,b = map(int,input().split())
if a not in edges.keys():
edges[a] = [b]
else:
edges[a].append(b)
if b not in edges.keys():
edges[b] = [a]
else:
edges[b].append(a)
Solve(edges,energy)
main()
```
No
| 87,028 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Submitted Solution:
```
n, m = map(int, input().split())
r = 0
w = [0] + list(map(int, input().split()))
g = {x+1: [] for x in range(n)}
polz = {x+1: 0 for x in range(n)}
def cut(node):
global r, dpolz, w, g
for i in g[node]:
r += w[i]
g[i].remove(node)
dpolz[i] += w[node]
dpolz[i] -= w[i]
del g[node]
del dpolz[node]
for i in range(m):
f, t = map(int, input().split())
g[f].append(t)
g[t].append(f)
for i in g.keys():
polz[i] = w[i] * len(g[i])
for j in g[i]:
polz[i] -= w[j]
dpolz = polz
while len(polz):
polz = sorted(dpolz.items(), key=lambda x: x[1], reverse=True)
dpolz = dict(polz)
#print(polz)
cut(polz.pop(0)[0])
print(r)
```
No
| 87,029 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Submitted Solution:
```
n, m = map(int, input().split())
v = [0] + [int(i) for i in input().split()]
sums = [1e9] + [0] * n
sums2 = [-1] + [0] * n
adj = {}
for i in range(n):
adj[i + 1] = []
for i in range(m):
a, b = map(int, input().split())
adj[a].append(b)
adj[b].append(a)
sums[a] += v[b]
sums[b] += v[a]
sums2[a] += v[a] - v[b]
sums2[b] += v[b] - v[a]
energy = 0
for i in range(n):
ma2 = max(sums2)
part = sums2.index(ma2)
adj_nodes = adj[part]
energy += sum([v[node] for node in adj_nodes])
for node in adj_nodes:
sums2[node] += v[part]
adj[node].remove(part)
sums2[part] = -1
print (energy)
```
No
| 87,030 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
Input
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output
Output the minimum total energy the child should spend to remove all n parts of the toy.
Examples
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
Note
One of the optimal sequence of actions in the first sample is:
* First, remove part 3, cost of the action is 20.
* Then, remove part 2, cost of the action is 10.
* Next, remove part 4, cost of the action is 10.
* At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Submitted Solution:
```
ans=0
def dfs(i):
global ans
x=i
vis[i]=1
for j in grid[i]:
ans+=min(l[x-1],l[j-1])
if vis[j]==0:
dfs(j)
for _ in range(1):
n,k=map(int,input().split())
l=list(map(int,input().split()))
grid=[[] for i in range(n+1)]
for i in range(k) :
a,b=map(int,input().split())
grid[a].append(b)
grid[b].append(a)
print(grid)
vis=[0]*(n+1)
for i in range(1,n+1):
if vis[i]==0:
dfs(i)
print(ans//2)
```
No
| 87,031 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is a born Berland film director, he is currently working on a new blockbuster, "The Unexpected". Vasya knows from his own experience how important it is to choose the main characters' names and surnames wisely. He made up a list of n names and n surnames that he wants to use. Vasya haven't decided yet how to call characters, so he is free to match any name to any surname. Now he has to make the list of all the main characters in the following format: "Name1 Surname1, Name2 Surname2, ..., Namen Surnamen", i.e. all the name-surname pairs should be separated by exactly one comma and exactly one space, and the name should be separated from the surname by exactly one space. First of all Vasya wants to maximize the number of the pairs, in which the name and the surname start from one letter. If there are several such variants, Vasya wants to get the lexicographically minimal one. Help him.
An answer will be verified a line in the format as is shown above, including the needed commas and spaces. It's the lexicographical minimality of such a line that needs to be ensured. The output line shouldn't end with a space or with a comma.
Input
The first input line contains number n (1 ≤ n ≤ 100) — the number of names and surnames. Then follow n lines — the list of names. Then follow n lines — the list of surnames. No two from those 2n strings match. Every name and surname is a non-empty string consisting of no more than 10 Latin letters. It is guaranteed that the first letter is uppercase and the rest are lowercase.
Output
The output data consist of a single line — the needed list. Note that one should follow closely the output data format!
Examples
Input
4
Ann
Anna
Sabrina
John
Petrov
Ivanova
Stoltz
Abacaba
Output
Ann Abacaba, Anna Ivanova, John Petrov, Sabrina Stoltz
Input
4
Aa
Ab
Ac
Ba
Ad
Ae
Bb
Bc
Output
Aa Ad, Ab Ae, Ac Bb, Ba Bc
Submitted Solution:
```
n = int(input())
F = [input() for _ in range(n)]
L = [input() for _ in range(n)]
F.sort()
L.sort()
i = 0
j = 0
def name(a,b):
return a + ' ' + b
names = []
while i < len(F) and j < len(L):
if F[i][0] == L[j][0]:
names.append(name(F[i], L[j]))
del F[i]
del L[j]
elif F[i][0] < L[j][0]:
i += 1
elif F[i][0] > L[j][0]:
j += 1
othernames = [name(a,b) for a,b in zip(F,L)]
names.reverse()
othernames.reverse()
res = []
while names and othernames:
if names[-1] > othernames[-1]:
res.append(othernames.pop())
elif names[-1] < othernames[-1]:
res.append(names.pop())
res += names
res += othernames
print(', '.join(res))
```
No
| 87,032 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
#code by aanchaltiwari__
def dfs(x, y, color):
visited = [False for i in range(n + 1)]
visited[x] = True
stack = [x]
while stack:
node = stack.pop()
for child, childcolor in g[node]:
if visited[child] == False and childcolor == color:
visited[child] = True
stack.append(child)
if visited[y] == True:
return True
return False
n, m = map(int, input().split())
g = {i: [] for i in range(1, n + 1)}
s = set()
for i in range(m):
u, v, c = map(int, input().split())
s.add(c)
g[u].append([v, c])
g[v].append([u, c])
s = list(s)
# print(g)
# print(s)
ans = [[0 for i in range(n+1)]for j in range(n+1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
for c in s:
if i != j:
if dfs(i, j, c):
ans[i][j] += 1
# print(ans)
q = int(input())
for i in range(q):
u, v = map(int, input().split())
print(ans[u][v])
```
| 87,033 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
def find(c, x):
p = dsu[c]
if x == p[x]:
return x
return find(c, p[x])
def union(c, x, y):
x = find(c, x)
y = find(c, y)
if x == y:
return
p = dsu[c]
p[x] = y
n, m = map(int, input().split())
dsu = [[i for i in range(n + 1)] for _ in range(m + 1)]
for _ in range(m):
a, b, c = map(int, input().split())
union(c, a, b)
q = int(input())
for _ in range(q):
a, b = map(int, input().split())
count = 0
for c in range(1, m + 1):
if find(c, a) == find(c, b):
count += 1
print(count)
```
| 87,034 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
class CodeforcesTask505BSolution:
def __init__(self):
self.result = ''
self.n_m = []
self.edges = []
self.q = 0
self.queries = []
def read_input(self):
self.n_m = [int(x) for x in input().split(" ")]
for x in range(self.n_m[1]):
self.edges.append([int(y) for y in input().split(" ")])
self.q = int(input())
for x in range(self.q):
self.queries.append([int(y) for y in input().split(" ")])
def process_task(self):
graphs = [[[] for x in range(self.n_m[0])] for c in range(self.n_m[1])]
for edge in self.edges:
graphs[edge[2] - 1][edge[0] - 1].append(edge[1])
graphs[edge[2] - 1][edge[1] - 1].append(edge[0])
results = []
for query in self.queries:
to_visit = [(query[0], c) for c in range(self.n_m[1])]
used = set()
visited = [[False] * self.n_m[0] for x in range(self.n_m[1])]
while to_visit:
visiting = to_visit.pop(-1)
if visiting[1] not in used and not visited[visiting[1]][visiting[0] - 1]:
visited[visiting[1]][visiting[0] - 1] = True
if visiting[0] == query[1]:
used.add(visiting[1])
else:
to_visit.extend([(x, visiting[1]) for x in graphs[visiting[1]][visiting[0] - 1]])
colors = len(used)
results.append(colors)
self.result = "\n".join([str(x) for x in results])
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask505BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
```
| 87,035 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
class Union:
def __init__(self, size):
self.ancestor = [i for i in range(size+1)]
def find(self, node):
if self.ancestor[node] == node:
return node
self.ancestor[node] = self.find(self.ancestor[node])
return self.ancestor[node]
def merge(self, a, b):
a, b = self.find(a), self.find(b)
self.ancestor[a] = b
n, m = map(int, input().split())
unions = [Union(n) for _ in range(m+1)]
graph = [[] for _ in range(n+1)]
for _ in range(m):
a, b, c = map(int, input().split())
graph[a].append((b, c))
graph[b].append((a, c))
unions[c].merge(a, b)
for _ in range(int(input())):
a, b = map(int, input().split())
ans = 0
for i in range(1, m+1):
ans += unions[i].find(a) == unions[i].find(b)
print(ans)
```
| 87,036 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
#def input(): return sys.stdin.readline().strip()
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
ilelec = lambda: map(int1,input().split())
alelec = lambda: list(map(int1, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
n,m = ilele()
Color = defaultdict(set)
G = defaultdict(set)
C = set()
def addEdge(a,b):
G[a].add(b)
G[b].add(a)
def addColor(a,b,c):
Color[(a,b)].add(c)
Color[(b,a)].add(c)
C.add(c)
for i in range(m):
a,b,c = ilele()
addColor(a,b,c)
addEdge(a,b)
vis = [False]*(n+1)
Ans = []
def fun(node,dest,vis,grp):
#print(node,vis,grp)
if not grp:
return
if node == dest:
for i in grp:
Ans.append(i)
return
vis[node] = True
for i in G.get(node,[]):
#print(i)
if not vis[i]:
newvis = vis.copy()
#newvis[c] =True
z = grp.intersection(Color[node,i])
#print(z)
fun(i,dest,newvis,z)
#print(Color,G)
for i in range(int(input())):
a,b = ilele()
vis = [False]*(n+1)
grp = C.copy()
fun(a,b,vis,grp)
#print(Ans)
print(len(set(Ans)))
Ans =[]
```
| 87,037 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
def main():
def dfs(index, color):
visited[index] = True
for p in adj[index]:
if not visited[p[0]] and p[1] == color:
dfs(p[0], color)
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
for _ in range(m):
a, b, c = map(int, input().split())
adj[a - 1].append((b - 1, c))
adj[b - 1].append((a - 1, c))
q = int(input())
for _ in range(q):
a, b = map(int, input().split())
ans = 0
for i in range(1, m + 1):
visited = [False] * n
dfs(a - 1, i)
if visited[b - 1]:
ans += 1
print(ans)
if __name__ == "__main__":
main()
```
| 87,038 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
n,m=map(int,input().split())
g=[[] for _ in range(n)]
for _ in range(m):
a,b,c=map(int,input().split())
g[a-1].append((b-1,c-1))
g[b-1].append((a-1,c-1))
def dfs(x,c,t):
if x==t:return True
v[x]=1
for j in g[x]:
if j[1]==c and v[j[0]]==0:
if dfs(j[0],c,t):return True
return False
q=int(input())
o=[0]*q
v=[]
for i in range(q):
f,y=map(int,input().split())
for c in range(100):
v=[0]*n
if dfs(f-1,c,y-1):o[i]+=1
print('\n'.join(list(map(str,o))))
```
| 87,039 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin,stdout
input = stdin.readline
def main():
n, m = map(int,input().split())
sets = [list(range(n+1)) for i in range(m)]
sizes = [[1]*(n+1) for i in range(m)]
def get(a,ind):
if sets[ind][a] != a:
sets[ind][a] = get(sets[ind][a],ind)
return sets[ind][a]
def union(a, b,ind):
a = get(a,ind)
b = get(b,ind)
if a == b:return
if sizes[ind][a] > sizes[ind][b]:
a,b = b,a
sets[ind][a] = b
sizes[ind][b] += sizes[ind][a]
for i in range(m):
a, b, c = map(int,input().split())
a -= 1
b -= 1
c -= 1
union(a,b,c)
q = int(input())
for i in range(q):
ans = 0
u,v = map(int,input().split())
u-=1
v-=1
for j in range(m):
ans += int(get(u,j) == get(v,j))
print(ans)
main()
```
| 87,040 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
n,m = map(int, input().split())
l = []
for i in range(m):
a,b,c = map(int, input().split())
if len(l) <= c-1:
for i in range(c-len(l)):
l.append([])
p = l[c-1]
m = []
for i in range(len(p)):
if a in p[i] or b in p[i]:
m.append(i)
new = [a,b]
for i in range(len(m)):
new = new + p[m[i]]
for i in range(len(m)):
p.pop(m[i]-i)
p.append(new)
l[c-1] = p
q = int(input())
for i in range(q):
counter = 0
u,v = map(int, input().split())
for j in range(len(l)):
yes = 0
for k in range(len(l[j])):
if yes == 0 and u in l[j][k] and v in l[j][k]:
yes = 1
counter += 1
print(counter)
```
Yes
| 87,041 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
def solution():
n,m = [int(x) for x in input().split(' ')]
graphs = {}
edges = {}
for i in range(m):
x,y,c = input().split(' ')
if c not in graphs:
graphs[c]={}
if x not in graphs[c]:
graphs[c][x] = []
if y not in graphs[c]:
graphs[c][y] = []
graphs[c][x].append(y)
graphs[c][y].append(x)
q = int(input())
queries = []
for i in range(q):
x,y = input().split(' ')
ans = 0
for c,graph in graphs.items():
ans+=1 if areConnected(x,y,graph) else 0
print(ans)
def areConnected(x,y,graph):
if x not in graph or y not in graph:
return False
queu = [x]
already = [x]
while len(queu) != 0:
current = queu[0]
if current == y:
return True
del queu[0]
already.append(current)
for i in graph[current]:
if i not in already and i not in queu:
if i == y:
return True
queu.append(i)
return False
solution()
```
Yes
| 87,042 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
# !/usr/bin/env python3
# coding: UTF-8
# Modified: <19/Feb/2019 06:31:43 PM>
# ✪ H4WK3yE乡
# Mohd. Farhan Tahir
# Indian Institute Of Information Technology (IIIT),Gwalior
# Question Link
#
#
# ///==========Libraries, Constants and Functions=============///
import sys
inf = float("inf")
mod = 1000000007
def get_array(): return list(map(int, sys.stdin.readline().split()))
def get_ints(): return map(int, sys.stdin.readline().split())
def input(): return sys.stdin.readline()
# ///==========MAIN=============///
N = 105
graph = [[] for _ in range(N)]
component = [0] * N
visited = [False] * N
def explore(node):
global cnt
visited[node] = True
component[node] = cnt
for neighbour, color in graph[node]:
if visited[neighbour] == False:
explore(neighbour)
def dfs(n):
global cnt
cnt = 0
for i in range(1, n + 1):
if visited[i] == False:
cnt += 1
explore(i)
def explore_o(node, c):
global ans, s
visited[node] = True
for neighbour, color in graph[node]:
if visited[neighbour] == False and color == c:
if neighbour == v:
s.add(color)
explore_o(neighbour, c)
def dfs_o(u):
global visited, ans, flag, s
ans = 0
s = set()
for neighbour, color in graph[u]:
visited = [False] * N
visited[u] = True
flag = 0
if neighbour == v:
s.add(color)
continue
explore_o(neighbour, color)
return len(s)
def main():
global n, m
n, m = get_ints()
for _ in range(m):
u, x, c = get_ints()
graph[u].append((x, c))
graph[x].append((u, c))
dfs(n)
global v
for tc in range(int(input())):
u, v = get_ints()
if component[u] != component[v]:
print(0)
continue
print(dfs_o(u))
if __name__ == "__main__":
main()
```
Yes
| 87,043 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
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")
#'%.9f'%ans
##########################################################
from collections import defaultdict
def dfs(s,f):
if s==v:
return True
vis[s]=1
for i in g[s]:
if vis[i[0]]==0 and i[1]==f:
if(dfs(i[0],f)):
return True
return False
#for _ in range(int(input())):
#n = int(input())
n,m = map(int, input().split())
g=[[] for i in range(n+2)]
for i in range(m):
u,v,d = map(int, input().split())
g[u].append([v,d])
g[v].append([u,d])
q= int(input())
for _ in range(q):
u, v= map(int, input().split())
cnt=0
for i in range(1,101):
vis=[0]*101
if (dfs(u,i)):
cnt+=1
print(cnt)
#g=[[] for i in range(n+1)]
#arr = list(list(map(int, input().split())))
```
Yes
| 87,044 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
n,m = [int(_) for _ in input().split()]
d = [[] for i in range(n+1)]
for i in range(m):
a,b,c = [int(_) for _ in input().split()]
d[a].append((b,c))
d[b].append((a,c))
q = int(input())
def query(d,a,b):
if a > b:
a,b = b,a
l = []
for i in range(len(d[a])):
l.append(d[a][i])
cnt = 0
v = [False] * (n+1)
while len(l) > 0:
if l[0][0] == b:
cnt += 1
del l[0]
continue
for i in range(len(d[l[0][0]])):
if v[d[l[0][0]][i][0]] == False and d[l[0][0]][i][1] == l[0][1]:
l.append(d[l[0][0]][i])
if d[l[0][0]][i][0] != b:
v[d[l[0][0]][i][0]] = True
del l[0]
return cnt
for qu in range(q):
a,b = [int(_) for _ in input().split()]
print(query(d,a,b))
```
No
| 87,045 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
def dfs_paths(graph, start, goal, path=list()):
if not path:
path.append(start)
if start == goal:
yield path
for vertex in graph[start] - set(path):
yield from dfs_paths(graph, vertex, goal, path=path + [vertex])
n, m = map(int, input().split())
graph = {}
for _ in range(m):
a, b, c = map(int, input().split())
if c not in graph:
graph[c] = {}
if a not in graph[c]:
graph[c][a] = set()
if b not in graph[c]:
graph[c][b] = set()
graph[c][a].add(b)
graph[c][b].add(a)
q = int(input())
for _ in range(q):
u, v = map(int, input().split())
count = 0
for k in graph:
if u not in graph[k] or v not in graph[k]:
continue
if len(list(dfs_paths(graph[k], u, v))) > 0:
count += 1
print(count)
```
No
| 87,046 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
def IsPossible(graph,colors,start,end,color,u):
#print (start,end)
if start == end:
return True
arr = []
stack = [start]
while stack:
curr = stack.pop()
if curr not in arr:
arr.append(curr)
for kid in graph[curr]:
for color1 in colors[(curr,kid)]:
if kid == end and color1 != color:
return False
if color1 == color and kid != u:
stack.append(kid)
if kid == end:
#print ('here',curr,kid)
return True
return False
def Solve(graph,colors,u,v):
count = 0
for kid in graph[u]:
for color in colors[(u,kid)]:
if IsPossible(graph,colors,kid,v,color,u):
count += 1
return count
def main():
graph = {}
colors = {}
n,m = map(int,input().split())
for i in range(1,n+1):
graph[i] = []
for i in range(m):
a,b,c = map(int,input().split())
if (a,b) not in colors.keys():
colors[(a,b)] = [c]
else:
colors[(a,b)].append(c)
if (b,a) not in colors.keys():
colors[(b,a)] = [c]
else:
colors[(b,a)].append(c)
if b not in graph[a]:
graph[a].append(b)
if a not in graph[b]:
graph[b].append(a)
q = int(input())
for i in range(q):
u,v = map(int,input().split())
print (Solve(graph,colors,u,v))
main()
```
No
| 87,047 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Submitted Solution:
```
import sys
input = sys.stdin.readline
def multi_input():
return map(int, input().split())
def array_print(arr):
print(' '.join(map(str, arr)))
def dfs(n, previous, start, end, graph, color, temp_color):
if start == end:
return 1
ans = 0
for i in graph[start]:
if i[1] == color and [start, i[0], i[1]] not in visited:
node = i[0]
visited.append([start, i[0], i[1]])
ans += dfs(n, start, node, end, graph, color, i[1])
return ans
graph = {}
n, m = multi_input()
for i in range(n+1):
graph[i] = []
for i in range(m):
u, v, c = multi_input()
graph[u].append([v, c])
graph[v].append([u, c])
q = int(input())
for q1 in range(q):
u, v = multi_input()
visited = []
ans = 0
for i in graph[u]:
if [u, i[0], i[1]] not in visited:
visited.append([u, i[0], i[1]])
ans += dfs(n, 0, i[0], v, graph, i[1], i[1])
print(ans)
```
No
| 87,048 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Tags: data structures
Correct Solution:
```
from math import inf, log2
class LazySegmentTree:
def __init__(self, array, func=max):
self.n = len(array)
self.size = 2**(int(log2(self.n-1))+1) if n != 1 else 1
self.func = func
self.default = 0 if self.func != min else inf
self.data = [self.default] * (2 * self.size)
self.lazy = [0] * (2 * self.size)
self.process(array)
def process(self, array):
self.data[self.size : self.size+self.n] = array
for i in range(self.size-1, -1, -1):
self.data[i] = self.func(self.data[2*i], self.data[2*i+1])
def push(self, index):
self.lazy[2*index] += self.lazy[index]
self.lazy[2*index+1] += self.lazy[index]
self.data[2 * index] += self.lazy[index]
self.data[2 * index + 1] += self.lazy[index]
self.lazy[index] = 0
def build(self, index):
"""Build data with the new changes!"""
index >>= 1
while index:
self.data[index] = self.func(self.data[2*index], self.data[2*index+1]) + self.lazy[index]
index >>= 1
def query(self, alpha, omega):
res = self.default
alpha += self.size
omega += self.size + 1
for i in range(len(bin(alpha)[2:])-1, 0, -1):
self.push(alpha >> i)
for i in range(len(bin(omega-1)[2:])-1, 0, -1):
self.push((omega-1) >> i)
while alpha < omega:
if alpha & 1:
res = self.func(res, self.data[alpha])
alpha += 1
if omega & 1:
omega -= 1
res = self.func(res, self.data[omega])
alpha >>= 1
omega >>= 1
return res
def update(self, alpha, omega, value):
alpha += self.size
omega += self.size + 1
l, r = alpha, omega
while alpha < omega:
if alpha & 1:
self.data[alpha] += value
self.lazy[alpha] += value
alpha += 1
if omega & 1:
omega -= 1
self.data[omega] += value
self.lazy[omega] += value
alpha >>= 1
omega >>= 1
self.build(l)
self.build(r-1)
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
n = int(input())
a = list(map(int, input().split()))
m = int(input())
st = LazySegmentTree(a, func=min)
for _ in range(m):
s = input().split()
if len(s) == 3:
a, b, c = map(int, s)
if a > b:
st.update(a, n-1, c)
st.update(0, b, c)
else:
st.update(a,b,c)
else:
a, b = map(int, s)
if a > b:
print(min(st.query(a,n-1), st.query(0,b)))
else:
print(st.query(a,b))
```
| 87,049 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Tags: data structures
Correct Solution:
```
import math,sys,bisect,heapq,os
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
def input(): return sys.stdin.readline().rstrip('\r\n')
#input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
aj = lambda: list(map(int, input().split()))
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
def solve():
n=int(input())
a=list(map(int,input().split()))
class st:
def __init__(self, size):
N = 1
h = 0
while N < size:
N <<= 1
h += 1
self.N = N
self.h = h
self.t = [float('inf')] * (2 * N)
self.d = [0] * N
def apply(self, p, value):
self.t[p] += value
if (p < self.N):
self.d[p] += value
def build(self, p):
t = self.t
d = self.d
while p > 1:
p >>= 1
t[p] = min(t[p<<1], t[p<<1|1]) + d[p]
def rebuild(self):
t = self.t
for p in reversed(range(1, self.N)):
t[p] = min(t[p<<1], t[p<<1|1])
def push(self, p):
d = self.d
for s in range(self.h, 0, -1):
i = p >> s
if d[i] != 0:
self.apply(i<<1, d[i])
self.apply(i<<1|1, d[i])
d[i] = 0
def inc(self, l, r, value):
if l > r:
return
l += self.N
r += self.N+1
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l, value)
l += 1
if r & 1:
r -= 1
self.apply(r, value)
l >>= 1
r >>= 1
self.build(l0)
self.build(r0 - 1)
def query(self, l, r):
if l > r:
return float('inf')
t = self.t
l += self.N
r += self.N+1
self.push(l)
self.push(r - 1)
res = float('inf')
while l < r:
if l & 1:
res = min(res, t[l])
l += 1
if r & 1:
r -= 1
res = min(t[r], res)
l >>= 1
r >>= 1
return res
se=st(n)
N=se.N
for i in range(n):
se.t[i+N]=a[i]
se.rebuild()
q=int(input())
for i in range(q):
b=list(map(int,input().split()))
if len(b)==2:
l=b[0]
r=b[1]
if l>r:
print(min(se.query(l,n-1),se.query(0,r)))
else:print(se.query(l,r))
else:
l=b[0]
r=b[1]
v=b[2]
if l>r:
se.inc(0,r,v)
se.inc(l,n-1,v)
else:se.inc(l,r,v)
try:
#os.system("online_judge.py")
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
solve()
```
| 87,050 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Tags: data structures
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n=int(input())
a=list(map(int,input().split()))
class st:
def __init__(self, size):
N = 1
h = 0
while N < size:
N <<= 1
h += 1
self.N = N
self.h = h
self.t = [float('inf')] * (2 * N)
self.d = [0] * N
def apply(self, p, value):
self.t[p] += value
if (p < self.N):
self.d[p] += value
def build(self, p):
t = self.t
d = self.d
while p > 1:
p >>= 1
t[p] = min(t[p<<1], t[p<<1|1]) + d[p]
def rebuild(self):
t = self.t
for p in reversed(range(1, self.N)):
t[p] = min(t[p<<1], t[p<<1|1])
def push(self, p):
d = self.d
for s in range(self.h, 0, -1):
i = p >> s
if d[i] != 0:
self.apply(i<<1, d[i])
self.apply(i<<1|1, d[i])
d[i] = 0
def inc(self, l, r, value):
if l >= r:
return
l += self.N
r += self.N
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l, value)
l += 1
if r & 1:
r -= 1
self.apply(r, value)
l >>= 1
r >>= 1
self.build(l0)
self.build(r0 - 1)
def query(self, l, r):
if l >= r:
return float('inf')
t = self.t
l += self.N
r += self.N
self.push(l)
self.push(r - 1)
res = float('inf')
while l < r:
if l & 1:
res = min(res, t[l])
l += 1
if r & 1:
r -= 1
res = min(t[r], res)
l >>= 1
r >>= 1
return res
se=st(n)
N=se.N
for i in range(n):
se.t[i+N]=a[i]
se.rebuild()
q=int(input())
for i in range(q):
b=list(map(int,input().split()))
if len(b)==2:
l=b[0]
r=b[1]
if l>r:
print(min(se.query(l,n),se.query(0,r+1)))
else:print(se.query(l,r+1))
else:
l=b[0]
r=b[1]
v=b[2]
if l>r:
se.inc(0,r+1,v)
se.inc(l,n,v)
else:se.inc(l,r+1,v)
```
| 87,051 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Tags: data structures
Correct Solution:
```
import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
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')
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
n=int(input())
a=list(map(int,input().split()))
class st:
def __init__(self, size):
N = 1
h = 0
while N < size:
N <<= 1
h += 1
self.N = N
self.h = h
self.t = [float('inf')] * (2 * N)
self.d = [0] * N
def apply(self, p, value):
self.t[p] += value
if (p < self.N):
self.d[p] += value
def build(self, p):
t = self.t
d = self.d
while p > 1:
p >>= 1
t[p] = min(t[p<<1], t[p<<1|1]) + d[p]
def rebuild(self):
t = self.t
for p in reversed(range(1, self.N)):
t[p] = min(t[p<<1], t[p<<1|1])
def push(self, p):
d = self.d
for s in range(self.h, 0, -1):
i = p >> s
if d[i] != 0:
self.apply(i<<1, d[i])
self.apply(i<<1|1, d[i])
d[i] = 0
def inc(self, l, r, value):
if l >= r:
return
l += self.N
r += self.N
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l, value)
l += 1
if r & 1:
r -= 1
self.apply(r, value)
l >>= 1
r >>= 1
self.build(l0)
self.build(r0 - 1)
def query(self, l, r):
if l >= r:
return float('inf')
t = self.t
l += self.N
r += self.N
self.push(l)
self.push(r - 1)
res = float('inf')
while l < r:
if l & 1:
res = min(res, t[l])
l += 1
if r & 1:
r -= 1
res = min(t[r], res)
l >>= 1
r >>= 1
return res
se=st(n)
N=se.N
for i in range(n):
se.t[i+N]=a[i]
se.rebuild()
q=int(input())
for i in range(q):
b=list(map(int,input().split()))
if len(b)==2:
l=b[0]
r=b[1]
if l>r:
print(min(se.query(l,n),se.query(0,r+1)))
else:print(se.query(l,r+1))
else:
l=b[0]
r=b[1]
v=b[2]
if l>r:
se.inc(0,r+1,v)
se.inc(l,n,v)
else:se.inc(l,r+1,v)
```
| 87,052 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Tags: data structures
Correct Solution:
```
import math,sys,bisect,heapq,os
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
def input(): return sys.stdin.readline().rstrip('\r\n')
#input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
aj = lambda: list(map(int, input().split()))
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
def solve():
n=int(input())
a=list(map(int,input().split()))
class st:
def __init__(self, size):
N = 1
h = 0
while N < size:
N <<= 1
h += 1
self.N = N
self.h = h
self.t = [float('inf')] * (2 * N)
self.d = [0] * N
def apply(self, p, value):
self.t[p] += value
if (p < self.N):
self.d[p] += value
def build(self, p):
t = self.t
d = self.d
while p > 1:
p >>= 1
t[p] = min(t[p<<1], t[p<<1|1]) + d[p]
def rebuild(self):
t = self.t
for p in reversed(range(1, self.N)):
t[p] = min(t[p<<1], t[p<<1|1])
def push(self, p):
d = self.d
for s in range(self.h, 0, -1):
i = p >> s
if d[i] != 0:
self.apply(i<<1, d[i])
self.apply(i<<1|1, d[i])
d[i] = 0
def inc(self, l, r, value):
if l >= r:
return
l += self.N
r += self.N
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l, value)
l += 1
if r & 1:
r -= 1
self.apply(r, value)
l >>= 1
r >>= 1
self.build(l0)
self.build(r0 - 1)
def query(self, l, r):
if l >= r:
return float('inf')
t = self.t
l += self.N
r += self.N
self.push(l)
self.push(r - 1)
res = float('inf')
while l < r:
if l & 1:
res = min(res, t[l])
l += 1
if r & 1:
r -= 1
res = min(t[r], res)
l >>= 1
r >>= 1
return res
se=st(n)
N=se.N
for i in range(n):
se.t[i+N]=a[i]
se.rebuild()
q=int(input())
for i in range(q):
b=list(map(int,input().split()))
if len(b)==2:
l=b[0]
r=b[1]
if l>r:
print(min(se.query(l,n),se.query(0,r+1)))
else:print(se.query(l,r+1))
else:
l=b[0]
r=b[1]
v=b[2]
if l>r:
se.inc(0,r+1,v)
se.inc(l,n,v)
else:se.inc(l,r+1,v)
try:
#os.system("online_judge.py")
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
solve()
```
| 87,053 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Tags: data structures
Correct Solution:
```
import math,sys,bisect,heapq,os
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
def input(): return sys.stdin.readline().rstrip('\r\n')
#input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
aj = lambda: list(map(int, input().split()))
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
def solve():
n=int(input())
a=list(map(int,input().split()))
class st:
def __init__(self, size):
n = size
h = int(math.log2(n-1))+1 if n>1 else 0
N = 2**h
self.t = [float('inf')]*(2*N)
self.d = [0]*N
# N = 1
# h = 0
# while N < size:
# N <<= 1
# h += 1
self.N = N
self.h = h
self.t = [float('inf')] * (2 * N)
self.d = [0] * N
def apply(self, p, value):
self.t[p] += value
if (p < self.N):
self.d[p] += value
def build(self, p):
t = self.t
d = self.d
while p > 1:
p >>= 1
t[p] = min(t[p<<1], t[p<<1|1]) + d[p]
def rebuild(self):
t = self.t
for p in reversed(range(1, self.N)):
t[p] = min(t[p<<1], t[p<<1|1])
def push(self, p):
d = self.d
for s in range(self.h, 0, -1):
i = p >> s
if d[i] != 0:
self.apply(i<<1, d[i])
self.apply(i<<1|1, d[i])
d[i] = 0
def inc(self, l, r, value):
if l > r:
return
l += self.N
r += self.N+1
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l, value)
l += 1
if r & 1:
r -= 1
self.apply(r, value)
l >>= 1
r >>= 1
self.build(l0)
self.build(r0 - 1)
def query(self, l, r):
if l > r:
return float('inf')
t = self.t
l += self.N
r += self.N+1
self.push(l)
self.push(r - 1)
res = float('inf')
while l < r:
if l & 1:
res = min(res, t[l])
l += 1
if r & 1:
r -= 1
res = min(t[r], res)
l >>= 1
r >>= 1
return res
se=st(n)
N=se.N
for i in range(n):
se.t[i+N]=a[i]
se.rebuild()
q=int(input())
for i in range(q):
b=list(map(int,input().split()))
if len(b)==2:
l=b[0]
r=b[1]
if l>r:
print(min(se.query(l,n-1),se.query(0,r)))
else:print(se.query(l,r))
else:
l=b[0]
r=b[1]
v=b[2]
if l>r:
se.inc(0,r,v)
se.inc(l,n-1,v)
else:se.inc(l,r,v)
try:
#os.system("online_judge.py")
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
solve()
```
| 87,054 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Tags: data structures
Correct Solution:
```
import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
inf = float('inf')
class LazySegmentTree:
def __init__(self, data, default=inf, func=min):
"""initialize the lazy segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self._lazy = [0] * (2 * _size)
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __len__(self):
return self._len
def _push(self, idx):
"""push query on idx to its children"""
# Let the children know of the queries
q, self._lazy[idx] = self._lazy[idx], 0
self._lazy[2 * idx] += q
self._lazy[2 * idx + 1] += q
self.data[2 * idx] += q
self.data[2 * idx + 1] += q
def _update(self, idx):
"""updates the node idx to know of all queries applied to it via its ancestors"""
for i in reversed(range(1, idx.bit_length())):
self._push(idx >> i)
def _build(self, idx):
"""make the changes to idx be known to its ancestors"""
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
idx >>= 1
def add(self, start, stop, value):
"""lazily add value to [start, stop)"""
start = start_copy = start + self._size
stop = stop_copy = stop + self._size
while start < stop:
if start & 1:
self._lazy[start] += value
self.data[start] += value
start += 1
if stop & 1:
stop -= 1
self._lazy[stop] += value
self.data[stop] += value
start >>= 1
stop >>= 1
# Tell all nodes above of the updated area of the updates
self._build(start_copy)
self._build(stop_copy - 1)
def query(self, start, stop, default=inf):
"""func of data[start, stop)"""
start += self._size
stop += self._size
# Apply all the lazily stored queries
self._update(start)
self._update(stop - 1)
res = default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "LazySegmentTree({0})".format(self.data)
n = int(input())
a = [int(i) for i in input().split()]
q = int(input())
st = LazySegmentTree(a)
for i in range (q):
qi = [int(i) for i in input().split()]
if len(qi)==3:
if qi[0]>qi[1]:
st.add(qi[0],n,qi[2])
st.add(0,qi[1]+1,qi[2])
else:
st.add(qi[0],qi[1]+1, qi[2])
else:
if qi[0]>qi[1]:
ans = min(st.query(qi[0],n), st.query(0,qi[1]+1))
else:
ans = st.query(qi[0],qi[1]+1)
print(ans)
```
| 87,055 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Tags: data structures
Correct Solution:
```
import math,sys,bisect,heapq,os
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
def input(): return sys.stdin.readline().rstrip('\r\n')
#input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
aj = lambda: list(map(int, input().split()))
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
def solve():
n=int(input())
a=list(map(int,input().split()))
class st:
def __init__(self, size):
n = size
h = int(math.log2(n-1))+1 if n>1 else 0
N = 2**h
self.t = [float('inf')]*(2*N)
self.d = [0]*N
self.N = N
self.h = h
def apply(self, p, value):
self.t[p] += value
if (p < self.N):
self.d[p] += value
def build(self, p):
t = self.t
d = self.d
while p > 1:
p >>= 1
t[p] = min(t[p<<1], t[p<<1|1]) + d[p]
def rebuild(self):
t = self.t
for p in reversed(range(1, self.N)):
t[p] = min(t[p<<1], t[p<<1|1])
def push(self, p):
d = self.d
for s in range(self.h, 0, -1):
i = p >> s
if d[i] != 0:
self.apply(i<<1, d[i])
self.apply(i<<1|1, d[i])
d[i] = 0
def inc(self, l, r, value):
if l > r:
return
l += self.N
r += self.N+1
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l, value)
l += 1
if r & 1:
r -= 1
self.apply(r, value)
l >>= 1
r >>= 1
self.build(l0)
self.build(r0 - 1)
def query(self, l, r):
if l > r:
return float('inf')
t = self.t
l += self.N
r += self.N+1
self.push(l)
self.push(r - 1)
res = float('inf')
while l < r:
if l & 1:
res = min(res, t[l])
l += 1
if r & 1:
r -= 1
res = min(t[r], res)
l >>= 1
r >>= 1
return res
se=st(n)
N=se.N
for i in range(n):
se.t[i+N]=a[i]
se.rebuild()
q=int(input())
for i in range(q):
b=list(map(int,input().split()))
if len(b)==2:
l=b[0]
r=b[1]
if l>r:
print(min(se.query(l,n-1),se.query(0,r)))
else:print(se.query(l,r))
else:
l=b[0]
r=b[1]
v=b[2]
if l>r:
se.inc(0,r,v)
se.inc(l,n-1,v)
else:se.inc(l,r,v)
try:
#os.system("online_judge.py")
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
solve()
```
| 87,056 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Submitted Solution:
```
from math import inf, log2
class LazySegmentTree:
def __init__(self, array, func=max):
self.n = len(array)
self.size = 2**(int(log2(self.n-1))+1) if n != 1 else 1
self.func = func
self.default = 0 if self.func != min else inf
self.data = [self.default] * (2 * self.size)
self.lazy = [0] * (2 * self.size)
self.process(array)
def process(self, array):
self.data[self.size : self.size+self.n] = array
for i in range(self.size-1, -1, -1):
self.data[i] = self.func(self.data[2*i], self.data[2*i+1])
def push(self, index):
"""Push the information of the root to it's children!"""
self.lazy[2*index] += self.lazy[index]
self.lazy[2*index+1] += self.lazy[index]
self.data[2 * index] += self.lazy[index]
self.data[2 * index + 1] += self.lazy[index]
self.lazy[index] = 0
def build(self, index):
"""Build data with the new changes!"""
index >>= 1
while index:
self.data[index] = self.func(self.data[2*index], self.data[2*index+1]) + self.lazy[index]
index >>= 1
def query(self, alpha, omega):
"""Returns the result of function over the range (inclusive)!"""
res = self.default
alpha += self.size
omega += self.size + 1
for i in range(len(bin(alpha)[2:])-1, 0, -1):
self.push(alpha >> i)
for i in range(len(bin(omega-1)[2:])-1, 0, -1):
self.push((omega-1) >> i)
while alpha < omega:
if alpha & 1:
res = self.func(res, self.data[alpha])
alpha += 1
if omega & 1:
omega -= 1
res = self.func(res, self.data[omega])
alpha >>= 1
omega >>= 1
return res
def update(self, alpha, omega, value):
"""Increases all elements in the range (inclusive) by given value!"""
alpha += self.size
omega += self.size + 1
l, r = alpha, omega
while alpha < omega:
if alpha & 1:
self.data[alpha] += value
self.lazy[alpha] += value
alpha += 1
if omega & 1:
omega -= 1
self.data[omega] += value
self.lazy[omega] += value
alpha >>= 1
omega >>= 1
self.build(l)
self.build(r-1)
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
n = int(input())
a = list(map(int, input().split()))
m = int(input())
st = LazySegmentTree(a, func=min)
for _ in range(m):
s = input().split()
if len(s) == 3:
a, b, c = map(int, s)
if a > b:
st.update(a, n-1, c)
st.update(0, b, c)
else:
st.update(a,b,c)
else:
a, b = map(int, s)
if a > b:
print(min(st.query(a,n-1), st.query(0,b)))
else:
print(st.query(a,b))
```
Yes
| 87,057 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Submitted Solution:
```
from typing import TypeVar, Generic, Callable, List
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
T = TypeVar('T')
S = TypeVar('S')
class StarrySkyTree(Generic[T, S]):
__slots__ = ['size', 'node', 'lazy', 'unit', 'lazy_unit',
'op', 'upd', 'lazy_upd', 'subt_size']
def __init__(self, size: int, default: T, unit: T, lazy_unit: S,
op: Callable[[T, T], T]) -> None:
self.size = size2 = 1 << (len(bin(size)) - 2)
self.unit, self.lazy_unit = unit, lazy_unit
self.node = [default] * (size2 * 2)
self.lazy = [lazy_unit] * (size2 * 2)
self.op = op
self.subt_size = subt = [0] * size2 + [1] * size + [0] * (size2 - size)
for i in range(size2 * 2 - 1, 1, -1):
subt[i >> 1] += subt[i]
def build(self, a: List[T]) -> None:
node = self.node
node[self.size:self.size + len(a)] = a
for i in range(self.size - 1, 0, -1):
node[i] = self.op(node[i << 1], node[(i << 1) + 1])
def find(self, left: int, right: int) -> T:
left, right = left + self.size, right + self.size
node, lazy = self.node, self.lazy
self.__propagate(self.__enum_index(left, right))
result = self.unit
while left < right:
if left & 1:
if lazy[left] == self.lazy_unit:
result = self.op(node[left], result)
else:
# node + lazy
result = self.op(node[left] + lazy[left], result)
left += 1
if right & 1:
if lazy[right - 1] == self.lazy_unit:
result = self.op(node[right - 1], result)
else:
# node + lazy
result = self.op(node[right - 1] + lazy[right - 1], result)
left, right = left >> 1, right >> 1
return result
def update(self, left: int, right: int, value: S) -> None:
left, right = left + self.size, right + self.size
node, lazy, l_unit = self.node, self.lazy, self.lazy_unit
_l, _r = left, right
while _l < _r:
if _l & 1:
# update lazy
lazy[_l] += value
_l += 1
if _r & 1:
# update lazy
lazy[_r - 1] += value
_l, _r = _l >> 1, _r >> 1
for i in self.__enum_index(left, right):
node[i] = self.op(
node[i * 2] if lazy[i * 2] == l_unit else node[i * 2] + lazy[i * 2],
node[i * 2 + 1] if lazy[i * 2 + 1] == l_unit else node[i * 2 + 1] + lazy[i * 2 + 1])
def __enum_index(self, left: int, right: int) -> List[int]:
flag, idx = 0, []
while left < right:
if flag & 1:
idx.append(left)
if flag & 2:
idx.append(right)
flag |= (left & 1) | ((right & 1) * 2)
left, right = left >> 1, right >> 1
while left:
idx.append(left)
left >>= 1
return idx
def __propagate(self, index_list):
node, lazy, l_unit = self.node, self.lazy, self.lazy_unit
for i in reversed(index_list):
if lazy[i] != l_unit:
# refresh node
node[i] += lazy[i]
if i < self.size:
# update lazy
lazy[i * 2] += lazy[i]
lazy[i * 2 + 1] += lazy[i]
lazy[i] = l_unit
n = int(input())
segt = StarrySkyTree[int, int](n, 10**9, 10**18, 0, min)
segt.build(list(map(int, input().split())))
t = int(input())
ans = []
for _ in range(t):
q = tuple(map(int, input().split()))
if len(q) == 3:
if q[0] > q[1]:
segt.update(q[0], n + 1, q[2])
segt.update(0, q[1] + 1, q[2])
else:
segt.update(q[0], q[1] + 1, q[2])
else:
if q[0] > q[1]:
ans.append(min(segt.find(q[0], n + 1), segt.find(0, q[1] + 1)))
else:
ans.append(segt.find(q[0], q[1] + 1))
print(*ans, sep='\n')
```
Yes
| 87,058 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Submitted Solution:
```
import math,sys,bisect,heapq,os
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
def input(): return sys.stdin.readline().rstrip('\r\n')
#input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
aj = lambda: list(map(int, input().split()))
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
def solve():
class st:
def __init__(self, n):
self.ntrl = float('inf')
h = int(math.log2(n-1))+1 if n>1 else 0
N = 2**h
self.t = [self.ntrl]*(2*N)
self.d = [0]*N
self.N = N
self.h = h
def merge(self,a,b):
return min(a,b)
def apply(self, p, value):
self.t[p] += value
if (p < self.N):
self.d[p] += value
def build(self, p):
t = self.t
d = self.d
while p > 1:
p >>= 1
t[p] = self.merge(t[p<<1], t[p<<1|1]) + d[p]
def rebuild(self):
t = self.t
for p in reversed(range(1, self.N)):
t[p] = self.merge(t[p<<1], t[p<<1|1])
def push(self, p):
d = self.d
for s in range(self.h, 0, -1):
i = p >> s
if d[i] != 0:
self.apply(i<<1, d[i])
self.apply(i<<1|1, d[i])
d[i] = 0
def inc(self, l, r, value):
if l > r:
return
l += self.N
r += self.N+1
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l, value)
l += 1
if r & 1:
r -= 1
self.apply(r, value)
l >>= 1
r >>= 1
self.build(l0)
self.build(r0 - 1)
def query(self, l, r):
if l > r:
return self.ntrl
t = self.t
l += self.N
r += self.N+1
self.push(l)
self.push(r - 1)
res = self.ntrl
while l < r:
if l & 1:
res = self.merge(res, t[l])
l += 1
if r & 1:
r -= 1
res = self.merge(t[r], res)
l >>= 1
r >>= 1
return res
n,=aj()
a=aj()
se=st(n)
N=se.N
for i in range(n):
se.t[i+N]=a[i]
se.rebuild()
q=int(input())
for i in range(q):
b=list(map(int,input().split()))
if len(b)==2:
l=b[0]
r=b[1]
if l>r:
print(min(se.query(l,n-1),se.query(0,r)))
else:print(se.query(l,r))
else:
l=b[0]
r=b[1]
v=b[2]
if l>r:
se.inc(0,r,v)
se.inc(l,n-1,v)
else:se.inc(l,r,v)
try:
#os.system("online_judge.py")
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
solve()
```
Yes
| 87,059 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Submitted Solution:
```
import sys
from math import inf, log2
class LazySegmentTree:
def __init__(self, array, func=min):
self.n = len(array)
self.size = 2**(int(log2(self.n-1))+1) if n != 1 else 1
self.func = func
self.default = 0 if self.func != min else inf
self.data = [self.default] * (2 * self.size)
self.lazy = [0] * (2 * self.size)
self.process(array)
def process(self, array):
self.data[self.size : self.size+self.n] = array
for i in range(self.size-1, -1, -1):
self.data[i] = self.func(self.data[2*i], self.data[2*i+1])
def push(self, index):
self.lazy[2*index] += self.lazy[index]
self.lazy[2*index+1] += self.lazy[index]
self.data[2 * index] += self.lazy[index]
self.data[2 * index + 1] += self.lazy[index]
self.lazy[index] = 0
def build(self, index):
index >>= 1
while index:
self.data[index] = self.func(self.data[2*index], self.data[2*index+1]) + self.lazy[index]
index >>= 1
def query(self, alpha, omega):
res = self.default
alpha += self.size
omega += self.size + 1
for i in range(len(bin(alpha)[2:])-1, 0, -1):
self.push(alpha >> i)
for i in range(len(bin(omega-1)[2:])-1, 0, -1):
self.push((omega-1) >> i)
while alpha < omega:
if alpha & 1:
res = self.func(res, self.data[alpha])
alpha += 1
if omega & 1:
omega -= 1
res = self.func(res, self.data[omega])
alpha >>= 1
omega >>= 1
return res
def update(self, alpha, omega, value):
alpha += self.size
omega += self.size + 1
l, r = alpha, omega
while alpha < omega:
if alpha & 1:
self.data[alpha] += value
self.lazy[alpha] += value
alpha += 1
if omega & 1:
omega -= 1
self.data[omega] += value
self.lazy[omega] += value
alpha >>= 1
omega >>= 1
self.build(l)
self.build(r-1)
debug=True
lines = sys.stdin.read().split("\n")
lines.pop(-1)
debug=False
n = int(lines.pop(0))
nodes = [int(x) for x in lines.pop(0).split(" ")]
ops = int(lines.pop(0))
segtree = LazySegmentTree(nodes)
counter=1
for line in lines:
values = line.split(" ")
if len(values) == 2:
a,b = values
a=int(a)
b=int(b)
if (debug):
print("===================================")
print("Consulta de Minimo N "+str(counter)+":")
print("A es "+str(a))
print("B es "+str(b))
print("Resultado:",end="")
if a <b:
print(segtree.query(a,b))
elif a==b:
print(segtree.query(a%n,a%n))
else:
if abs(a-b)== 1:
print(segtree.query(0, n-1))
else:
print(min(segtree.query(a%n,n-1), segtree.query(0,b) ) )
counter+=1
else:
a,b,v = values
a=int(a)
b=int(b)
v=int(v)
if (debug):
print("==========")
#print(segtree)
print("Update de Rango:")
print("A es "+str(a))
print("B es "+str(b))
print("V es "+str(v))
if a<=b:
segtree.update(a,b,v)
else:
segtree.update(a,n-1,v)
segtree.update(0,b,v);
```
Yes
| 87,060 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Submitted Solution:
```
from math import ceil, log2
def inc(segment, lazy, fr, to, value, L, R, index):
if(R < L):
return INF
if(lazy[index] != 0):
segment[index] += lazy[index]
if(L != R):
lazy[index*2+1] += lazy[index]
lazy[index*2+2] += lazy[index]
lazy[index] = 0
if(to < L or R< fr):
return min(INF, segment[index])
elif(fr <= L and to >= R):
segment[index]+= value
if(L!= R):
lazy[index*2 +1] += value
lazy[index*2 +2] += value
return segment[index]
else:
mid = (L +R) //2
u =inc(segment, lazy, fr, to, value, L, mid, index*2+1)
v = inc(segment, lazy, fr, to, value, mid+ 1, R, index*2+2)
segment[index] = min(u,v)
return segment[index]
def RMQ(segment, lazy, fr, to, L, R , index):
# -- L ---fr --to-R
if(L >R):
return INF
if(lazy[index] != 0):
segment[index] += lazy[index]
if(L != R):
lazy[index*2+1] += lazy[index]
lazy[index*2+2] += lazy[index]
lazy[index] = 0
if(to < L or R < fr):
return INF
elif(fr <= L and to >= R):
return segment[index]
else:
mid = (L + R) //2
u = RMQ(segment, lazy, fr, to, L,mid , 2* index+ 1)
v = RMQ(segment, lazy, fr, to, mid + 1,R , 2* index+ 2)
segment[index] = min(u, v)
return segment[index]
def buildTree(segment, a, L ,R, index):
if(L ==R) :
segment[index] = a[L]
return segment[index]
mid= (L + R) //2
u = buildTree(segment, a,L ,mid , 2* index + 1 )
v = buildTree(segment,a, mid + 1 ,R, 2* index + 2)
segment[index] = min(u, v)
return segment[index]
if __name__ == '__main__':
INF = 1e9
n = int(input())
a = list(map(int, input().split()))
# for i in range(0, n-1, 1):
# a.append(a[i])
# print(a)
size = (2*( 2** (ceil(log2( len(a) ) )) ) - 1)
segment = [INF] * size
lazy = [0] * size
buildTree(segment,a, 0 , len(a) -1, 0)
# print(segment)
Q = int(input())
for _ in range(Q):
info = list(map(int, input().split()))
if(len(info) == 2):
fr,to = info[0], info[1]
# ans = INF
if(fr > to):
# print('0sdfdf', to, len(a)-1) ## 3 fr -- 0to
u = RMQ(segment, lazy, fr, len(a) -1, 0, len(a) -1 , 0)
# print('1dfdffd',0, fr)
v = RMQ(segment, lazy, 0, to, 0, len(a) -1 , 0)
ans = min(u, v)
print(ans)
else:
ans = RMQ(segment, lazy, fr, to, 0, len(a) -1 , 0)
print(ans)
# print(ans)
else:
fr, to , value = info[0],info[1], info[2]
if(fr > to):
# print('0 dfdf', to, len(a)-1)
u = inc(segment, lazy, fr, len(a) -1, value, 0, len(a) -1, 0)
# print('1df df' ,0, fr)
v = inc(segment, lazy, 0, to, value, 0, len(a) -1, 0)
else:
inc(segment, lazy, fr, to, value, 0, len(a) -1, 0)
```
No
| 87,061 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Submitted Solution:
```
useless = input()
array = input().split(' ')
operation_amount = input()
operations = list()
for i in range(int(operation_amount)):
operations.append(input().split(' '))
def result(operations, array):
transformed_array = list(map(int, array))
results = list()
for operation in operations:
if len(operation) == 2:
results.append(req(operation[0], operation[1], transformed_array))
else:
add(operation[0], operation[1], operation[2], transformed_array)
return results
def add(start, end, value, array):
if start == end:
array[int(start)] += int(value)
elif int(start) < int(end):
for i in range(int(start), int(end) + 1):
array[i] += int(value)
else:
for i in range(int(start), len(array) + int(end) + 1):
array[i % len(array)] += int(value)
def req(start, end, array):
if start == end:
return array[int(start)]
elif int(start) < int(end):
return min(array[int(start):int(end) + 1])
else:
print(array[int(end):-len(array) - int(start)],
len(array), -len(array) + int(start), int(end))
return min(array[i % len(array)] for i in range(int(start), len(array) + int(end) + 1))
for i in result(operations, array):
print(i)
```
No
| 87,062 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Submitted Solution:
```
class stree:
def __init__(self, n):
self.n = n
self.tree = [0]*(4*n+1)
self.delta = [0]*(4*n+1)
def prop(self, i):
self.delta[2*i] += self.delta[i]
self.delta[2*i+1] += self.delta[i]
self.delta[i] = 0
def update(self, i):
self.tree[i] = min(self.tree[2*i]+self.delta[2*i], self.tree[2*i+1]+self.delta[2*i+1])
def incr(self, node, i, j, l, r, val):
if i > r or j < l:
return
if i <= l and j >= r:
self.delta[node] += val
#print(val,"added to", node)
return
self.prop(node)
mid = (l+r)//2
self.incr(2*node, i, j, l, mid, val)
self.incr(2*node+1, i, j, mid+1, r, val)
self.update(node)
def query(self, node, i, j, l, r):
if i > r or j < l:
return 10**7
if i <= l and j >= r:
return self.delta[node]+self.tree[node]
self.prop(node)
mid = (l+r)//2
left = self.query(2*node, i, j, l, mid)
right = self.query(2*node+1, i, j, mid+1, r)
return min(left, right)
n = int(input().strip())
arr = list(map(int, input().strip().split()))
i = 0
st = stree(n)
while i<n:
st.incr(1, i, i, 0, n-1, arr[i])
i += 1
q = int(input().strip())
#print(st.tree," and ", st.delta)
while q:
a = list(map(int, input().strip().split()))
if len(a) == 2:
if a[0] <= a[1]:
print(st.query(1, a[0], a[1], 0, n-1))
else:
print(min(st.query(1, a[0], n-1, 0, n-1), st.query(1, 0, a[1], 0, n-1)))
else:
if a[0] <= a[1]:
st.incr(1, a[0], a[1], 0, n-1, a[2])
else:
st.incr(1, a[0], n-1, 0, n-1, a[2])
st.incr(1, 0, a[1], 0, n-1, a[2])
q -= 1
```
No
| 87,063 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it:
* inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v;
* rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively).
Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.
Write program to process given sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.
Output
For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
4
1 2 3 4
4
3 0
3 0 -1
0 1
2 1
Output
1
0
0
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#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")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**30, func=lambda a, b: min(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
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) # To make sure already calculated n^-1
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
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] > k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
n=int(input())
a=list(map(int,input().split()))
q=int(input())
tree=[0]*(3*n)
lazy=[0]*(3*n)
def push(v):
tree[2*v]+=lazy[v]
lazy[2*v]=lazy[v]
tree[2 * v+1] += lazy[v]
lazy[2 * v+1] = lazy[v]
lazy[v]=0
def build(a,st,end,ind):
if st==end:
tree[ind]=a[st]
else:
mid=(st+end)//2
build(a,st,mid,2*ind)
build(a,mid+1,end,2*ind+1)
tree[ind]=min(tree[2*ind],tree[2*ind+1])
def update(a,l,r,st,end,ind,val):
if l>r:
return
if st==end:
tree[ind]+=val
elif l==st and r==end:
tree[ind]+=val
lazy[ind]+=val
else:
push(ind)
mid = (st + end) // 2
update(a,l,min(r,mid),st,mid,2*ind,val)
update(a, max(l, mid+1),r,mid+1,end, 2 * ind+1,val)
tree[ind]=min(tree[2*ind],tree[2*ind+1])
def query(a,l,r,st,end,ind):
if l>r:
return 999999
if st==end:
return tree[ind]
elif l==st and r==end:
return tree[ind]
else:
push(ind)
mid = (st + end) // 2
return min(query(a,l,min(r,mid),st,mid,2*ind),query(a, max(l, mid+1),r,mid+1,end, 2 * ind+1))
build(a,0,n-1,1)
for i in range(q):
l=list(map(int,input().split()))
if len(l)==2:
le,ri=l
if le>ri:
w=query(a,le,n-1,0,n-1,1)
w1=query(a,0,ri,0,n-1,1)
print(min(w,w1))
else:
w=query(a,le,ri,0,n-1,1)
print(w)
else:
le,ri,val=l
if le > ri:
update(a,le,n-1,0,n-1,1,val)
update(a, 0, ri, 0, n - 1,1, val)
else:
update(a, le, ri, 0, n - 1,1, val)
```
No
| 87,064 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-known detective. Now he is preparing a defense against a possible attack by hackers on a major computer network.
In this network are n vertices, some pairs of vertices are connected by m undirected channels. It is planned to transfer q important messages via this network, the i-th of which must be sent from vertex si to vertex di via one or more channels, perhaps through some intermediate vertices.
To protect against attacks a special algorithm was developed. Unfortunately it can be applied only to the network containing directed channels. Therefore, as new channels can't be created, it was decided for each of the existing undirected channels to enable them to transmit data only in one of the two directions.
Your task is to determine whether it is possible so to choose the direction for each channel so that each of the q messages could be successfully transmitted.
Input
The first line contains three integers n, m and q (1 ≤ n, m, q ≤ 2·105) — the number of nodes, channels and important messages.
Next m lines contain two integers each, vi and ui (1 ≤ vi, ui ≤ n, vi ≠ ui), that means that between nodes vi and ui is a channel. Between a pair of nodes can exist more than one channel.
Next q lines contain two integers si and di (1 ≤ si, di ≤ n, si ≠ di) — the numbers of the nodes of the source and destination of the corresponding message.
It is not guaranteed that in it initially possible to transmit all the messages.
Output
If a solution exists, print on a single line "Yes" (without the quotes). Otherwise, print "No" (without the quotes).
Examples
Input
4 4 2
1 2
1 3
2 3
3 4
1 3
4 2
Output
Yes
Input
3 2 2
1 2
3 2
1 3
2 1
Output
No
Input
3 3 2
1 2
1 2
3 2
1 3
2 1
Output
Yes
Note
In the first sample test you can assign directions, for example, as follows: 1 → 2, 1 → 3, 3 → 2, 4 → 3. Then the path for for the first message will be 1 → 3, and for the second one — 4 → 3 → 2.
In the third sample test you can assign directions, for example, as follows: 1 → 2, 2 → 1, 2 → 3. Then the path for the first message will be 1 → 2 → 3, and for the second one — 2 → 1.
Submitted Solution:
```
print("No")
```
No
| 87,065 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-known detective. Now he is preparing a defense against a possible attack by hackers on a major computer network.
In this network are n vertices, some pairs of vertices are connected by m undirected channels. It is planned to transfer q important messages via this network, the i-th of which must be sent from vertex si to vertex di via one or more channels, perhaps through some intermediate vertices.
To protect against attacks a special algorithm was developed. Unfortunately it can be applied only to the network containing directed channels. Therefore, as new channels can't be created, it was decided for each of the existing undirected channels to enable them to transmit data only in one of the two directions.
Your task is to determine whether it is possible so to choose the direction for each channel so that each of the q messages could be successfully transmitted.
Input
The first line contains three integers n, m and q (1 ≤ n, m, q ≤ 2·105) — the number of nodes, channels and important messages.
Next m lines contain two integers each, vi and ui (1 ≤ vi, ui ≤ n, vi ≠ ui), that means that between nodes vi and ui is a channel. Between a pair of nodes can exist more than one channel.
Next q lines contain two integers si and di (1 ≤ si, di ≤ n, si ≠ di) — the numbers of the nodes of the source and destination of the corresponding message.
It is not guaranteed that in it initially possible to transmit all the messages.
Output
If a solution exists, print on a single line "Yes" (without the quotes). Otherwise, print "No" (without the quotes).
Examples
Input
4 4 2
1 2
1 3
2 3
3 4
1 3
4 2
Output
Yes
Input
3 2 2
1 2
3 2
1 3
2 1
Output
No
Input
3 3 2
1 2
1 2
3 2
1 3
2 1
Output
Yes
Note
In the first sample test you can assign directions, for example, as follows: 1 → 2, 1 → 3, 3 → 2, 4 → 3. Then the path for for the first message will be 1 → 3, and for the second one — 4 → 3 → 2.
In the third sample test you can assign directions, for example, as follows: 1 → 2, 2 → 1, 2 → 3. Then the path for the first message will be 1 → 2 → 3, and for the second one — 2 → 1.
Submitted Solution:
```
print("Yes")
```
No
| 87,066 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Tags: bitmasks, brute force, constructive algorithms, geometry, implementation, math
Correct Solution:
```
__author__ = 'User'
def f(arr, value, deep, vis):
global flag
if flag == True:
return
fl = False
#print("Num")
pos = (0, 0)
for i in range(n):
for j in range(n):
#print(i, j, arr[i][j], end = " ")
if arr[i][j] == 0:
pos = (i, j)
fl = True
break
if fl == True:
break
#print()
#print(n, "N")
#print(arr, "AAAAAA")
#print(pos, vis)
symbol = value[2]
for y, x in value[:-1]:
#print(y, x, "YX" + symbol)
tarr = arr[:]
y0, x0 = pos[0], pos[1]
if y0 < n and x0 < n and arr[y0][x0] == 0:
if x0 + x - 1 < n and y0 + y - 1 < n:
tr = True
for i in range(y0, y0 + y):
for j in range(x0, x0 + x):
if arr[i][j] != 0:
tr = False
break
arr[i][j] = symbol
if tr == False:
break
if tr:
"""print(tr)
for i in range(n):
print(*tarr[i])
print()"""
if deep == 0:
print(n)
flag = True
for i in range(n):
print(*arr[i], sep = '')
return
for k in range(3):
if vis[k] == 0:
vis[k] = -1
#print(tarr, val[k], deep - 1, vis)
f(arr, val[k], deep - 1, vis)
"""
for i in range(n):
print(*arr[i])
print()
"""
tr = True
for i in range(y0, y0 + y):
for j in range(x0, x0 + x):
if arr[i][j] == symbol:
arr[i][j] = 0
else:
tr = False
break
if tr == False:
break
x1, y1, x2, y2, x3, y3 = map(int, input().split())
val = [[(x1, y1), (y1, x1), "A"], [(x2, y2) , (y2, x2), "B"], [(x3, y3) , (y3, x3), "C"]]
s = x1 * y1 + x2 * y2 + x3 * y3
flag = True
mx = max(x1, x2, x3, y1, y2, y3)
if round((s) ** (1/2)) == round((s) ** (1/2), 8):
n = int(s ** 0.5)
if n < mx:
flag = False
else:
flag = False
if flag == True:
flag = False
arr = [n * [0] for i in range(n)]
for i in range(3):
deep = 3
vis = [0] * 3
vis[i] = -1
#print(n, "N")
f(arr, val[i], deep - 1, vis)
if flag == False:
print(-1)
else:
print(-1)
```
| 87,067 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Tags: bitmasks, brute force, constructive algorithms, geometry, implementation, math
Correct Solution:
```
v=list(map(int,input().split()))
def funk(a):
if ((a[0]==a[2]+a[4])and(a[1]+a[3]==a[0])and(a[3]==a[5])):
print(a[0])
for i in range(a[1]):
print('A'*a[0])
for i in range(a[3]):
print('B'*a[2]+'C'*a[4])
elif ((a[0]==a[2]==a[4])and(a[1]+a[3]+a[5]==a[0])):
print(a[0])
for i in range(a[1]):
print('A'*a[0])
for i in range(a[3]):
print('B'*a[2])
for i in range(a[5]):
print('C'*a[4])
elif ((a[0]+a[2]+a[4]==a[1])and(a[1]==a[3]==a[5])):
print(a[1])
for i in range(a[1]):
print('A'*a[0]+'B'*a[2]+'C'*a[4])
elif ((a[0]+a[2]==a[4])and(a[1]==a[3])and(a[1]+a[5]==a[4])):
print(a[4])
for i in range(a[1]):
print('A'*a[0]+'B'*a[2])
for i in range(a[5]):
print('C'*a[4])
elif ((a[0]+a[2]==a[1])and(a[2]==a[4])and(a[3]+a[5]==a[1])):
print(a[1])
for i in range(a[3]):
print('A'*a[0]+'B'*a[2])
for i in range(a[5]):
print('A'*a[0]+'C'*a[4])
elif ((a[0]+a[2]==a[3])and(a[0]==a[4])and(a[1]+a[5]==a[3])):
print(a[3])
for i in range(a[1]):
print('A'*a[0]+'B'*a[2])
for i in range(a[5]):
print('C'*a[4]+'B'*a[2])
else:
#~ print('-1')
return 0
return 1
s=0
for i in range(2):
v[0],v[1]=v[1],v[0]
for i1 in range(2):
v[2],v[3]=v[3],v[2]
for i2 in range(2):
v[4],v[5]=v[5],v[4]
if s==0:
s=funk(v)
if s:break
if s==0:
print('-1')
```
| 87,068 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Tags: bitmasks, brute force, constructive algorithms, geometry, implementation, math
Correct Solution:
```
x1, y1, x2, y2, x3, y3 = map(int, input().split())
x1, y1 = max(x1, y1), min(x1, y1)
x2, y2 = max(x2, y2), min(x2, y2)
x3, y3 = max(x3, y3), min(x3, y3)
x1c, y1c, x2c, y2c, x3c, y3c = x1, y1, x2, y2, x3, y3
if x2 == max(x1, x2, x3) :
x1, y1, x2, y2 = x2, y2, x1, y1
elif x3 == max(x1, x2, x3) :
x1, y1, x3, y3 = x3, y3, x1, y1
if x1 == x1c and y1 == y1c and x2 == x2c and y2 == y2c :
s1 = 'A'
s2 = 'B'
s3 = 'C'
elif x1 == x1c and y1 == y1c and x2 == x3c and y2 == y3c :
s1 = 'A'
s2 = 'C'
s3 = 'B'
elif x1 == x2c and y1 == y2c and x2 == x1c and y2 == y1c :
s1 = 'B'
s2 = 'A'
s3 = 'C'
elif x1 == x2c and y1 == y2c and x2 == x3c and y2 == y3c :
s1 = 'B'
s2 = 'C'
s3 = 'A'
elif x1 == x3c and y1 == y3c and x2 == x1c and y2 == y1c :
s1 = 'C'
s2 = 'A'
s3 = 'B'
elif x1 == x3c and y1 == y3c and x2 == x2c and y2 == y2c :
s1 = 'C'
s2 = 'B'
s3 = 'A'
if x1 == x2 == x3 and y1 + y2 + y3 == x1 :
print(x1)
for i in range(x1) :
for j in range(x1) :
if i < y1 :
print(s1, end = '')
elif y1 <= i < y1 + y2 :
print(s2, end = '')
else :
print(s3, end = '')
print()
elif x1 == y2 + x3 and x2 + y1 == y3 + y1 == x1 :
print(x1)
for i in range(x1) :
for j in range(x1) :
if i < y1 :
print(s1, end = '')
else :
if j < y2 :
print(s2, end = '')
else :
print(s3, end = '')
print()
elif x1 == x2 + y3 and y2 + y1 == x3 + y1 == x1 :
print(x1)
for i in range(x1) :
for j in range(x1) :
if i < y1 :
print(s1, end = '')
else :
if j < x2 :
print(s2, end = '')
else :
print(s3, end = '')
print()
elif x1 == x2 + x3 and y2 + y1 == y3 + y1 == x1 :
print(x1)
for i in range(x1) :
for j in range(x1) :
if i < y1 :
print(s1, end = '')
else :
if j < x2 :
print(s2, end = '')
else :
print(s3, end = '')
print()
elif x1 == y2 + y3 and x2 + y1 == x3 + y1 == x1 :
print(x1)
for i in range(x1) :
for j in range(x1) :
if i < y1 :
print(s1, end = '')
else :
if j < y2 :
print(s2, end = '')
else :
print(s3, end = '')
print()
else :
print(-1)
```
| 87,069 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Tags: bitmasks, brute force, constructive algorithms, geometry, implementation, math
Correct Solution:
```
from sys import *
inp = lambda : stdin.readline()
def main():
x1,y1,x2,y2,x3,y3 = map(int,inp().split())
m = max(x1,x2,x3,y1,y2,y3)
l = [(x1,y1),(x2,y2),(x3,y3)]
ans = [ ['C' for i in range(m)] for i in range(m)]
bools = True
if all([m in x for x in l]):
if min(x1, y1) + min(x2, y2) + min(x3, y3) != m:
bools = False
else:
for i in range(0,min(x1,y1)):
ans[i] = ['A' for i in range(m)]
for i in range(min(x1,y1),min(x1,y1)+min(x2,y2)):
ans[i] = ['B' for i in range(m)]
else:
if x2 * y2 + x3 * y3 + x1 * y1 != m * m:
bools = False
elif m in l[0]:
if not all([m-min(x1,y1) in i for i in [l[1],l[2]]]):
bools = False
else:
for i in range(0,min(x1,y1)):
ans[i] = ['A' for i in range(m)]
if min(x2,y2) + min(x1,y1) == m:
for i in range(min(x1, y1), m):
ans[i] = ['B' for i in range(max(x2,y2))] + ['C' for i in range(m-max(x2,y2))]
else:
for i in range(min(x1, y1), m):
ans[i] = ['B' for i in range(min(x2, y2))] + ['C' for i in range(m - min(x2, y2))]
elif m in l[1]:
if not all([m - min(x2, y2) in i for i in [l[0], l[2]]]):
bools = False
else:
x1,x2=x2,x1
y1,y2=y2,y1
for i in range(0, min(x1, y1)):
ans[i] = ['B' for i in range(m)]
if min(x2, y2) + min(x1, y1) == m:
for i in range(min(x1, y1), m):
ans[i] = ['A' for i in range(max(x2, y2))] + ['C' for i in range(m - max(x2, y2))]
else:
for i in range(min(x1, y1), m):
ans[i] = ['A' for i in range(min(x2, y2))] + ['C' for i in range(m - min(x2, y2))]
elif m in l[2]:
if not all([m - min(x3, y3) in i for i in [l[1], l[0]]]):
bools = False
else:
x1, x3 = x3, x1
y1, y3 = y3, y2
for i in range(0, min(x1, y1)):
ans[i] = ['C' for i in range(m)]
if min(x2, y2) + min(x1, y1) == m:
for i in range(min(x1, y1), m):
ans[i] = ['B' for i in range(max(x2, y2))] + ['A' for i in range(m - max(x2, y2))]
else:
for i in range(min(x1, y1), m):
ans[i] = ['B' for i in range(min(x2, y2))] + ['A' for i in range(m - min(x2, y2))]
if bools:
print(m)
for i in ans:
print("".join(map(str,i)))
else:
print(-1)
if __name__ == "__main__":
main()
```
| 87,070 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Tags: bitmasks, brute force, constructive algorithms, geometry, implementation, math
Correct Solution:
```
#!/usr/bin/python3
from itertools import permutations
def isqrt(x):
l, r = 0, 10**100
while l < r - 1:
mid = (l + r) // 2
if mid ** 2 > x:
r = mid
else:
l = mid
return l
x1, y1, x2, y2, x3, y3 = map(int, input().split())
p = [(x1, y1, "A"), (x2, y2, "B"), (x3, y3, "C")]
s = x1 * y1 + x2 * y2 + x3 * y3
x = isqrt(s)
if x * x != s:
print(-1)
exit(0)
for mask in range(1 << 3):
q = []
for i in range(3):
if (mask >> i) & 1:
q.append((p[i][0], p[i][1], p[i][2]))
else:
q.append((p[i][1], p[i][0], p[i][2]))
if q[0][0] == q[1][0] == q[2][0] == x:
print(x)
for i in range(q[0][1]):
print("A" * x)
for i in range(q[1][1]):
print("B" * x)
for i in range(q[2][1]):
print("C" * x)
exit(0)
for r in permutations(q):
t = list(r)
if t[0][0] == x and t[0][1] + t[1][1] == x and t[0][1] + t[2][1] == x and t[1][0] + t[2][0] == x:
print(x)
for i in range(t[0][1]):
print(t[0][2] * x)
for i in range(x - t[0][1]):
print(t[1][2] * t[1][0] + t[2][2] * t[2][0])
exit(0)
print(-1)
```
| 87,071 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Tags: bitmasks, brute force, constructive algorithms, geometry, implementation, math
Correct Solution:
```
inp = input().split()
a = [int(inp[0]),int(inp[1])]
b = [int(inp[2]),int(inp[3])]
c = [int(inp[4]),int(inp[5])]
a.sort()
a.reverse()
a.append("A")
b.sort()
b.reverse()
b.append("B")
c.sort()
c.reverse()
c.append("C")
first = [a, b ,c]
first.sort()
first.reverse()
second = [a, b, c]
second.sort()
second.reverse()
third = [a, b, c]
#print(first)
#print(second)
def swap(a):
temp = a[0]
a[0] = a[1]
a[1] = temp
def check_first(x):
#print(x)
fla = (x[0][0] == x[1][0] + x[2][0])
#print(x[0][0], "==", x[1][0], "+", x[2][0])
#print(fla)
flb = (x[1][1] == x[2][1] == (x[0][0] - x[0][1]))
#print(x[1][1], "==", x[2][1], "==", x[0][0] - x[0][1])
#print(flb)
return fla and flb
def check_second(x):
if (x[0][0] == x[1][0]) and (x[0][1] + x[1][1] == x[2][0] == x[0][0]):
return True
else:
return False
flag = False
ind = 0
res = -1
s = ""
while (not flag):
ind = 1
if check_first(first):
break
swap(first[1])
if check_first(first):
break
swap(first[2])
if check_first(first):
break
swap(first[1])
if check_first(first):
break
ind = 2
if check_second(second):
break
swap(second[2])
if check_second(second):
break
if (third[0][0] == third[1][0] == third[2][0]) and (third[0][0] == third[0][1] + third[1][1] + third[2][1]):
ind = 3
break
flag = True
if flag:
print(-1)
elif ind == 1:
print(first[0][0])
for i in range(first[0][1]):
print(first[0][2] * first[0][0])
for i in range(first[1][1]):
print(first[1][2]*first[1][0] + first[2][2] * first[2][0])
elif ind == 2:
print(second[2][1])
for i in range(second[0][1]):
print(second[0][2]*second[0][0] + second[2][2]*second[2][0])
for i in range(second[1][1]):
print(second[1][2]*second[1][0] + second[2][2]*second[2][0])
elif ind == 3:
print(third[0][0])
for i in range(third[0][1]):
print(third[0][2]*third[0][0])
for i in range(third[1][1]):
print(third[1][2]*third[0][0])
for i in range(third[2][1]):
print(third[2][2]*third[0][0])
```
| 87,072 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Tags: bitmasks, brute force, constructive algorithms, geometry, implementation, math
Correct Solution:
```
import sys
def get_sol(a, b, c, n, reverse):
#1
if reverse[0]:
a = (a[1], a[0], a[2])
if reverse[1]:
b = (b[1], b[0], b[2])
if reverse[2]:
c = (c[1], c[0], c[2])
ans = []
if a[0] == b[0] == c[0] == n:
if a[1] + b[1] + c[1] == n:
for i in range(a[1]):
ans.append(a[2]*n)
for i in range(b[1]):
ans.append(b[2]*n)
for i in range(c[1]):
ans.append(c[2]*n)
return True, ans
if a[0] + c[0] == b[0] + c[0] == n and c[1] == n == a[1] + b[1]:
for i in range(a[1]):
ans.append(a[2]*a[0] + c[2] * c[0])
for i in range(b[1]):
ans.append(b[2]*b[0] + c[2] * c[0])
return True, ans
return False, ans
def printans(ans, n):
print(n)
for line in ans:
print(line)
exit()
#sys.stdin = open('input.txt')
#sys.stdout = open('output.txt', 'w')
x1, y1, x2, y2, x3, y3 = [int(i) for i in input().split()]
total_area = x1*y1 + x2*y2 + x3*y3
n = 0
while n ** 2 < total_area:
n += 1
if n ** 2 != total_area:
print(-1)
else:
first = (x1, y1, 'A')
second = (x2, y2, 'B')
third = (x3, y3, 'C')
pereb = ( (first, second, third),
(first, third, second),
(second, first, third),
(second, third, first),
(third, first, second),
(third, second, first))
for rev1 in (False, True):
for rev2 in (False, True):
for rev3 in (False, True):
for per in pereb:
reverse = (rev1, rev2, rev3)
is_ans, ans = get_sol(per[0], per[1], per[2], n, reverse)
if is_ans: printans(ans, n)
print(-1)
```
| 87,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Tags: bitmasks, brute force, constructive algorithms, geometry, implementation, math
Correct Solution:
```
a,b,c,d,e,f=map(int,input().split())
m=sorted([(max(a,b),min(a,b),"A"),(max(c,d),min(c,d),"B"),(max(e,f),min(e,f),"C")])
ma=m[-1][0]
ma2=ma-m[-1][1]
ans=[["A"]*ma for i in range(ma)]
if a*b+c*d+e*f!=ma*ma: print(-1)
elif m[0][0]*m[0][1]+m[1][0]*m[1][1]!=ma2*ma: print(-1)
elif m[0][0]!=m[1][0]:
if m[0][0]!=m[1][1] and m[0][1]!=m[1][1] : print(-1)
else:
for i in range(m[-1][1]):
for j in range(ma): ans[i][j]=m[-1][2]
for i in range(m[-1][1],ma):
for j in range(m[0][0]+m[0][1]-ma2): ans[i][j]=m[0][2]
for i in range(m[-1][1],ma):
for j in range(m[0][0]+m[0][1]-ma2,ma): ans[i][j]=m[1][2]
print(ma)
for x in ans:
print(''.join(x))
else:
for i in range(m[-1][1]):
for j in range(ma): ans[i][j]=m[-1][2]
if m[0][0]==ma:
for i in range(m[-1][1],m[-1][1]+m[0][1]):
for j in range(ma): ans[i][j]=m[0][2]
for i in range(m[-1][1]+m[0][1],ma):
for j in range(ma): ans[i][j]=m[1][2]
else:
for i in range(m[-1][1],ma):
for j in range(m[0][1]): ans[i][j]=m[0][2]
for i in range(m[-1][1],ma):
for j in range(m[0][1],ma): ans[i][j]=m[1][2]
print(ma)
for x in ans:
print(''.join(x))
```
| 87,074 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Submitted Solution:
```
def possible(arr):
# 4 possible cases
a,b,c,d,e,f = arr
if(a == c == e and b + d + f == a):
one = "A" * b + "B" * d + "C" * f
print(a)
for i in range(a):
print(one)
return True
if(b == d == f and a + c + e == d):
print(b)
for i in range(a):
print("A" * b)
for i in range(c):
print("B" * b)
for i in range(e):
print("C" * b)
return True
ns = [(a,b,"A"),(c,d,"B"),(e,f,"C")]
fs = [(b, a,"A"),(d, c,"B"),(f, e,"C")]
ns.sort(reverse = True)
x,y,z = ns
a,b,t1 = x
c,d,t2 = y
e,f,t3 = z
if(c + e == a and d == f and d + b == a):
print(a)
mat = [["." for i in range(a)] for j in range(a)]
for i in range(a):
for j in range(b):
mat[i][j] = t1
for i in range(c):
for j in range(b, a):
mat[i][j] = t2
for i in range(c, a):
for j in range(b, a):
mat[i][j] = t3
for i in range(a):
print("".join(mat[i]))
return True
fs.sort(reverse = True)
x,y,z = fs
b,a,t1 = x
d,c,t2 = y
f,e,t3 = z
if(d + f == b and c == e and c + a == b):
print(b)
mat = [["." for i in range(b)] for j in range(b)]
for i in range(a):
for j in range(b):
mat[i][j] =t1
for i in range(a, b):
for j in range(d):
mat[i][j] = t2
for i in range(a, b):
for j in range(d, b):
mat[i][j] = t3
for i in range(b):
print("".join(mat[i]))
return True
return False
arr = [int(x) for x in input().split()]
cnt = 0
ok = False
for i in range(8):
send = [x for x in arr]
if(i&1):
send[0], send[1] = send[1], send[0]
if(i&2):
send[2], send[3] = send[3], send[2]
if(i&4):
send[4], send[5] = send[5], send[4]
if(possible(send)):
ok = True
break
if(not ok):
print(-1)
```
Yes
| 87,075 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Submitted Solution:
```
x1, y1, x2, y2, x3, y3 = map(int, input().split())
rect1 = [x1, y1]
rect2 = [x2, y2]
rect3 = [x3, y3]
def func():
rect11 = [x1, y1]
rect22 = [x2, y2]
rect33 = [x3, y3]
rect1 = [x1, y1]
rect2 = [x2, y2]
rect3 = [x3, y3]
recta = [x1, y1]
rectb = [x2, y2]
rectc = [x3, y3]
for i in rect11:
for ii in rect22:
for iii in rect33:
if i==ii:
rect1.remove(i)
rect2.remove(ii)
if rect1[0]+rect2[0]==iii:
rect3.remove(iii)
if i+rect3[0]==iii:
print(iii)
for j in range(iii):
if j<rect1[0]:
print("C"*rect3[0]+"A"*i)
else:
print("C"*rect3[0]+"B"*ii)
exit()
rect1=recta.copy()
rect2=rectb.copy()
rect3=rectc.copy()
if i==iii:
rect1.remove(i)
rect3.remove(iii)
if rect1[0]+rect3[0]==ii:
rect2.remove(ii)
if i+rect2[0]==ii:
print(ii)
for j in range(ii):
if j<rect1[0]:
print("B"*rect2[0]+"A"*i)
else:
print("B"*rect2[0]+"C"*iii)
exit()
rect1 = recta.copy()
rect2 = rectb.copy()
rect3 = rectc.copy()
if ii==iii:
rect2.remove(ii)
rect3.remove(iii)
if rect2[0]+rect3[0]==i:
rect1.remove(i)
if i==rect1[0]+ii:
print(i)
for j in range(i):
if j<rect2[0]:
print("A"*rect1[0]+"B"*ii)
else:print("A"*rect1[0]+"C"*iii)
exit()
rect1=recta.copy()
rect2=rectb.copy()
rect3=rectc.copy()
return print(-1)
for i in rect1:
for ii in rect2:
for iii in rect3:
recta = [x1, y1]
rectb = [x2, y2]
rectc = [x3, y3]
if i==ii==iii:
rect1.remove(i)
rect2.remove(i)
rect3.remove(i)
if rect1[0]+rect2[0]+rect3[0]==i:
print(i)
for j in range(i):
print("A"*rect1[0]+"B"*rect2[0]+"C"*rect3[0])
exit()
rect1=recta
rect2=rectb
rect3=rectc
func()
```
Yes
| 87,076 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Submitted Solution:
```
def getprint(c1, c2, c3, maxi, ost, delta):
ans = str(maxi) + "\n" + (c1 * maxi + "\n") * ost
return ans + (c2 * delta + c3 * (maxi - delta) + "\n") * (maxi - ost)
def solve():
a = list(map(int, input().split()))
if max(a) ** 2 != a[0] * a[1] + a[2] * a[3] + a[4] * a[5]:
return -1
maxi = max(a)
if maxi in a[:2] and maxi in a[2:4] and maxi in a[4:]:
return str(maxi) + "\n" + ("A" * maxi + "\n") * min(a[:2]) + ("B" * maxi + "\n") * min(a[2:4]) + ("C" * maxi + "\n") * min(a[4:])
ind = a.index(maxi)
ost = a[ind ^ 1]
if ind // 2 == 0 and maxi - ost in a[2:4] and maxi - ost in a[4:]:
return getprint("A", "B", "C", maxi, ost, a[2] * a[3] // (maxi - ost))
elif ind // 2 == 1 and maxi - ost in a[:2] and maxi - ost in a[4:]:
return getprint("B", "A", "C", maxi, ost, a[0] * a[1] // (maxi - ost))
elif ind // 2 == 2 and maxi - ost in a[:2] and maxi - ost in a[2:4]:
return getprint("C", "A", "B", maxi, ost, a[0] * a[1] // (maxi - ost))
return -1
print(solve())
```
Yes
| 87,077 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Submitted Solution:
```
import sys
#this solves only a specific orientation
#is fine because we consider all orientations
import itertools
def can(h1, w1, h2, w2, h3, w3, c1, c2, c3, tot):
#height = h1
if tot % h1 == 0 and tot // h1 == h1:
# side by side or on top of each other are the two options
# side by side
if h1 == h2 == h3:
print(h1)
for r in range(h1):
temp = ""
for c in range(w1 + w2 + w3):
if c < w1: temp += c1
elif c < w1 + w2: temp += c2
else: temp += c3
print(temp)
return True
if h2 + h3 == h1 and w2 == w3:
print(h1)
for r in range(h1):
temp = ""
for c in range(w1 + w2):
if c < w1: temp += c1
else:
if r < h2: temp += c2
else: temp += c3
print(temp)
return True
return False
def solve(perm):
x1, y1 = perm[0][0][0], perm[0][0][1]
x2, y2 = perm[1][0][0], perm[1][0][1]
x3, y3 = perm[2][0][0], perm[2][0][1]
c1 = perm[0][1]
c2 = perm[1][1]
c3 = perm[2][1]
tot = x1 * y1 + x2 * y2 + x3 * y3
for sw1 in range(2):
for sw2 in range(2):
for sw3 in range(2):
h1, w1, h2, w2, h3, w3 = x1, y1, x2, y2, x3, y3
if sw1 == 1: h1, w1 = w1, h1
if sw2 == 1: h2, w2 = w2, h2
if sw3 == 1: h3, w3 = w3, h3
if can(h1, w1, h2, w2, h3, w3, c1, c2, c3, tot):
return True
def supersolve():
x1, y1, x2, y2, x3, y3, = rv()
a = [([x1, y1], 'A'), ([x2, y2], 'B'), ([x3, y3], 'C')]
for perm in itertools.permutations(a):
if solve(perm): return
print(-1)
def prt(l): return print(' '.join(map(str, l)))
def rs(): return map(str, input().split())
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
supersolve()
```
Yes
| 87,078 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Submitted Solution:
```
def stripe(a, b, c, x):
y1 = a[0] if a[1] == x else a[1]
y2 = b[0] if b[1] == x else b[1]
y3 = c[0] if c[1] == x else c[1]
ans = []
ans.append('\n'.join('A'*x for _ in range(y1)))
ans.append('\n'.join('B'*x for _ in range(y2)))
ans.append('\n'.join('C'*x for _ in range(y3)))
return '\n'.join(ans)
def tt(aa):
return (aa[1], aa[0], aa[2])
def one_two(a, b, c):
ans = []
ans.append('\n'.join(a[2]*a[0] for _ in range(a[1])))
for _ in range(b[1]):
ans.append(b[2]*b[0] + c[2]*c[0])
return '\n'.join(ans)
def solve():
x1, y1, x2, y2, x3, y3 = map(int, input().split())
a = (x1, y1, 'A')
b = (x2, y2, 'B')
c = (x3, y3, 'C')
# case 1, stripe
for x in a:
if x in b and x in c:
return stripe(a, b, c, x)
# case 2
from itertools import permutations
for a, b, c in permutations((a, b, c)):
for a, b, c in ((a, b, c), (tt(a), b, c), (a, tt(b), c), (a, b, tt(c)),
(tt(a), tt(b), c), (tt(a), b, tt(c)), (a, tt(b), tt(c)),
(tt(a), tt(b), tt(c))):
if a[0] == b[0] + c[0] and b[1] == c[1]:
return one_two(a, b, c)
return -1
print(solve())
```
No
| 87,079 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Submitted Solution:
```
"""
Author - Satwik Tiwari .
21th NOV , 2020 - Saturday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
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 graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
for pp in range(t):
solve(pp)
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))
def solve(case):
x1,y1,x2,y2,x3,y3 = sep()
arr = x1*y1 + x2*y2 + x3*y3
for jj in range(8):
# print(x1,x2,x3,y1,y2,y3,x1 == x2,x2 == x3,y1+y2+y2, x1)
if(x1 == x2 and x2 == x3 and y1+y2+y3 == x1):
print(x1)
g = [[0 for _ in range(x1)] for __ in range(x1)]
for i in range(x1):
for j in range(y1):
g[i][j] = 'A'
for i in range(x1):
for j in range(y1,y1+y2):
g[i][j] = 'B'
for i in range(x1):
for j in range(y1+y2,y1+y2+y3):
g[i][j] = 'C'
for i in range(x1):
print(''.join(g[i]))
return
else:
pass
x1,y1 = y1,x1
if(jj%2==1):
x2,y2 = y2,x2
if(jj%4==3):
x3,y3 = y3,x3
# print('==')
# x1,y1 = y1,x1
# x2,y2 = y2,x2
# x3,y3 = y3,x3
for jj in range(8):
# print(x1,y1,x2,y2,x3,y3)
n = [x1+x2,x1+x3,x2+x3]
for i in range(len(n)):
# print(arr,n[i]*n[i])
if(arr != (n[i]*n[i])):
continue
g = [[0 for _ in range(n[i])] for __ in range(n[i])]
if(i == 0 or i == 5):
for j in range(x1):
for k in range(y1):
g[j][k] = 'A'
for j in range(x1,x1+x2):
for k in range(y2):
g[j][k] = 'B'
for j in range(n[i]):
for k in range(n[i]):
if(g[j][k] == 0):
g[j][k] = 'C'
print(n[i])
for ii in range(n[i]):
print(''.join(g[ii]))
return
if(i == 1 or i == 4):
# print(x1,x2,x3,y1,y2,y3,n[i],i)
for j in range(x1):
for k in range(y1):
g[j][k] = 'A'
for j in range(x1,x1+x3):
for k in range(y3):
g[j][k] = 'C'
for j in range(n[i]):
for k in range(n[i]):
if(g[j][k] == 0):
g[j][k] = 'B'
print(n[i])
for ii in range(n[i]):
print(''.join(g[ii]))
return
if(i == 2 or i==3):
# print(x1,x2,x3,y1,y2,y3,n[i])
for j in range(x2):
for k in range(y2):
g[j][k] = 'B'
for j in range(x2,x3+x2):
for k in range(y3):
g[j][k] = 'C'
for j in range(n[i]):
for k in range(n[i]):
if(g[j][k] == 0):
g[j][k] = 'A'
print(n[i])
for ii in range(n[i]):
print(''.join(g[ii]))
return
x1,y1 = y1,x1
if(jj%2==1):
x2,y2 = y2,x2
if(jj%4==3):
x3,y3 = y3,x3
print(-1)
testcase(1)
# testcase(int(inp()))
```
No
| 87,080 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Submitted Solution:
```
x1, y1, x2, y2, x3, y3 = map(int, input().split())
x1, y1 = max(x1, y1), min(x1, y1)
x2, y2 = max(x2, y2), min(x2, y2)
x3, y3 = max(x3, y3), min(x3, y3)
x1c, y1c, x2c, y2c, x3c, y3c = x1, y1, x2, y2, x3, y3
if x2 == max(x1, x2, x3) :
x1, y1, x2, y2 = x2, y2, x1, y1
elif x3 == max(x1, x2, x3) :
x1, y1, x3, y3 = x3, y3, x1, y1
if x1 == x1c and y1 == y1c and x2 == x2c and y2 == y2c :
s1 = 'A'
s2 = 'B'
s3 = 'C'
elif x1 == x1c and y1 == y1c and x2 == x3c and y2 == y3c :
s1 = 'A'
s2 = 'C'
s3 = 'B'
elif x1 == x2c and y1 == y2c and x2 == x1c and y2 == y1c :
s1 = 'B'
s2 = 'A'
s3 = 'C'
elif x1 == x2c and y1 == y2c and x2 == x3c and y2 == y3c :
s1 = 'B'
s2 = 'C'
s3 = 'A'
elif x1 == x3c and y1 == y3c and x2 == x1c and y2 == y1c :
s1 = 'C'
s2 = 'A'
s3 = 'B'
elif x1 == x3c and y1 == y3c and x2 == x2c and y2 == y2c :
s1 = 'C'
s2 = 'B'
s3 = 'A'
if x1 == x2 == x3 and y1 + y2 + y3 == x1 :
print(x1)
for i in range(x1) :
for j in range(x1) :
if i < y1 :
print(s1, end = '')
elif y1 <= i < y1 + y2 :
print(s2, end = '')
else :
print(s3, end = '')
print()
elif x1 == y2 + x3 and x2 + y1 == y3 + y1 == x1 :
print(x1)
for i in range(x1) :
for j in range(x1) :
if i < y1 :
print(s1, end = '')
else :
if j < y2 :
print(s2, end = '')
else :
print(s3, end = '')
print()
elif x1 == x2 + y3 and y2 + y1 == x3 + y1 == x1 :
print(x1)
for i in range(x1) :
for j in range(x1) :
if i < y1 :
print(s1, end = '')
else :
if j < x2 :
print(s2, end = '')
else :
print(s3, end = '')
print()
else :
print(-1)
```
No
| 87,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.
Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.
Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.
Input
The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.
Output
If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).
If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that:
* the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company,
* the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company,
* the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company,
Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.
See the samples to better understand the statement.
Examples
Input
5 1 2 5 5 2
Output
5
AAAAA
BBBBB
BBBBB
CCCCC
CCCCC
Input
4 4 2 6 4 2
Output
6
BBBBBB
BBBBBB
AAAACC
AAAACC
AAAACC
AAAACC
Submitted Solution:
```
from collections import namedtuple
from itertools import permutations
Rect = namedtuple("Rect", "h w")
def rotations(r):
yield r
yield Rect(r[1], r[0])
def main():
a, b, c, d, e, f = map(int, input().split())
a = Rect(a, b)
b = Rect(c, d)
c = Rect(e, f)
del d, e, f
for a0 in rotations(a):
for b0 in rotations(b):
for c0 in rotations(c):
for x, y, z in permutations((a0, b0, c0), 3):
if x.w == y.w == z.w == x.h + y.h + z.h:
# AAA
# BBB
# CCC
print(x.w)
for i in range(x.h):
print('A' * x.w)
for i in range(y.h):
print('B' * y.w)
for i in range(z.h):
print('C' * z.w)
return
elif x.w == y.w + z.w == x.h + y.h and y.h == z.h:
# AAA
# BBC
# BBC
print(x.w)
for i in range(x.h):
print('A' * x.w)
for i in range(y.h):
print('B' * y.w, end="")
print('C' * z.w)
return
print(-1)
main()
```
No
| 87,082 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109).
The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Tags: games, math
Correct Solution:
```
from functools import reduce
def gao(x,y):
if x==1:
return 1
if x==2:
return (~y&1)*2
if x==3:
return y&1
if x&1:
return 0
if ~y&1:
return 1
l=len(bin(x))-bin(x).rfind('1')-1
if x>>l==3:
l+=1
return 2-l%2
n,k=map(int,input().split())
s=reduce(lambda x,y:x^gao(y,k),map(int,[0]+input().split()))
if s:
print('Kevin')
else:
print('Nicky')
```
| 87,083 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109).
The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Tags: games, math
Correct Solution:
```
f = lambda: map(int, input().split())
n, k = f()
s = 0
for a in f():
d = 0
while a & 1 << d == 0: d += 1
t = (a == 3 << d) ^ (d & 1)
x = a & 1 if a < 4 else 0 if a & 1 else 2 - t
y = a if a < 3 else a & 1 ^ 1
s ^= x if k & 1 else y
print('Kevin' if s else 'Nicky')
# Made By Mostafa_Khaled
```
| 87,084 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109).
The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Tags: games, math
Correct Solution:
```
f = lambda: map(int, input().split())
n, k = f()
s = 0
for a in f():
d = 0
while a & 1 << d == 0: d += 1
t = (a == 3 << d) ^ (d & 1)
x = a & 1 if a < 4 else 0 if a & 1 else 2 - t
y = a if a < 3 else a & 1 ^ 1
s ^= x if k & 1 else y
print('Kevin' if s else 'Nicky')
```
| 87,085 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109).
The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Tags: games, math
Correct Solution:
```
G_EVEN = {0:0, 1:1, 2:2}
G_ODD = {0:0, 1:1, 2:0, 3:1}
def grundy(k, ai):
if k % 2:
if ai <= 3:
return G_ODD[ai]
elif ai % 2:
return 0
else:
p = 0
j = ai
while not j & 1:
p += 1
j >>= 1
if j == 3:
return 2 if p % 2 else 1
else:
return 1 if p % 2 else 2
return 1 + p % 2
else:
if ai <= 2:
return G_EVEN[ai]
else:
return ~ai & 1
def nim_sum(ns):
s = 0
for ni in ns:
s ^= ni
return s
def winner(k, a):
return bool(nim_sum(grundy(k, ai) for ai in a))
if __name__ == '__main__':
n, k = map(int, input().split())
a = list(map(int, input().split()))
print("Kevin" if winner(k, a) else "Nicky")
```
| 87,086 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109).
The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Tags: games, math
Correct Solution:
```
def grundy(n, k):
if k % 2 == 0:
if n <= 2:
return n
else:
return n % 2 == 0
else:
if n <= 4:
return [0, 1, 0, 1, 2][n]
elif n % 2 == 1:
return 0
else:
return 2 if grundy(n // 2, k) == 1 else 1
if __name__ == "__main__":
n, k = map(int, input().split())
xList = map(int, input().split())
res = 0
for x in xList:
res ^= grundy(x, k)
print("Kevin" if res else "Nicky")
```
| 87,087 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109).
The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Tags: games, math
Correct Solution:
```
def solve(x, k):
if k%2 == 0:
if x <= 2:
return x;
return (x+1)%2
else:
if x == 3 or x == 1:
return 1
if x%2 == 1:
return 0
if x == 0 or x == 2:
return 0
twos = 1
while x%2 == 0:
twos += 1
x //= 2
if x == 3:
twos += 1
return (twos%2)+1
(n, k) = map(int, input().split())
A = list(map(int, input().split()))
x = 0
for a in A:
x ^= solve(a,k)
if x == 0:
print("Nicky")
else:
print("Kevin")
```
| 87,088 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109).
The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Tags: games, math
Correct Solution:
```
f = lambda: map(int, input().split())
n, k = f()
s = 0
for a in f():
d = 0
while a % (2 << d) == 0: d += 1
x = a & 1 if a < 4 else 0 if a & 1 else 1 if (a == 3 << d) ^ (d & 1) else 2
y = a if a < 3 else a & 1 ^ 1
s ^= x if k & 1 else y
print('Kevin' if s else 'Nicky')
```
| 87,089 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109).
The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Submitted Solution:
```
def solve(x, k):
if k%2 == 0:
if x == 0:
return 0;
return (x+1)%2+1
else:
if x == 3 or x == 1:
return 1
if x%2 == 1:
return 0
if x == 0 or x == 2:
return 0
twos = 1
while x%2 == 0:
twos += 1
x //= 2
if x == 3:
twos += 1
return (twos%2)+1
(n, k) = map(int, input().split())
A = list(map(int, input().split()))
x = 0
for a in A:
x ^= solve(a,k)
if x == 0:
print("Nicky")
else:
print("Kevin")
```
No
| 87,090 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109).
The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Submitted Solution:
```
f = lambda: map(int, input().split())
n, k = f()
s = 0
for a in f():
d = 0
while a % (2 << d) == 0: d += 1
x = a & 1 if a < 4 else 0 if a & 1 else (a == 3 << d) ^ (d & 1)
y = a if a < 3 else a & 1 ^ 1
s ^= x if k & 1 else y
print('Kevin' if s else 'Nicky')
```
No
| 87,091 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109).
The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Submitted Solution:
```
f = lambda: map(int, input().split())
n, k = f()
s = 0
for a in f():
d = 0
while a % (2 << d) == 0: d += 1
x = a & 1 if a < 4 else 0 if a & 1 else 2 - (a == 3 << d) ^ (d & 1)
y = a if a < 3 else a & 1 ^ 1
s ^= x if k & 1 else y
print('Kevin' if s else 'Nicky')
```
No
| 87,092 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:
1. Remove a single cow from a chosen non-empty pile.
2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each.
The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109).
The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.
Output
Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).
Examples
Input
2 1
3 4
Output
Kevin
Input
1 2
3
Output
Nicky
Note
In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
Submitted Solution:
```
f = lambda: map(int, input().split())
n, k = f()
s = 0
for a in f():
d = 0
while a % (2 << d) == 0: d += 1
x = a & 1 if a < 4 else 0 if a & 1 else 1 + (a == 3 << d) ^ (d & 1 ^ 1)
y = a if a < 3 else a & 1 ^ 1
s ^= x if k & 1 else y
print('Kevin' if s else 'Nicky')
```
No
| 87,093 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.
Input
The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.
The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.
Output
Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.
Examples
Input
6
URLLDR
Output
2
Input
4
DLUU
Output
0
Input
7
RLRLRLR
Output
12
Note
In the first case, the entire source code works, as well as the "RL" substring in the second and third characters.
Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.
Tags: brute force, implementation
Correct Solution:
```
n = int(input(""))
s = str(input(""))
c = 0
for i in range(0, n - 1):
for f in range(i + 2, n + 1):
if s[i:f].count('R') == s[i:f].count('L') and s[i:f].count('U') == s[i:f].count('D'):
c = c + 1
r = 'S'
else:
r = ''
#print (i, f, s[i:f], r)
print (c)
```
| 87,094 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.
Input
The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.
The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.
Output
Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.
Examples
Input
6
URLLDR
Output
2
Input
4
DLUU
Output
0
Input
7
RLRLRLR
Output
12
Note
In the first case, the entire source code works, as well as the "RL" substring in the second and third characters.
Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.
Tags: brute force, implementation
Correct Solution:
```
def retorna(caminho):
l, r, u, d = 0, 0, 0, 0
for e in caminho:
if e == 'L':
l += 1
elif e == 'R':
r += 1
elif e == 'U':
u += 1
elif e == 'D':
d += 1
if l == r and u == d and u + d + l + r != 0:
return True
return False
n = int(input())
moves = input()
if n == 1:
print(0)
else:
i = 0
ans = 0
while i < n - 1:
for j in range(1, len(moves)):
if retorna(moves[i:j+1]):
ans += 1
i += 1
print(ans)
```
| 87,095 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.
Input
The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.
The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.
Output
Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.
Examples
Input
6
URLLDR
Output
2
Input
4
DLUU
Output
0
Input
7
RLRLRLR
Output
12
Note
In the first case, the entire source code works, as well as the "RL" substring in the second and third characters.
Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.
Tags: brute force, implementation
Correct Solution:
```
n = int(input())
moves = list(input())
mapping = {'U':1,
'D':-1,
'R':1,
'L':-1}
ans = 0
for i in range(n):
hor = 0
vert = 0
for j in range(i,n):
move = moves[j]
if move == 'U' or move == 'D':
vert += mapping[move]
else:
hor += mapping[move]
if hor == 0 and vert == 0:
ans += 1
print(ans)
```
| 87,096 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.
Input
The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.
The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.
Output
Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.
Examples
Input
6
URLLDR
Output
2
Input
4
DLUU
Output
0
Input
7
RLRLRLR
Output
12
Note
In the first case, the entire source code works, as well as the "RL" substring in the second and third characters.
Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.
Tags: brute force, implementation
Correct Solution:
```
tam = int(input())
string = input()
total = 0
substrings = [string[i: j] for i in range(len(string)) for j in range(i + 1, len(string) + 1)]
filtered = []
for sub in substrings:
if len(sub) % 2 == 0:
filtered.append(sub)
for palavra in filtered:
countD = 0
countU = 0
countR = 0
countL = 0
for letra in palavra:
if(letra == 'D'):
countD += 1
elif(letra == 'U'):
countU += 1
elif(letra == 'R'):
countR += 1
elif(letra == 'L'):
countL += 1
if(countD == countU and countL == countR):
total += 1
print(total)
```
| 87,097 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.
Input
The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.
The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.
Output
Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.
Examples
Input
6
URLLDR
Output
2
Input
4
DLUU
Output
0
Input
7
RLRLRLR
Output
12
Note
In the first case, the entire source code works, as well as the "RL" substring in the second and third characters.
Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.
Tags: brute force, implementation
Correct Solution:
```
n = int(input())
commands = input()
vertical = [0]
horizontal = [0]
for i in range(1,n+1):
vert_diff = 0
hor_diff = 0
if commands[i-1] == 'U':
vert_diff = 1
elif commands[i-1] == 'D':
vert_diff = -1
elif commands[i-1] == 'R':
hor_diff = 1
else:
hor_diff = -1
vertical.append(vertical[i-1] + vert_diff)
horizontal.append(horizontal[i-1] + hor_diff)
total = 0
for i in range(1,n+1):
for j in range(i+1, n+1):
hor_diff = horizontal[j] - horizontal[i-1]
vert_diff = vertical[j] - vertical[i-1]
if hor_diff == 0 and vert_diff == 0:
total += 1
print(total)
```
| 87,098 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.
Input
The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands.
The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code.
Output
Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square.
Examples
Input
6
URLLDR
Output
2
Input
4
DLUU
Output
0
Input
7
RLRLRLR
Output
12
Note
In the first case, the entire source code works, as well as the "RL" substring in the second and third characters.
Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.
Tags: brute force, implementation
Correct Solution:
```
n, s = int(input()), input()
a = [s[i:j+1] for i in range(n) for j in range(i, n)]
print(sum(i.count('L') == i.count('R') and i.count('D') == i.count('U') for i in a))
```
| 87,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.