message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are 2N points evenly spaced on the circumference of a circle. These points are numbered 1 to 2N in clockwise order, starting from some of them.
Snuke will divide these points into N pairs, then for each pair, he will draw a line segment connecting the two points. After the line segments are drawn, two points are connected when one can reach from one of those points to the other by traveling only on the line segments. The number of the connected parts here is the number of the connected components in the graph with 2N vertices, corresponding to the 2N points, where every pair of vertices corresponding to two connected points is connected with an edge.
Snuke has already decided K of the pairs, and the i-th of them is a pair of Point A_i and Point B_i.
He is thinking of trying all possible ways to make the remaining N-K pairs and counting the number of the connected parts for each of those ways. Find the sum of those numbers of the connected parts. As the answer can be extremely large, compute the sum modulo 10^9+7.
Constraints
* 1 \leq N \leq 300
* 0 \leq K \leq N
* 1 \leq A_i,B_i \leq 2N
* A_1,\ A_2,\ ...\ A_K,\ B_1,\ B_2,\ ...\ B_K are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_1 B_1
A_2 B_2
:
A_K B_K
Output
Print the sum of the numbers of the connected parts for all possible ways to make the remaining N-K pairs.
Examples
Input
2 0
Output
5
Input
4 2
5 2
6 1
Output
6
Input
20 10
10 18
11 17
14 7
4 6
30 28
19 24
29 22
25 32
38 34
36 39
Output
27087418
Submitted Solution:
```
import sys
import socket
if socket.gethostname() in ['N551J', 'F551C']:
sys.stdin = open('d1.in')
def read_int_list():
return list(map(int, input().split()))
def read_int():
return int(input())
def read_str_list():
return input().split()
def read_str():
return input()
def solve1(N, K, a, b):
n = 2 * N
a = [u - 1 for u in a]
b = [u - 1 for u in b]
M = 10 ** 9 + 7
g = [0] * (n + 1)
g[0] = 1
for x in range(2, n + 1, 2):
g[x] = (x - 1) * g[x - 2]
# Number of paired points inside the interval [i, j]
x = [[0] * n for i in range(n)]
# Number of paired points strictly outside [i, j]
y = [[0] * n for i in range(n)]
ok = [[True] * n for i in range(n)]
for i in range(n):
for j in range(i + 1, n):
for l in range(K):
inside = (i <= a[l] <= j) + (i <= b[l] <= j)
outside = 2 - inside
ok[i][j] &= inside == 2 or outside == 2
if not ok[i][j]:
continue
x[i][j] += inside
y[i][j] += outside
dp = [[0] * n for i in range(n)]
for k in range(1, n):
for i in range(n):
j = i + k
if j < n:
if ok[i][j]:
rem_x = j - i + 1 - x[i][j]
dp[i][j] = g[rem_x] % M
for l in range(i + 1, j):
rem_z = j - l - x[l + 1][j]
dp[i][j] = (dp[i][j] - dp[i][l] * g[rem_z] ) % M
res = 0
for i in range(n):
for j in range(i + 1, n):
rem_y = n - j + i - 1 - y[i][j]
res = (res + dp[i][j] * g[rem_y]) % M
return res
def solve():
N, K = read_int_list()
rows = [read_int_list() for i in range(K)]
a = []
b = []
if rows:
a, b = map(list, zip(*rows))
return solve1(N, K, a, b)
def main():
res = solve()
print(res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 78,942 | 13 | 157,884 |
No | output | 1 | 78,942 | 13 | 157,885 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are 2N points evenly spaced on the circumference of a circle. These points are numbered 1 to 2N in clockwise order, starting from some of them.
Snuke will divide these points into N pairs, then for each pair, he will draw a line segment connecting the two points. After the line segments are drawn, two points are connected when one can reach from one of those points to the other by traveling only on the line segments. The number of the connected parts here is the number of the connected components in the graph with 2N vertices, corresponding to the 2N points, where every pair of vertices corresponding to two connected points is connected with an edge.
Snuke has already decided K of the pairs, and the i-th of them is a pair of Point A_i and Point B_i.
He is thinking of trying all possible ways to make the remaining N-K pairs and counting the number of the connected parts for each of those ways. Find the sum of those numbers of the connected parts. As the answer can be extremely large, compute the sum modulo 10^9+7.
Constraints
* 1 \leq N \leq 300
* 0 \leq K \leq N
* 1 \leq A_i,B_i \leq 2N
* A_1,\ A_2,\ ...\ A_K,\ B_1,\ B_2,\ ...\ B_K are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_1 B_1
A_2 B_2
:
A_K B_K
Output
Print the sum of the numbers of the connected parts for all possible ways to make the remaining N-K pairs.
Examples
Input
2 0
Output
5
Input
4 2
5 2
6 1
Output
6
Input
20 10
10 18
11 17
14 7
4 6
30 28
19 24
29 22
25 32
38 34
36 39
Output
27087418
Submitted Solution:
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
"""
AGC028 D
"""
import itertools
from functools import reduce
from functools import lru_cache
nn, k = map(int, input().split())
n = 2*nn
abli = []
for i in range(k):
a, b = map(int, input().split())
if a < b:
abli.append((a, b))
else:
abli.append((b, a))
flattenabli = itertools.chain.from_iterable(abli)
cut = 10**9+7
unused = [1 for i in range(n+1)]
for a in flattenabli:
unused[a] -= 1
unusedacum = list(itertools.accumulate(unused))
def modInverse(a, b, divmod=divmod):
r0, r1, s0, s1 = a, b, 1, 0
while r1 != 0:
q, rtmp = divmod(r0, r1)
stmp = s0-q*s1
r0, s0 = r1, s1
r1, s1 = rtmp, stmp
return s0 % cut
@lru_cache(maxsize=None)
def doubleFactorial(x):
return reduce(lambda y, z: y*z % cut, range(x, 0, -2))
@lru_cache(maxsize=None)
def isSandwiched(i, j):
return any(map(lambda k: abli[k][0] < i <= abli[k][1] <= j or i <= abli[k][0] <= j < abli[k][1], range(k)))
nonSandwichedNums = [[] for i in range(n+1)]
for i in range(1, n+1):
for j in range(i+1, n+1):
if not isSandwiched(i, j):
nonSandwichedNums[i].append(j)
def numberUnderterminedBetween(i, j):
return unusedacum[j]-unusedacum[i-1]
def pairCombinations(x):
if x == 0:
return 1
elif x % 2 == 0:
return doubleFactorial(x-1)
else:
return 0
def g(i, j):
x = numberUnderterminedBetween(i, j)
return pairCombinations(x)
undetermined = numberUnderterminedBetween(1, n)
ggg = [[0]*(i+1) for i in range(n+1)]
for i in range(1, n+1):
for j in range(i+1, n+1):
ggg[i].append(g(i, j))
ans = 0
dp = [[0]*(n+1) for i in range(n+1)]
for i in range(1, n+1):
for j in nonSandwichedNums[i]:
dp[i][j] = (ggg[i][j]-sum([dp[i][kk]*ggg[kk+1][j] for kk in nonSandwichedNums[i] if kk < j])) % cut
ans = (ans + dp[i][j]*pairCombinations(undetermined-numberUnderterminedBetween(i, j))) % cut
print(ans)
``` | instruction | 0 | 78,943 | 13 | 157,886 |
No | output | 1 | 78,943 | 13 | 157,887 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are 2N points evenly spaced on the circumference of a circle. These points are numbered 1 to 2N in clockwise order, starting from some of them.
Snuke will divide these points into N pairs, then for each pair, he will draw a line segment connecting the two points. After the line segments are drawn, two points are connected when one can reach from one of those points to the other by traveling only on the line segments. The number of the connected parts here is the number of the connected components in the graph with 2N vertices, corresponding to the 2N points, where every pair of vertices corresponding to two connected points is connected with an edge.
Snuke has already decided K of the pairs, and the i-th of them is a pair of Point A_i and Point B_i.
He is thinking of trying all possible ways to make the remaining N-K pairs and counting the number of the connected parts for each of those ways. Find the sum of those numbers of the connected parts. As the answer can be extremely large, compute the sum modulo 10^9+7.
Constraints
* 1 \leq N \leq 300
* 0 \leq K \leq N
* 1 \leq A_i,B_i \leq 2N
* A_1,\ A_2,\ ...\ A_K,\ B_1,\ B_2,\ ...\ B_K are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_1 B_1
A_2 B_2
:
A_K B_K
Output
Print the sum of the numbers of the connected parts for all possible ways to make the remaining N-K pairs.
Examples
Input
2 0
Output
5
Input
4 2
5 2
6 1
Output
6
Input
20 10
10 18
11 17
14 7
4 6
30 28
19 24
29 22
25 32
38 34
36 39
Output
27087418
Submitted Solution:
```
print(5)
``` | instruction | 0 | 78,944 | 13 | 157,888 |
No | output | 1 | 78,944 | 13 | 157,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2 | instruction | 0 | 79,151 | 13 | 158,302 |
Tags: graphs, greedy, shortest paths
Correct Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
from io import BytesIO, IOBase
import sys
from heapq import *
from collections import deque
inf=1000000000000000
def main():
n,m,k=map(int,input().split())
tree,b=[[] for _ in range(n+1)],{}
for i in range(m):
x,y,z=map(float,input().split())
x,y=int(x),int(y)
b[(x,y)],b[(y,x)]=i+1,i+1
tree[x].append((y,z))
tree[y].append((x,z))
dis=[inf]*(n+1)
dis[1]=0
a=[(0,1)]
while a:
d,node=heappop(a)
if dis[node]<d:
continue
for x,y in tree[node]:
if dis[x]>d+y:
dis[x]=d+y
heappush(a,(d+y,x))
ans=[]
if k:
q=deque([1])
v=[0]*(n+1)
v[1]=1
while q:
node,f=q.popleft(),0
for x,y in tree[node]:
if dis[x]==dis[node]+y and not v[x]:
ans.append(b[(node,x)])
q.append(x)
v[x]=1
if len(ans)==k:
f=1
break
if f:
break
print(len(ans))
print(*ans)
# FAST INPUT OUTPUT 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 79,151 | 13 | 158,303 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2 | instruction | 0 | 79,152 | 13 | 158,304 |
Tags: graphs, greedy, shortest paths
Correct Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
mod=10**9+7
from heapq import *
def main():
n,m,k=map(int,input().split())
graph=[[] for _ in range(n+1)]
for _ in range(m):
a,b,c=map(int,input().split())
graph[a].append((b,c,_+1))
graph[b].append((a,c,_+1))
dist=[10**15]*(n+1)
vis=[0]*(n+1)
parent=[0]*(n+1)
dist[1]=0
hp=[(0,1)]
heapify(hp)
ans=[]
k+=1
dct=dict()
dct[1]=-1
while hp and k:
d,x=heappop(hp)
if vis[x]:
continue
vis[x]=1
ans.append(dct[x])
k-=1
for b,c,id in graph[x]:
if not vis[b] and dist[b]>dist[x]+c:
dist[b]=dist[x]+c
parent[b]=x
dct[b]=id
heappush(hp,(dist[b],b))
print(len(ans)-1)
print(*ans[1:])
#----------------------------------------------------------------------------------------
# region fastio
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')
# endregion
if __name__ == '__main__':
main()
``` | output | 1 | 79,152 | 13 | 158,305 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2 | instruction | 0 | 79,153 | 13 | 158,306 |
Tags: graphs, greedy, shortest paths
Correct Solution:
```
import heapq as heap
import sys
input = sys.stdin.readline
from math import inf
import gc, os
from os import _exit
gc.disable()
def dijkstra(g, n, l):
ans = []
dis, vis = [inf]*(n+1), [0]*(n+1)
dis[1] = 0
q = [(0, 1, -1)]
while q:
_, i, k = heap.heappop(q)
if vis[i]==1:
continue
vis[i]=1
if k!=-1:
ans.append(k)
if len(ans)==l:
return ans
for j,w,k in g[i]:
if dis[j]>dis[i]+w:
dis[j]=dis[i]+w
heap.heappush(q, (dis[j], j, k))
return ans
n,m,k = map(int, input().split())
g = [[] for i in range(n+1)]
for i in range(m):
x,y,w = map(int, input().split())
g[x].append((y,w,i+1))
g[y].append((x,w,i+1))
ans = dijkstra(g, n, k)
print(len(ans))
print(*ans)
sys.stdout.flush()
_exit(0)
``` | output | 1 | 79,153 | 13 | 158,307 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2 | instruction | 0 | 79,154 | 13 | 158,308 |
Tags: graphs, greedy, shortest paths
Correct Solution:
```
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import defaultdict
from math import inf
from heapq import heappop,heappush
ans=[]
def dijkstra(start):
heap,dist,vis=[(0,start,-1)],[inf]*(n+1),[0]*(n+1)
dist[start]=0
while heap:
d,vertex,index=heappop(heap)
if vis[vertex]==1:
continue
vis[vertex]=1
if index!=-1:
ans.append(index)
if len(ans)==n-1 or len(ans)==k:
return(ans)
for child,weight,index in graph[vertex]:
weight+=d
if dist[child]>weight:
dist[child]=weight
heappush(heap,(weight,child,index))
return(ans)
graph=defaultdict(list)
n,m,k=map(int,input().split())
for i in range(m):
x,y,w=map(int,input().split())
graph[x].append((y,w,i+1))
graph[y].append((x,w,i+1))
dijkstra(1)
print(len(ans))
ans=' '.join(map(str,ans))
sys.stdout.write(ans)
``` | output | 1 | 79,154 | 13 | 158,309 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2 | instruction | 0 | 79,155 | 13 | 158,310 |
Tags: graphs, greedy, shortest paths
Correct Solution:
```
from collections import Counter, defaultdict
import heapq
from sys import stdin, stdout
raw_input = stdin.readline
xrange=range
n,m,k=map(int,raw_input().split())
k=min(n-1,k)
p=[0]*(n+1)
vis = [0]*(n+1)
d=[[] for i in xrange(n+1)]
ans=[]
dp={}
for i in xrange(m):
u,v,w=map(int,raw_input().split())
d[u].append((v,w))
d[v].append((u,w))
dp[(u,v)]=i+1
dp[(v,u)]=i+1
q=[(0,1,1)]
c=0
while q:
wt,x,par=heapq.heappop(q)
if vis[x]:
continue
vis[x]=1
c+=1
if par!=x:
ans.append(str(dp[(par,x)]))
if c>k:
break
for i,w in d[x]:
if not vis[i]:
heapq.heappush(q,(wt+w,i,x))
print(len(ans))
print(' '.join(ans))
``` | output | 1 | 79,155 | 13 | 158,311 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2 | instruction | 0 | 79,156 | 13 | 158,312 |
Tags: graphs, greedy, shortest paths
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
from heapq import *
def main():
n,m,k = map(int,input().split())
path = [[] for _ in range(n)]
for _ in range(m):
u1,v1,w1 = map(int,input().split())
path[u1-1].append((v1-1,w1,_+1))
path[v1-1].append((u1-1,w1,_+1))
visi = [0]+[-1]*(n-1)
ans = []
he = [(i[1],i[0],i[2]) for i in path[0]]
heapify(he)
# weight ; v ; #
while len(he) and len(ans) != k:
w,v,num = heappop(he)
if visi[v] != -1:
continue
visi[v] = w
ans.append(num)
for to,weight,number in path[v]:
if visi[to] == -1:
heappush(he,(visi[v]+weight,to,number))
print(len(ans))
print(*ans)
# Fast IO 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")
sys.stdin,sys.stdout = IOWrapper(sys.stdin),IOWrapper(sys.stdout)
input = lambda:sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 79,156 | 13 | 158,313 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2 | instruction | 0 | 79,157 | 13 | 158,314 |
Tags: graphs, greedy, shortest paths
Correct Solution:
```
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n,m,k = map(int, input().split())
g = [[] for i in range(n)]
toid = {}
for i in range(m):
x,y,w = map(int, input().split())
x,y = x-1, y-1
g[x].append((w,y))
g[y].append((w,x))
toid[(x,y)] = i
toid[(y,x)] = i
if k == 0:
print(0)
exit()
import heapq
INF = 10**18
def dijkstra(s, edge):
n = len(edge)
dist = [INF]*n
prev = [-1]*n
dist[s] = 0
edgelist = []
heapq.heappush(edgelist,(dist[s], s))
while edgelist:
minedge = heapq.heappop(edgelist)
if dist[minedge[1]] < minedge[0]:
continue
v = minedge[1]
for e in edge[v]:
if dist[e[1]] > dist[v]+e[0]:
dist[e[1]] = dist[v]+e[0]
prev[e[1]] = v
heapq.heappush(edgelist,(dist[e[1]], e[1]))
return dist, prev
dist, prev = dijkstra(0, g)
G = [[] for i in range(n)]
for i, p in enumerate(prev):
if prev[i] != -1:
G[p].append(i)
#print(G)
s = []
s.append(0)
order = []
while s:
v = s.pop()
order.append(v)
for u in G[v]:
s.append(u)
#print(order)
ans = []
for v in order:
for u in G[v]:
ans.append(toid[(v, u)]+1)
if len(ans) == k:
break
else:
continue
break
print(len(ans))
print(*ans)
``` | output | 1 | 79,157 | 13 | 158,315 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2 | instruction | 0 | 79,158 | 13 | 158,316 |
Tags: graphs, greedy, shortest paths
Correct Solution:
```
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import defaultdict
from math import inf
from heapq import heappop,heappush
ans=[]
def dijkstra(start):
heap,dist,vis=[(0,start,-1)],[inf]*(n+1),[0]*(n+1)
dist[start]=0
while heap:
d,vertex,index=heappop(heap)
if vis[vertex]==1:
continue
vis[vertex]=1
if index!=-1:
ans.append(index)
if len(ans)==min(n-1,k):
return(ans)
for child,weight,index in graph[vertex]:
weight+=d
if dist[child]>weight:
dist[child]=weight
heappush(heap,(weight,child,index))
return(ans)
graph=defaultdict(list)
n,m,k=map(int,input().split())
for i in range(m):
x,y,w=map(int,input().split())
graph[x].append((y,w,i+1))
graph[y].append((x,w,i+1))
dijkstra(1)
print(len(ans))
ans=' '.join(map(str,ans))
sys.stdout.write(ans)
``` | output | 1 | 79,158 | 13 | 158,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2
Submitted Solution:
```
import sys
from array import array # noqa: F401
import typing as Tp # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def main():
from heapq import heappop, heappush
n, m, k = map(int, input().split())
adj = [[] for _ in range(n)]
for i, (u, v, w) in enumerate((map(int, input().split()) for _ in range(m)), start=1):
adj[u - 1].append((v - 1, float(w), i))
adj[v - 1].append((u - 1, float(w), i))
inf, eps = 1e18, 1e-7
dp = [0] + [inf] * (n - 1)
prev_edge = [-1] * n
visited = array('b', [1] + [0] * (n - 1))
ans_edge, hq = [], []
for dest, weight, edge_i in adj[0]:
prev_edge[dest] = edge_i
dp[dest] = weight
heappush(hq, (weight, dest))
while k and hq:
weight, v = heappop(hq)
if visited[v]:
continue
ans_edge.append(prev_edge[v])
visited[v] = 1
k -= 1
for dest, edge_weight, edge_i in adj[v]:
if dp[dest] < weight + edge_weight + eps:
continue
dp[dest] = weight + edge_weight
prev_edge[dest] = edge_i
heappush(hq, (weight + edge_weight, dest))
sys.stdout.buffer.write(f'{len(ans_edge)}\n{" ".join(map(str, ans_edge))}\n'.encode('utf-8'))
if __name__ == '__main__':
main()
``` | instruction | 0 | 79,159 | 13 | 158,318 |
Yes | output | 1 | 79,159 | 13 | 158,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
from io import BytesIO, IOBase
import sys
from heapq import *
from collections import deque
inf=1000000000000000
def main():
n,m,k=map(int,input().split())
tree,b=[[] for _ in range(n+1)],{}
for i in range(m):
x,y,z=map(float,input().split())
x,y=int(x),int(y)
b[(x,y)],b[(y,x)]=i+1,i+1
tree[x].append((y,z))
tree[y].append((x,z))
dis,ans,v,p=[inf]*(n+1),[],[0]*(n+1),[0]*(n+1)
dis[1]=0
a=[(0,1)]
while a and len(ans)!=k:
d,node=heappop(a)
if v[node]:
continue
v[node]=1
if p[node]:
ans.append((p[node],node))
if dis[node]<d:
continue
for x,y in tree[node]:
if dis[x]>d+y:
dis[x]=d+y
heappush(a,(d+y,x))
p[x]=node
print(len(ans))
for i in ans:
print(b[i],end=" ")
# FAST INPUT OUTPUT 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 79,160 | 13 | 158,320 |
Yes | output | 1 | 79,160 | 13 | 158,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
from io import BytesIO, IOBase
import sys
from heapq import *
from collections import deque
inf=1000000000000000
def main():
n,m,k=map(int,input().split())
tree,dis,v=[[] for _ in range(n+1)],[inf]*(n+1),[0]*(n+1)
for i in range(m):
x,y,z=map(int,input().split())
z=float(z)
tree[x].append((y,z,i+1))
tree[y].append((x,z,i+1))
dis[1],a,ans=0,[(0,1,0)],[]
while a and len(ans) != k:
d, node,z= heappop(a)
if v[node]:
continue
v[node] = 1
if z:
ans.append(z)
if dis[node] < d:
continue
for x, y,z in tree[node]:
if dis[x] > d + y:
dis[x] = d + y
heappush(a, (d + y, x,z))
print(len(ans))
print(*ans)
# FAST INPUT OUTPUT 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 79,161 | 13 | 158,322 |
Yes | output | 1 | 79,161 | 13 | 158,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
import heapq
n,m,k = map(int,input().split())
k = min(n-1,k)
graph = [[] for i in range(n)]
edge = {}
for i in range(m):
x,y,w = map(int,input().split())
edge[(x-1,y-1)] = (w,i)
edge[(y-1,x-1)] = (w,i)
graph[x-1].append(y-1)
graph[y-1].append(x-1)
ans = []
vis = [0]*n
vis[0] = 1
root = 0
q =[]
for i in graph[root]:
heapq.heappush(q,(edge[i,root][0],root,i))
while len(ans)!=k:
w,s,e = heapq.heappop(q)
if vis[e]:
continue
ans.append(edge[s,e][1]+1)
vis[e] = 1
for i in graph[e]:
if not vis[i]:
heapq.heappush(q,(w+edge[(i,e)][0],e,i))
print (len(ans))
print (" ".join(map(str,ans)))
``` | instruction | 0 | 79,162 | 13 | 158,324 |
Yes | output | 1 | 79,162 | 13 | 158,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
from io import BytesIO, IOBase
import sys
from heapq import *
from collections import deque
inf=1000000000000000
def main():
n,m,k=map(int,input().split())
tree,b=[[] for _ in range(n+1)],{}
for i in range(n):
x,y,z=map(float,input().split())
x,y=int(x),int(y)
b[(x,y)],b[(y,x)]=i+1,i+1
tree[x].append((y,z))
tree[y].append((x,z))
dis,ans,v,p=[inf]*(n+1),[],[0]*(n+1),[0]*(n+1)
dis[1]=0
a=[(0,1)]
while a and len(ans)!=k:
d,node=heappop(a)
if v[node]:
continue
v[node]=1
if p[node]:
ans.append((p[node],node))
if dis[node]<d:
continue
for x,y in tree[node]:
if dis[x]>d+y:
dis[x]=d+y
heappush(a,(d+y,x))
p[x]=node
print(len(ans))
for i in ans:
print(b[i],end=" ")
# FAST INPUT OUTPUT 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 79,163 | 13 | 158,326 |
No | output | 1 | 79,163 | 13 | 158,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2
Submitted Solution:
```
class Graph:
def __init__(self, n):
self.n=n
self.edges={}
def add_edge(self, x, y, w, cnt): #a cnt az Γ©l azonosΓtΓ³ szΓ‘ma, amit a beolvasΓ‘s sorrendje ad meg
if x in self.edges.keys():
self.edges[x]+=[(y,w, cnt)]
else:
self.edges[x]=[(y,w, cnt)]
if y in self.edges.keys():
self.edges[y]+=[(x,w, cnt)]
else:
self.edges[y]=[(x,w, cnt)]
class VertexData:
def __init__(self):
self.vertex=0
self.weight=0
self.parent=0
self.processed=False
self.edge_number=0 #annak az Γ©lnek az az szΓ‘ma, ami az 1-bΕl hozzΓ‘vezetΕ min ΓΊt utolsΓ³ Γ©le
def __str__(self):
return 'vertex: '+str(self.vertex)+' weight: '+str(self.weight)+' parent: '+str(self.parent)+' processed: '+str(self.processed)
class BinaryHeap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
self.vertexPlace={}
def print_heap(self):
print("print heap")
for i in self.heapList:
if i==0:
print(0)
else:
print(str(i))
print('size= '+str(self.currentSize))
print(self.vertexPlace)
print()
print()
def percUp(self,i):
while i // 2 > 0:
if self.heapList[i].weight < self.heapList[i // 2].weight:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self.vertexPlace[self.heapList[i//2].vertex]=i//2
self.heapList[i] = tmp
self.vertexPlace[self.heapList[i].vertex]=i
i = i // 2
def insert(self,k):
self.heapList.append(k)
self.currentSize = self.currentSize + 1
self.vertexPlace[k.vertex]=self.currentSize
self.percUp(self.currentSize)
def percDown(self,i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapList[i].weight > self.heapList[mc].weight:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[mc]
self.heapList[mc] = tmp
self.vertexPlace[self.heapList[i].vertex]=i
self.vertexPlace[self.heapList[mc].vertex]=mc
i = mc
def minChild(self,i):
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapList[i*2].weight < self.heapList[i*2+1].weight:
return i * 2
else:
return i * 2 + 1
def delMin(self):
assert(self.currentSize!=0)
retval = self.heapList[1]
self.heapList[1] = self.heapList[self.currentSize]
self.vertexPlace[self.heapList[1].vertex]=1
self.vertexPlace[retval.vertex]=-1
self.currentSize = self.currentSize - 1
self.heapList.pop()
self.percDown(1)
return retval
def keyReduction(self, datai):
place=self.vertexPlace[datai.vertex]
self.vertexPlace.pop(datai.vertex)
self.vertexPlace[datai.vertex]=place
self.heapList[place]=datai
self.percUp(place)
def Dijkstra(v, g, k):
data={}
start=VertexData()
start.vertex=v
start.parent=v
start.weight=0
start.processed=False
start.edge_number=0
data[v]=start
heap=BinaryHeap()
heap.insert(start)
edges=[]
while heap.currentSize>0:
if len(edges)==k:
return edges
curr=heap.delMin()
for i in g.edges[curr.vertex]:
vertex=i[0]
w=i[1]
if vertex in data.keys() and data[vertex].processed:
pass
elif vertex in data.keys():
if w<data[vertex].weight:
data[vertex].weight=w
data[vertex].parent=curr
data[vertex].edge_number=i[2]
heap.keyReduction(data[vertex])
else:
onedata=VertexData()
onedata.vertex=vertex
onedata.parent=curr
onedata.weight=w
onedata.processed=False
onedata.edge_number=i[2]
data[vertex]=onedata
heap.insert(onedata)
if curr.vertex!=1:
edges+=[curr.edge_number]
data[curr.vertex].processed=True
return edges
#main
n, m, k=input().split()
n=int(n)
m=int(m)
k=int(k)
g=Graph(n)
for i in range(m):
x,y,w=input().split()
x=int(x)
y=int(y)
w=int(w)
g.add_edge(x,y,w,i+1)
#n, k, m=3, 3, 2
#g=Graph(n)
#g.add_edge(1, 2, 1, 1)
#g.add_edge(3, 2, 1, 2)
#g.add_edge(1, 3, 3, 3)
edges=Dijkstra(1,g,k)
print(len(edges))
out=""
edges.sort()
for i in edges:
out+=str(i)+' '
print(out)
``` | instruction | 0 | 79,164 | 13 | 158,328 |
No | output | 1 | 79,164 | 13 | 158,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2
Submitted Solution:
```
#sys.setRecursionLimit
#Class to represent a graph
class Graph:
def __init__(self,vertices):
self.V= vertices #No. of vertices
self.graph = [] # default dictionary
# to store graph
# function to add an edge to graph
def addEdge(self,u,v,w):
self.graph.append([u,v,w])
# A utility function to find set of an element i
# (uses path compression technique)
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
# A function that does union of two sets of x and y
# (uses union by rank)
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
# Attach smaller rank tree under root of
# high rank tree (Union by Rank)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
# If ranks are same, then make one as root
# and increment its rank by one
else :
parent[yroot] = xroot
rank[xroot] += 1
# The main function to construct MST using Kruskal's
# algorithm
def KruskalMST(self):
result =[] #This will store the resultant MST
i = 0 # An index variable, used for sorted edges
e = 0 # An index variable, used for result[]
# Step 1: Sort all the edges in non-decreasing
# order of their
# weight. If we are not allowed to change the
# given graph, we can create a copy of graph
self.graph = sorted(self.graph,key=lambda item: item[2])
parent = [] ; rank = []
# Create V subsets with single elements
for node in range(self.V):
parent.append(node)
rank.append(0)
# Number of edges to be taken is equal to V-1
while e < self.V -1 :
# Step 2: Pick the smallest edge and increment
# the index for next iteration
u,v,w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent ,v)
# If including this edge does't cause cycle,
# include it in result and increment the index
# of result for next edge
if x != y:
e = e + 1
result.append([u,v,w])
self.union(parent, rank, x, y)
# Else discard the edge
# print the contents of result[] to display the built MST
#print "Following are the edges in the constructed MST"
arr=[]
dd={}
for u,v,weight in result:
#print str(u) + " -- " + str(v) + " == " + str(weight)
arr.append((u,v,weight))
if u in dd.keys():
dd[u].append(v)
else:
dd[u]=[v]
if v in dd.keys():
dd[v].append(u)
else:
dd[v]=[u]
#print ("%d -- %d == %d" % (u,v,weight))
return arr,dd
n,m,k=map(int,input().split())
g=Graph(n)
d={}
d2={}
for i in range(m):
a,b,c=map(int,input().split())
if a-1 not in d.keys():
d[a-1]={}
if b-1 not in d[a-1].keys():
d[a-1][b-1]={}
d[a-1][b-1][c]=i
if b-1 not in d.keys():
d[b-1]={}
if a-1 not in d[b-1].keys():
d[b-1][a-1]={}
d[b-1][a-1][c]=i
if a-1 not in d2.keys():
d2[a-1]={}
d2[a-1][b-1]=i
if b-1 not in d2.keys():
d2[b-1]={}
d2[b-1][a-1]=i
g.addEdge(a-1,b-1,c)
arr,dd=g.KruskalMST()
if k==0:
print(0)
elif len(arr)<=k:
#print(arr)
print(len(arr))
for i in range(len(arr)):
#print(arr[i])
print(d[arr[i][0]][arr[i][1]][arr[i][2]]+1,end=" ")
print("")
else:
depth=[0 for i in range(n)]
parent=[[] for i in range(n)]
parent[0]=[0, 0, 0]
markings=[]
curr=0
index=0
visited=[0 for i in range(n)]
visited[0]=1
#print(visited)
if n==3*10**5:
print("")
else:
cc=0
flag1=0
print(k)
while True:
#print(curr,curr in dd.keys(),markings,visited)
if curr in dd.keys():
flag=0
for i in range(index,len(dd[curr])):
if visited[dd[curr][i]]==0:
#print(dd,curr,i,dd[curr][i],markings)
#depth[dd[curr][i]]=depth[curr]+1
#parent[dd[curr][i]]=[depth[curr]+1,dd[curr][i],curr]
markings.append([curr,i])
visited[dd[curr][i]]=1
print(d2[curr][dd[curr][i]]+1,end=" ")
cc+=1
curr,index=dd[curr][i],0
if cc==k:
flag1=1
break
flag=1
break
if flag1==1:
break
if flag==1:
continue
if curr==0:
break
curr,index=markings.pop()
else:
#print(11111111111)
curr,index=markings.pop()
#print(depth)
#print(parent)
#parent.sort()
#print(parent)
#print(arr)
"""
s=set()
for i in range(0,k+1):
s.add(parent[i][1])
s.add(parent[i][2])
s=list(s)
"""
print("")
``` | instruction | 0 | 79,165 | 13 | 158,330 |
No | output | 1 | 79,165 | 13 | 158,331 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected connected weighted graph consisting of n vertices and m edges. Let's denote the length of the shortest path from vertex 1 to vertex i as d_i.
You have to erase some edges of the graph so that at most k edges remain. Let's call a vertex i good if there still exists a path from 1 to i with length d_i after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
Input
The first line contains three integers n, m and k (2 β€ n β€ 3 β
10^5, 1 β€ m β€ 3 β
10^5, n - 1 β€ m, 0 β€ k β€ m) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then m lines follow, each containing three integers x, y, w (1 β€ x, y β€ n, x β y, 1 β€ w β€ 10^9), denoting an edge connecting vertices x and y and having weight w.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
Output
In the first line print e β the number of edges that should remain in the graph (0 β€ e β€ k).
In the second line print e distinct integers from 1 to m β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
Examples
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2
Submitted Solution:
```
from collections import defaultdict
d=defaultdict(list)
a=list(map(int,input().split()))
for i in range(a[1]):
b=list(map(int,input().split()))
d[b[0]].append([b[2],b[0],b[1],i+1])
d[b[1]].append([b[2],b[1],b[0],i+1])
for keys in d:
d[keys].sort()
t=[0]*(a[0]+1)
stack=[1]
lis=[]
for i in range(a[2]):
m=pow(10,9)+1
li=[m,0,0,0]
for val in stack:
for keys in d[val]:
li=d[val][0].copy()
li[0]+=t[li[1]]
break
if(m>li[0]):
m=li[0]
l=li
print(l)
stack.append(l[2])
t[l[2]]=l[0]
d[l[1]].remove([l[0]-t[l[1]],l[1],l[2],l[3]])
d[l[2]].remove([l[0]-t[l[1]],l[2],l[1],l[3]])
lis.append(l[3])
print(len(lis))
print(*lis)
``` | instruction | 0 | 79,166 | 13 | 158,332 |
No | output | 1 | 79,166 | 13 | 158,333 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!
The United States of America can be modeled as a tree (why though) with n vertices. The tree is rooted at vertex r, wherein lies Kuroni's hotel.
Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices u and v, and it'll return a vertex w, which is the lowest common ancestor of those two vertices.
However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most β n/2 β times. After that, the phone would die and there will be nothing left to help our dear friend! :(
As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?
Interaction
The interaction starts with reading a single integer n (2 β€ n β€ 1000), the number of vertices of the tree.
Then you will read n-1 lines, the i-th of them has two integers x_i and y_i (1 β€ x_i, y_i β€ n, x_i β y_i), denoting there is an edge connecting vertices x_i and y_i. It is guaranteed that the edges will form a tree.
Then you can make queries of type "? u v" (1 β€ u, v β€ n) to find the lowest common ancestor of vertex u and v.
After the query, read the result w as an integer.
In case your query is invalid or you asked more than β n/2 β queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.
When you find out the vertex r, print "! r" and quit after that. This query does not count towards the β n/2 β limit.
Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.
After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
To hack, use the following format:
The first line should contain two integers n and r (2 β€ n β€ 1000, 1 β€ r β€ n), denoting the number of vertices and the vertex with Kuroni's hotel.
The i-th of the next n-1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β denoting there is an edge connecting vertex x_i and y_i.
The edges presented should form a tree.
Example
Input
6
1 4
4 2
5 3
6 3
2 3
3
4
4
Output
? 5 6
? 3 1
? 1 2
! 4
Note
Note that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.
The image below demonstrates the tree in the sample test:
<image>
Submitted Solution:
```
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
n=int(input())
trees={}
for i in range(n-1):
t1,t2 = list(map(int,input().split()))
t1t,t1f=trees.get(t1,[[],0])
t1t.append(t2)
t1f+=1
trees[t1]=[t1t,t1f]
t2t,t2f=trees.get(t2,[[],0])
t2t.append(t1)
t2f+=1
trees[t2]=[t2t,t2f]
print(trees)
itemrino=list(trees.items())
itemrino.sort(key=lambda x:x[1][1])
singlenode=list(filter(lambda x:x[1][1]==1,itemrino))
toquery=list(map(lambda x:x[0],singlenode))
print(toquery)
queried=[]
while True:
n=len(toquery)
if n<2:
break
query = "?"
node1,node2=toquery[0],toquery[1]
query += " "
query += str(node1)
query += " "
query += str(node2)
print (query, flush = True)
top=int(input())
if top not in toquery:
toquery=toquery[2:]+[top]
print ("!" , toquery[-1] , flush = True)
##for i in range(k+1):
##
## query = "?"
## for j in range(k+1):
## if i != j:
## query += " "
## query += str(q[j])
##
## print (query, flush = True)
##
## pos,num = map(int,input().split())
## if num not in exist:
## exist.append(num)
## dic[num] = 1
## else:
## dic[num] += 1
##
##exist.sort()
##print ("!" , dic[exist[-1]] , flush = True)
``` | instruction | 0 | 79,290 | 13 | 158,580 |
No | output | 1 | 79,290 | 13 | 158,581 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!
The United States of America can be modeled as a tree (why though) with n vertices. The tree is rooted at vertex r, wherein lies Kuroni's hotel.
Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices u and v, and it'll return a vertex w, which is the lowest common ancestor of those two vertices.
However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most β n/2 β times. After that, the phone would die and there will be nothing left to help our dear friend! :(
As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?
Interaction
The interaction starts with reading a single integer n (2 β€ n β€ 1000), the number of vertices of the tree.
Then you will read n-1 lines, the i-th of them has two integers x_i and y_i (1 β€ x_i, y_i β€ n, x_i β y_i), denoting there is an edge connecting vertices x_i and y_i. It is guaranteed that the edges will form a tree.
Then you can make queries of type "? u v" (1 β€ u, v β€ n) to find the lowest common ancestor of vertex u and v.
After the query, read the result w as an integer.
In case your query is invalid or you asked more than β n/2 β queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.
When you find out the vertex r, print "! r" and quit after that. This query does not count towards the β n/2 β limit.
Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.
After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
To hack, use the following format:
The first line should contain two integers n and r (2 β€ n β€ 1000, 1 β€ r β€ n), denoting the number of vertices and the vertex with Kuroni's hotel.
The i-th of the next n-1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β denoting there is an edge connecting vertex x_i and y_i.
The edges presented should form a tree.
Example
Input
6
1 4
4 2
5 3
6 3
2 3
3
4
4
Output
? 5 6
? 3 1
? 1 2
! 4
Note
Note that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.
The image below demonstrates the tree in the sample test:
<image>
Submitted Solution:
```
from sys import stdout,stdin
input = lambda : stdin.readline()
n = int(input())
g = [set() for i in range(n)]
l = set()
for i in range(n-1):
a,b = map(int,input().split())
g[a-1].add(b-1)
g[b-1].add(a-1)
if n==2:
print('?', 1, 2)
stdout.flush()
ans = int(input())
print('!',ans)
exit(0)
all = set([i for i in range(n)])
for i in range(n):
if len(g[i])==1:
l.add(i)
# if len(l)==n-1:
# print('?',l.pop()+1,l.pop()+1)
# stdout.flush()
# ans = int(input())
# print('!', ans)
# exit(0)
used = [0]*n
def dfs(v,stop):
if v==stop:
return 0
used[v]=1
for u in g[v]:
if used[u] == 0 and u!=stop:
dfs(u,stop)
a = l.pop()
b = l.pop()
print('?', a+1, b+1)
stdout.flush()
stop = int(input())-1
dfs(a,stop)
dfs(b,stop)
a,b=0,1
while len(l)>2:
a = l.pop()
b = l.pop()
print('?', a+1, b+1)
stdout.flush()
stop = int(input())-1
dfs(a, stop)
dfs(b, stop)
if len(l)==1:
x = l.pop()
for i in range(n):
if used[i] == 0 and i!= x:
print('?', x + 1, i + 1)
stdout.flush()
stop = int(input()) - 1
dfs(x, stop)
dfs(i, stop)
for i in range(n):
if used[i]==0:
print('!',i+1)
``` | instruction | 0 | 79,291 | 13 | 158,582 |
No | output | 1 | 79,291 | 13 | 158,583 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!
The United States of America can be modeled as a tree (why though) with n vertices. The tree is rooted at vertex r, wherein lies Kuroni's hotel.
Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices u and v, and it'll return a vertex w, which is the lowest common ancestor of those two vertices.
However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most β n/2 β times. After that, the phone would die and there will be nothing left to help our dear friend! :(
As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?
Interaction
The interaction starts with reading a single integer n (2 β€ n β€ 1000), the number of vertices of the tree.
Then you will read n-1 lines, the i-th of them has two integers x_i and y_i (1 β€ x_i, y_i β€ n, x_i β y_i), denoting there is an edge connecting vertices x_i and y_i. It is guaranteed that the edges will form a tree.
Then you can make queries of type "? u v" (1 β€ u, v β€ n) to find the lowest common ancestor of vertex u and v.
After the query, read the result w as an integer.
In case your query is invalid or you asked more than β n/2 β queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.
When you find out the vertex r, print "! r" and quit after that. This query does not count towards the β n/2 β limit.
Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.
After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
To hack, use the following format:
The first line should contain two integers n and r (2 β€ n β€ 1000, 1 β€ r β€ n), denoting the number of vertices and the vertex with Kuroni's hotel.
The i-th of the next n-1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β denoting there is an edge connecting vertex x_i and y_i.
The edges presented should form a tree.
Example
Input
6
1 4
4 2
5 3
6 3
2 3
3
4
4
Output
? 5 6
? 3 1
? 1 2
! 4
Note
Note that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.
The image below demonstrates the tree in the sample test:
<image>
Submitted Solution:
```
"""
Template written to be used by Python Programmers.
Use at your own risk!!!!
Owned by enraged(rating - 5 star at CodeChef and Specialist at Codeforces).
"""
import sys
import bisect
import heapq
from math import *
from collections import defaultdict as dd # defaultdict(<datatype>) Free of KeyError.
from collections import deque # deque(list) append(), appendleft(), pop(), popleft() - O(1)
from collections import Counter as c # Counter(list) return a dict with {key: count}
from itertools import combinations as comb
from bisect import bisect_left as bl, bisect_right as br, bisect
# sys.setrecursionlimit(2*pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(var): sys.stdout.write(var)
def l(): return list(map(int, data().split()))
def sl(): return list(map(str, data().split()))
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [[val for i in range(n)] for j in range(m)]
def leaves(arr):
leaf = []
for i in arr.keys():
if len(arr[i]) == 1:
leaf.append(i)
return leaf
def removeLeaves(arr, f, s):
for i in arr.keys():
arr[i].discard(f)
arr[i].discard(s)
del arr[f]
del arr[s]
return arr
n = int(data())
mat = dd(set)
for i in range(n - 1):
x, y = sp()
if x == y:
continue
mat[x].add(y)
mat[y].add(x)
while True:
if len(mat) == 3:
for i in mat.keys():
if len(mat[i]) == 2:
print("! %d" % i)
exit()
if len(mat) == 2:
for i in mat.keys():
print("! %d" % i)
exit()
s = leaves(mat)
if len(s) == 1:
print("! %d" % s[0])
exit()
first = s.pop()
second = s.pop()
print("? %d %d" % (first, second))
sys.stdout.flush()
w = int(data())
if first == w or second == w:
print("! %d" % w)
exit()
mat = removeLeaves(mat, first, second)
``` | instruction | 0 | 79,292 | 13 | 158,584 |
No | output | 1 | 79,292 | 13 | 158,585 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!
The United States of America can be modeled as a tree (why though) with n vertices. The tree is rooted at vertex r, wherein lies Kuroni's hotel.
Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices u and v, and it'll return a vertex w, which is the lowest common ancestor of those two vertices.
However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most β n/2 β times. After that, the phone would die and there will be nothing left to help our dear friend! :(
As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?
Interaction
The interaction starts with reading a single integer n (2 β€ n β€ 1000), the number of vertices of the tree.
Then you will read n-1 lines, the i-th of them has two integers x_i and y_i (1 β€ x_i, y_i β€ n, x_i β y_i), denoting there is an edge connecting vertices x_i and y_i. It is guaranteed that the edges will form a tree.
Then you can make queries of type "? u v" (1 β€ u, v β€ n) to find the lowest common ancestor of vertex u and v.
After the query, read the result w as an integer.
In case your query is invalid or you asked more than β n/2 β queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.
When you find out the vertex r, print "! r" and quit after that. This query does not count towards the β n/2 β limit.
Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.
After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
To hack, use the following format:
The first line should contain two integers n and r (2 β€ n β€ 1000, 1 β€ r β€ n), denoting the number of vertices and the vertex with Kuroni's hotel.
The i-th of the next n-1 lines should contain two integers x_i and y_i (1 β€ x_i, y_i β€ n) β denoting there is an edge connecting vertex x_i and y_i.
The edges presented should form a tree.
Example
Input
6
1 4
4 2
5 3
6 3
2 3
3
4
4
Output
? 5 6
? 3 1
? 1 2
! 4
Note
Note that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.
The image below demonstrates the tree in the sample test:
<image>
Submitted Solution:
```
import collections
import sys
def getAnc(u,v):
print('? {} {}'.format(u,v))
w = int(input())
sys.stdout.flush()
return w
def f():
n = int(input())
neibors = [[] for i in range(n+1)]
for i in range(n-1):
a, b = [int(s) for s in input().split()]
neibors[a].append(b)
neibors[b].append(a)
visited = [0]*(n+1)
rem = [n]
def bfs(u,v,w):
q = collections.deque([u,v])
if u != w:
visited[u] = 1
q.append(u)
rem[0] -= 1
if v != w:
visited[v] = 1
q.append(v)
rem[0] -= 1
while q:
node = q.popleft()
for nb in neibors[node]:
if (nb != w) and (not visited[nb]):
visited[nb] = 1
rem[0] -= 1
q.append(nb)
w = 1
while rem[0] > 1:
for i in range(1,n+1):
if (i != w) and (not visited[i]):
u = i
break
v = w
w = getAnc(u,v)
bfs(u,v,w)
for i in range(1,n+1):
if not visited[i]:
r = i
break
print('! {}'.format(r))
return
f()
``` | instruction | 0 | 79,293 | 13 | 158,586 |
No | output | 1 | 79,293 | 13 | 158,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba. | instruction | 0 | 79,356 | 13 | 158,712 |
Tags: brute force, constructive algorithms, graphs, greedy, implementation
Correct Solution:
```
t = int(input())
for _ in range(t):
n, m = [int(x) for x in input().split()]
grid = [input() for _ in range(n)]
if m % 2 == 1:
print("YES")
print("1 2 "*((m+1)//2))
continue
for i in range(n):
found = False
for j in range(n):
if j == i:
continue
for k in range(n):
if k == i:
continue
if grid[j][i] == grid[i][k]:
found = True
break
if found:
break
if found:
break
else:
print("NO")
continue
i += 1
j += 1
k += 1
if j == k:
print("YES")
print(i, (f"{j} {i} ")*(m//2))
else:
print("YES")
if (m // 2) % 2 == 0:
print((f"{k} {j} "*(m//4)) + (f"{i} ") + (f"{k} {j} "*(m//4)))
else:
print(j, (f"{k} {j} "*((m-2)//4)) + (f"{i} ") + (f"{k} {j} "*((m-2)//4)) + f"{k}")
``` | output | 1 | 79,356 | 13 | 158,713 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba. | instruction | 0 | 79,357 | 13 | 158,714 |
Tags: brute force, constructive algorithms, graphs, greedy, implementation
Correct Solution:
```
import sys,os,io
from collections import defaultdict
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
input = sys.stdin.readline
for _ in range (int(input())):
n,m = [int(i) for i in input().split()]
grid = []
for i in range (n):
grid.append(list(input().strip()))
a,b = 0,0
flag = 0
for i in range (n):
for j in range (n):
if i==j:
continue
if grid[i][j]==grid[j][i]:
a,b=i+1,j+1
flag = 1
break
if flag==1:
ans = []
for i in range (m+1):
if i%2:
ans.append(a)
else:
ans.append(b)
print("YES")
print(*ans)
continue
elif m%2:
ans = []
for i in range (m+1):
if i%2:
ans.append(1)
else:
ans.append(2)
print("YES")
print(*ans)
else:
if n==2:
print("NO")
continue
a,b,c,d = 0,0,0,0
if grid[0][1]==grid[1][2]:
a = 0
b = 1
c = 2
elif grid[1][2]==grid[2][0]:
a=1
b=2
c=0
elif grid[2][0]==grid[0][1]:
a = 2
b = 0
c = 1
a+=1
b+=1
c+=1
if m%4==0:
ans = []
for i in range (m+1):
if i%4==0:
ans.append(b)
elif i%4==1:
ans.append(c)
elif i%4==2:
ans.append(b)
elif i%4==3:
ans.append(a)
print("YES")
print(*ans)
continue
else:
ans = []
print("YES")
for i in range (m+1):
if i%4==0:
ans.append(a)
elif i%4==1:
ans.append(b)
elif i%4==2:
ans.append(c)
elif i%4==3:
ans.append(b)
print(*ans)
``` | output | 1 | 79,357 | 13 | 158,715 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba. | instruction | 0 | 79,358 | 13 | 158,716 |
Tags: brute force, constructive algorithms, graphs, greedy, implementation
Correct Solution:
```
import sys
max_int = 2147483648 # 2^31
min_int = -max_int
t = int(input())
for _t in range(t):
n, m = map(int, sys.stdin.readline().split())
m += 1
M = []
s_out = []
for nn in range(n):
s = input()
M.append(s)
s_out.append(set(list(s)))
if not m % 2:
print('YES')
print(('1 2 ' * (m // 2)).strip())
continue
has_to_break = False
same = ()
s_in = [set() for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
s_in[j].add(M[i][j])
s_in[i].add(M[j][i])
if M[i][j] == M[j][i]:
same = (i, j)
has_to_break = True
break
if has_to_break:
break
if same:
print('YES')
tmp = str(same[0] + 1) + ' ' + str(same[1] + 1) + ' '
tmp *= m // 2
if m % 2:
tmp += str(same[0] + 1)
else:
tmp = tmp.strip()
print(tmp)
continue
has_to_break = False
for i in range(n):
for ch in ('a', 'b'):
p1, p2, p3 = -1, -1, -1
if ch in s_in[i] and ch in s_out[i]:
p2 = i
else:
continue
for j in range(n):
if M[p2][j] == ch:
p3 = str(j + 1)
break
for j in range(n):
if M[j][p2] == ch:
p1 = str(j + 1)
break
if p1 == -1 or p3 == -1:
continue
p2 = str(p2 + 1)
if not m % 2:
out = (p1 + ' ' + p2 + ' ') * (m // 2)
else:
h = m // 2
if h % 2:
out = (p1 + ' ' + p2 + ' ') * (h // 2) + p1 + ' ' + p2 + ' ' + p3 + (' ' + p2 + ' ' + p3) * (h // 2)
else:
out = (p2 + ' ' + p1 + ' ') * (h // 2) + p2 + (' ' + p3 + ' ' + p2) * (h // 2)
print('YES')
print(out.strip())
has_to_break = True
break
if has_to_break:
break
else:
print('NO')
``` | output | 1 | 79,358 | 13 | 158,717 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba. | instruction | 0 | 79,359 | 13 | 158,718 |
Tags: brute force, constructive algorithms, graphs, greedy, implementation
Correct Solution:
```
def arrIn():
return list(map(int,input().split()))
def mapIn():
return map(int,input().split())
for ii in range(int(input())):
n,k=mapIn()
arr=[[0]*n for i in range(n)]
for i in range(n):
s=input()
for j in range(n):
arr[i][j]=s[j]
if k==1:
print("YES")
print(1,2)
continue
char=None
flg1=False
flg2=False
for i in range(n):
j2=-1
for j in range(n):
if i!=j:
if arr[i][j]==arr[j][i]:
char1=arr[i][j]
flg1=True
i1=i+1
j1=j+1
break
else:
if j2!=-1 and arr[i][j]!=arr[i][j2-1]:
i1=i+1
j1=j+1
# print(i1,j1,j2)
flg2=True
break
elif j2==-1:
i1=i+1
j2=j+1
if flg1 or flg2:
break
if flg1==True:
# print("F1")
print("YES")
for i in range(k+1):
if i%2==0:
print(i1,end=" ")
else:
print(j1,end=" ")
print()
elif flg2==True:
# print("f2")
print("YES")
if k%2==1:
for i in range(k+1):
if i%2==0:
print(i1,end=" ")
else:
print(j2,end=" ")
print()
else:
if (k//2)%2==1:
# print("operator1")
# print(i1,j1,j2)
for i in range(k+1):
if i%4==0:
print(j1,end=" ")
elif i%4==1:
print(i1,end=" ")
elif i%4==2:
print(j2,end=" ")
else:
print(i1,end=" ")
print()
else:
for i in range(k+1):
if i%4==0:
print(i1,end=" ")
elif i%4==1:
print(j1,end=" ")
elif i%4==2:
print(i1,end=" ")
else:
print(j2,end=" ")
print()
else:
if k%2==0:
print("NO")
else:
print("YES")
for i in range(k+1):
if i%2==0:
print(i1,end=" ")
else:
print(j2,end=" ")
print()
``` | output | 1 | 79,359 | 13 | 158,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba. | instruction | 0 | 79,360 | 13 | 158,720 |
Tags: brute force, constructive algorithms, graphs, greedy, implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
for _ in range(int(input())):
N, M = map(int, input().split())
e = [list(input())[: -1] for _ in range(N)]
res = [0] * (M + 1)
for i in range(N):
for j in range(N):
if i == j: continue
if e[i][j] == e[j][i]:
for k in range(M + 1):
if k % 2: res[k] = i + 1
else: res[k] = j + 1
break
else: continue
break
if res[0]:
print("YES")
print(*res)
continue
if M % 2:
for k in range(M + 1):
if k % 2: res[k] = 1
else: res[k] = 2
print("YES")
print(*res)
continue
else:
for i in range(N):
a = -1
b = -1
for j in range(N):
if e[i][j] == "a": a = j
if e[i][j] == "b": b = j
if a >= 0 and b >= 0:
if M % 4 == 0:
for k in range(M + 1):
if k % 4 == 0: res[k] = i + 1
elif k % 4 == 1: res[k] = a + 1
elif k % 4 == 2: res[k] = i + 1
elif k % 4 == 3: res[k] = b + 1
else:
for k in range(M // 2 + 1):
if k % 2 == 0: res[k] = a + 1
elif k % 2 == 1: res[k] = i + 1
for k in range(M // 2 + 1, M + 1):
if k % 2 == 0: res[k] = b + 1
elif k % 2 == 1: res[k] = i + 1
print("YES")
print(*res)
break
else: print("NO")
``` | output | 1 | 79,360 | 13 | 158,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba. | instruction | 0 | 79,361 | 13 | 158,722 |
Tags: brute force, constructive algorithms, graphs, greedy, implementation
Correct Solution:
```
'''Author- Akshit Monga'''
from sys import stdin, stdout
input = stdin.readline
def f1(i,j,k):
global all
if mat[i][j] == mat[j][k] and mat[j][i] == mat[k][j]:
all = []
for p in range(m // 2 + 1):
if p % 2 == 0:
all.append(i+1)
else:
all.append(j+1)
all.pop()
for p in range(m // 2 + 1):
if p % 2 == 0:
all.append(j+1)
else:
all.append(k+1)
# print(all)
return True
return False
def f2(i,j,k):
global all
if mat[i][j] == mat[j][k] and mat[j][i] == mat[k][j]:
all = []
for p in range(m // 2 + 1):
if p % 2 == 0:
all.append(j+1)
else:
all.append(i+1)
all.pop()
for p in range(m // 2 + 1):
if p % 2 == 0:
all.append(j+1)
else:
all.append(k+1)
# print(all)
return True
return False
t = int(input())
for _ in range(t):
n,m=map(int,input().split())
mat=[[0 for i in range(n)] for j in range(n)]
for i in range(n):
s=input()[:-1]
for j in range(n):
mat[i][j]=s[j]
# if t==320:
# if _==73:
# print(n,m)
# for i in range(n):
# print(''.join(mat[i]))
# continue
if m%2:
print("YES")
for i in range(m+1):
if i%2:
stdout.write(str(1)+" ")
else:
stdout.write(str(2) + " ")
print()
continue
pivot=0
for i in range(n):
for j in range(n):
if i==j:
continue
if mat[i][j]==mat[j][i]:
pivot=1
a=i+1
b=j+1
# print(a,b)
print("YES")
for k in range(m+1):
if k % 2:
stdout.write(str(a) + " ")
else:
stdout.write(str(b) + " ")
print()
break
if pivot:
break
if pivot:
continue
if n==2:
print("no")
continue
print("yes")
if (m//2)%2:
all=[]
f1(0,1,2)
if len(all)>0:
print(*all)
continue
f1(0,2,1)
if len(all)>0:
print(*all)
continue
f1(1,0,2)
if len(all)>0:
print(*all)
continue
f1(1,2,0)
if len(all)>0:
print(*all)
continue
f1(2,0,1)
if len(all)>0:
print(*all)
continue
f1(2,1,0)
if len(all)>0:
print(*all)
continue
else:
all=[]
f2(0, 1, 2)
if len(all)>0:
print(*all)
continue
f2(0, 2, 1)
if len(all)>0:
print(*all)
continue
f2(1, 0, 2)
if len(all)>0:
print(*all)
continue
f2(1, 2, 0)
if len(all)>0:
print(*all)
continue
f2(2, 0, 1)
if len(all)>0:
print(*all)
continue
f2(2, 1, 0)
if len(all)>0:
print(*all)
continue
``` | output | 1 | 79,361 | 13 | 158,723 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba. | instruction | 0 | 79,362 | 13 | 158,724 |
Tags: brute force, constructive algorithms, graphs, greedy, implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
t=int(input())
for tests in range(t):
n,m=map(int,input().split())
S=[input().strip() for i in range(n)]
flag=0
for i in range(n):
for j in range(i+1,n):
if S[i][j]==S[j][i]:
ANSX=(i,j)
flag=1
break
if flag==1:
break
if flag==1:
print("YES")
ANS=[]
for i in range(m+1):
ANS.append(ANSX[i%2]+1)
print(*ANS)
continue
if m%2==1:
print("YES")
ANSX=(0,1)
ANS=[]
for i in range(m+1):
ANS.append(ANSX[i%2]+1)
print(*ANS)
continue
if n==2:
print("NO")
continue
GO=[[0,0] for i in range(n)]
for i in range(n):
for j in range(n):
if i==j:
continue
if S[i][j]=="a":
GO[i][0]=1
else:
GO[i][1]=1
for i in range(n):
if GO[i][0]==1 and GO[i][1]==1:
USE=i
break
UA=-1
UB=-1
for i in range(n):
if i==USE:
continue
if S[USE][i]=="a":
UA=i
else:
UB=i
m2=m//2
print("YES")
if m2%2==0:
ANS=[]
ANSX=(USE,UA)
for i in range(m2+1):
ANS.append(ANSX[i%2]+1)
ANSX=(UB,USE)
for i in range(m2):
ANS.append(ANSX[i%2]+1)
print(*ANS)
continue
else:
ANS=[]
ANSX=(UA,USE)
for i in range(m2+1):
ANS.append(ANSX[i%2]+1)
ANSX=(UB,USE)
for i in range(m2):
ANS.append(ANSX[i%2]+1)
print(*ANS)
continue
``` | output | 1 | 79,362 | 13 | 158,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba. | instruction | 0 | 79,363 | 13 | 158,726 |
Tags: brute force, constructive algorithms, graphs, greedy, implementation
Correct Solution:
```
import sys
input = iter(sys.stdin.read().splitlines()).__next__
def solve():
n, m = map(int, input().split())
edges = [input() for _ in range(n)]
if m % 2:
path = [1, 2]*(m//2+1)
return f"YES\n{' '.join(map(str, path))}"
for u in range(n):
for v in range(u+1, n):
if edges[u][v] == edges[v][u]:
path = [u+1, v+1]*(m//2+1)
return f"YES\n{' '.join(map(str, path[:m+1]))}"
# at this point there is no pair of nodes with same in either direction
incoming = [set() for _ in range(n)]
outgoing = [set() for _ in range(n)]
for u in range(n):
for v in range(n):
if u == v:
continue
incoming[u].add(edges[v][u])
outgoing[u].add(edges[u][v])
for u in range(n):
in_and_out = incoming[u] & outgoing[u]
if not in_and_out:
continue
char_needed = in_and_out.pop()
# go .... a i a i u o b o b ....
# i != o so we can have a = o and b = i
for i in range(n):
if edges[i][u] == char_needed:
break
o = edges[u].index(char_needed)
needed_each_side = m // 2
if needed_each_side % 2:
path = [i, o]*(needed_each_side//2)
path.append(i)
path.append(u)
path.extend([o, i]*(needed_each_side//2))
path.append(o)
else:
left = [o, i]*(needed_each_side//2)
right = left.copy()
path = left
path.append(u)
path.extend(right)
return f"YES\n{' '.join(map(lambda vertex: str(vertex+1), path))}"
# counts_a = [edge.count('a') for edge in edges]
# counts_b = [n-1-count for count in counts_a]
# for u in range(n):
# if counts_a[u] >= 2:
# indices = [i for i, label in enumerate(edges[u]) if label == 'a']
# elif counts_b[u] >= 2:
# indices = [i for i, label in enumerate(edges[u]) if label == 'b']
# else:
# continue
# v, w = indices.pop(), indices.pop()
# path = [u, v]*(m//2)
# path.extend([u, w])
# return f"YES\n{' '.join(map(lambda vertex: str(vertex+1), path))}"
return "NO"
t = int(input())
output = []
for _ in range(t):
output.append(solve())
print(*output, sep="\n")
``` | output | 1 | 79,363 | 13 | 158,727 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba.
Submitted Solution:
```
def solveTestCase():
nm = [int(i) for i in input().split()]
G = []
for i in range(nm[0]):
G.append(input())
if nm[1]%2 == 1:
print("YES")
for i in range(nm[1]//2+1):
print("1 2", end=" ")
print()
return
mypaire = (0, 0)
for i in range(nm[0]):
if mypaire[0]!=0:
break
for j in range(nm[0]):
if i != j and G[i][j] == G[j][i]:
mypaire = (i+1, j+1)
break
if mypaire[0]!=0:
print("YES")
for i in range(nm[1]//2):
print(str(mypaire[0]) + " " + str(mypaire[1]) , end=" ")
print(str(mypaire[0]))
return
mytriple = (0, 0, 0)
for i in range(nm[0]):
if mytriple[0]!=0: break
for j in range(nm[0]):
if mytriple[0]!=0: break
if i == j: continue
for k in range(nm[0]):
if j == k or k == i: continue
if G[i][j] == G[j][k]:
mytriple = (i+1, j+1, k+1)
break
if mytriple[0]!=0:
print("YES")
if nm[1]%4 == 0:
print(str(mytriple[1]), end=" ")
for i in range(nm[1]//2-1):
print(mytriple[i%2], end=" ")
else:
for i in range(nm[1]//2):
print(mytriple[i%2], end=" ")
print(str(mytriple[1]) + " " + str(mytriple[2]), end=" ")
for i in range(nm[1]//2-1):
print(mytriple[(i%2)+1], end=" ")
print()
else:
print("NO")
if __name__ == "__main__":
t = int(input().split()[0])
while t > 0:
t -= 1
solveTestCase()
``` | instruction | 0 | 79,364 | 13 | 158,728 |
Yes | output | 1 | 79,364 | 13 | 158,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba.
Submitted Solution:
```
#from math import *
#from collections import *
#from bisect import *
import sys
input=sys.stdin.readline
def inp():
return int(input())
def st():
return input().rstrip('\n')
def lis():
return list(map(int,input().split()))
def ma():
return map(int,input().split()) # HEY DEAR!!!
t=inp()
while(t):
t-=1
n,m=ma()
deg=[[] for i in range(n)]
dma={i:[] for i in range(n)}
dmb={i:[] for i in range(n)}
for i in range(n):
s=st()
for j in range(n):
deg[i].append(s[j])
if(s[j]=='a'):
dma[i].append(j)
elif(s[j]=='b'):
dmb[i].append(j)
if(m==1):
print("YES")
print(1,2)
continue
fl=0
for i in range(n):
for j in range(n):
if(i==j):
continue
if(deg[i][j]==deg[j][i]):
fl=1
pos=i+1
pos2=j+1
break
if(fl):
print("YES")
for i in range(m+1):
if(i%2):
print(pos,end=' ')
else:
print(pos2,end=' ')
print()
continue
if(m%2):
print("YES")
for i in range(m+1):
print(i%2 +1,end=' ')
print()
continue
if(n==2 ):
print("NO")
continue
else:
if((m//2)%2):
ff=0
for i in range(n):
for j in range(n):
if(i==j):
continue
ha=deg[i][j]
if(ha=='a'):
if(len(dma[j])):
pos1=i+1
pos2=j+1
ll=0
for kk in dma[j]:
if(kk!=pos1-1):
pos3=kk+1
ll=1
break
if(ll ^ 1):
continue
ff=1
break
else:
if(len(dmb[j])):
pos1=i+1
pos2=j+1
ll=0
for kk in dmb[j]:
if(kk!=pos1-1):
pos3=kk+1
ll=1
break
if(ll ^ 1):
continue
ff=1
break
if(ff):
break
if(ff==0):
print("NO")
continue
print("YES")
for i in range(m//2 +1):
if(i%2==0):
print(pos1,end=' ')
else:
print(pos2,end=' ')
for i in range(m//2):
if(i%2):
print(pos2,end=' ')
else:
print(pos3,end=' ')
else:
ff=0
for i in range(n):
for j in range(n):
if(i==j):
continue
ha=deg[i][j]
if(ha=='a'):
if(len(dmb[i])):
pos1=i+1
pos2=j+1
ll=0
for kk in dmb[i]:
if(kk!=pos2-1):
pos3=kk+1
ll=1
break
if(ll ^ 1):
continue
ff=1
break
else:
if(len(dma[i])):
pos1=i+1
pos2=j+1
ll=0
for kk in dma[i]:
if(kk!=pos2-1):
pos3=kk+1
ll=1
break
if(ll ^ 1):
continue
ff=1
break
if(ff):
break
if(ff==0):
print("NO")
continue
print("YES")
for i in range(m//2 +1):
if(i%2==0):
print(pos1,end=' ')
else:
print(pos2,end=' ')
for i in range(m//2):
if(i%2):
print(pos1,end=' ')
else:
print(pos3,end=' ')
print()
``` | instruction | 0 | 79,365 | 13 | 158,730 |
Yes | output | 1 | 79,365 | 13 | 158,731 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba.
Submitted Solution:
```
for _ in range(int(input())):
n, m = map(int, input().split())
graph = [input() for i in range(n)]
# if m is odd, then the answer is always YES
# x -> y -> x -> y -> ...
if m%2 == 1:
print("YES")
print("1 2 "*(m//2+1))
continue
ans = []
for v in range(n):
for u1 in range(n):
for u2 in range(n):
# case1: x -> y == y -> x
# case2: x -> y == y ->z and z -> y == y -> x
if v!=u1 and v!=u2 and graph[u2][v] == graph[v][u1] and graph[u1][v] == graph[v][u2]:
ans = ([u1+1, v+1]*m)[:m//2][::-1] + [v+1] + ([u2+1, v+1]*m)[:m//2]
break
else:continue
break
else:continue
break
if len(ans) > 0:
print("YES")
print(*ans)
continue
print("NO")
``` | instruction | 0 | 79,366 | 13 | 158,732 |
Yes | output | 1 | 79,366 | 13 | 158,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba.
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
T = int(input())
for _ in range(T):
N, M = map(int, input().split())
X = [[0 if a == "a" else 1 if a == "b" else -1 for a in input()] for _ in range(N)]
if M % 2:
print("YES")
print(*[1, 2] * (M // 2 + 1))
continue
f = 0
for i in range(N):
for j in range(i):
if X[i][j] == X[j][i]:
print("YES")
print(*[i+1] + [j+1, i+1] * (M // 2))
f = 1
break
if f: break
if f: continue
if N == 2:
print("NO")
continue
if X[0][1] == X[1][2]:
i, j, k = 1, 2, 3
elif X[1][2] == X[2][0]:
i, j, k = 2, 3, 1
else:
i, j, k = 3, 1, 2
print("YES")
if M % 4:
print(*[i] + [j, i] * (M // 4) + [j, k] * (M // 4 + 1))
else:
print(*[j, i] * (M // 4) + [j, k] * (M // 4) + [j])
``` | instruction | 0 | 79,367 | 13 | 158,734 |
Yes | output | 1 | 79,367 | 13 | 158,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba.
Submitted Solution:
```
# author : empr #
import sys
input=sys.stdin.buffer.readline
ri=lambda: int(input())
rl=lambda: list(map(int,input().split()))
rs=lambda: input().decode().rstrip('\n\r')
wrt=sys.stdout.write
pr=lambda *args,end='\n': wrt(' '.join([str(x) for x in args])+end)
xrange=lambda *args: reversed(range(*args))
cdiv=lambda x,y: (-(-x//y))
enum=enumerate; inf=float('inf')
mod=10**9 + 7
# Am I debugging ? Check if I'm using same variable name in two places
# fun() returning empty list ? check new=temp[:] or new=temp
# Am I breaking or returning from a loop while reading input
# check if I am initializing any ans correctly
from collections import defaultdict as dd,Counter
from queue import deque
#from heapq import *
#from math import gcd
#lcm=lambda x,y: x*y//gcd(x,y)
Testcase=ri()
for testcase in range(Testcase):
n,m=rl()
gr=[]
for i in range(n):
gr.append(rs())
if m%2:
a=[1,2]
print("YES")
for i in range(m+1):
print(a[i%2],end=' ')
print()
else:
poss=False
p,q=-1,-1
for i in range(n):
for j in range(i+1,n):
if gr[i][j]==gr[j][i]!='*':
poss=True
p,q=i,j
break
if poss:
break
if not poss:
print("NO")
else:
a=[p+1,q+1]
print("YES")
for i in range(m+1):
print(a[i%2],end=' ')
print()
``` | instruction | 0 | 79,368 | 13 | 158,736 |
No | output | 1 | 79,368 | 13 | 158,737 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba.
Submitted Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.buffer.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
#INF = float('inf')
mod = int(1e9)+7
def solve(x,y,z):
ans=[]
if m%4:
for i in range(m+1):
if i%4==0 or i%4==2:
ans.append(y)
elif i%4==1:
ans.append(z)
else:
ans.append(x)
else:
for i in range(m+1):
if i%4==1 or i%4==3:
ans.append(y)
elif i%4==2:
ans.append(z)
else:
ans.append(x)
outl(ans)
for t in range(int(data())):
n,m=mdata()
Edg = [data() for i in range(n)]
if m%2:
out("YES")
outl([1,2]*(m//2+1))
else:
flag=False
for i in range(n):
for j in range(i+1,n):
if Edg[i][j]==Edg[j][i]:
ans=[i+1,j+1]
out("YES")
outl(ans * (m // 2) + [ans[0]])
flag=True
break
if flag:
break
d1=dd(int)
d2=dd(int)
for j in range(n):
if j!=i:
d1[Edg[j][i]]=j+1
d2[Edg[i][j]]=j+1
if d1['a'] and d2['a']:
solve(d1['a'],i+1,d2['a'])
flag = True
break
elif d1['b'] and d2['b']:
out("YES")
solve(d1['a'],i+1,d2['a'])
flag = True
break
if not flag:
out("NO")
``` | instruction | 0 | 79,369 | 13 | 158,738 |
No | output | 1 | 79,369 | 13 | 158,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba.
Submitted Solution:
```
from sys import stdin,stdout
from math import gcd,sqrt,factorial,pi,inf
from collections import deque,defaultdict
from bisect import bisect,bisect_left
from time import time
from itertools import permutations as per
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
L=lambda:list(R())
P=lambda x:stdout.write(str(x)+'\n')
lcm=lambda x,y:(x*y)//gcd(x,y)
nCr=lambda x,y:(f[x]*inv((f[y]*f[x-y])%N))%N
inv=lambda x:pow(x,N-2,N)
sm=lambda x:(x**2+x)//2
N=10**9+7
t=I()
for _ in range(t):
n,m=R()
s=[S() for i in range(n)]
if t==320:
if _==128:print(s)
continue
if n==2 and m%2==0 and s[0][1]!=s[1][0]:print('NO');continue
flg=False
AB=[]
A=[]
B=[]
print('YES')
for i in range(n):
a=[]
b=[]
for j in range(n):
if s[i][j]==s[j][i]!='*':flg=[i+1,j+1];break
if s[i][j]=='a':a=[i+1,j+1]
elif s[i][j]=='b':b=[i+1,j+1]
if not a:B+=b,
elif not b:A+=a,
else:AB+=[a[0],a[1],b[1]],
if flg:break
if flg:
for i in range(m+1):
print(flg[i%2],end=' ')
print()
elif m%2:
for i in range(m+1):
print(2-i%2,end=' ')
print()
else:
if A and B:
flg=[A[0][0],B[0][0]]
ex=0
elif A:
flg=[A[0][0],AB[0][0]]
ex=1
elif B:
flg=[AB[0][0],B[0][0]]
ex=1
else:
if s[AB[0][0]-1][AB[1][0]-1]=='a':
flg=[AB[0][0],AB[1][0]]
else:
flg=[AB[1][0],AB[0][0]]
ex=2
for i in range(m//2):
print(flg[i%2],end=' ')
p=flg[i%2]-1
print(AB[ex][0],end=' ')
if s[p][AB[ex][0]-1]=='a':
flg=[AB[ex][1],AB[ex][0]]
else:
flg=[AB[ex][2],AB[ex][0]]
for i in range(m//2):
print(flg[i%2],end=' ')
print()
"""*aaa
b*bb
ba*a
bab*
*aa
b*b
ba*
2 3 1
*ab
b*a
ab*
abaaba"""
``` | instruction | 0 | 79,370 | 13 | 158,740 |
No | output | 1 | 79,370 | 13 | 158,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.
<image>
You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β v) has both directed edges (u, v) and (v, u).
Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels).
You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.
You can visit the same vertex and the same directed edge any number of times.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains two integers n and m (2 β€ n β€ 1000; 1 β€ m β€ 10^{5}) β the number of vertices in the graph and desirable length of the palindrome.
Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j.
Every character is either 'a' or 'b' if i β j, or '*' if i = j, since the graph doesn't contain self-loops.
It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5.
Output
For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.
Otherwise, (if there is no answer) print "NO".
Example
Input
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*
Output
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO
Note
The graph from the first three test cases is shown below:
<image>
In the first test case, the answer sequence is [1,2] which means that the path is:
$$$1 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is b.
In the second test case, the answer sequence is [2,1,3,2] which means that the path is:
$$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$
So the string that is obtained by the given path is bab.
In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is:
$$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$
So the string that is obtained by the given path is aaaa.
The string obtained in the fourth test case is abaaba.
Submitted Solution:
```
#!/usr/bin/env python3
# created : 2021
from sys import stdin, stdout
def solve(tc):
n, m = map(int, stdin.readline().split())
grid = []
for i in range(n):
grid.append(stdin.readline().strip())
ans = []
for i in range(n):
for j in range(i+1, n):
if grid[i][j] == grid[j][i]:
for k in range(m+1):
if len(ans) & 1:
ans.append(i+1)
else:
ans.append(j+1)
print("YES")
print(' '.join(map(lambda x: str(x), ans)))
return
if m % 2:
for k in range(m+1):
if len(ans) & 1:
ans.append(1)
else:
ans.append(2)
print("YES")
print(' '.join(map(lambda x: str(x), ans)))
return
if n == 2:
print("NO")
return
for k in range(m//2+1):
if len(ans) & 1:
ans.append(1)
else:
ans.append(2)
ch = grid[ans[-2]-1][ans[-1]-1]
for j in range(n):
if j == ans[-1]-1 or grid[ans[-2]-1][ans[-1]-1] != ch:
continue
ans.append(j+1)
break
while len(ans) <= m:
ans.append(ans[-2])
print("YES")
print(' '.join(map(lambda x: str(x), ans)))
tcs = 1
tcs = int(stdin.readline().strip())
tc = 1
while tc <= tcs:
solve(tc)
tc += 1
``` | instruction | 0 | 79,371 | 13 | 158,742 |
No | output | 1 | 79,371 | 13 | 158,743 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.
Constraints
* N is an integer.
* 1 \leq N \leq 10^{5}
Input
Input is given from Standard Input in the following format:
N
Output
If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:
a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}
Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.
Examples
Input
3
Output
Yes
1 2
2 3
3 4
4 5
5 6
Input
1
Output
No | instruction | 0 | 79,733 | 13 | 159,466 |
"Correct Solution:
```
import sys, collections
def solve():
input = sys.stdin.readline
N = int(input())
k = 1
while k <= N:
if k == N:
print("No")
break
else: k *= 2
else:
if N % 2 == 1:
print("Yes")
ans = ""
ans += "1 2\n"
ans += "2 3\n"
ans += "3 " + str(N + 1) + "\n"
ans += str(N + 1) + " " + str(N + 2) + "\n"
ans += str(N + 2) + " " + str(N + 3) + "\n"
for i in range(2, N // 2 + 1):
ans += str(2 * i) + " " + str(2 * i + 1) + "\n"
ans += str(2*i+1) + " 1\n"
ans += "1 " + str(N + 2*i) + "\n"
ans += str(N+2*i) + " " + str(N+2*i+1) + "\n"
print(ans)
else:
print("Yes")
ans = ""
ans += "1 2\n"
ans += "2 3\n"
ans += "3 " + str(N + 1) + "\n"
ans += str(N + 1) + " " + str(N + 2) + "\n"
ans += str(N + 2) + " " + str(N + 3) + "\n"
for i in range(2, N // 2):
ans += str(2 * i) + " " + str(2 * i + 1) + "\n"
ans += str(2*i+1) + " 1\n"
ans += "1 " + str(N + 2*i) + "\n"
ans += str(N+2*i) + " " + str(N+2*i+1) + "\n"
b = N ^ (N - 1)
ans += str(N) + " " + str(N-1) + "\n"
if b % 2 == 1:
ans += str(N + b - 1) + " " + str(2 * N)
else:
ans += str(b + 1) + " " + str(2 * N)
print(ans)
return 0
if __name__ == "__main__":
solve()
``` | output | 1 | 79,733 | 13 | 159,467 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.
Constraints
* N is an integer.
* 1 \leq N \leq 10^{5}
Input
Input is given from Standard Input in the following format:
N
Output
If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:
a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}
Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.
Examples
Input
3
Output
Yes
1 2
2 3
3 4
4 5
5 6
Input
1
Output
No | instruction | 0 | 79,734 | 13 | 159,468 |
"Correct Solution:
```
def is_2power(n: int)->bool:
a = 1
while a < n:
a <<= 1
return a == n
def skolem_xor_tree(N: int)->list:
if is_2power(N):
return []
res = [
(1, 2),
(2, 3),
(3, N+1),
(N+1, N+2),
(N+2, N+3),
]
for a in range(4, N+(N % 2), 2):
res.append((1, a))
res.append((a, a+1))
res.append((1, N+a+1))
res.append((N+a+1, N+a))
if N % 2 == 0:
a = N ^ 1
b = None
for i in range(2, N):
if (a ^ i) < N:
a = a ^ i
b = i
break
if not b:
raise Exception()
if a < N and a % 2 == 1:
a += N
if b < N and b % 2 == 1:
b += N
res.append((a, N))
res.append((b, N+N))
return res
if __name__ == "__main__":
N = int(input())
ans = skolem_xor_tree(N)
if ans:
print('Yes')
for a, b in ans:
print(a, b)
else:
print('No')
``` | output | 1 | 79,734 | 13 | 159,469 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.
Constraints
* N is an integer.
* 1 \leq N \leq 10^{5}
Input
Input is given from Standard Input in the following format:
N
Output
If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:
a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}
Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.
Examples
Input
3
Output
Yes
1 2
2 3
3 4
4 5
5 6
Input
1
Output
No | instruction | 0 | 79,735 | 13 | 159,470 |
"Correct Solution:
```
def solve(n):
if n < 3:
print('No')
return
d, m = divmod(n, 4)
l = d * 4
if m == 3:
d += 1
l += 4
ans = ['{} {}'.format(x, y) for x, y in ((1, 2), (2, 3), (3, 1 + n), (1 + n, 2 + n), (2 + n, 3 + n))]
if bin(l).count('1') == 1:
if m == 0:
print('No')
return
if m < 3:
ans.extend('{} {}'.format(x, y) for x, y in ((1, l), (l, l + 1), (1, l + n + 1), (l + n + 1, l + n)))
if m == 2:
ans.extend('{} {}'.format(x, y) for x, y in ((2, l + 2), (l + n + 1, l + n + 2)))
m = 3
for i in range(4, l, 4):
ans.extend('{} {}'.format(x, y) for x, y in (
(i, i + 1), (i + 1, i + 2), (i + 2, i + 3), (i + 3, i + n),
(i + n, i + n + 1), (i + n + 1, i + n + 2), (i + n + 2, i + n + 3)))
if m == 3:
for i in range(4, l, 4):
ans.append('{} {}'.format(1, i))
print('Yes')
print('\n'.join(ans))
return
min_k = k = l & -l
prev = 1
connected = set()
while k < l:
if k & l:
ans.append('{} {}'.format(prev, k))
connected.add(k)
prev = k
k <<= 1
for i in range(4, l, 4):
if i in connected:
continue
ans.append('{} {}'.format(1, i))
# print(*ans, sep='\n')
# print('--')
ans.append('{} {}'.format(l, min_k))
ans.append('{} {}'.format(l + n, prev))
if m >= 1:
ans.append('{} {}'.format(l + 1, 1))
ans.append('{} {}'.format(l + 1 + n, prev))
if m >= 2:
ans.append('{} {}'.format(l + 2, 1))
ans.append('{} {}'.format(l + 2 + n, prev + 2))
assert len(ans) == 2 * n - 1
print('Yes')
print('\n'.join(ans))
n = int(input())
solve(n)
``` | output | 1 | 79,735 | 13 | 159,471 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.
Constraints
* N is an integer.
* 1 \leq N \leq 10^{5}
Input
Input is given from Standard Input in the following format:
N
Output
If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:
a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}
Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.
Examples
Input
3
Output
Yes
1 2
2 3
3 4
4 5
5 6
Input
1
Output
No | instruction | 0 | 79,736 | 13 | 159,472 |
"Correct Solution:
```
n,k,i=int(input()),1,2
v=n+1
p=print
if-n&n==n:p("No");exit()
p("Yes",v,3)
while i<n:p(1,i,i,i+1,1,v+i,v+i,n+i);i+=2;k<<=k*2<v
if~n&1:p(n,v+k,n+n,n^k)
``` | output | 1 | 79,736 | 13 | 159,473 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.
Constraints
* N is an integer.
* 1 \leq N \leq 10^{5}
Input
Input is given from Standard Input in the following format:
N
Output
If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:
a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}
Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.
Examples
Input
3
Output
Yes
1 2
2 3
3 4
4 5
5 6
Input
1
Output
No | instruction | 0 | 79,737 | 13 | 159,474 |
"Correct Solution:
```
N = int(input())
n = 1<<N.bit_length()-1
if N == n:
print("No")
else:
print("Yes")
# print(n)
ANS = []
if N % 2:
for i in range(1, n-1):
ANS.append((i, i+1))
ANS.append((n-1, N+1))
for i in range(1, n-1):
ANS.append((i+N, i+N+1))
for i in range(0, N-n, 2):
ANS.append((1+N, i+n))
ANS.append((i+n, i+n+1))
ANS.append((1+N, i+n+1+N))
ANS.append((i+n+1+N, i+n+N))
else:
a, b, c = N-2, N-1, N
X = [i for i in range(1, n) if i != a^c] + [c, a]
# print("X =", X)
for i in range(n-1):
ANS.append((X[i], X[i+1]))
ANS.append((X[n-1], X[0]+N))
for i in range(n-1):
ANS.append((X[i]+N, X[i+1]+N))
for i in range(0, N-n-3, 2):
ANS.append((1+N, i+n))
ANS.append((i+n, i+n+1))
ANS.append((1+N, i+n+1+N))
ANS.append((i+n+1+N, i+n+N))
ANS.append((a, a^c))
ANS.append((c, (a^c)+N))
ANS.append((1+N, b))
ANS.append((a, b+N))
# print(len(ANS))
# print(ANS)
if N == 3:
ANS = [(1,2),(2,3),(3,4),(4,5),(5,6)]
for ans in ANS:
print(*ans)
# print("len =", len(ANS))
``` | output | 1 | 79,737 | 13 | 159,475 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.
Constraints
* N is an integer.
* 1 \leq N \leq 10^{5}
Input
Input is given from Standard Input in the following format:
N
Output
If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:
a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}
Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.
Examples
Input
3
Output
Yes
1 2
2 3
3 4
4 5
5 6
Input
1
Output
No | instruction | 0 | 79,738 | 13 | 159,476 |
"Correct Solution:
```
def main():
import sys
input = sys.stdin.readline
N = int(input())
k = N.bit_length()
if 1<<(k-1) == N:
print('No')
exit()
print('Yes')
if N == 3:
for i in range(1, 6):
print(i, i+1)
exit()
N0 = 1<<(k-1)
e = [(N0-1, N+1)]
for i in range(1, N0-1):
e.append((i, i+1))
e.append((i+N, i+1+N))
if N%2 == 0:
v = N ^ N0
e.append((N, v))
e.append((N*2, N0))
for i in range(N0, N):
if i % 2 == 0:
e.append((i, v))
e.append((i + N, i+N+1))
else:
e.append((i, i - 1))
e.append((i + N, v + 1))
else:
for i in range(N0, N + 1):
if i % 2 == 0:
e.append((i, 2))
e.append((i + N, i + 1 + N))
else:
e.append((i, i - 1))
e.append((i + N, 3 + N))
for edge in e:
print(*edge)
if __name__ == '__main__':
main()
``` | output | 1 | 79,738 | 13 | 159,477 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.
Constraints
* N is an integer.
* 1 \leq N \leq 10^{5}
Input
Input is given from Standard Input in the following format:
N
Output
If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:
a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}
Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.
Examples
Input
3
Output
Yes
1 2
2 3
3 4
4 5
5 6
Input
1
Output
No | instruction | 0 | 79,739 | 13 | 159,478 |
"Correct Solution:
```
#!/usr/bin/env python3
import sys
YES = "Yes" # type: str
NO = "No" # type: str
def solve(N: int):
k = 1
while k < N:
k *= 2
if N == k:
print(NO)
return
print(YES)
if N % 2 == 0:
n = N - 1
even = True
else:
n = N
even = False
for i in range(2, n+1):
if i % 2 == 0:
print(1, i)
print(N+i+1, N+i)
else:
print(i, i-1)
print(N+i, 1)
print(3, N+1)
if even:
k //= 2
print(N, k)
a = N ^ k ^ 1
print(a + N, N * 2)
return
# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template)
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
solve(N)
if __name__ == '__main__':
main()
``` | output | 1 | 79,739 | 13 | 159,479 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.
Constraints
* N is an integer.
* 1 \leq N \leq 10^{5}
Input
Input is given from Standard Input in the following format:
N
Output
If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:
a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}
Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.
Examples
Input
3
Output
Yes
1 2
2 3
3 4
4 5
5 6
Input
1
Output
No | instruction | 0 | 79,740 | 13 | 159,480 |
"Correct Solution:
```
n,k,i=int(input()),1,2
v=n+1
p=print
while k*2<v:k*=2
if-n&k:p("No");exit()
p("Yes",v,3)
while i<n:p(1,i,i,i+1,1,v+i,v+i,n+i);i+=2
if~n&1:p(n,v+k,n+n,n^k)
``` | output | 1 | 79,740 | 13 | 159,481 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.
Constraints
* N is an integer.
* 1 \leq N \leq 10^{5}
Input
Input is given from Standard Input in the following format:
N
Output
If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:
a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}
Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.
Examples
Input
3
Output
Yes
1 2
2 3
3 4
4 5
5 6
Input
1
Output
No
Submitted Solution:
```
n=int(input())
if n<=2 or n==4:
print("No")
elif n==3:
print("Yes")
for i in range(5):
print(i+1,i+2)
elif n%2==0:
nn=n.bit_length()
if n==2**(nn-1):
print("No")
else:
print("Yes")
print(1,2)
print(2,3)
print(3,n+1)
print(n+1,n+2)
print(n+2,n+3)
for i in range(4,n):
print(n+1,i)
if i%2==0:
print(i,i+n+1)
else:
print(i,i+n-1)
n1,n2=2**(nn-1),(n+1)-2**(nn-1)
print(n1,n)
print(n2,2*n)
else:
print("Yes")
print(1,2)
print(2,3)
print(3,n+1)
print(n+1,n+2)
print(n+2,n+3)
for i in range(4,n+1):
print(1,i)
if i%2==0:
print(i,i+n+1)
else:
print(i,i+n-1)
``` | instruction | 0 | 79,741 | 13 | 159,482 |
Yes | output | 1 | 79,741 | 13 | 159,483 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.
Constraints
* N is an integer.
* 1 \leq N \leq 10^{5}
Input
Input is given from Standard Input in the following format:
N
Output
If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:
a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}
Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.
Examples
Input
3
Output
Yes
1 2
2 3
3 4
4 5
5 6
Input
1
Output
No
Submitted Solution:
```
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
#A
def A():
n = I()
a = LI()
ans = 0
for i in a:
ans ^= i
if not ans:
print("Yes")
else:
print("No")
return
#B
def B():
n,m = LI()
return
#C
def C():
n = I()
p = [(1<<i) for i in range(100)]
if n in p:
print("No")
quit()
if n+1 in p:
print("Yes")
for i in range(1,2*n):
print(i,i+1)
quit()
ans = []
for i in range(1,3):
ans.append((i,i+1))
ans.append((3,n+1))
for i in range(1,3):
ans.append((i+n,i+n+1))
u = 1
d = 1
for i in range(2,n//2+n%2):
ans.append((u,2*i))
ans.append((d,2*i+1))
ans.append((2*i,2*i+n+1))
ans.append((2*i+1,2*i+n))
u = 2*i+n+1
d = 2*i+n
if n%2:
print("Yes")
for i,j in ans:
print(i,j)
else:
ans.append((n-1,n))
for i in range(n):
if p[i]&n:
break
ans.append((p[i+1]-2,2*n))
print("Yes")
for i,j in ans:
print(i,j)
return
#D
def D():
n = I()
return
#E
def E():
n = I()
return
#F
def F():
n = I()
return
#Solve
if __name__ == "__main__":
C()
``` | instruction | 0 | 79,742 | 13 | 159,484 |
Yes | output | 1 | 79,742 | 13 | 159,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.
* Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.
Constraints
* N is an integer.
* 1 \leq N \leq 10^{5}
Input
Input is given from Standard Input in the following format:
N
Output
If there exists a tree satisfying the condition in the statement, print `Yes`; otherwise, print `No`. Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:
a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}
Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.
Examples
Input
3
Output
Yes
1 2
2 3
3 4
4 5
5 6
Input
1
Output
No
Submitted Solution:
```
N = int(input())
if N & (N-1) == 0:
print("No")
exit()
print("Yes")
print(1, 2)
print(2, 3)
print(3, N+1)
print(N+1, N+2)
print(N+2, N+3)
for i in range(4, N, 2):
print(i, i+1)
print(i+1, N+1)
print(N+1, N+i)
print(N+i, N+i+1)
if N % 2 == 0:
print(N, N-1)
x = N^(N-1)^1
if x % 2 == 0:
print(N+x, 2*N)
else:
print(x, 2*N)
``` | instruction | 0 | 79,743 | 13 | 159,486 |
Yes | output | 1 | 79,743 | 13 | 159,487 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.