input
stringlengths 20
127k
| target
stringlengths 20
119k
| problem_id
stringlengths 6
6
|
---|---|---|
from collections import deque
N = int(eval(input()))
edges = [[] for _ in range(N + 1)]
for edge_idx in range(1, N):
a, b = list(map(int, input().split()))
edges[a].append([edge_idx, b])
edges[b].append([edge_idx, a])
used_edges = []
colors = [1 for _ in range(1, N + 1)]
used_colors = [[] for _ in range(N + 1)]
stack = deque([[edges[1], 0]])
max_col = 1
while stack:
edge_info, parent_node_idx = stack.popleft()
cur_color = 1
for edge_idx, node_idx in edge_info:
if edge_idx in used_edges: continue
while cur_color in used_colors[node_idx] or cur_color in used_colors[parent_node_idx]:
cur_color += 1
used_colors[node_idx].append(cur_color)
colors[edge_idx] = cur_color
stack.append([edges[node_idx], node_idx])
used_edges.append(edge_idx)
max_col = max(max_col, cur_color)
cur_color += 1
print(max_col)
for c in colors[1:]:
print(c)
|
from collections import deque
N = int(eval(input()))
edges = [[] for _ in range(N + 1)]
for edge_idx in range(1, N):
a, b = list(map(int, input().split()))
edges[a].append([edge_idx, b])
edges[b].append([edge_idx, a])
used_edges = set()
colors = [1 for _ in range(1, N + 1)]
used_colors = [set() for _ in range(N + 1)]
stack = deque([[edges[1], 0]])
max_col = 1
while stack:
edge_info, parent_node_idx = stack.pop()
cur_color = 1
for edge_idx, node_idx in edge_info:
if edge_idx in used_edges: continue
while cur_color in used_colors[node_idx] or cur_color in used_colors[parent_node_idx]:
cur_color += 1
used_colors[node_idx].add(cur_color)
colors[edge_idx] = cur_color
stack.append([edges[node_idx], node_idx])
used_edges.add(edge_idx)
max_col = max(max_col, cur_color)
cur_color += 1
print(max_col)
for c in colors[1:]:
print(c)
|
p02850
|
n = int(eval(input()))
l = [[] for _ in range(n+1)]
s = [0 for _ in range(n+1)]
ll = []
for _ in range(n-1):
ai,bi = list(map(int,input().split()))
l[ai].append(bi)
l[bi].append(ai)
ll.append([ai,bi])
s[ai] += 1
s[bi] += 1
mx = 0
for i in range(1,n+1):
if s[i] > mx:
mx = s[i]
mxi = i
print(mx)
ans = [[0 for _ in range(n+1)] for _ in range(n+1)]
def dfs(a,b,c):
i = 1
for h in l[a]:
if h != b:
if i == c:
i += 1
ans[a][h] = i
ans[h][a] = i
dfs(h,a,i)
i += 1
return
dfs(mxi,0,0)
for xx in ll:
print((ans[xx[0]][xx[1]]))
|
import sys
import resource
sys.setrecursionlimit(10**5)
n = int(eval(input()))
l = [[] for _ in range(n+1)]
s = [0 for _ in range(n+1)]
ll = []
for i in range(n-1):
ai,bi = list(map(int,input().split()))
l[ai].append([bi,i])
l[bi].append([ai,i])
s[ai] += 1
s[bi] += 1
mx = 0
for i in range(1,n+1):
if s[i] > mx:
mx = s[i]
mxi = i
print(mx)
ans = [0 for _ in range(n-1)]
def dfs(a,b,c):
i = 1
for h,j in l[a]:
if h != b:
if i == c:
i += 1
ans[j] = i
dfs(h,a,i)
i += 1
return
dfs(mxi,0,0)
for x in ans:
print(x)
|
p02850
|
N = int(eval(input()))
edges = [[] for i in range(N)]
ans = [[0 for i in range(N + 1)] for i in range(N + 1)]
lines = []
for i in range(N - 1):
a, b = list(map(int, input().split()))
lines.append((a, b,))
edges[a - 1].append(b - 1)
q = [(0, 0,)]
max_color = 0
while q:
v, color = q.pop()
c = 0
for nv in edges[v]:
c += 1
if c == color:
c += 1
q.append((nv, c,))
ans[v + 1][nv + 1] = c
max_color = max(max_color, c)
print(max_color)
for i in range(N - 1):
a, b = lines[i]
print((ans[a][b]))
|
N = int(eval(input()))
edges = [[] for i in range(N)]
ans = [-1] * (N - 1)
lines = []
for i in range(N - 1):
a, b = list(map(int, input().split()))
lines.append((a, b))
edges[a - 1].append((b - 1, i,))
q = [(0, 0,)]
max_color = 0
while q:
v, c = q.pop()
color = 1
if c == color:
color += 1
for nv, i in edges[v]:
ans[i] = color
q.append((nv, color,))
color += 1
if c == color:
color += 1
print((max(ans)))
for i in range(N - 1):
a, b = lines[i]
print((ans[i]))
|
p02850
|
import sys
input = sys.stdin.readline
N = int(eval(input()))
graph = [[] for _ in range(N)]
Ed = {}
for i in range(N-1):
a, b = list(map(int, input().split()))
graph[a-1].append(b-1)
graph[b-1].append(a-1)
Ed[(a-1)*N+b-1] = i
Ed[(b-1)*N+a-1] = i
q = [0]
checked = [False]*N
checked[0] = True
V_color = [None]*N
V_color[0] = 0
ans = [None]*(N-1)
while q:
qq = []
for p in q:
c = V_color[p]
t = 1
for np in graph[p]:
if not checked[np]:
checked[np] = True
qq.append(np)
ind = Ed[p*N+np]
if t == c:
t += 1
ans[ind] = t
V_color[np] = t
t += 1
q = qq
print((max(ans)))
for a in ans:
print(a)
|
import sys
input = sys.stdin.readline
N = int(eval(input()))
graph = [[] for _ in range(N)]
Edges = []
for _ in range(N-1):
a, b = list(map(int, input().split()))
graph[a-1].append(b-1)
graph[b-1].append(a-1)
Edges.append((a-1, b-1))
Col = 0
for n in range(N):
Col = max(Col, len(graph[n]))
Color = dict()
checked = [-1]*N
q = [0]
checked[0] = Col+1
while q:
qq = []
for p in q:
c = checked[p]
t = 0
for np in graph[p]:
if checked[np] == -1:
if t == c:
t += 1
checked[np] = t
Color[(p, np)] = t
Color[(np, p)] = t
t += 1
qq.append(np)
q = qq
print(Col)
for a, b in Edges:
print((Color[(a, b)]+1))
|
p02850
|
import sys
sys.setrecursionlimit(10**8)
N = int(eval(input()))
adj = [[] for _ in range(N+1)]
for e in range(1,N):
a,b = list(map(int, input().split()))
adj[a].append((b,e))
adj[b].append((a,e))
#print(adj)
col_num = max([len(ad) for ad in adj])
edge_color = [0]*N
visited = [False]*(N+1)
def dfs(v,e=-1):
visited[v] = True
#print(v,e,edge_color)
col_lis = [i for i in range(1,col_num+1)]
if e >0:
col_lis.remove(edge_color[e])
#color = 1
for w,f in adj[v]:
if visited[w]==False:
#if c==color: color+=1
edge_color[f] = col_lis.pop(0)
dfs(w,f)
#color+=1
dfs(1)
print(col_num)
for i in range(1,N):
print((edge_color[i]))
|
import sys
sys.setrecursionlimit(10**8)
def dfs(v,c):
now = 1
for u,i in edge[v]:
if color[i]==0:
if now==c:
now += 1
color[i] = now
dfs(u,now)
now += 1
return 0
N = int(input())
edge = [[] for _ in range(N)]
for i in range(N-1):
a,b = map(int, input().split())
edge[a-1].append([b-1,i])
edge[b-1].append([a-1,i])
color = [0]*(N-1)
dfs(0,1<<30)
print(max(color))
print(*color, sep='\n')
|
p02850
|
N = int(eval(input()))
E = []
A = [[-1 for j in range(N+1)] for i in range(N+1)]
edges = [[] for i in range(N+1)]
for i in range(N-1):
a, b = list(map(int, input().split()))
if i == 0:
root = a
E.append((a,b))
edges[a].append(b)
edges[b].append(a)
def dfs(u):
visited = ["white"] * (N + 1)
stack = [(u, -1, -1)]
mcolor = -1
while stack:
u, p, c = stack.pop()
visited[u] = "black"
next = 1
for v in edges[u]:
if v != p and visited[v] != "black":
if next == c:
next += 1
mcolor = max(mcolor, next)
A[u][v] = next
A[v][u] = next
stack.append((v, u, next))
next += 1
return mcolor
print((dfs(root)))
for edge in E:
a, b = edge
print((A[a][b]))
|
N = int(eval(input()))
edges = [[] for i in range(N+1)]
A = [-1 for i in range(N-1)]
for i in range(N-1):
a, b = list(map(int, input().split()))
if i == 0:
root = a
edges[a].append((b, i))
edges[b].append((a, i))
def dfs(u):
visited = ["white"] * (N + 1)
stack = [(u, -1, -1)]
mcolor = -1
while stack:
u, p, c = stack.pop()
visited[u] = "black"
next = 1
for (v, i) in edges[u]:
if v != p and visited[v] != "black":
if next == c:
next += 1
mcolor = max(mcolor, next)
A[i] = next
stack.append((v, u, next))
next += 1
return mcolor
print((dfs(root)))
for a in A:
print(a)
|
p02850
|
N = int(eval(input()))
A = [[-1 for j in range(N+1)] for i in range(N+1)]
ans = [-1 for i in range(N-1)]
edges = [[] for i in range(N+1)]
for i in range(N-1):
a, b = list(map(int, input().split()))
if i == 0:
root = a
edges[a].append((b, i))
edges[b].append((a,i))
def dfs(u):
visited = ["white"] * (N + 1)
stack = [(u, -1, -1)]
mcolor = -1
while stack:
u, p, c = stack.pop()
visited[u] = "black"
next = 1
for (v, i) in edges[u]:
if v != p and visited[v] != "black":
if next == c:
next += 1
mcolor = max(mcolor, next)
A[u][v] = next
A[v][u] = next
stack.append((v, u, next))
ans[i] = next
next += 1
return mcolor
print((dfs(root)))
for a in ans:
print(a)
|
N = int(eval(input()))
EDGES = [[] for _ in range(N+1)]
P = [(set(), 1) for _ in range(N+1)]
for i in range(N-1):
a, b = list(map(int, input().split()))
if i == 0:
root = a
EDGES[a].append((b, i))
EDGES[b].append((a, i))
ans = [None for i in range(N-1)]
def dfs(root):
# from, parent, color
stack = [(root, -1, -1)]
visited = set()
while stack:
u, parent, color = stack.pop()
visited.add(u)
nextColor = 1
for (v, index) in EDGES[u]:
if v not in visited and v != parent:
if nextColor == color:
nextColor += 1
stack.append((v, u, nextColor))
ans[index] = nextColor
nextColor += 1
dfs(root)
print((max(ans)))
for a in ans:
print(a)
|
p02850
|
from collections import defaultdict
N = int(eval(input()))
P = [[] for _ in range(N)]
C = [set([]) for _ in range(N)]
T = set([])
D = defaultdict(int)
for _ in range(N-1):
a, b = [int(x)-1 for x in input().split()]
P[a].append(b)
#P[b].append(a)
D[(a, b)]
def bfs(s):
d = [-1] * N
d[s] = 0
p_old = [s]
M = 0
while p_old:
p_new = []
for i in p_old:
for j in P[i]:
temp = T - C[i]
if temp:
v = temp.pop()
D[(i, j)] = v
C[i].add(v)
C[j].add(v)
else:
M += 1
T.add(M)
D[(i, j)] = M
C[i].add(M)
C[j].add(M)
d[j] = 0
p_new.append(j)
p_old = p_new
return M
print((bfs(0)))
for x in list(D.values()):
print(x)
|
N = int(eval(input()))
graph = [[] for _ in range(N+1)]
AB = []
for _ in range(N-1):
a, b = list(map(int, input().split()))
graph[a].append(b)
graph[b].append(a)
AB.append((a, b))
root = 1
parent = [0] * (N+1)
order = []
stack = [root]
while stack:
x = stack.pop()
order.append(x)
for y in graph[x]:
if y == parent[x]:
continue
parent[y] = x
stack.append(y)
color = [-1] * (N+1)
K = -1
for x in order:
ng = color[x]
c = 1
for y in graph[x]:
if y == parent[x]:
continue
if c == ng:
c += 1
K = max(c, K)
color[y] = c
c += 1
ans = []
for a, b in AB:
if parent[a] == b:
ans.append(color[a])
else:
ans.append(color[b])
print(K)
for i in ans:
print(i)
|
p02850
|
import sys,collections
input = sys.stdin.readline
n = int(eval(input()))
l=[[]]
cnt = [0]*(n+1)
nn = []
for _ in range(n+1):
l.append([])
for i in range(n-1):
a,b = list(map(int,input().split()))
l[a].append(b)
l[b].append(a)
nn.append(b)
m = max(list(map(len,l)))
co = []
for i in range(n+1):
co.append( set(range(1,m+1) ))
col = [0 for i in range(n+1)]
col[1] = 1
for i in range(1,n+1):
for la in l[i]:
if col[la] ==0:
col[la] = co[i].pop()
co[la].discard(col[la])
print(m)
for i in range(n-1):
print((col[nn[i]]))
|
import sys
input = sys.stdin.readline
n = int(eval(input()))
l=[[]]
nn = []
for _ in range(n+1):
l.append([])
for i in range(n-1):
a,b = list(map(int,input().split()))
l[a].append(b)
l[b].append(a)
nn.append(b)
ml = list(map(len,l))
m = max(ml)
co = []
for i in range(n+1):
co.append( set(range(1,ml[i]+1) ))
col = [0]*(n+1)
col[1] = 1
for i in range(1,n+1):
for la in l[i]:
if col[la] ==0:
col[la] = co[i].pop()
co[la].discard(col[la])
print(m)
for i in range(n-1):
print((col[nn[i]]))
|
p02850
|
from collections import deque
N = int(eval(input()))
tree = [[] for _ in range(N)]
ans = {}
tmp = []
for _ in range(N-1):
a, b = [int(x)-1 for x in input().split()]
tree[a].append(b)
tree[b].append(a)
ans[(a, b)] = 0
tmp.append((a, b)) # 最後に出力する際に使う, 順番通りに出力する必要があるから。
# print(tree)
visited = [False]*N
colors = [-1]*N # そのノードに上から刺さっている辺の色 (colors[根のノードのindex]は変わらない)
q = deque([0]) # 始まりのノード
visited[0] = True
while len(q):
# vは数字, 親のノードのインデックス
v = q.pop()
color = 1
for e in tree[v]:
if visited[e]: # 到達済みなら次のノードへ
continue
visited[e] = True
if colors[v] == color: # 親のノードに刺さっている辺の色が今から塗ろうとしている色と同じなら、変更する
color += 1
ans[(v, e)] = color
colors[e] = color
color += 1
q.append(e)
print((max(colors)))
for a, b in tmp:
print((ans[(a, b)]))
|
from collections import deque
N = int(eval(input()))
visited = [False]*N
tree = [[] for _ in range(N)]
tmp = []
for _ in range(N-1):
a, b = [int(x)-1 for x in input().split()]
tree[a].append(b)
tree[b].append(a)
tmp.append((a, b)) # 順番を保持するため
ans = {} # 連想配列で保持する
q = deque([0]) # 開始のノード
colors = [-1]*N # そのノードにささっている辺の色
visited[0] = True
while len(q): # 幅優先探索を開始する
v = q.pop() # 部分木の親のノード
color = 1
for e in tree[v]: # 子供に対して操作を行う
if visited[e]:
continue
visited[e] = True
if colors[v] == color:
color += 1
ans[(v, e)] = color
colors[e] = color
color += 1
q.append(e)
print((max(colors)))
for a, b in tmp:
print((ans[(a, b)]))
|
p02850
|
import sys
from collections import deque
input = sys.stdin.readline
def main():
N = int(eval(input()))
visited = [False] * N
E = [deque() for i in range(N)]
nums = [set() for i in range(N)]
ans = [None] * (N-1)
for i in range(N-1):
a, b = list(map(int, input().split()))
E[a-1].append((b-1, i))
E[b-1].append((a-1, i))
ans_ = max([len(e) for e in E])
G = set(i for i in range(ans_))
q = deque([0])
while q:
v = q.popleft()
if visited[v]: continue
visited[v] = True
use_nums = deque(list(G - nums[v]))
for u, idx in E[v]:
if visited[u]: continue
n = use_nums.popleft()
ans[idx] = str(n+1)
nums[u].add(n)
q.append(u)
print(ans_)
print(('\n'.join(ans)))
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*
import sys
input = sys.stdin.readline
def main():
N = int(eval(input()))
G = [[] for i in range(N)]
ans = [None] * (N-1)
for i in range(N-1):
a, b = list(map(int, input().split()))
a, b = a-1, b-1
G[a].append((b, i))
G[b].append((a, i))
q = [(0, -1)]
visited = [False] * N
cur = 0
while q and cur < N:
v, c = q.pop(0)
if visited[v]: continue
visited[v] = True
cur += 1
k = 0
for u, idx in G[v]:
if visited[u]: continue
if c == k: k += 1
ans[idx] = k
q.append((u, k))
k += 1
print((max(ans)+1))
for a in ans: print((a+1))
if __name__ == '__main__':
main()
|
p02850
|
n = int(eval(input()))
ikeru = [[] for _ in range(n)]
for i in range(n-1):
a, b = list(map(int, input().split()))
ikeru[a-1].append((b-1, i))
settansaku = set([])
setmada = {0}
listmada = [(0, None)] #left: Vertex, right: Color
kouho = 1
num = [0 for _ in range(n-1)]
while kouho != 0:
for i, cnt in listmada[:]:
colors = {cnt}
settansaku.add(i)
setmada.remove(i)
listmada.remove((i, cnt))
kouho -= 1
for k, j in ikeru[i]:
if not k in setmada:
if not k in settansaku:
setmada.add(k)
c = 0
while True:
if c not in colors:
listmada.append((k, c))
colors.add(c)
num[j] = c
break
c += 1
kouho += 1
print((max(num)+1))
print(("\n".join([str(i+1) for i in num])))
|
n = int(eval(input()))
ikeru = [[] for _ in range(n)]
for i in range(n-1):
a, b = list(map(int, input().split()))
ikeru[a-1].append((b-1, i))
settansaku = set([])
setmada = {0}
listmada = [(0, None)] #left: Vertex, right: Color
kouho = 1
num = [0 for _ in range(n-1)]
while kouho != 0:
for i, cnt in listmada[:]:
colors = {cnt}
settansaku.add(i)
setmada.remove(i)
listmada.remove((i, cnt))
kouho -= 1
c = 0
for k, j in ikeru[i]:
if not k in setmada:
if not k in settansaku:
setmada.add(k)
while True:
if c not in colors:
listmada.append((k, c))
colors.add(c)
num[j] = c
break
c += 1
kouho += 1
print((max(num)+1))
print(("\n".join([str(i+1) for i in num])))
|
p02850
|
from collections import deque
N = int(eval(input()))
edge = [[] for _ in range(N)]
for i in range(N - 1):
a, b = list(map(int, input().split()))
edge[a - 1].append((b - 1, i))
edge[b - 1].append((a - 1, i))
ec = [0] * (N - 1)
def bfs():
q = deque()
q.append((0, 0))
while len(q):
v, pc = q.popleft()
color = 1
for e in edge[v]:
if color == pc:
color += 1
if ec[e[1]] == 0:
ec[e[1]] = color
q.append((e[0], color))
color += 1
bfs()
print((max(ec)))
for c in ec:
print(c)
|
import sys
sys.setrecursionlimit(10 ** 6)
def dfs(v, c):
nc = 0
k = 0
for nv, idx in edge[v]:
if status[nv] == 0:
nc = nc + 1 + ((nc + 1) == c)
color[idx] = nc
status[nv] = 1
k = max(k, dfs(nv, nc))
return max(nc, k)
N = int(eval(input()))
edge = [[] for _ in range(N)]
for idx, line in enumerate(sys.stdin.readlines()):
a, b = [int(x) - 1 for x in line.split()]
edge[a].append((b, idx))
edge[b].append((a, idx))
status = [0] * N
color = [0] * (N - 1)
status[0] = 1
K = dfs(0, 0)
print(K)
for c in color:
print(c)
|
p02850
|
from collections import deque
n = int(eval(input()))
ab = [list(map(int,input().split())) for i in range(n-1)]
ver = [[] for i in range(n)]
for i in range(n-1):
a,b = ab[i][0],ab[i][1]
ver[a-1].append(b-1)
ver[b-1].append(a-1)
#print(ver)
color = [dict() for i in range(n)]
q = deque()
i = 1
for v in ver[0]:
color[0][v] = i
color[v][0] = i
q.append((0,v))
i += 1
#print(q)
while q:
f,t = q.popleft()
i = 1
for v in ver[t]:
if v == f:
continue
if i == color[f][t]:
i += 1
color[t][v] = i
color[v][t] = i
q.append((t,v))
i += 1
#print(color)
k = 0
for i in range(n):
k = max(k,len(ver[i]))
print(k)
for i in range(n-1):
a,b = ab[i][0],ab[i][1]
print((color[a-1][b-1]))
|
import sys
sys.setrecursionlimit(10**8)
n = int(eval(input()))
edge = [[] for i in range(n)]
for i in range(n-1):
a,b = list(map(int,input().split()))
edge[a-1].append((b-1,i))
edge[b-1].append((a-1,i))
k = max(len(e) for e in edge)
print(k)
ans = [-1]*(n-1)
def dfs(v=0, p=-1, to_p_col = -1):
col = 1
for u, idx in edge[v]:
if u != p:
if col == to_p_col:
col += 1
ans[idx] = col
dfs(u, v, col)
col += 1
dfs()
print(('\n'.join(map(str,ans))))
|
p02850
|
# -*- coding: utf-8 -*-
"""
D - Coloring Edges on Tree
https://atcoder.jp/contests/abc146/tasks/abc146_d
"""
import sys
from collections import OrderedDict, deque
def main(args):
N = int(eval(input()))
G = [[] for _ in range(N+1)]
res = OrderedDict()
for _ in range(N-1):
a, b = list(map(int, input().split()))
res[(a, b)] = -1
G[a].append(b)
G[b].append(a)
k = max(len(g) for g in G)
colors = [set(range(1, k+1)) for _ in range(N+1)]
q = deque([1])
visited = set([1])
while q:
cn = q.popleft()
for nn in G[cn]:
if nn not in visited:
visited.add(nn)
q.append(nn)
c = min(colors[cn])
colors[cn].discard(c)
colors[nn].discard(c)
if (cn, nn) in res:
res[(cn, nn)] = c
if (nn, cn) in res:
res[(nn, cn)] = c
print(k)
for v in list(res.values()):
print(v)
if __name__ == '__main__':
main(sys.argv[1:])
|
# -*- coding: utf-8 -*-
"""
D - Coloring Edges on Tree
https://atcoder.jp/contests/abc146/tasks/abc146_d
"""
import sys
from collections import OrderedDict, deque
def main(args):
N = int(eval(input()))
G = [[] for _ in range(N+1)]
res = OrderedDict()
for _ in range(N-1):
a, b = list(map(int, input().split()))
res[(a, b)] = -1
G[a].append(b)
G[b].append(a)
k = max(len(g) for g in G)
colors = [0 for _ in range(N+1)]
q = deque([1])
visited = set([1])
while q:
cn = q.popleft()
color = 1
for nn in G[cn]:
if nn not in visited:
if color == colors[cn]:
color += 1
visited.add(nn)
q.append(nn)
c = color
colors[nn] = color
color += 1
if (cn, nn) in res:
res[(cn, nn)] = c
if (nn, cn) in res:
res[(nn, cn)] = c
print(k)
for v in list(res.values()):
print(v)
if __name__ == '__main__':
main(sys.argv[1:])
|
p02850
|
"""Coloring Edges on Tree
https://atcoder.jp/contests/abc146/tasks/abc146_d
"""
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 5 + 1)
class Node:
def __init__(self, num):
self.num = num
self.edge = set()
self.edge_color = set()
def dfs(node, p):
used_color = node.edge_color
for e in node.edge:
if e != p:
# 子のノードを取得
child = tree[e]
child_used_color = child.edge_color
# このnodeと子のノードでまだ使っていない色を特定
unused_colors = colors - (used_color | child_used_color)
if len(unused_colors) == 0:
color_num = max(colors) + 1
colors.add(color_num)
else:
color_num = min(unused_colors)
# このノードと、子のノードに使用ずみの色をマーク
node.edge_color.add(color_num)
child.edge_color.add(color_num)
# 答えを記録
if a < b:
ans['{0} {1}'.format(node.num, child.num)] = color_num
else:
ans['{0} {1}'.format(child.num, node.num)] = color_num
# 掘る
dfs(child, node.num)
N = int(eval(input()))
ans = {}
colors = {1}
# treeの初期化
tree = [Node(i) for i in range(0, N + 1)]
edges = []
for i in range(N - 1):
a, b = list(map(int, input().split()))
tree[a].edge.add(b)
tree[b].edge.add(a)
if a < b:
edges.append('{0} {1}'.format(a, b))
else:
edges.append('{0} {1}'.format(b, a))
dfs(tree[1], -1)
# print("edges:{}".format(edges))
print((len(colors)))
# print(ans)
for edge in edges:
# print(edge)
print((str(ans.get(edge))))
|
"""Coloring Edges on Tree
https://atcoder.jp/contests/abc146/tasks/abc146_d
"""
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 5 + 1)
class Node:
def __init__(self, num):
self.num = num
self.edge = set()
self.edge_color = set()
def dfs(node, c = -1 , p = -1):
k = 1
for e in node.edge:
if e == p:
continue
if k == c:
k += 1
# 子のノードを取得
child = tree[e]
# 答えを記録
if a < b:
ans['{0} {1}'.format(node.num, child.num)] = k
else:
ans['{0} {1}'.format(child.num, node.num)] = k
k += 1
# 掘る
dfs(child,k - 1, node.num)
N = int(eval(input()))
ans = {}
# colors = {1}
# treeの初期化
tree = [Node(i) for i in range(0, N + 1)]
edges = []
for i in range(N - 1):
a, b = list(map(int, input().split()))
tree[a].edge.add(b)
tree[b].edge.add(a)
if a < b:
edges.append('{0} {1}'.format(a, b))
else:
edges.append('{0} {1}'.format(b, a))
dfs(tree[1], -1)
# print("edges:{}".format(edges))
# print(max(c))
# print(ans)
count = 0
for node in tree:
count = max(count, len(node.edge))
print(count)
for edge in edges:
# print(edge)
print((str(ans.get(edge))))
|
p02850
|
import collections
N=int(eval(input()))
AB=[list(map(int,input().split())) for i in range(N-1)]
AB_C=[0 for i in range(N-1)]
D=collections.Counter([i[0] for i in AB]+[i[1] for i in AB]).most_common()
M=D[0][1]
print(M)
data=[set() for i in range(N+1)]
idxdata=set([i for i in range(N-1)])
d=0
while idxdata or d<=2:
#print(idxdata)
count_c=1
delidx=set()
for i in idxdata:
a,b=AB[i]
if a==D[d][0] or b==D[d][0]:
while not(count_c not in data[a] and count_c not in data[b]):
count_c+=1
AB_C[i]=count_c
data[a].add(count_c)
data[b].add(count_c)
delidx.add(i)
d+=1
idxdata=idxdata-delidx
for i in idxdata:
a,b=AB[i]
#print(a,b,"a,b")
for m in range(1,M+1):
if m not in data[a] and m not in data[b]:
data[a].add(m)
data[b].add(m)
print(m)
break
for i in AB_C:
print(i)
|
from collections import deque
N=int(eval(input()))
AB=[list(map(int,input().split())) for i in range(N-1)]
P=[set() for i in range(N+1)]
C=[set() for i in range(N+1)]
for a,b in AB:
P[a].add(b)
P[b].add(a)
Cpath={}
stack=deque([1])
delset=set()
while stack:
#print(C)
#print(Cpath,"Cpath")
a=stack[0]
count=1
for b in P[a]:
#b=P[a][-1]
while count in C[a]:
count+=1
C[a].add(count)
C[b].add(count)
Cpath[(a,b) if a<b else (b,a)]=count
stack.append(b)
#P[a].remove(b)
P[b].remove(a)
P[a].clear()
stack.popleft()
print((max([Cpath[i] for i in Cpath])))
for a,b in AB:
print((Cpath[(a,b)]))
|
p02850
|
from collections import deque
N = int(eval(input()))
B = []
L = []
for i in range(N-1):
ta,tb = list(map(int,input().split()))
B.append(ta)
B.append(tb)
L.append([ta,tb])
B =B[1::2]
E = [[] for _ in range(N + 1)]
for a, b in L:
E[a].append(b)
Q = deque([1])
C = [0] * (N + 1)
while Q:
v = Q.popleft()
c = 0
for u in E[v]:
c += 1 + (c + 1 == C[v])
C[u] = c
Q.append(u)
print((max(C)))
print(("\n".join(str(C[b]) for b in B)))
|
def main():
from collections import deque
N = int(eval(input()))
B = []
L = []
for i in range(N-1):
ta,tb = list(map(int,input().split()))
B.append(ta)
B.append(tb)
L.append([ta,tb])
B =B[1::2]
E = [[] for _ in range(N + 1)]
for a, b in L:
E[a].append(b)
Q = deque([1])
C = [0] * (N + 1)
while Q:
v = Q.popleft()
c = 0
for u in E[v]:
c += 1 + (c + 1 == C[v])
C[u] = c
Q.append(u)
print((max(C)))
print(("\n".join(str(C[b]) for b in B)))
main()
|
p02850
|
n = int(eval(input()))
arr = []
for i in range(n-1):
arr.append([int(s) for s in input().split(" ")])
mmk = [[0 for i in range(n+1)] for i in range(n+1)]
childNodeNums = [0 for i in range(n)]
childNodeStatus = [-1 for i in range(n)]
nodeLines = [0 for i in range(n - 1)]
def prepare(n, arr):
s = [[] for i in range(n)]
for ar in arr:
s[ar[0] - 1].append(ar[1] - 1)
s[ar[1] - 1].append(ar[0] - 1)
return s
# x为记录入边的颜色
def dfs(currentNode, arr, x):
childNodes = arr[currentNode]
if len(childNodes) == 0:
return
childNodeNums[currentNode] = childNodeNums[currentNode] + len(arr[currentNode])
childNodeStatus[currentNode] = 1
kk = 0
for i, childNodeIndex in enumerate(childNodes):
if childNodeStatus[childNodeIndex] == -1:
kk = kk + 1
if x == kk:
kk = kk + 1
mmk[currentNode+1][childNodeIndex+1] = kk
dfs(childNodeIndex, arr, kk)
data = prepare(n, arr)
dfs(0, data, -1)
print((max(childNodeNums)))
for ar in arr:
a0 = ar[0]
a1 = ar[1]
print((mmk[a0][a1]))
|
from sys import setrecursionlimit
def genid(a, b):
if b < a:
a, b = b, a
return a * 100000 + b
def paint(currentNode, usedColor, parentNode, edges, colors):
color = 1
for childNode in edges[currentNode]:
if childNode == parentNode:
continue
if color == usedColor:
color += 1
colors[genid(currentNode, childNode)] = color
paint(childNode, color, currentNode, edges, colors)
color += 1
setrecursionlimit(100000)
N = int(eval(input()))
ab = [list(map(int, input().split())) for _ in range(N - 1)]
edges = [[] for _ in range(N)]
for a, b in ab:
edges[a - 1].append(b - 1)
edges[b - 1].append(a - 1)
colors = {}
paint(0, -1, -1, edges, colors)
print((max(len(e) for e in edges)))
for a, b in ab:
print((colors[genid(a - 1, b - 1)]))
|
p02850
|
from collections import defaultdict
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
n = int(eval(input()))
ab = []
edges = [[]for _ in range(n)]
for _ in range(n-1):
a, b = list([int(x)-1 for x in input().split()])
edges[a].append(b)
edges[b].append(a)
ab.append((a, b))
colors = defaultdict(int)
k = 1
init_v = 0
for v in range(n):
if k < len(edges[v]):
k = len(edges[v])
init_v = v
# v-v2間の色をぬる
def dfs(v, parent):
# v-parent間で使用済みの色は使えない
if v < parent:
palette = [i for i in range(k, 0, -1) if i != colors[(v, parent)]]
else:
palette = [i for i in range(k, 0, -1) if i != colors[(parent, v)]]
for v2 in edges[v]:
if v2 == parent:
continue
color = palette.pop()
if v2 < v:
colors[(v2, v)] = color
else:
colors[(v, v2)] = color
dfs(v2, v)
dfs(init_v, -1)
print(k)
for a, b in ab:
print((colors[(a, b)]))
|
from collections import defaultdict
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
n = int(eval(input()))
ab = []
edges = [[]for _ in range(n)]
for _ in range(n-1):
a, b = list([int(x)-1 for x in input().split()])
edges[a].append(b)
edges[b].append(a)
ab.append((a, b))
colors = defaultdict(int)
k = 1
init_v = 0
for v in range(n):
if k < len(edges[v]):
k = len(edges[v])
init_v = v
def dfs(v, parent):
palette = [i for i in range(len(edges[v])+1, 0, -1)
if i != colors[(parent, v)]]
for v2 in edges[v]:
if v2 == parent:
continue
color = palette.pop()
colors[(v2, v)] = color
colors[(v, v2)] = color
dfs(v2, v)
dfs(init_v, -1)
print(k)
for a, b in ab:
print((colors[(a, b)]))
|
p02850
|
from collections import deque
n = int(eval(input()))
e = [list(map(int, input().split())) for _ in range(n-1)]
c = [0 for _ in range(n-1)]
cmap = [[0 for _ in range(n)] for _ in range(n)]
for l in e:
cmap[l[0]-1][l[1]-1] = cmap[l[1]-1][l[0]-1]=-1
d = deque()
d.append(1)
while(d):
ed = d.popleft() -1
clist = list()
usedc = set()
for i in range(n):
if cmap[ed][i]:
clist.append([i, cmap[ed][i]])
usedc.add(cmap[ed][i])
for color in clist:
if color[1] == -1:
d.append(color[0]+1)
cn = 1
while(1):
if cn in usedc:
cn+=1
else:
usedc.add(cn)
break
cmap[ed][color[0]] = cmap[color[0]][ed] = cn
for i in range(n-1):
c[i] = cmap[e[i][0]-1][e[i][1]-1]
print((max(c)))
for num in c:
print(num)
|
from collections import deque
n = int(eval(input()))
ls = [list() for _ in range(n)]
ls2 = [list() for _ in range(n)]
edge = []
for i in range(n-1):
x,y = list(map(int,input().split()))
ls[x-1].append(i)
ls2[y-1].append(i)
edge.append([x-1,y-1])
d = deque()
color = [0]*(n-1)
d.append(0)
while len(d):
c = d.pop()
cl = []
for i in ls2[c]:
if color[i]:
cl.append(color[i])
idx = 1
for i in ls[c]:
while(1):
if not idx in cl:
break
else:
idx += 1
color[i] = idx
cl.append(idx)
d.append(edge[i][1])
print((max(color)))
for i in color:
print(i)
|
p02850
|
class ColorMgmt:
def __init__(self, n):
self.colors_hash = [set() for _ in range(n)]
self.next_colors = [1] * n
def set_color(self, v, c):
self.colors_hash[v].add(c)
if self.next_colors[v] != c:
return
cnt = 1
while cnt in self.colors_hash[v]:
cnt += 1
self.next_colors[v] = cnt
def get_color(self, v):
return self.next_colors[v]
N = int(eval(input()))
ab = [list(map(int, input().split())) for _ in range(N-1)]
edge = [[] for _ in range(N)]
edge_cnt = [0] * N
for idx, (a, b) in enumerate(ab):
a, b = a-1, b-1
edge[a].append([b, a, 0, idx])
edge_cnt[a] += 1
edge_cnt[b] += 1
K = max(edge_cnt)
next_list = []
now_list = [0]
color_mgmt = ColorMgmt(N)
while len(now_list) > 0:
for v in now_list:
for idx, nextv in enumerate(edge[v]):
if v == nextv[0]:
continue
colors1 = color_mgmt.get_color(nextv[1])
colors2 = color_mgmt.get_color(nextv[0])
color = max(colors1, colors2)
color_mgmt.set_color(nextv[1], color)
color_mgmt.set_color(nextv[0], color)
edge[v][idx][2] = color
next_list.append(nextv[0])
now_list = list(next_list)
next_list = []
ret = []
for edges in edge:
for e in edges:
ret.append(e)
ret.sort(key=lambda x:x[3])
print(K)
for r in ret:
print((r[2]))
|
class ColorMgmt:
from heapq import heappop, heappush
def __init__(self, n):
self.colors_hash = [set() for _ in range(n)]
self.next_colors = [1] * n
def set_color(self, v, c):
self.colors_hash[v].add(c)
while self.next_colors[v] in self.colors_hash[v]:
self.next_colors[v] += 1
def get_color(self, v):
return self.next_colors[v]
N = int(eval(input()))
ab = [list(map(int, input().split())) for _ in range(N-1)]
edge = [[] for _ in range(N)]
edge_cnt = [0] * N
for idx, (a, b) in enumerate(ab):
a, b = a-1, b-1
edge[a].append([b, a, 0, idx])
edge_cnt[a] += 1
edge_cnt[b] += 1
K = max(edge_cnt)
next_list = []
now_list = [0]
color_mgmt = ColorMgmt(N)
while len(now_list) > 0:
for v in now_list:
for idx, nextv in enumerate(edge[v]):
if v == nextv[0]:
continue
colors1 = color_mgmt.get_color(nextv[1])
colors2 = color_mgmt.get_color(nextv[0])
color = max(colors1, colors2)
color_mgmt.set_color(nextv[1], color)
color_mgmt.set_color(nextv[0], color)
edge[v][idx][2] = color
next_list.append(nextv[0])
now_list = list(next_list)
next_list = []
ret = []
for edges in edge:
for e in edges:
ret.append(e)
ret.sort(key=lambda x:x[3])
print(K)
for r in ret:
print((r[2]))
|
p02850
|
import collections
import sys
input = sys.stdin.readline
N = int(eval(input()))
ab = [list(map(int, input().split())) for i in range(N-1)]
eda = [set() for i in range(N)]
for a, b in ab:
eda[a-1].add(b)
eda[b-1].add(a)
max_e = 0
for i in range(N-1):
max_e = max(max_e, len(eda[i]))
id = 0
for i in range(N):
if len(eda[i]) == max_e:
id = i
q = collections.deque([(id, 0)])
print(max_e)
d = dict()
for a, b in ab:
d[(a-1, b-1)] = 0
d[(b-1, a-1)] = 0
eda2 = [set() for j in range(N)]
g = [set() for i in range(N)]
for a, b in ab:
g[a-1].add(b-1)
g[b-1].add(a-1)
while(q):
x, color = q.popleft()
i = 1
for y in g[x]:
if i == color:
i += 1
d[(x, y)] = i
d[(y, x)] = i
g[y].remove(x)
q.append((y, i))
i += 1
for a, b in ab:
print((d[(a-1, b-1)]))
|
import collections
N = int(input())
G = [set() for i in range(N)]
ab = [tuple(map(int, input().split())) for i in range(N-1)]
d = dict()
i = 0
for a, b in ab:
a -= 1
b -= 1
d[(a, b)] = i
d[(b, a)] = i
i += 1
G[a].add(b)
G[b].add(a)
q = collections.deque()
r = set()
r.add(0)
q.append((0, 0))
ans = [0]*(N-1)
while(q):
x, s = q.popleft()
i = 1
for y in G[x]:
if y in r:
continue
else:
r.add(y)
if i == s:
i += 1
ans[d[(x, y)]] = i
q.append((y, i))
i += 1
print(max(ans))
print(*ans, sep='\n')
|
p02850
|
n = int(eval(input()))
ab = [list([int(x)-1 for x in input().split()]) for _ in range(n-1)]
e = [[] for _ in range(n)]
d = [[0 for _ in range(n)] for _ in range(n)]
c = [0] * n
for a, b in ab:
c[a] += 1
c[b] += 1
e[a].append(b)
e[b].append(a)
me = max(c)
print(me)
for a, b in ab:
c = [0] * n
for f in e[a]:
c[d[a][f]] = 1
for f in e[b]:
c[d[b][f]] = 1
for i, x in enumerate(c):
if x == 0:
print(i)
d[a][b] = i
d[b][a] = i
break
|
from sys import setrecursionlimit
setrecursionlimit(10 ** 6)
n = int(eval(input()))
ab = [list([int(x)-1 for x in input().split()]) for _ in range(n-1)]
e = [[] for _ in range(n)]
d = [[0 for _ in range(n)] for _ in range(n)]
c = [0] * n
for a, b in ab:
c[a] += 1
c[b] += 1
e[a].append(b)
e[b].append(a)
me = max(c)
print(me)
def func(x, p, pc):
color = 1
for z in e[x]:
if color == pc:
color += 1
if z == p:
continue
else:
d[x][z] = color
d[z][x] = color
func(z, x, color)
color += 1
func(0, -1, -1)
for a, b in ab:
print((d[a][b]))
|
p02850
|
from sys import setrecursionlimit
setrecursionlimit(10 ** 6)
n = int(eval(input()))
ab = [list([int(x)-1 for x in input().split()]) for _ in range(n-1)]
e = [[] for _ in range(n)]
d = [[0 for _ in range(n)] for _ in range(n)]
c = [0] * n
for a, b in ab:
c[a] += 1
c[b] += 1
e[a].append(b)
e[b].append(a)
me = max(c)
print(me)
def func(x, p, pc):
color = 1
for z in e[x]:
if color == pc:
color += 1
if z == p:
continue
else:
d[x][z] = color
d[z][x] = color
func(z, x, color)
color += 1
func(0, -1, -1)
for a, b in ab:
print((d[a][b]))
|
from sys import setrecursionlimit
setrecursionlimit(10 ** 6)
n = int(eval(input()))
ab = [list([int(x)-1 for x in input().split()]) for _ in range(n-1)]
e = [[] for _ in range(n)]
d = [[0 for _ in range(n)] for _ in range(n)]
c = [0] * n
for a, b in ab:
e[a].append(b)
e[b].append(a)
me = 0
for i in range(n):
me = max(me, len(e[i]))
print(me)
def func(x, p, pc):
color = 1
for z in e[x]:
if color == pc:
color += 1
if z == p:
continue
else:
d[x][z] = color
d[z][x] = color
func(z, x, color)
color += 1
func(0, -1, -1)
for a, b in ab:
print((d[a][b]))
|
p02850
|
from collections import defaultdict, deque
N = int(eval(input()))
E = [[] for _ in range(N+1)]
inp = []
for i in range(N-1):
a, b = list(map(int, input().split()))
E[a].append(b)
E[b].append(a)
inp.append((a, b))
# node: (id, parent_id)
root_node = (1, -1)
open_list = deque([root_node])
n2c = defaultdict(list)
ans = {}
colors = [-1]*(N-1)
while open_list:
cur_node = open_list.popleft()
cur_id, parent_id = cur_node
adj_id_list = E[cur_id]
for child_id in adj_id_list:
if child_id == parent_id:
continue
color = 1
while True:
if not color in n2c[cur_id]:
n2c[cur_id].append(color)
n2c[child_id].append(color)
ans[(cur_id, child_id)] = color
break
color += 1
open_list.append((child_id, cur_id))
print((max(list([len(x) for x in list(n2c.values())]))))
for a, b in inp:
if (a, b) in list(ans.keys()):
print((ans[(a, b)]))
else:
print((ans[(b, a)]))
|
from collections import defaultdict, deque
N = int(eval(input()))
E = [[] for _ in range(N+1)]
edge_order = []
for i in range(N-1):
a, b = list(map(int, input().split()))
E[a].append(b)
E[b].append(a)
edge_order.append(b)
# node: (id, parent_id)
root_node = (1, -1)
open_list = deque([root_node])
ans = {}
colors = [-1]*(N+1)
while open_list:
cur_node = open_list.popleft()
cur_id, parent_id = cur_node
adj_id_list = E[cur_id]
c = 1
for child_id in adj_id_list:
if child_id == parent_id:
continue
if c == colors[cur_id]:
c += 1
colors[child_id] = c
c += 1
open_list.append((child_id, cur_id))
print((max(colors)))
for i in edge_order:
print((colors[i]))
|
p02850
|
import sys
from collections import deque
input = sys.stdin.readline
N = int(eval(input()))
graph = [[] for _ in range(N)]
ab = [list([int(x)-1 for x in input().split()]) for _ in range(N-1)]
col_max = 0
for i in range(N-1):
a, b = ab[i]
graph[a] += [b]
graph[b] += [a]
for i in range(N):
col_max = max(col_max, len(graph[i]))
print(col_max)
def bfs(s):
q = deque([s])
col = [-1]*N
col[s] = 0
edge_col = {}
while q:
c = 1
u = q.pop()
for v in graph[u]:
if col[v] == -1:
if c == col[u]:
c += 1
col[v] = c
q.append(v)
edge_col[(u, v)] = c
edge_col[(v, u)] = c
c += 1
return edge_col
col = bfs(0)
for a, b in ab:
print((col[(a, b)]))
|
import sys
sys.setrecursionlimit(1000000000)
input = sys.stdin.readline
N = int(eval(input()))
graph = [[] for _ in range(N)]
ab = [list([int(x)-1 for x in input().split()]) for _ in range(N-1)]
d = {}
for a, b in ab:
graph[a] += [b]
graph[b] += [a]
def dfs(u, pre, c):
color = 0
for v in graph[u]:
if v != pre:
color += 1
if color == c:
color += 1
d[(u, v)] = color
d[(v, u)] = color
dfs(v, u, color)
dfs(0, -1, -1)
s = set()
for a, b in ab:
s.add(d[(a, b)])
print((len(s)))
for a, b in ab:
print((d[(a, b)]))
|
p02850
|
from collections import deque, Counter
N = int(eval(input()))
edge = [[] for i in range(N-1)]
to = [[] for i in range(N)]
color = {}
edge_list = []
for i in range(N-1):
a, b = list(map(int, input().split()))
to[a-1].append(b-1)
to[b-1].append(a-1)
edge[i] = [a-1, b-1]
edge_list.append(a-1)
edge_list.append(b-1)
K = Counter(edge_list).most_common()[0][1]
q = deque([])
q.append([0,-1])
is_visited = [False] * N
while(len(q) != 0):
cur_node, pre_col = q.popleft()
col_list = [False] * K
if not pre_col == -1:
col_list[pre_col] = True
is_visited[cur_node] = True
for next_node in to[cur_node]:
if not is_visited[next_node]:
for i in range(K):
if not col_list[i]:
col_list[i] = True
color[(cur_node,next_node)] = i
q.append([next_node, i])
break
print(K)
for i in range(N-1):
print((color[tuple(edge[i])] + 1))
|
from collections import deque, Counter
N = int(eval(input()))
edge = [[] for i in range(N-1)]
to = [[] for i in range(N)]
color = {}
edge_list = []
for i in range(N-1):
a, b = list(map(int, input().split()))
to[a-1].append(b-1)
to[b-1].append(a-1)
edge[i] = [a-1, b-1]
edge_list.append(a-1)
edge_list.append(b-1)
K = Counter(edge_list).most_common()[0][1]
q = deque([])
q.append([0,-1])
is_visited = [False] * N
while(len(q) != 0):
cur_node, pre_col = q.popleft()
is_visited[cur_node] = True
col_use = 0
for next_node in to[cur_node]:
if not is_visited[next_node]:
if col_use == pre_col:
col_use += 1
color[(cur_node,next_node)] = col_use
q.append([next_node, col_use])
col_use += 1
print(K)
for i in range(N-1):
print((color[tuple(edge[i])] + 1))
|
p02850
|
from collections import deque
n = int(eval(input()))
matrix= []
lis = [[] for i in range(n)]
ans = [[0 for i in range(n)] for j in range(n)]
for i in range(n-1):
a,b = list(map(int, input().split()))
a -= 1
b -= 1
matrix.append(sorted([a,b]))
lis[a].append(b)
lis[b].append(a)
color = [-1 for _ in range(n)]
queue = deque([0])
color[0] = 1001001001
maxc = 0
while len(queue) > 0:
now = queue.pop()
used = color[now]
tmp = 1
for i in lis[now]:
if color[i] == -1:
queue.append(i)
if tmp == used:
tmp += 1
color[i] = tmp
ans[now][i] = tmp
ans[i][now] = tmp
maxc = max(maxc, tmp)
tmp += 1
print(maxc)
for i in range(n-1):
root = matrix[i]
print((ans[root[0]][root[1]]))
|
from collections import deque
n = int(eval(input()))
matrix= []
lis = [[] for i in range(n)]
ans = {}
for i in range(n):
ans[i] = {}
for i in range(n-1):
a,b = list(map(int, input().split()))
a -= 1
b -= 1
matrix.append(sorted([a,b]))
lis[a].append(b)
lis[b].append(a)
color = [-1 for _ in range(n)]
queue = deque([0])
color[0] = 1001001001
maxc = 0
while len(queue) > 0:
now = queue.pop()
used = color[now]
tmp = 1
for i in lis[now]:
if color[i] == -1:
queue.append(i)
if tmp == used:
tmp += 1
color[i] = tmp
ans[now][i] = tmp
ans[i][now] = tmp
maxc = max(maxc, tmp)
tmp += 1
print(maxc)
for i in range(n-1):
root = matrix[i]
print((ans[root[0]][root[1]]))
|
p02850
|
import heapq
import collections
from collections import deque
n = int(eval(input()))
ab = []
visit = [-1 for _ in range(n+1)]
tree = [[] for _ in range(n+1)]
for i in range(n-1):
a, b = list(map(int,input().split()))
ab.append([a, b])
tree[a].append(b)
tree[b].append(a)
colors = [ [-1] * (n + 1) for _ in range(n + 1)] # abの色を格納
visit[1]=1
q = deque([(1,0)]) #V,color のtuple
K = 0
while q:
v,from_color = q.popleft()
c = 1
for next_v in tree[v]:
if visit[next_v] == -1:
visit[next_v] = 1
if c == from_color:
c += 1
colors[v][next_v] = colors[next_v][v] = c
q.append((next_v,c))
c += 1
anss = []
K = 0
for temp in ab:
a,b = temp
K = max(K, colors[a][b])
anss.append(colors[a][b])
print(K)
for c in anss:
print(c)
# for k,v in di:
# color = max(colors,len(v))
|
import heapq
import collections
from collections import deque
n = int(eval(input()))
ab = []
visit = [-1 for _ in range(n+1)]
tree = [[] for _ in range(n+1)]
colors = {}
for i in range(n-1):
a, b = list(map(int,input().split()))
ab.append((a, b))
tree[a].append(b)
tree[b].append(a)
colors[(a,b)] = -1
colors[(b,a)] = -1
# abの色を格納
visit[1]=1
q = deque([(1,0)]) #V,color のtuple
K = 0
while q:
v,from_color = q.popleft()
c = 1
for next_v in tree[v]:
if visit[next_v] == -1:
visit[next_v] = 1
if c == from_color:
c += 1
colors[(v,next_v)] = colors[(next_v,v)] = c
q.append((next_v,c))
c += 1
anss = []
K = 0
for temp in ab:
a,b = temp
K = max(K, colors[(a,b)] )
anss.append(colors[(a,b)])
print(K)
for c in anss:
print(c)
# for k,v in di:
# color = max(colors,len(v))
|
p02850
|
N = int(eval(input()))
ab = [list(map(int, input().split())) for i in range(N-1)]
tree = {i:[] for i in range(1, N+1)}
for a, b in ab:
tree[a].append(b)
tree[b].append(a)
stree = sorted(list(tree.items()), key=lambda x: -len(x[1]))
print((len(stree[0][1])))
start = stree[0][0]
colormap = {i:[0]*(N+1) for i in range(1, N+1)}
from collections import deque
q = deque([start])
visited = {start}
while q:
n = q.popleft()
for p in tree[n]:
if p in visited:
continue
i = 1
while True:
if i not in colormap[n] and i not in colormap[p]:
colormap[n][p] = i
colormap[p][n] = i
break
i += 1
if p not in visited:
q.append(p)
visited.add(p)
for a, b in ab:
print((colormap[a][b]))
|
from collections import deque
N = int(input())
ab = [list(map(int, input().split())) for i in range(N-1)]
tree = [list() for _ in range(N+1)]
color = [0] * (N-1)
for i, (a, b) in enumerate(ab):
tree[a].append((b, i))
q = deque([(1, 0)]) # パス先, パスの色でキューに追加
while q:
v, pc = q.popleft()
nc = 0 # 使用する色
for nv, edge in tree[v]: # nv=パス先 edge=abでの順番
nc += 1
if nc == pc: # 渡ってきたパスの色と同じなら+1した色にする
nc += 1
color[edge] = nc # 使用する色を答えのリストに格納
q.append((nv, nc))
print(max(color))
print(*color, sep="\n")
|
p02850
|
import sys
N = int(sys.stdin.buffer.readline())
neighbor = [[] for _ in range(N)]
edge = []
for i in range(N-1):
a, b = list(map(int, sys.stdin.buffer.readline().split()))
neighbor[a-1].append(b-1)
neighbor[b-1].append(a-1)
edge.append([a-1, b-1, i])
K = len(max(neighbor, key=len))
print(K)
color = [set(range(1, K+1)) for _ in range(N)]
edge = sorted(edge, key = lambda x:x[0])
for idx in range(N-1):
c = color[edge[idx][0]].pop()
edge[idx].append(c)
color[edge[idx][1]].remove(c)
edge = sorted(edge, key=lambda x: x[2])
for x in edge:
print((x[-1]))
|
import sys
sys.setrecursionlimit(500000)
N = int(sys.stdin.buffer.readline())
neighbor = [[] for _ in range(N)]
for i in range(N-1):
a, b = list(map(int, sys.stdin.buffer.readline().split()))
neighbor[a-1].append([b-1, i])
neighbor[b-1].append([a-1, i])
K = max(len(l) for l in neighbor)
print(K)
ans = [-1]*(N-1)
def dfs(current_point, parent_point, parent_edge_color):
color = 1
for next_point, idx in neighbor[current_point]:
if next_point != parent_point:
if parent_edge_color == color:
color += 1
ans[idx] = color
dfs(next_point, current_point, color)
color += 1
dfs(0, -1, -1)
print(("\n".join(map(str, ans))))
|
p02850
|
import sys
# import re
# import math
# import collections
# import decimal
# import bisect
# import itertools
# import fractions
# import functools
# import copy
# import heapq
# import decimal
# import statistics
import queue
sys.setrecursionlimit(10000001)
INF = 10 ** 16
MOD = 10 ** 9 + 7
ni = lambda: int(sys.stdin.readline())
ns = lambda: list(map(int, sys.stdin.readline().split()))
na = lambda: list(map(int, sys.stdin.readline().split()))
# ===CODE===
def main():
n = ni()
edge = [[] for i in range(n)]
origin_edge = []
edge_dic = {}
for i in range(n - 1):
a, b = ns()
a -= 1
b -= 1
edge[a].append(b)
edge[b].append(a)
edge_dic[(a, b)] = -1
origin_edge.append((a, b))
max_root = 0
for e in edge:
max_root = max(max_root, len(e))
node_unused_color = [{i for i in range(max_root)} for j in range(n)]
que = queue.Queue()
que.put(0)
while que.qsize() > 0:
node = que.get()
for k in edge[node]:
ai = min(node, k)
bi = max(node, k)
if edge_dic[(ai, bi)] > -1:
continue
chosen_color = -1
for tmp_a in node_unused_color[ai]:
if tmp_a in node_unused_color[bi]:
chosen_color = tmp_a
break
node_unused_color[ai] -= {chosen_color}
node_unused_color[bi] -= {chosen_color}
edge_dic[(ai, bi)] = chosen_color
que.put(k)
print(max_root)
for a, b in origin_edge:
print((edge_dic[(a, b)] + 1))
if __name__ == '__main__':
main()
|
import sys
# import re
# import math
# import collections
# import decimal
# import bisect
# import itertools
# import fractions
# import functools
# import copy
# import heapq
# import decimal
# import statistics
import queue
sys.setrecursionlimit(10000001)
INF = 10 ** 16
MOD = 10 ** 9 + 7
ni = lambda: int(sys.stdin.readline())
ns = lambda: list(map(int, sys.stdin.readline().split()))
na = lambda: list(map(int, sys.stdin.readline().split()))
# ===CODE===
def main():
n = ni()
edge = [[] for i in range(n)]
origin_edge = []
edge_dic = {}
for i in range(n - 1):
a, b = ns()
a -= 1
b -= 1
edge[a].append(b)
edge[b].append(a)
edge_dic[(a, b)] = -1
origin_edge.append((a, b))
max_root = 0
for e in edge:
max_root = max(max_root, len(e))
que = queue.Queue()
que.put((0, -1))
while que.qsize() > 0:
node, used_color = que.get()
current_color = 0 if used_color != 0 else 1
for k in edge[node]:
ai = min(node, k)
bi = max(node, k)
if edge_dic[(ai, bi)] > -1:
continue
edge_dic[(ai, bi)] = current_color
que.put((k, current_color))
current_color = current_color + 1 if used_color != current_color + 1 else current_color + 2
print(max_root)
for a, b in origin_edge:
print((edge_dic[(a, b)] + 1))
if __name__ == '__main__':
main()
|
p02850
|
import sys
sys.setrecursionlimit(100000)
def rootedTree(node,parent,root,add):
A.append([node,parent,root,add])
for root_num,num in root:
if len(tree[root_num])!=0:
rootedTree(root_num,node,tree[root_num],num)
else:
A.append([root_num,node,tree[root_num],num])
n=int(eval(input()))
AB=[list(map(int,input().split()))+[i+1] for i in range(n-1)]
A=[]
tree=[[] for i in range(n+1)]
for a,b,c in AB:
tree[a] +=[[b,c]]
rootedTree(1,0,tree[1],0)
ans=[0]*n
for node,parent,root,num in A:
flag=0
for i,j in enumerate(root):
if ans[num]==i+1:flag=1
if flag:
ans[j[1]]=i+2
continue
ans[j[1]]=i+1
print((max(ans)))
for i in range(1,n):print((ans[i]))
|
import sys
sys.setrecursionlimit(100000)
def rootedTree(node,parent,root,add):
A.append([node,parent,root,add])
for root_num,num in root:
rootedTree(root_num,node,tree[root_num],num)
n=int(eval(input()))
AB=[list(map(int,input().split()))+[i+1] for i in range(n-1)]
A=[]
tree=[[] for i in range(n+1)]
for a,b,c in AB:
tree[a] +=[[b,c]]
rootedTree(1,0,tree[1],0)
ans=[0]*n
for node,parent,root,num in A:
flag=0
for i,j in enumerate(root):
if ans[num]==i+1:flag=1
if flag:
ans[j[1]]=i+2
continue
ans[j[1]]=i+1
print((max(ans)))
for i in range(1,n):print((ans[i]))
|
p02850
|
import sys
sys.setrecursionlimit(100000)
def rootedTree(node,parent,root,num):
A.append([node,parent,root,num])
for root_num,num in root:
rootedTree(root_num,node,tree[root_num],num)
n=int(eval(input()))
AB=[list(map(int,input().split()))+[i+1] for i in range(n-1)]
A=[]
tree=[[] for i in range(n+1)]
for a,b,c in AB:
tree[a] +=[[b,c]]
rootedTree(1,0,tree[1],0)
ans=[0]*n
for node,parent,root,num in A:
flag=0
for i,j in enumerate(root):
if ans[num]==i+1:flag=1
ans[j[1]]=i+1+flag
print((max(ans)))
for i in range(1,n):print((ans[i]))
|
import sys
sys.setrecursionlimit(10**7)
def rootedTree(node,parent,root,num):
A.append([node,parent,root,num])
for root_num,num in root:
rootedTree(root_num,node,tree[root_num],num)
n=int(eval(input()))
AB=[list(map(int,input().split()))+[i+1] for i in range(n-1)]
A=[]
tree=[[] for i in range(n+1)]
for a,b,c in AB:
tree[a] +=[[b,c]]
rootedTree(1,0,tree[1],0)
ans=[0]*n
for node,parent,root,num in A:
flag=0
for i,j in enumerate(root):
if ans[num]==i+1:flag=1
ans[j[1]]=i+1+flag
print((max(ans)))
for i in range(1,n):print((ans[i]))
|
p02850
|
from collections import deque
import sys
input = sys.stdin.readline
n = int(eval(input()))
edges = [[] for _ in range(n)]
l = []
for i in range(n-1):
a,b = list(map(int,input().split()))
edges[a-1].append(b-1)
edges[b-1].append(a-1)
l.append([a-1,b-1])
ans = [[0 for _ in range(n)] for __ in range(n)]
visited = [False]*n
q = deque([(0,0)])
visited[0] = True
mx = 0
while q:
key,v = q.popleft()
i = 1
for x in edges[v]:
if not visited[x]:
if key != i:
visited[x] = True
ans[v][x] = i
ans[x][v] = i
q.append((i,x))
mx = max(mx,i)
i += 1
else:
visited[x] = True
i += 1
ans[v][x] = i
ans[x][v] = i
q.append((i,x))
mx = max(mx,i)
i += 1
print(mx)
for i in range(n-1):
print((ans[l[i][0]][l[i][1]]))
|
from collections import deque
import sys
input = sys.stdin.readline
n = int(eval(input()))
edges = [[] for _ in range(n)]
l = {}
for i in range(n-1):
a,b = list(map(int,input().split()))
edges[a-1].append(b-1)
edges[b-1].append(a-1)
l[(a-1,b-1)]=i
l[(b-1,a-1)]=i
ans = [0]*(n-1)
visited = [False]*n
q = deque([(0,0)])
visited[0] = True
mx = 0
while q:
key,v = q.popleft()
i = 1
for x in edges[v]:
if not visited[x]:
if key != i:
visited[x] = True
ans[l[(v,x)]]=i
q.append((i,x))
mx = max(mx,i)
i += 1
else:
visited[x] = True
i += 1
ans[l[(v,x)]]=i
q.append((i,x))
mx = max(mx,i)
i += 1
print(mx)
for i in range(n-1):
print((ans[i]))
|
p02850
|
from collections import deque
n = int(eval(input()))
l = [0 for i in range(n)]
l2 = []
l3 = [[] for i in range(n+1)]
for i in range(n-1):
a,b = list(map(int,input().split()))
l2.append([a,b])
l3[a].append(b)
l3[b].append(a)
l[a-1] += 1
l[b-1] += 1
a = max(l)
print(a)
rl = [0 for i in range(n+1)]
d = deque()
d.append([1,0])
rl[1] = 1
cl = [[0 for i in range(n+1)] for i in range(n+1)]
while len(d):
now,c = d.popleft()
rl[now] = 1
if c == 0:
count = 1
for i in l3[now]:
cl[now][i] = count
d.append([i,count])
count += 1
else:
count = 1
for i in l3[now]:
if rl[i] == 0:
if c == count:
count += 1
cl[now][i] = count
d.append([i,count])
count += 1
for i in range(n-1):
print((cl[l2[i][0]][l2[i][1]]))
|
from collections import deque
n = int(eval(input()))
l = [0 for i in range(n)]
l2 = []
l3 = [[] for i in range(n+1)]
for i in range(n-1):
a,b = list(map(int,input().split()))
l2.append([a,b])
l3[a].append(b)
l3[b].append(a)
l[a-1] += 1
l[b-1] += 1
a = max(l)
print(a)
rl = [0 for i in range(n+1)]
d = deque()
d.append([1,0])
rl[1] = 1
dic = {}
while len(d):
now,c = d.popleft()
rl[now] = 1
if c == 0:
count = 1
for i in l3[now]:
dic["{0},{1}".format(now,i)] = count
d.append([i,count])
count += 1
else:
count = 1
for i in l3[now]:
if rl[i] == 0:
if c == count:
count += 1
dic["{0},{1}".format(now,i)] = count
d.append([i,count])
count += 1
for i in range(n-1):
print((dic["{0},{1}".format(l2[i][0],l2[i][1])]))
|
p02850
|
N = int(input())
A = set([i for i in range(1, 10**5)])
s = [[] for _ in range(N)]
r = []
for _ in range(N-1):
a, b = map(int, input().split())
n = min(A - set(s[a-1] + s[b-1]))
s[a-1] += [n]
s[b-1] += [n]
r.append(n)
print(max(r))
print(*r, sep='\n')
|
from collections import deque
N = int(input())
G = [[] for _ in range(N)]
for i in range(N-1):
a, b = map(int, input().split())
G[a-1].append([b-1, i])
G[b-1].append([a-1, i])
q = deque()
q.append([0, 0, 0])
colors = [0] * (N-1)
while q:
node, parent, edge_color = q.popleft()
c = 1
for child, index in G[node]:
if child == parent:
continue
if c == edge_color:
c += 1
q.append([child, node, c])
colors[index] = c
c += 1
print(max(colors))
print(*colors, sep='\n')
|
p02850
|
import sys
sys.setrecursionlimit(10**6)
n = int(eval(input()))
data = [[] for _ in range(n)]
for i in range(n-1):
a,b = list(map(int,input().split()))
a -= 1
b -= 1
data[a].append([i,b]) # i本目でbに
data[b].append([i,a])
k = max(len(data[i]) for i in range(n))
print(k)
ans = [-1 for i in range(n)]
stack = [[0,n,k]]
while stack:
now,pre,pre_path = stack.pop()
color = [True for i in range(k + 1)]
color[ans[pre_path]] = False
for nex_path, nex in data[now]:
if nex == pre: continue
for num, c in enumerate(color):
if c:
ans[nex_path] = num
color[num] = False
stack.append([nex, now, nex_path])
break
for x in ans[:-1]:
print((x+1))
|
n = int(input())
G = [[] for _ in range(n)]
d = {}
for i in range(n-1):
a,b = map(int,input().split())
a -= 1
b -= 1
G[a].append(b)
G[b].append(a)
d[(a,b)] = d[(b,a)] = i
k = 0
ans = [None]*(n-1)
stack = [(0,-1)] #node, par
while stack:
now,pre = stack.pop()
color = 1
for nex in G[now]:
if nex == pre:continue
stack.append((nex,now))
if pre != -1:
if color == ans[d[(now,pre)]]:
color += 1
ans[d[(now,nex)]] = color
k = max(k,color)
color += 1
print(k)
print(*ans, sep="\n")
|
p02850
|
import sys
input = sys.stdin.readline
N = int(eval(input()))
edges = [[int(i) for i in input().split()] for _ in range(N-1)]
edge_col = [0]*(N-1)
cols = [set() for _ in range(N)]
gp = [[] for _ in range(N)]
for ind, (a, b) in enumerate(edges):
gp[a-1].append((b-1, ind))
gp[b-1].append((a-1, ind))
seen = set()
stk = [0]
max_col = 0
while stk:
pt = stk.pop()
if(pt in seen):
continue
seen.add(pt)
for nxt, ind in gp[pt]:
if(nxt in seen):
continue
col = 1
while col in cols[pt]:
col += 1
max_col = max(col, max_col)
edge_col[ind] = col
cols[pt].add(col)
cols[nxt].add(col)
stk.append(nxt)
print(max_col)
for i in edge_col:
print(i)
|
import sys
input = sys.stdin.readline
N = int(eval(input()))
edges = [[int(i) for i in input().split()] for _ in range(N-1)]
edge_col = [0]*(N-1)
gp = [[] for _ in range(N)]
for ind, (a, b) in enumerate(edges):
gp[a-1].append((b-1, ind))
gp[b-1].append((a-1, ind))
cols = [set(list([x+1 for x in range(len(gp[i]))])) for i in range(N)]
seen = set()
stk = [0]
max_col = 0
while stk:
pt = stk.pop()
#print(pt)
if(pt in seen):
continue
seen.add(pt)
for nxt, ind in gp[pt]:
if(nxt in seen):
continue
col = cols[pt].pop()
max_col = max(col, max_col)
edge_col[ind] = col
try:
cols[nxt].remove(col)
except:
pass
stk.append(nxt)
print(max_col)
for i in edge_col:
print(i)
|
p02850
|
import sys
sys.setrecursionlimit(10**6)
def dfs(G,v,p,color):
cnt=1
for nv in G[v]:
if(nv==p):
continue
if cnt in liset[v]:
while(cnt in liset[v]):
cnt+=1
liset[v].add(cnt)
liset[nv].add(cnt)
dic[str(v)+'t'+str(nv)]=cnt
dfs(G,nv,v,cnt)
N=int(eval(input()))
G=[[] for i in range(N)]
e=[]
for i in range(N-1):
a,b=[int(x)-1 for x in input().split()]
G[a].append(b)
G[b].append(a)
e.append([a,b])
l=0
for i in range(N):
l=max(l,len(G[i]))
liset=[set() for i in range(N)]
dic={}
dfs(G,0,-1,0)
print(l)
for i in range(N-1):
if str(e[i][0])+'t'+str(e[i][1]) in dic:
print((dic[str(e[i][0])+'t'+str(e[i][1])]))
else:
print((dic[str(e[i][1])+'t'+str(e[i][0])]))
|
import sys
sys.setrecursionlimit(10**6)
def dfs(G,v,p,color):
cnt=1
for nv in G[v]:
if(nv==p):
continue
while(cnt in s[v]):
cnt+=1
s[v].add(cnt)
s[nv].add(cnt)
dic[tuple(sorted([v,nv]))]=cnt
dfs(G,nv,v,cnt)
N=int(eval(input()))
G=[[] for i in range(N)]
e=[]
s=[set() for i in range(N)]
dic={}
for i in range(N-1):
a,b=[int(x)-1 for x in input().split()]
G[a].append(b)
G[b].append(a)
e.append(sorted([a,b]))
l=0
for i in range(N):
l=max(l,len(G[i]))
dfs(G,0,-1,0)
print(l)
for i in range(N-1):
print((dic[e[i][0],e[i][1]]))
|
p02850
|
# ある頂点で、子供に対して順に1,2,3...と辺の色を渡していく
# 親から来た色を持っておき、親から来た色と同色になったときはスキップして次の色を渡す
# グラフ構築の際に、辺の番号を持っておく
import sys
readline = sys.stdin.readline
N = int(readline())
G = [[] for i in range(N)]
for i in range(N - 1):
a,b = list(map(int,readline().split()))
G[a-1].append([b-1,i])
G[b-1].append([a-1,i])
ans = [0 for i in range(N - 1)]
from collections import deque
# 頂点、親から来た色、親
q = deque([[0, 0, -1]])
while q:
v,pcol,parent = q.popleft()
cnt = 1
for child in G[v]:
if child[0] == parent:
continue
if cnt == pcol:
cnt += 1
ans[child[1]] = cnt
q.append([child[0],cnt,v])
cnt += 1
print((max(ans)))
for a in ans:
print(a)
|
import sys
readline = sys.stdin.readline
N = int(readline())
G = [[] for i in range(N)]
from collections import defaultdict
E = defaultdict(int)
for i in range(N - 1):
a,b = list(map(int,readline().split()))
G[a - 1].append(b - 1)
G[b - 1].append(a - 1)
E[(a - 1, b - 1)] = i
from collections import deque
q = deque([])
ans = [None] * (N - 1)
q.append([0, -1, 0])
maxcol = 0
while q:
v, parent, color = q.popleft()
if color > maxcol:
maxcol = color
if (v, parent) in E:
ans[E[(v, parent)]] = color
elif (parent, v) in E:
ans[E[(parent, v)]] = color
next_col = 0
for child in G[v]:
if child == parent:
continue
next_col += 1
if next_col == color:
next_col += 1
q.append([child, v, next_col])
print(maxcol)
for a in ans:
print(a)
|
p02850
|
import sys
from collections import deque
read = sys.stdin.read
N, *ab = list(map(int, read().split()))
graph = [[] for _ in range(N + 1)]
for a, b in zip(*[iter(ab)] * 2):
graph[a].append(b)
color = [0] * (N + 1)
queue = deque([1])
color_v = [[] for _ in range(N + 1)]
while queue:
V = queue.popleft()
number = 1
for v in graph[V]:
if number in color_v[V]:
number += 1
color[v] = number
color_v[V].append(number)
color_v[v].append(number)
queue.append(v)
number += 1
print((max(color)))
for a, b in zip(*[iter(ab)] * 2):
print((color[b]))
|
import sys
from collections import deque
read = sys.stdin.read
N, *ab = list(map(int, read().split()))
graph = [[] for _ in range(N + 1)]
for a, b in zip(*[iter(ab)] * 2):
graph[a].append(b)
color = [0] * (N + 1)
queue = deque([1])
color_v = [set() for _ in range(N + 1)]
while queue:
V = queue.popleft()
number = 1
for v in graph[V]:
if number in color_v[V]:
number += 1
color[v] = number
color_v[V].add(number)
color_v[v].add(number)
queue.append(v)
number += 1
print((max(color)))
for a, b in zip(*[iter(ab)] * 2):
print((color[b]))
|
p02850
|
import sys
from collections import deque
read = sys.stdin.read
N, *ab = list(map(int, read().split()))
graph = [[] for _ in range(N + 1)]
for a, b in zip(*[iter(ab)] * 2):
graph[a].append(b)
color = [0] * (N + 1)
queue = deque([1])
color_v = [set() for _ in range(N + 1)]
while queue:
V = queue.popleft()
number = 1
for v in graph[V]:
if number in color_v[V]:
number += 1
color[v] = number
color_v[V].add(number)
color_v[v].add(number)
queue.append(v)
number += 1
print((max(color)))
for a, b in zip(*[iter(ab)] * 2):
print((color[b]))
|
import sys
from collections import deque
read = sys.stdin.read
N, *ab = list(map(int, read().split()))
graph = [[] for _ in range(N + 1)]
for a, b in zip(*[iter(ab)] * 2):
graph[a].append(b)
color = [0] * (N + 1)
queue = deque([1])
while queue:
V = queue.popleft()
number = 1
for v in graph[V]:
if number == color[V]:
number += 1
color[v] = number
queue.append(v)
number += 1
print((max(color)))
for a, b in zip(*[iter(ab)] * 2):
print((color[b]))
|
p02850
|
N=int(eval(input()))
G=[[] for i in range(N)]
a=[]
b=[]
for i in range(N-1):
ai,bi=list(map(int,input().split()))
a.append(ai-1)
b.append(bi-1)
G[ai-1].append(bi-1)
G[bi-1].append(ai-1)
k=[0]*N
from collections import deque
q=deque([0])
C=[[-1]*N for i in range(N)]
p=[-1]*N
kmx=0
while q:
x=q.popleft()
for i in G[x]:
if C[x][i]!=-1:continue
if p[x]==k[x]:
k[x]+=1
C[x][i] = k[x]
C[i][x] = k[x]
p[i] = k[x]
k[x] += 1
kmx=max(kmx,k[x])
q.append(i)
print(kmx)
for i in range(N-1):
print((C[a[i]][b[i]]+1))
|
N=int(eval(input()))
G=[[] for i in range(N)]
a=[]
b=[]
for i in range(N-1):
ai,bi=list(map(int,input().split()))
a.append(ai-1)
b.append(bi-1)
G[ai-1].append(bi-1)
G[bi-1].append(ai-1)
k=[0]*N
from collections import deque
q=deque([0])
visited=[0]*N
ans={}
p=[-1]*N
kmx=0
while q:
x=q.popleft()
visited[x]=1
cnt=1
for i in G[x]:
if visited[i]!=0:continue
if p[x]==cnt:
cnt+=1
ans[(x,i)]=cnt
ans[(i,x)]=cnt
p[i] = cnt
cnt += 1
kmx=max(kmx,cnt-1)
q.append(i)
print(kmx)
for i in range(N-1):
print((ans[(a[i],b[i])]))
|
p02850
|
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline
from collections import defaultdict
from heapq import heappop, heappush
from decimal import *
##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)
##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除&その最小値を出力
# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと
##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順
# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順
##### 累乗 #####
# pow(x, y, z) -> x**y % z
##### 割り算の切り上げ #####
# tmp = -(-4 // 3)
##### dict の for文 #####
# for k, v in d.items():
# print(k, v)
def inputInt(): return int(eval(input()))
def inputMap(): return list(map(int, input().split()))
def inputList(): return list(map(int, input().split()))
def inputStr(): return input()[:-1]
inf = float('inf')
mod = 1000000007
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
def main():
N = inputInt()
ki = [[] for i in range(N)]
inp = {}
ans = [inf for i in range(N-1)]
ansInt = 0
for i in range(N-1):
a,b = inputMap()
a -= 1
b -= 1
ki[a].append(b)
ki[b].append(a)
inp[(a,b)] = i
for i in ki:
if len(i) > ansInt:
ansInt = len(i)
for i in range(N):
ko = ki[i]
dame = []
mi = []
for j in ko:
#print("{} {} {}".format(i,j,ko))
if i < j:
mi.append(j)
else:
dame.append(ans[inp[(j,i)]])
for j in mi:
for ii in range(ansInt+1):
tmp = bisect_right(dame, ii)
if ii in dame:
pass
else:
ans[inp[(i,j)]] = ii
dame.append(ii)
break
#print(ans)
#print(ki)
#print(inp)
#print(ans)
print(ansInt)
for i in ans:
print((i+1))
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# N 個のボールを K グループに分ける場合のパターン数
def sunuke(N, K, mod=10**9+7):
if N < K or K-1 < 0:
return 0
else:
return combination(N-1, K-1, mod)
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# nCr mod m
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9+7):
r = min(r, n-r)
res = 1
for i in range(r):
res = res * (n - i) * modinv(i+1, mod) % mod
return res
# mを法とするaの乗法的逆元
def modinv(a, mod=10**9+7):
return pow(a, mod-2, mod)
def egcd(a, b):
if a == 0:
return b, 0, 1
else:
g, y, x = egcd(b % a, a)
return g, x - (b // a) * y, y
# nHr mod m
# 問題によって、combination()を切り替えること
def H(n, r, mod=10**9+7):
# comb = Combination(n+r-1, mod)
# return comb(n+r-1, r)
return combination(n+r-1, r, mod)
class Combination:
"""
O(n)の前計算を1回行うことで,O(1)でnCr mod mを求められる
n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
使用例:
comb = Combination(1000000)
print(comb(5, 3)) # 10
"""
def __init__(self, n_max, mod=10**9+7):
self.mod = mod
self.modinv = self.make_modinv_list(n_max)
self.fac, self.facinv = self.make_factorial_list(n_max)
def __call__(self, n, r):
return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod
def make_factorial_list(self, n):
# 階乗のリストと階乗のmod逆元のリストを返す O(n)
# self.make_modinv_list()が先に実行されている必要がある
fac = [1]
facinv = [1]
for i in range(1, n+1):
fac.append(fac[i-1] * i % self.mod)
facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
return fac, facinv
def make_modinv_list(self, n):
# 0からnまでのmod逆元のリストを返す O(n)
modinv = [0] * (n+1)
modinv[1] = 1
for i in range(2, n+1):
modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
return modinv
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# dfs のサンプル
def dfs(graph,parent,counter,edge):
stk = []
stk.append(edge)
while len(stk) > 0:
p = stk.pop()
for e in graph[p]:
if parent[p] == e:
continue
else:
parent[e] = p
counter[e] += counter[p]
stk.append(e)
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline
from collections import defaultdict
from heapq import heappop, heappush
from decimal import *
##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)
##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除&その最小値を出力
# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと
##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順
# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順
##### 累乗 #####
# pow(x, y, z) -> x**y % z
##### 割り算の切り上げ #####
# tmp = -(-4 // 3)
##### dict の for文 #####
# for k, v in d.items():
# print(k, v)
def inputInt(): return int(eval(input()))
def inputMap(): return list(map(int, input().split()))
def inputList(): return list(map(int, input().split()))
def inputStr(): return input()[:-1]
inf = float('inf')
mod = 1000000007
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
def main():
N = inputInt()
ki = [[] for i in range(N)]
inp = {}
ans = [inf for i in range(N-1)]
ansInt = 0
for i in range(N-1):
a,b = inputMap()
a -= 1
b -= 1
ki[a].append(b)
ki[b].append(a)
inp[(a,b)] = i
for i in ki:
if len(i) > ansInt:
ansInt = len(i)
for i in range(N):
ko = ki[i]
dame = []
mi = []
for j in ko:
#print("{} {} {}".format(i,j,ko))
if i < j:
mi.append(j)
else:
dame.append(ans[inp[(j,i)]])
#dame.sort()
mark = 0
for j in mi:
for ii in range(mark,ansInt+1):
if ii in dame:
pass
else:
ans[inp[(i,j)]] = ii
dame.append(ii)
break
mark += 1
#print(ans)
#print(ki)
#print(inp)
#print(ans)
print(ansInt)
for i in ans:
print((i+1))
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# N 個のボールを K グループに分ける場合のパターン数
def sunuke(N, K, mod=10**9+7):
if N < K or K-1 < 0:
return 0
else:
return combination(N-1, K-1, mod)
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# nCr mod m
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9+7):
r = min(r, n-r)
res = 1
for i in range(r):
res = res * (n - i) * modinv(i+1, mod) % mod
return res
# mを法とするaの乗法的逆元
def modinv(a, mod=10**9+7):
return pow(a, mod-2, mod)
def egcd(a, b):
if a == 0:
return b, 0, 1
else:
g, y, x = egcd(b % a, a)
return g, x - (b // a) * y, y
# nHr mod m
# 問題によって、combination()を切り替えること
def H(n, r, mod=10**9+7):
# comb = Combination(n+r-1, mod)
# return comb(n+r-1, r)
return combination(n+r-1, r, mod)
class Combination:
"""
O(n)の前計算を1回行うことで,O(1)でnCr mod mを求められる
n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
使用例:
comb = Combination(1000000)
print(comb(5, 3)) # 10
"""
def __init__(self, n_max, mod=10**9+7):
self.mod = mod
self.modinv = self.make_modinv_list(n_max)
self.fac, self.facinv = self.make_factorial_list(n_max)
def __call__(self, n, r):
return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod
def make_factorial_list(self, n):
# 階乗のリストと階乗のmod逆元のリストを返す O(n)
# self.make_modinv_list()が先に実行されている必要がある
fac = [1]
facinv = [1]
for i in range(1, n+1):
fac.append(fac[i-1] * i % self.mod)
facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
return fac, facinv
def make_modinv_list(self, n):
# 0からnまでのmod逆元のリストを返す O(n)
modinv = [0] * (n+1)
modinv[1] = 1
for i in range(2, n+1):
modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
return modinv
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# dfs のサンプル
def dfs(graph,parent,counter,edge):
stk = []
stk.append(edge)
while len(stk) > 0:
p = stk.pop()
for e in graph[p]:
if parent[p] == e:
continue
else:
parent[e] = p
counter[e] += counter[p]
stk.append(e)
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
if __name__ == "__main__":
main()
|
p02850
|
import sys
input = sys.stdin.readline
N = int(eval(input()))
X = [[] for _ in range(N)]
P = [-1] * N
for i in range(N-1):
a, b = list(map(int, input().split()))
X[a-1].append((i, b-1))
#print(X)
P[b-1] = a-1
Q = [(0, -1)]
ANS = [-1] * (N-1)
while Q:
x, c0 = Q.pop()
c = 1
for i, y in X[x]:
if c == c0: c += 1
ANS[i] = c
Q.append((y, c))
c += 1
print((max(ANS)))
for ans in ANS:
print(ans)
|
import sys
input = sys.stdin.readline
N = int(eval(input()))
X = [[] for _ in range(N)]
P = [-1] * N
for i in range(N-1):
a, b = list(map(int, input().split()))
X[a-1].append((i, b-1))
#print(X)
#P[b-1] = a-1
#print(X)
Q = [(0, -1)]
ANS = [-1] * (N-1)
maxc = 0
while Q:
x, c0 = Q.pop()
c = 1
for i, y in X[x]:
if c == c0: c += 1
ANS[i] = c
if c>maxc:maxc=c
Q.append((y, c))
c += 1
print(maxc)
for ans in ANS:
print(ans)
|
p02850
|
import sys
input = sys.stdin.readline
N = int(eval(input()))
X = [[] for _ in range(N)]
P = [-1] * N
for i in range(N-1):
a, b = list(map(int, input().split()))
X[a-1].append((i, b-1))
#print(X)
#P[b-1] = a-1
#print(X)
Q = [(0, -1)]
ANS = [-1] * (N-1)
maxc = 0
while Q:
x, c0 = Q.pop()
c = 1
for i, y in X[x]:
if c == c0: c += 1
ANS[i] = c
if c>maxc:maxc=c
Q.append((y, c))
c += 1
print(maxc)
for ans in ANS:
print(ans)
|
import sys
input = sys.stdin.readline
N = int(eval(input()))
X = [[] for _ in range(N)]
P = [-1] * N
for i in range(N-1):
a, b = list(map(int, input().split()))
X[a-1].append((i, b-1))
#print(X)
#P[b-1] = a-1
#print(X)
Q = [(0, -1)]
ANS = [-1] * (N-1)
cmax = 0
while Q:
x, c0 = Q.pop()
c = 1
for i, y in X[x]:
if c == c0: c += 1
ANS[i] = c
Q.append((y, c))
c += 1
cmax = max(cmax, c-1)
print(cmax)
for ans in ANS:
print(ans)
|
p02850
|
import sys
from collections import deque
input = sys.stdin.readline
N = int(eval(input()))
X = [deque() for _ in range(N)]
P = [-1] * N
for i in range(N-1):
a, b = list(map(int, input().split()))
X[a-1].append((i, b-1))
#print(X)
#P[b-1] = a-1
#print(X)
Q = deque([(0, -1)])
ANS = [-1] * (N-1)
cmax = 0
while Q:
x, c0 = Q.pop()
c = 1
for i, y in X[x]:
if c == c0: c += 1
ANS[i] = c
Q.appendleft((y, c))
c += 1
cmax = max(cmax, c-1)
print(cmax)
for ans in ANS:
print(ans)
|
import sys
from collections import deque
input = sys.stdin.readline
N = int(eval(input()))
X = [[] for _ in range(N)]
P = [-1] * N
for i in range(N-1):
a, b = list(map(int, input().split()))
X[a-1].append((i, b-1))
#print(X)
#P[b-1] = a-1
#print(X)
Q = deque([(0, -1)])
ANS = [-1] * (N-1)
cmax = 0
while Q:
x, c0 = Q.pop()
c = 1
for i, y in X[x]:
if c == c0: c += 1
ANS[i] = c
Q.appendleft((y, c))
c += 1
cmax = max(cmax, c-1)
print(cmax)
for ans in ANS:
print(ans)
|
p02850
|
import sys
from collections import deque
input = sys.stdin.readline
N = int(eval(input()))
bi=[0]* N
children = [[] for _ in range(N)]
for i in range(N-1):
a, b = list(map(int, input().split()))
bi[i]=b-1
children[a-1].append(b-1)
queue = deque([0])
colors = [0] * N
maxColor = 0
while queue:
node = queue.popleft()
nodeColor = colors[node]
color = 1
for child in children[node]:
if color == nodeColor: color += 1
colors[child] = color
queue.append(child)
color += 1
maxColor = max(maxColor, color-1)
print(maxColor)
for i in range(N-1):
print((colors[bi[i]]))
|
import sys
from collections import deque
input = sys.stdin.readline
N = int(eval(input()))
bi=[0]* N
children = [[] for _ in range(N)]
for i in range(N-1):
a, b = list(map(int, input().split()))
bi[i]=b-1
children[a-1].append(bi[i])
queue = deque([0])
colors = [0] * N
maxColor = 0
while queue:
node = queue.popleft()
nodeColor = colors[node]
color = 1
for child in children[node]:
if color == nodeColor: color += 1
colors[child] = color
queue.append(child)
color += 1
maxColor = max(maxColor, color-1)
print(maxColor)
for i in range(N-1):
print((colors[bi[i]]))
|
p02850
|
import sys
from collections import deque
input = sys.stdin.readline
N = int(eval(input()))
bi=[0]* N
children = [[] for _ in range(N)]
for i in range(N-1):
a, b = list(map(int, input().split()))
b-=1
bi[i]=b
children[a-1].append(b)
queue = deque([0])
colors = [0] * N
maxColor = 0
while queue:
node = queue.popleft()
nodeColor = colors[node]
color = 1
for child in children[node]:
if color == nodeColor: color += 1
colors[child] = color
queue.append(child)
color += 1
maxColor = max(maxColor, color-1)
print(maxColor)
for i in range(N-1):
print((colors[bi[i]]))
|
import sys
from collections import deque
input = sys.stdin.readline
N = int(eval(input()))
bi=[0]* N
children = [[] for _ in range(N)]
for i in range(N-1):
a, b = list(map(int, input().split()))
b-=1
bi[i]=b
children[a-1].append(b)
queue = deque([0])
colors = [0] * N
#maxColor = 0
while queue:
node = queue.popleft()
nodeColor = colors[node]
color = 1
for child in children[node]:
if color == nodeColor: color += 1
colors[child] = color
queue.append(child)
color += 1
#maxColor = max(maxColor, color-1)
print((max(colors)))
for i in range(N-1):
print((colors[bi[i]]))
|
p02850
|
import queue
N = int(eval(input()))
ab = []
deg = [0 for i in range(N)]
child = [[] for _ in range(N)]
edge = {}
color = [0 for _ in range(N-1)]
for i in range(N-1):
tmp = list(map(int, input().split()))
deg[tmp[0]-1] += 1
deg[tmp[1]-1] += 1
child[tmp[0]-1].append(tmp[1]-1)
child[tmp[1]-1].append(tmp[0]-1)
tmp = [tmp[0]-1, tmp[1]-1]
edge[tuple(tmp)] = i
q = queue.Queue()
q.put([None, 0, None])
used = [0]
# parent, self, color
while not q.empty():
current = q.get()
if current[0] is not None:
cnt = 1
for c in child[current[1]]:
if c in used:
continue
used.append(c)
if cnt == current[2]:
cnt += 1
q.put([current[1], c, cnt])
ind = [current[1], c] if current[1] < c else [c, current[1]]
color[edge[tuple(ind)]] = cnt
cnt += 1
else:
for i, c in enumerate(child[current[1]]):
used.append(c)
q.put([current[1], c, i+1])
ind = [current[1], c] if current[1] < c else [c, current[1]]
#print(edge[tuple(ind)], i+1)
color[edge[tuple(ind)]] = i+1
print((max(deg)))
for c in color:
print(c)
|
import queue
N = int(eval(input()))
ab = []
deg = [0 for i in range(N)]
child = [[] for _ in range(N)]
edge = {}
color = [0 for _ in range(N-1)]
for i in range(N-1):
tmp = list(map(int, input().split()))
deg[tmp[0]-1] += 1
deg[tmp[1]-1] += 1
child[tmp[0]-1].append(tmp[1]-1)
child[tmp[1]-1].append(tmp[0]-1)
tmp = [tmp[0]-1, tmp[1]-1]
edge[tuple(tmp)] = i
q = queue.Queue()
q.put([None, 0, None])
used = [0]
# parent, self, color
while not q.empty():
current = q.get()
if current[0] is not None:
cnt = 1
for c in child[current[1]]:
# if c in used:
# continue
used.append(c)
if cnt == current[2]:
cnt += 1
q.put([current[1], c, cnt])
ind = [current[1], c] if current[1] < c else [c, current[1]]
color[edge[tuple(ind)]] = cnt
child[c].remove(current[1])
cnt += 1
else:
for i, c in enumerate(child[current[1]]):
used.append(c)
q.put([current[1], c, i+1])
ind = [current[1], c] if current[1] < c else [c, current[1]]
#print(edge[tuple(ind)], i+1)
color[edge[tuple(ind)]] = i+1
child[c].remove(current[1])
print((max(deg)))
for c in color:
print(c)
|
p02850
|
from collections import deque
N = int(input())
# mtx = np.zeros([N, N], dtype=np.int32)
tree = [[] for i in range(N)]
key_order = [0] * (N-1)
for i in range(N-1):
in1, in2 = map(int, input().split())
in1 -= 1
in2 -= 1
tree[in1].append(in2)
tree[in2].append(in1)
key_order[i] = (in1, in2)
# [print(i, t) for i, t in enumerate(tree)]
def bfs(tree, p):
seen = [False] * len(tree)
queue = deque((p,))
node_colors = [set() for _ in tree]
edge_colors = dict()
all_colors = set()
color = 0
while len(queue) > 0:
q = queue.popleft()
seen[q] = True
for v in tree[q]:
if not seen[v]:
residual = all_colors - node_colors[q]
if len(residual) > 0:
this_color = residual.pop()
else:
color += 1
this_color = color
edge_colors[(q, v)] = this_color
node_colors[q].add(this_color)
node_colors[v].add(this_color)
all_colors.add(this_color)
queue.append(v)
return edge_colors
edge_colors = bfs(tree, 0)
print(max([c for key, c in edge_colors.items()]))
[print(edge_colors[t]) for t in key_order]
# print(edge_colors)
# show_tree(tree)
|
from collections import deque
N = int(input())
# mtx = np.zeros([N, N], dtype=np.int32)
tree = [[] for i in range(N)]
key_order = [0] * (N-1)
for i in range(N-1):
in1, in2 = map(int, input().split())
in1 -= 1
in2 -= 1
tree[in1].append(in2)
tree[in2].append(in1)
key_order[i] = (in1, in2)
# [print(i, t) for i, t in enumerate(tree)]
def bfs(tree, p):
seen = [False] * len(tree)
queue = deque((p,))
edge_colors = dict()
node_colors = [0] * len(tree)
while len(queue) > 0:
q = queue.popleft()
seen[q] = True
parent_color = node_colors[q]
cnt = 1
for v in tree[q]:
if not seen[v]:
if cnt == parent_color:
cnt += 1
edge_colors[(q, v)] = cnt
node_colors[v] = cnt
queue.append(v)
cnt += 1
"""
node_colors = [set() for _ in tree]
edge_colors = dict()
all_colors = set()
color = 0
while len(queue) > 0:
q = queue.popleft()
seen[q] = True
for v in tree[q]:
if not seen[v]:
residual = all_colors - node_colors[q]
if len(residual) > 0:
this_color = residual.pop()
else:
color += 1
this_color = color
edge_colors[(q, v)] = this_color
node_colors[q].add(this_color)
node_colors[v].add(this_color)
all_colors.add(this_color)
queue.append(v)
"""
return edge_colors
edge_colors = bfs(tree, 0)
print(max([c for key, c in edge_colors.items()]))
[print(edge_colors[t]) for t in key_order]
# print(edge_colors)
# show_tree(tree)
|
p02850
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
#import bisect
#from collections import deque
import math
sys.setrecursionlimit(10**5)
def input():
return sys.stdin.readline().rstrip('\n')
N = int(eval(input()))
peer_nodes = [[] for _ in range(N)]
edge_colors = [[0]*(N) for _ in range(N)]
pairs = []
for _ in range(N-1):
a,b = list(map(int, input().split()))
a -= 1
b -= 1
pairs.append([a,b])
peer_nodes[a].append(b)
if not a in peer_nodes[b]:
peer_nodes[b].append(a)
edge_colors[a][b] = 0
#print(peer_nodes,edge_colors)
def draw_color_return_max_colors(node):
max_colors = 0
peers = peer_nodes[node]
if len(peers) == 0:
return 0
used_colors = []
for p in peers:
c = edge_colors[node][p]
if c != 0:
used_colors.append(c)
#print('----', node, peers,used_colors)
if len(used_colors) == len(peers):
return 0
color = 1
for p in peers:
#print(node, p, edge_colors[node][p])
while(color in used_colors):
color += 1
if edge_colors[node][p] == 0:
used_colors.append(color)
edge_colors[node][p] = color
edge_colors[p][node] = color
max_colors = max(used_colors)
for p in peers:
max_colors = max(max_colors, draw_color_return_max_colors(p))
return max_colors
print((draw_color_return_max_colors(pairs[0][0])))
for a,b in pairs:
print((edge_colors[a][b]))
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
#import bisect
#from collections import deque
import math
sys.setrecursionlimit(10**5)
def input():
return sys.stdin.readline().rstrip('\n')
N = int(eval(input()))
peer_nodes = [[] for _ in range(N)]
edge_colors = [[0]*(N) for _ in range(N)]
pairs = []
for _ in range(N-1):
a,b = list(map(int, input().split()))
a -= 1
b -= 1
pairs.append([a,b])
peer_nodes[a].append(b)
if not a in peer_nodes[b]:
peer_nodes[b].append(a)
edge_colors[a][b] = 0
#print(peer_nodes,edge_colors)
def draw_color_return_max_colors(node):
max_colors = 0
peers = peer_nodes[node]
if len(peers) == 0:
return 0
used_colors = []
for p in peers:
c = edge_colors[node][p]
if c != 0:
used_colors.append(c)
#print('----', node, peers,used_colors)
if len(used_colors) == len(peers):
return 0
color = 1
for p in peers:
if edge_colors[node][p] > 0:
continue
else:
while(color in used_colors):
color += 1
if edge_colors[node][p] == 0:
used_colors.append(color)
edge_colors[node][p] = color
edge_colors[p][node] = color
max_colors = max(used_colors)
for p in peers:
max_colors = max(max_colors, draw_color_return_max_colors(p))
return max_colors
print((draw_color_return_max_colors(pairs[0][0])))
for a,b in pairs:
print((edge_colors[a][b]))
|
p02850
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
#import bisect
#from collections import deque
import math
sys.setrecursionlimit(10**5)
def input():
return sys.stdin.readline().rstrip('\n')
N = int(eval(input()))
peer_nodes = [[] for _ in range(N)]
edge_colors = [{} for _ in range(N)]
pairs = []
for _ in range(N-1):
a,b = list(map(int, input().split()))
a -= 1
b -= 1
pairs.append([a,b])
peer_nodes[a].append(b)
if not a in peer_nodes[b]:
peer_nodes[b].append(a)
edge_colors[a][b] = 0
#print(peer_nodes,edge_colors)
def draw_color_return_max_colors(node):
max_colors = 0
peers = peer_nodes[node]
if len(peers) == 0:
return 0
used_colors = []
for p in peers:
if node<p:
i,j = node,p
else:
i,j = p,node
c = edge_colors[i][j]
if c != 0:
used_colors.append(c)
#print('----', node, peers,used_colors)
if len(used_colors) == len(peers):
return 0
color = 1
for p in peers:
if node<p:
i,j = node,p
else:
i,j = p,node
if edge_colors[i][j] > 0:
continue
else:
while(color in used_colors):
used_colors.remove(color)
color += 1
used_colors.append(color)
edge_colors[i][j] = color
max_colors = max([color] + used_colors)
for p in peers:
max_colors = max(max_colors, draw_color_return_max_colors(p))
return max_colors
print((draw_color_return_max_colors(pairs[0][0])))
for a,b in pairs:
print((edge_colors[a][b]))
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
#import bisect
#from collections import deque
import math
sys.setrecursionlimit(10**5)
def input():
return sys.stdin.readline().rstrip('\n')
N = int(eval(input()))
peers = [[] for _ in range(N)]
colors = [{} for _ in range(N)]
pairs = []
for _ in range(N-1):
a,b = list(map(int, input().split()))
a -= 1
b -= 1
pairs.append([a,b])
peers[a].append(b)
colors[a][b] = 0
def draw(node, parent_edge_color):
_peers = peers[node]
if len(_peers) == 0:
return 0
color = 1
max_nrof_color = 1
for peer in _peers:
#print(node,peer,color)
if color == parent_edge_color:
color +=1
colors[node][peer] = color
max_nrof_color = max(max_nrof_color, color, draw(peer, color))
color += 1
return max_nrof_color
print((draw(0,0)))
for a,b in pairs:
print((colors[a][b]))
|
p02850
|
import sys
from collections import deque
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N, *AB = list(map(int, read().split()))
G = [[] for _ in range(N)]
for i, (a, b) in enumerate(zip(*[iter(AB)] * 2)):
G[a - 1].append((i, b - 1))
G[b - 1].append((i, a - 1))
color = [0] * (N - 1)
def dfs(v, p, pc):
c = 1
for i, nv in G[v]:
if nv == p:
continue
if c == pc:
c += 1
color[i] = c
dfs(nv, v, c)
c += 1
dfs(0, -1, 0)
print((max(color)))
print(('\n'.join(map(str, color))))
return
if __name__ == '__main__':
main()
|
import sys
from collections import deque
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N, *AB = map(int, read().split())
G = [[] for _ in range(N)]
for i, (a, b) in enumerate(zip(*[iter(AB)] * 2)):
G[a - 1].append((i, b - 1))
G[b - 1].append((i, a - 1))
queue = deque([0])
color = [0] * (N - 1)
color_from_parent = [0] * N
color_from_parent[0] = -1
while queue:
v = queue.popleft()
c = 1
for i, nv in G[v]:
if color_from_parent[nv] != 0:
continue
if c == color_from_parent[v]:
c += 1
color_from_parent[nv] = c
color[i] = c
c += 1
queue.append(nv)
print(max(color))
print(*color, sep='\n')
return
if __name__ == '__main__':
main()
|
p02850
|
from collections import deque
def main():
N = int(eval(input()))
path = [[] for _ in range(N)]
ab = []
ans = {}
visited = [False] * N
visited[0] = True
for _ in range(N-1):
a, b = list(map(int, input().split()))
path[a-1].append(b-1)
path[b-1].append(a-1)
ab.append((a-1, b-1))
que = deque([(0, 0)])
while que:
k = 1
# k = 0
pre, c = que.popleft()
for next_node in path[pre]:
if visited[next_node]:
continue
if c == k:
k += 1
visited[next_node] = True
ans[(pre, next_node)] = k
que.append((next_node, k))
k += 1
print((max(ans.values())))
for key in ab:
print((ans[key]))
if __name__ == '__main__':
main()
|
from collections import deque
def main():
N = int(eval(input()))
path = [[] for _ in range(N)]
ab = []
ans = {}
visited = [False] * N
visited[0] = True
for _ in range(N-1):
a, b = list(map(int, input().split()))
path[a-1].append(b-1)
# path[b-1].append(a-1)
ab.append((a-1, b-1))
que = deque([(0, 0)])
while que:
k = 1
pre, c = que.popleft()
for next_node in path[pre]:
if visited[next_node]:
continue
if c == k:
k += 1
visited[next_node] = True
ans[(pre, next_node)] = k
que.append((next_node, k))
k += 1
print((max(ans.values())))
for key in ab:
print((ans[key]))
if __name__ == '__main__':
main()
|
p02850
|
# ABC146 D - Coloring Edges on Tree
from collections import deque
n = int(eval(input()))
E = [[] for _ in range(n + 1)]
edge_order = []
for i in range(n-1):
a,b=list(map(int,input().split()))
E[a].append(b)
edge_order.append(b)
# 頂点1からBFS
q = deque([1])
color = [0] * (n+1)
while q:
V = q.popleft()
c = 1
for nv in E[V]:
if c == color[V]:
c += 1
color[nv] = c
c += 1
q.append(nv)
print((max(color)))
for i in edge_order:
print((color[i]))
|
n=int(eval(input()))
G=[[] for i in range(n+1)]
G_order=[]
for i in range(n-1):
a,b=list(map(int,input().split()))
G[a].append(b)
G_order.append(b)
from collections import deque
q=deque([1])
color=[0]*(n+1)
while q:
cur=q.popleft()
c=1
for nx in G[cur]:
if c==color[cur]:
c+=1
color[nx]=c
c+=1
q.append(nx)
print((max(color)))
for i in G_order:
print((color[i]))
|
p02850
|
n=int(eval(input()))
G=[[] for i in range(n+1)]
G_order=[]
for i in range(n-1):
a,b=list(map(int,input().split()))
G[a].append(b)
G_order.append(b)
from collections import deque
q=deque([1])
color=[0]*(n+1)
while q:
cur=q.popleft()
c=1
for nx in G[cur]:
if c==color[cur]:
c+=1
color[nx]=c
c+=1
q.append(nx)
print((max(color)))
for i in G_order:
print((color[i]))
|
n = int(eval(input()))
G = [[] for _ in range(n)]
edge = []
for _ in range(n-1):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
G[a].append(b)
edge.append(b)
from collections import deque
q = deque()
color = [0]*n
q.append(0)
while q:
cur = q.popleft()
c = 1
for nx in G[cur]:
if color[cur] == c:
c += 1
color[nx] = c
c += 1
q.append(nx)
print((max(color)))
for e in edge:
print((color[e]))
|
p02850
|
from collections import deque
N = int(eval(input()))
E = [tuple([int(x)-1 for x in input().split()]) for _ in range(N-1)]
K = 0
E_sorted = sorted(E, key=lambda x:x[0])
ans = {}
V = [deque([i for i in range(1, N)]) for _ in range(N)]
for e in E_sorted:
a, b = e
c = 1
req_K = True
c = V[a].popleft()
if c > K:
K = c
V[b].remove(c)
ans[e] = c
print(K)
for e in E:
print((ans[e]))
|
N = int(eval(input()))
E = [tuple([int(x)-1 for x in input().split()]) for _ in range(N-1)]
K = 0
E_sorted = sorted(E, key=lambda x:x[0])
ans = {}
V = [[] for _ in range(N)]
for e in E_sorted:
a, b = e
c = 1
req_K = True
c = 1
i = 1
while i <= K:
if not (i in V[a]):
c = i
req_K = False
break
i += 1
if req_K:
K += 1
c = K
V[a].append(c)
V[b].append(c)
ans[e] = c
print(K)
for e in E:
print((ans[e]))
|
p02850
|
N = int(eval(input()))
from collections import defaultdict
G = defaultdict(list)
EdaNum = defaultdict(int)
for i in range(N-1):
a,b = list(map(int,input().split()))
G[a].append(b)
G[b].append(a)
EdaNum[(a,b)] = i
ans = [-1]*(N-1)
que = [[1,-1,-1]]
K = 0
visited = [False]*(N+1)
for i in range(1,N+1):
K = max(K,len(G[i]))
while que != []:
#print(que)
now,parent,parentcolor = que.pop()
visited[now]=True
used = [False]*(K+1)
nowcolor = 1
for i in G[now]:
#print(i,parent)
if i != parent:
if nowcolor == parentcolor:
nowcolor += 1
ans[EdaNum[(min(now,i),max(now,i))]] = nowcolor
nowcolor += 1
if len(G[i])!=1:
que.append([i,now, nowcolor-1])
#print(que)
print(K)
for i in ans:
print(i)
|
N = int(eval(input()))
from collections import defaultdict
G = defaultdict(list)
EdaNum = defaultdict(int)
for i in range(N-1):
a,b = list(map(int,input().split()))
G[a].append(b)
G[b].append(a)
EdaNum[(a,b)] = i
ans = [-1]*(N-1)
que = [[1,-1,-1]]
K = 0
visited = [False]*(N+1)
for i in range(1,N+1):
K = max(K,len(G[i]))
while que != []:
#print(que)
now,parent,parentcolor = que.pop()
visited[now]=True
nowcolor = 1
for i in G[now]:
#print(i,parent)
if i != parent:
if nowcolor == parentcolor:
nowcolor += 1
ans[EdaNum[(min(now,i),max(now,i))]] = nowcolor
nowcolor += 1
if len(G[i])!=1:
que.append([i,now, nowcolor-1])
#print(que)
print(K)
for i in ans:
print(i)
|
p02850
|
from queue import deque
n = int(eval(input()))
l = [list(map(int,input().split())) for _ in range(n-1)]
li = [[0 for i in range(n)]for j in range(n)]
for i,j in l:
i,j = i-1,j-1
li[i][j] = 1
li[j][i] = 1
ans = [[0 for i in range(n)]for j in range(n)]
before_color = {}
before_color[0] = 0
visited_node = [False]*n
visited_node[0] = True
max_color = 1
# 幅優先探索(BFS)
def breadth_first_search(start, W):
global max_color
# リストをキューにする
work_queue = deque([])
visited = set()
# 初期化
work_queue.append(start)
visited.add(start)
while work_queue:
# 今いる頂点
here = work_queue.popleft()
# 今いる頂点に隣接する頂点すべてを処理する
for i, node in enumerate(W[here]):
# 隣接しなければ何もしない
if node == 0: continue
if i not in visited:
work_queue.append(i)
visited.add(i)
color = 1
for j in work_queue:
if visited_node[j]:
continue
else:
visited_node[j] = True
if color == before_color[here]:
color += 1
before_color[j] = color
ans[here][j] = color
ans[j][here] = color
max_color = max(max_color,color)
color += 1
return visited
breadth_first_search(0,li)
print(max_color)
for i,j in l:
i,j = i-1,j-1
print((ans[i][j]))
|
from queue import deque
n = int(eval(input()))
l = [list(map(int,input().split())) for _ in range(n-1)]
li = [[] for _ in range(n)]
for i,j in l:
i,j = i-1,j-1
li[i].append(j)
li[j].append(i)
stack = 0
color = [0]*n
work_queue = deque([])
visited = [False]*n
visited[0] = True
color_list = [0]*n
work_queue.append(stack)
path = {}
ma = 0
while work_queue:
here = work_queue.popleft()
color = 1
for i in li[here]:
if visited[i]:
continue
work_queue.append(i)
visited[i] = True
if color_list[here] == color:
color += 1
path[(here,i)] = color
color_list[i] = color
ma = max(ma,color)
color += 1
print(ma)
for i,j in l:
i,j = i-1,j-1
print((path[(i,j)]))
|
p02850
|
from collections import deque
N=int(eval(input()))
tree=[[] for _ in range(N)]
dirtree=[[] for _ in range(N)]
paths=[]
for i in range(N-1):
a,b=list(map(int,input().split()))
tree[a-1].append(b-1)
tree[b-1].append(a-1)
paths.append([a-1,b-1,i,0])
paths=sorted(paths,key=lambda x:x[1])
paths.sort(key=lambda x:x[0])
#print(paths)
v=0
d=deque()
d.append(v)
seen=[0]*N
col=[-1]*N
path=[]
dirtree = [[] for _ in range(N)]
while len(d)>0:
v=d.popleft()
seen[v]=1
for j in tree[v]:
if seen[j]==0:
d.append(j)
dirtree[v].append(j)
#print(dirtree)
v=0
d.append(v)
col[v]=0
while len(d)>0:
v=d.popleft()
seen[v]=0
c=0
for j in dirtree[v]:
if seen[j]==1:
d.append(j)
c=c+1
if c==col[v]:
c=c+1
path.append([min(j,v),max(j,v),c])
else:
path.append([min(j, v), max(j, v), c])
col[j]=c
path = sorted(path, key=lambda x: x[1])
path.sort(key=lambda x: x[0])
#print(path)
#input()
for i in range(N-1):
paths[i][3]=path[i][2]
paths.sort(key=lambda x:x[2])
path.sort(key=lambda x:x[2],reverse=True)
print((path[0][2]))
for i in range(N-1):
print((paths[i][3]))
|
from collections import deque
N=int(eval(input()))
tree=[[] for _ in range(N)]
dirtree=[[] for _ in range(N)]
paths=[]
for i in range(N-1):
a,b=list(map(int,input().split()))
tree[a-1].append(b-1)
tree[b-1].append(a-1)
paths.append([a-1,b-1,i,0])
paths=sorted(paths,key=lambda x:x[1])
paths.sort(key=lambda x:x[0])
#print(paths)
v=0
d=deque()
d.append(v)
seen=[0]*N
col=[-1]*N
path=[]
dirtree = [[] for _ in range(N)]
while len(d)>0:
v=d.popleft()
seen[v]=1
for j in tree[v]:
if seen[j]==0:
d.append(j)
dirtree[v].append(j)
#print(dirtree)
v=0
d.append(v)
col[v]=0
while len(d)>0:
v=d.popleft()
seen[v]=0
c=0
for j in dirtree[v]:
if seen[j]==1:
d.append(j)
c=c+1
if c==col[v]:
c=c+1
path.append([min(j,v),max(j,v),c])
else:
path.append([min(j, v), max(j, v), c])
col[j]=c
path = sorted(path, key=lambda x: x[1])
path.sort(key=lambda x: x[0])
#print(path)
#input()
for i in range(N-1):
paths[i][3]=path[i][2]
paths.sort(key=lambda x:x[2])
path.sort(key=lambda x:x[2],reverse=True)
print((path[0][2]))
for i in range(N-1):
print((paths[i][3]))
|
p02850
|
from collections import deque
N=int(eval(input()))
G=[[] for n in range(N)]
E=[]
color_map={}
for n in range(N-1):
a,b=list(map(int,input().split()))
E.append((a-1,b-1))
color_map[(a-1,b-1)]=0
G[a-1].append(b-1)
G[b-1].append(a-1)
deg=[len(v) for v in G]
K=max(deg)
Q=deque([0])
X=[]
while Q:
v=Q.popleft()
X.append(v)
for u in set(G[v])-set(X):
Q.append(u)
if v!=0:
p=(set(X)&set(G[v])).pop()
colors=set(range(1,K+1))
for q in G[p]:
p1,q1=min(p,q),max(p,q)
colors-={color_map[(p1,q1)]}
a,b=min(p,v),max(p,v)
color_map[(a,b)]=colors.pop()
print(K)
for edge in E:
print((color_map[edge]))
|
from collections import deque
N=int(eval(input()))
G=[[] for n in range(N)]
E=[]
for n in range(N-1):
a,b=list(map(int,input().split()))
E.append((a-1,b-1))
G[a-1].append(b-1)
G[b-1].append(a-1)
K=max([len(v) for v in G])
P=[-1]*N
Q=[0]
X=[]
count=0
while Q:
v=Q.pop()
X.append(v)
for u in G[v]:
if u==P[v]:
continue
P[u]=v
Q.append(u)
C={}
for v in X:
color=0
try:
p_color=C[tuple(sorted((v,P[v])))]
except:
p_color=-1
for u in G[v]:
if u==P[v]:
continue
if color==p_color:
color+=1
C[tuple(sorted((u,v)))]=color
color+=1
print(K)
for e in E:
print((C[e]+1))
|
p02850
|
from collections import deque
N=int(eval(input()))
G=[[] for n in range(N)]
E=[]
for n in range(N-1):
a,b=list(map(int,input().split()))
E.append((a-1,b-1))
G[a-1].append(b-1)
G[b-1].append(a-1)
K=max([len(v) for v in G])
P=[-1]*N
Q=[0]
X=[]
count=0
while Q:
v=Q.pop()
X.append(v)
for u in G[v]:
if u==P[v]:
continue
P[u]=v
Q.append(u)
C={}
for v in X:
color=0
try:
p_color=C[tuple(sorted((v,P[v])))]
except:
p_color=-1
for u in G[v]:
if u==P[v]:
continue
if color==p_color:
color+=1
C[tuple(sorted((u,v)))]=color
color+=1
print(K)
for e in E:
print((C[e]+1))
|
N=int(eval(input()))
G=[[] for n in range(N)]
E=[]
for n in range(N-1):
a,b=list(map(int,input().split()))
E.append((a-1,b-1))
G[a-1].append(b-1)
G[b-1].append(a-1)
K=max([len(v) for v in G])
P=[-1]*N
Q=[0]
X=[]
count=0
while Q:
v=Q.pop()
X.append(v)
for u in G[v]:
if u==P[v]:
continue
P[u]=v
Q.append(u)
C={}
for v in X:
color=0
try:
p_color=C[min(v,P[v]),max(v,P[v])]
except:
p_color=-1
for u in G[v]:
if u==P[v]:
continue
if color==p_color:
color+=1
C[min(u,v),max(u,v)]=color
color+=1
print(K)
for e in E:
print((C[e]+1))
|
p02850
|
n, m = list(map(int, input().split()))
g = [[i] for i in range(n)]
for _ in range(m):
u, v = [int(x) - 1 for x in input().split()]
g[u].append(v)
g[v].append(u)
q = int(eval(input()))
c = [None] * q
dp = [[-1 for j in range(n)] for i in range(11)]
for i in range(q):
v, d, c[i] = list(map(int, input().split()))
dp[d][v - 1] = i
for i in reversed(list(range(1, 11))):
dp[i - 1] = [max(dp[i - 1][u], max(dp[i][v] for v in g[u])) for u in range(n)]
for i in range(n):
if dp[0][i] == -1:
print('0')
else:
print((c[dp[0][i]]))
|
n, m = list(map(int, input().split()))
g = [[i] for i in range(n)]
for _ in range(m):
u, v = [int(x) - 1 for x in input().split()]
g[u].append(v)
g[v].append(u)
q = eval(input())
c = [None] * q
dp = [[-1 for j in range(n)] for i in range(11)]
for i in range(q):
v, d, c[i] = list(map(int, input().split()))
dp[d][v - 1] = i
for i in reversed(list(range(1, 11))):
dp[i - 1] = [max(dp[i - 1][u], max(dp[i][v] for v in g[u])) for u in range(n)]
for i in range(n):
if dp[0][i] == -1:
print('0')
else:
print((c[dp[0][i]]))
|
p03768
|
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
def find(x):
if par[x] < 0:
return x
else:
par[x] = find(par[x])
return par[x]
def unite(x,y):
x = find(x)
y = find(y)
if x == y:
return False
else:
if par[x] > par[y]:
x,y = y,x
par[x] += par[y]
par[y] = x
return True
def size(x):
return -par[find(x)]
n, m = map(int, readline().split())
par = [-1]*n
g = [[] * n for i in range(n)]
for i in range(m):
u, v = map(int,readline().split())
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
unite(u,v)
q = int(readline())
chk = []
for i in range(q):
V,D,C = map(int,readline().split())
chk.append((V,D,C))
from collections import deque
ans = [0]*n
cnt = [0]*n
def bfs(s,col,d,f,ss):
global end
que = deque()
que.append((s,1,col))
if ans[s] == 0:
ans[s] = col
cnt[f] += 1
while que:
now,p,col = que.popleft()
if cnt[f] == ss:
break
for i in g[now]:
if p <= d and ans[i] == 0:
ans[i] = col
cnt[f] += 1
end += 1
if cnt[f] == ss:
break
if p < d:
que.append((i,p+1,col))
end = 0
for i in chk[::-1]:
vv,d,cc = i
f = find(vv-1)
ss = size(f)
if end == n:
break
if cnt[f] == ss:
continue
bfs(vv-1,cc,d,f,ss)
print(*ans, sep='\n')
|
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(4100000)
n,m = list(map(int, readline().split()))
g = [[]*n for i in range(n)]
for i in range(m):
u,v = list(map(int,readline().split()))
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
q = int(readline())
chk = []
for i in range(q):
V,D,C = list(map(int,readline().split()))
chk.append((V,D,C))
memo = [[0]*11 for _ in range(n)]
def f(v,d,c):
if memo[v][d] != 0:
return
else:
memo[v][d] = c
if d > 0:
f(v,d-1,c)
for nxt in g[v]:
f(nxt,d-1,c)
else:
return
for V,D,C in chk[::-1]:
f(V-1,D,C)
for v in range(n):
print((memo[v][0]))
|
p03768
|
inf = 100
N, M = list(map(int, input().split()))
WF = [[inf]*N for _ in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
WF[a-1][b-1] = 1
WF[b-1][a-1] = 1
for i in range(N):
WF[i][i] = 0
for k in range(N):
for i in range(N):
for j in range(N):
WF[i][j] = min(WF[i][j], WF[i][k]+WF[k][j])
C = [0]*N
Q = int(eval(input()))
for _ in range(Q):
v, d, c = list(map(int, input().split()))
for i in range(N):
if WF[v-1][i] <= d:
C[i] = c
for i in range(N):
print((C[i]))
|
inf = 100
N, M = list(map(int, input().split()))
G = [[set([j]) for i in range(11)] for j in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
G[a-1][1].add(b-1)
G[b-1][1].add(a-1)
for i in range(N):
for d in range(1,11):
for j in G[i][d-1]:
G[i][d] |= G[j][1]
C = [0]*N
Q = int(eval(input()))
for _ in range(Q):
v, d, c = list(map(int, input().split()))
for i in G[v-1][d]:
C[i] = c
for i in range(N):
print((C[i]))
|
p03768
|
N, M = list(map(int, input().split()))
G = [[set([j]) for i in range(11)] for j in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
G[a-1][1].add(b-1)
G[b-1][1].add(a-1)
for i in range(N):
if len(G[i][1]) == 1:
continue
for d in range(1,11):
for j in G[i][d-1]:
G[i][d] |= G[j][1]
if len(G[i][d]) == N:
break
C = [0]*N
Q = int(eval(input()))
for _ in range(Q):
v, d, c = list(map(int, input().split()))
for i in G[v-1][d]:
C[i] = c
for i in range(N):
print((C[i]))
|
N, M = list(map(int, input().split()))
G = [[set([j]) for i in range(11)] for j in range(N)]
for _ in range(M):
a, b = list(map(int, input().split()))
G[a-1][1].add(b-1)
G[b-1][1].add(a-1)
for i in range(N):
if len(G[i][1]) == 1:
continue
for d in range(1,11):
G[i][d] |= G[i][d-1]
for j in G[i][d-1]:
G[i][d] |= G[j][1]
if len(G[i][d]) == N:
break
C = [0]*N
Q = int(eval(input()))
for _ in range(Q):
v, d, c = list(map(int, input().split()))
for i in G[v-1][d]:
C[i] = c
for i in range(N):
print((C[i]))
|
p03768
|
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N, M = list(map(int, input().split()))
e = dd(list)
for _ in range(M):
u, v = list(map(int, input().split()))
e[u].append(v)
e[v].append(u)
res = [set() for _ in range(N + 1)]
Q = int(eval(input()))
qd = [0] * Q
qc = [0] * Q
for i in range(Q):
v, d, c = list(map(int, input().split()))
qd[i] = d
qc[i] = c
res[v].add(i)
#print(qc)
def clean():
global res
for i in range(1, N + 1):
a = sorted(res[i], reverse = True)
d = -1
for j in range(len(a)):
x = a[j]
if qd[x] <= d: res[i].discard(x)
d = max(d, qd[x])
clean()
for t in range(10):
tres = [set() | s for s in res]
for x in range(1, N + 1):
for y in e[x]:
for z in res[x]:
if qd[z] > t: tres[y].add(z)
res = tres
#clean()
#print(res)
for r in res[1: ]:
if len(r): print((qc[max(r)]))
else: print((0))
|
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N, M = list(map(int, input().split()))
e = dd(list)
for _ in range(M):
u, v = list(map(int, input().split()))
e[u].append(v)
e[v].append(u)
mxd = 0
res = [set() for _ in range(N + 1)]
Q = int(eval(input()))
qd = [0] * Q
qc = [0] * Q
for i in range(Q):
v, d, c = list(map(int, input().split()))
qd[i] = d
qc[i] = c
res[v].add(i)
mxd = max(mxd, d)
#print(qc)
def clean():
global res
for i in range(1, N + 1):
a = sorted(res[i], reverse = True)
d = -1
for j in range(len(a)):
x = a[j]
if qd[x] <= d: res[i].discard(x)
d = max(d, qd[x])
clean()
for t in range(mxd):
tres = [set() | s for s in res]
for x in range(1, N + 1):
for y in e[x]:
for z in res[x]:
if qd[z] > t: tres[y].add(z)
res = tres
clean()
#print(res)
for r in res[1: ]:
if len(r): print((qc[max(r)]))
else: print((0))
|
p03768
|
import collections
n,m=list(map(int,input().split()))
g=[[] for _ in range(n+1)]
for _ in range(m):
a,b=list(map(int,input().split()))
g[a].append(b)
g[b].append(a)
q=int(eval(input()))
arr=[list(map(int,input().split())) for _ in range(q)]
color=[0]*(n+1)
for i in range(q):
v,d,c=arr[i]
tmp=0
tq=collections.deque()
tq.append((v,0,c))
checked=[0]*(n+1)
checked[v]=1
color[v]=c
while 1:
if len(tq)==0:
break
tv,td,tc=tq.popleft()
if td>=d:
break
for u in g[tv]:
if checked[u]==0:
checked[u]=1
color[u]=tc
tq.append((u,td+1,tc))
for i in range(1,n+1):
print((color[i]))
|
def dfs(i,v,d,c):
if dp[v][d]==-1:
dp[v][d]=i
if d>0:
dfs(i,v,d-1,c)
for u in g[v]:
dfs(i,u,d-1,c)
n,m=list(map(int,input().split()))
g=[[] for _ in range(n+1)]
for _ in range(m):
a,b=list(map(int,input().split()))
g[a].append(b)
g[b].append(a)
q=int(eval(input()))
arr=[]
for i in range(q):
v,d,c=list(map(int,input().split()))
arr.append((i,v,d,c))
dp=[[-1]*11 for _ in range(n+1)]
for i,v,d,c in arr[::-1]:
dfs(i,v,d,c)
ans=[]
for i in range(1,n+1):
if dp[i][0]==-1:
ans.append(0)
else:
ans.append(arr[dp[i][0]][3])
for i in range(n):
print((ans[i]))
|
p03768
|
import queue
N, M = list(map( int, input().split() ))
G = [ [] for i in range( N ) ]
for i in range( M ):
u, v = list(map( int, input().split() ))
G[ u - 1 ].append( v - 1 )
G[ v - 1 ].append( u - 1 )
Q = int( eval(input()) )
V = []
D = []
C = []
for qi in range( Q ):
v, d, c = list(map( int, input().split() ))
V.append( v - 1 )
D.append( d )
C.append( c )
vis = [ -1 for i in range( N ) ]
col = [ 0 for i in range( N ) ]
for qi in range( Q - 1, -1, -1 ):
if D[ qi ] <= vis[ V[ qi ] ]: continue # 影響力不足
que = queue.Queue()
vis[ V[ qi ] ] = D[ qi ]
que.put( ( D[ qi ], V[ qi ] ) )
if col[ V[ qi ] ] == 0:
col[ V[ qi ] ] = C[ qi ]
while not que.empty():
d, u = que.get()
if d == 0: continue
for v in G[ u ]:
if vis[ v ] >= d - 1: continue
vis[ v ] = d - 1
que.put( ( d - 1, v ) )
if col[ v ] == 0:
col[ v ] = C[ qi ]
for i in range( N ):
print(( col[ i ] ))
|
from collections import deque
N, M = list(map( int, input().split() ))
G = [ [] for i in range( N ) ]
for i in range( M ):
u, v = list(map( int, input().split() ))
G[ u - 1 ].append( v - 1 )
G[ v - 1 ].append( u - 1 )
Q = int( eval(input()) )
V = []
D = []
C = []
for qi in range( Q ):
v, d, c = list(map( int, input().split() ))
V.append( v - 1 )
D.append( d )
C.append( c )
vis = [ -1 for i in range( N ) ]
col = [ 0 for i in range( N ) ]
for qi in range( Q - 1, -1, -1 ):
if D[ qi ] <= vis[ V[ qi ] ]: continue # 影響力不足
que = deque()
vis[ V[ qi ] ] = D[ qi ]
que.append( ( D[ qi ], V[ qi ] ) )
if col[ V[ qi ] ] == 0:
col[ V[ qi ] ] = C[ qi ]
while len( que ):
d, u = que.popleft()
if d == 0: continue
for v in G[ u ]:
if vis[ v ] >= d - 1: continue
vis[ v ] = d - 1
que.append( ( d - 1, v ) )
if col[ v ] == 0:
col[ v ] = C[ qi ]
for i in range( N ):
print(( col[ i ] ))
|
p03768
|
from collections import deque
N,M=list(map(int,input().split()))
G=[[] for i in range(N)]
for i in range(M):
a,b=list(map(int,input().split()))
G[a-1].append(b-1)
G[b-1].append(a-1)
Q=int(eval(input()))
Colors=[0]*N
dp=[[False]*11 for i in range(N)]
def BFS(v,d,c):
global dp
for i in range(d+1):
dp[v][i]=True
stack=deque([(v,d)])
global Colors
while stack:
n,m=stack.popleft()
if m<0:
break
if Colors[n]==0:
Colors[n]=c
for u in G[n]:
if not dp[u][m]:
stack.append((u,m-1))
for i in range(m):
dp[u][i]=True
q=[list(map(int,input().split())) for i in range(Q)]
for i in q[::-1]:
v,d,c=i
BFS(v-1,d,c)
for c in Colors:
print(c)
|
N,M=list(map(int,input().split()))
E=[]
for i in range(M):
a,b=list(map(int,input().split()))
E.append((a-1,b-1))
Q=int(eval(input()))
dp=[[-1]*11 for i in range(N)]
C=[]
for i in range(Q):
v,d,c=list(map(int,input().split()))
dp[v-1][d]=i
C.append(c)
for d in range(1,11)[::-1]:
for n in range(N):
dp[n][d-1]=max(dp[n][d],dp[n][d-1])
for a,b in E:
dp[a][d-1]=max(dp[a][d-1],dp[b][d])
dp[b][d-1]=max(dp[b][d-1],dp[a][d])
for i in range(N):
if dp[i][0]>=0:
print((C[dp[i][0]]))
else:
print((0))
|
p03768
|
# -*- encoding: utf-8 -*-
N,M = list(map(int, input().split()))
C=[]
for i in range(N):
C.append(0)
AB=[]
for i in range(M):
AB.append(list(map(int, input().split())))
nextnodes=[]
for i in range(N):
nextnodes.append([])
for ab in AB:
#print("%d,%d,%d" % (N, ab[0], ab[1]))
nextnodes[ab[0]-1].append(ab[1])
nextnodes[ab[1]-1].append(ab[0])
Q = int(eval(input()))
VDC=[]
for i in range(Q):
VDC.append(list(map(int, input().split())))
for i in range(Q):
vdc=VDC[i]
current = []
next = []
v=vdc[0]
d=vdc[1]
c=vdc[2]
C[v-1] = c
#print("i: %d, dist: 0, n: %d, c: %d" % (i, v, c))
current.extend(nextnodes[v-1])
for dist in range(d):
if len(current) == 0:
break
for n in current:
C[n-1] = c
#print("i: %d, dist: %d, n: %d, c: %d" % (i, dist+1, n, c))
next.extend(nextnodes[n-1])
current = next
next = []
for i in C:
print(i)
|
# -*- encoding: utf-8 -*-
N,M = list(map(int, input().split()))
C=[]
for i in range(N):
C.append(0)
AB=[]
for i in range(M):
AB.append(list(map(int, input().split())))
nextnodes=[]
for i in range(N):
nextnodes.append([])
for ab in AB:
#print("%d,%d,%d" % (N, ab[0], ab[1]))
nextnodes[ab[0]-1].append(ab[1])
nextnodes[ab[1]-1].append(ab[0])
Q = int(eval(input()))
VDC=[]
for i in range(Q):
VDC.append(list(map(int, input().split())))
for i in range(Q):
vdc=VDC[i]
current = []
next = []
done = set()
v=vdc[0]
d=vdc[1]
c=vdc[2]
C[v-1] = c
#print("i: %d, dist: 0, n: %d, c: %d" % (i, v, c))
current.extend(nextnodes[v-1])
done.add(v)
for dist in range(d):
if len(current) == 0:
break
for n in current:
if n in done:
continue
C[n-1] = c
#print("i: %d, dist: %d, n: %d, c: %d" % (i, dist+1, n, c))
next.extend(nextnodes[n-1])
done.add(n)
current = next
next = []
for i in C:
print(i)
|
p03768
|
def recClr(v,d,c):
if clr[v-1]==0:
clr[v-1]=c
# print "recClr",v,d,c
if d>0:
if v in ab:
for b in ab[v]:
recClr(b,d-1,c)
N,M=list(map(int,input().split()))
ab={}
for i in range(M):
a,b=list(map(int,input().split()))
if a in ab:
ab[a].append(b)
else:
ab[a]=[b]
if b in ab:
ab[b].append(a)
else:
ab[b]=[a]
#print ab
clr=[0]*N
Q=eval(input())
op=[]
for i in range(Q):
v,d,c=list(map(int,input().split()))
op.append((v,d,c))
op.reverse()
for v,d,c in op:
recClr(v,d,c)
#print clr
for i in clr:
print(i)
|
def recClr(v,d,c):
# print "recClr",v,d,c
if visited[v-1] >= d:
return
else:
visited[v-1]=d
if clr[v-1]==0:
clr[v-1]=c
if d>0:
if v in ab:
for b in ab[v]:
recClr(b,d-1,c)
N,M=list(map(int,input().split()))
ab={}
for i in range(M):
a,b=list(map(int,input().split()))
if a in ab:
ab[a].append(b)
else:
ab[a]=[b]
if b in ab:
ab[b].append(a)
else:
ab[b]=[a]
#print ab
clr=[0]*N
visited=[-1]*N
Q=eval(input())
op=[]
for i in range(Q):
v,d,c=list(map(int,input().split()))
op.append((v,d,c))
op.reverse()
for v,d,c in op:
recClr(v,d,c)
#print clr
for i in clr:
print(i)
|
p03768
|
from queue import deque
def dijkstra(s, d):
queue = deque([(0, s)])
paint = set()
while queue:
cost, v = queue.popleft()
if cost > d:
break
paint.add(v)
queue.extend((cost + 1, u) for u in links[v] if u not in paint)
return paint
n, m = list(map(int, input().split()))
links = [None] + [set() for _ in range(n)]
for _ in range(m):
a, b = list(map(int, input().split()))
links[a].add(b)
links[b].add(a)
q = int(eval(input()))
queries = [list(map(int, input().split())) for _ in range(q)]
painted = set()
colors = [0] * (n + 1)
while queries:
v, d, c = queries.pop()
paint = dijkstra(v, d) - painted
for i in paint:
colors[i] = c
painted |= paint
for c in colors[1:]:
print(c)
|
from queue import deque
def paint(s, d, c):
queue = deque([(d, s)])
while queue:
remains, v = queue.popleft()
if painted[v] >= remains:
continue
if colors[v] == 0:
colors[v] = c
painted[v] = remains
if remains:
queue.extend((remains - 1, u) for u in links[v])
n, m = list(map(int, input().split()))
links = [None] + [set() for _ in range(n)]
for _ in range(m):
a, b = list(map(int, input().split()))
links[a].add(b)
links[b].add(a)
q = int(eval(input()))
queries = [list(map(int, input().split())) for _ in range(q)]
colors = [0] * (n + 1)
painted = [-1] * (n + 1)
while queries:
paint(*queries.pop())
for c in colors[1:]:
print(c)
|
p03768
|
n, m = list(map(int, input().split()))
node = [[] for _ in range(n + 1)]
for i in range(m):
a, b = list(map(int, input().split()))
node[a].append(b)
node[b].append(a)
q = int(eval(input()))
node_color = [0 for _ in range(n + 1)]
for j in range(q):
v, d, c = list(map(int, input().split()))
now = [v]
paint = {v}
for dist in range(d):
buff = []
now = list(set(now))
for k in now:
paint |= set(node[k])
buff.extend(node[k])
now = buff
for l in paint:
node_color[l] = c
for m in range(n):
print((node_color[m + 1]))
|
n, m = list(map(int, input().split()))
node = [[] for _ in range(n + 1)]
for i in range(m):
a, b = list(map(int, input().split()))
node[a].append(b)
node[b].append(a)
q = int(eval(input()))
node_color = [0 for _ in range(n + 1)]
vdc = [list(map(int, input().split())) for _ in range(q)]
vdc = vdc[::-1]
painted = set()
visited = [[0] * 11 for _ in range(n + 1)]
def dfs(now, dist, color):
if dist < 0:
return
if visited[now][dist]:
return
visited[now][dist] += 1
if not node_color[now]:
node_color[now] = color
for x in node[now]:
dfs(x, dist - 1, color)
for i in vdc:
v, d, c = i
dfs(v, d, c)
for m in range(n):
print((node_color[m + 1]))
|
p03768
|
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from collections import deque
def resolve():
n,m=map(int,input().split())
E=[[] for _ in range(n)]
for _ in range(m):
u,v=map(int,input().split())
u-=1; v-=1
E[u].append(v)
E[v].append(u)
q=int(input())
VDC=[None]*q
for i in range(q):
v,d,c=map(int,input().split())
v-=1
VDC[i]=(v,d,c)
VDC.reverse()
dp=[[0]*11 for _ in range(n)]
ans=[0]*n
for v,d,c in VDC:
Q=deque([(v,d)])
dp[v][d]=1
while(Q):
v,d=Q.popleft()
if(d>0):
Q.append((v,d-1))
for nv in E[v]:
if(dp[nv][d-1]): continue
dp[nv][d-1]=1
Q.append((nv,d-1))
if(ans[v]==0):
ans[v]=c
print(*ans,sep='\n')
resolve()
|
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from collections import deque
def resolve():
n,m=map(int,input().split())
E=[[] for _ in range(n)]
for _ in range(m):
u,v=map(int,input().split())
u-=1; v-=1
E[u].append(v)
E[v].append(u)
q=int(input())
VDC=[None]*q
for i in range(q):
v,d,c=map(int,input().split())
v-=1
VDC[i]=(v,d,c)
VDC.reverse()
dp=[[0]*11 for _ in range(n)]
ans=[0]*n
for v,d,c in VDC:
Q=deque([(v,d)])
dp[v][d]=1
while(Q):
v,d=Q.popleft()
if(d>0):
if(not dp[v][d-1]):
dp[v][d-1]=1
Q.append((v,d-1))
for nv in E[v]:
if(dp[nv][d-1]): continue
dp[nv][d-1]=1
Q.append((nv,d-1))
if(ans[v]==0):
ans[v]=c
print(*ans,sep='\n')
resolve()
|
p03768
|
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n,m = list(map(int,readline().split()))
data = list(map(int,read().split()))
ab = data[:2*m]
q = data[2*m]
vdc = data[2*m+1:]
links = [[] for _ in range(n+1)]
it = iter(ab)
for a,b in zip(it,it):
links[a].append(b)
links[b].append(a)
ans = [0] * (n+1)
length = [-1] * (n+1)
for i in range(q-1,-1,-1):
v,d,c = vdc[i*3:i*3+3]
if( length[v] >= d):
continue
stack = [(v,d)]
while(stack):
vj,dj = stack.pop()
if(ans[vj]==0):
ans[vj] = c
if(dj > 0):
for vk in links[vj]:
if( length[vk] < dj-1):
stack.append((vk,dj-1))
print(('\n'.join(map(str,ans[1:]))))
|
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n,m = list(map(int,readline().split()))
data = list(map(int,read().split()))
ab = data[:2*m]
q = data[2*m]
vdc = data[2*m+1:]
links = [[] for _ in range(n+1)]
it = iter(ab)
for a,b in zip(it,it):
links[a].append(b)
links[b].append(a)
ans = [0] * (n+1)
length = [-1] * (n+1)
for i in range(q-1,-1,-1):
v,d,c = vdc[i*3:i*3+3]
if( length[v] >= d):
continue
length[v] = d
stack = [(v,d)]
while(stack):
vj,dj = stack.pop()
if(ans[vj]==0):
ans[vj] = c
if(dj > 0):
for vk in links[vj]:
if( length[vk] < dj-1):
stack.append((vk,dj-1))
length[vk] = dj-1
print(('\n'.join(map(str,ans[1:]))))
|
p03768
|
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint
sys.setrecursionlimit(2147483647)
INF = 10 ** 15
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 998244353
n, m = LI()
G = [[] for _ in range(n)]
for _ in range(m):
a, b = LI()
G[a - 1] += [b - 1]
G[b - 1] += [a - 1]
ans = [0] * n
q = I()
Q = LIR(q)
dq = deque()
depth = [-1] * n
for v, d, c in Q[::-1]:
if depth[v - 1] >= d:
continue
if ans[v - 1] == 0:
ans[v - 1] = c
depth[v - 1] = d
dq += [v - 1]
while dq:
u = dq.popleft()
for x in G[u]:
if depth[x] >= depth[u] - 1:
continue
depth[x] = depth[u] - 1
if ans[x] == 0:
ans[x] = c
if depth[u] - 1 == 0:
continue
dq += [x]
print(*ans, sep="\n")
|
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint
sys.setrecursionlimit(2147483647)
INF = 10 ** 15
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 998244353
n, m = LI()
G = [[] for _ in range(n)]
for _ in range(m):
a, b = LI()
G[a - 1] += [b - 1]
G[b - 1] += [a - 1]
ans = [0] * n
q = I()
Q = LIR(q)
dq = deque()
depth = [-1] * n
for v, d, c in Q[::-1]:
if depth[v - 1] >= d:
continue
if ans[v - 1] == 0:
ans[v - 1] = c
depth[v - 1] = d
if d:
dq += [v - 1]
while dq:
u = dq.popleft()
for x in G[u]:
if ans[x] == 0:
ans[x] = c
if depth[x] >= depth[u] - 1:
continue
depth[x] = depth[u] - 1
if depth[x]:
dq += [x]
print(*ans, sep="\n")
|
p03768
|
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
n,m = list(map(int, input().split()))
from collections import defaultdict
ns = defaultdict(set)
for _ in range(m):
u,v = list(map(int, input().split()))
u -= 1
v -= 1
ns[u].add(v)
ns[v].add(u)
dp = [[(-1,0)]*n for _ in range(11)]
q = int(eval(input()))
qs = [None]*q
for i in range(q):
v,d,c = tuple(map(int, input().split()))
v -= 1
qs[i] = (i,v,d,c)
from itertools import product
for i0,i,u in product(list(range(10,-1,-1)), list(range(0,11)), list(range(n))):
# for i0 in range(10, -1, -1):
if i==0:
for i,v,d,_ in qs:
if i0<=d:
dp[0][v] = (i,d)
else:
# for i in range(1,11):
# for u in range(n):
if dp[i-1][u][0]>dp[i][u][0]:
ind0, d0 = dp[i-1][u]
else:
ind0, d0 = dp[i][u]
for v in ns[u]:
ind,d = dp[i-1][v]
if ind>ind0 and d>0:# and i0<=i+d:
ind0, d0 = ind, d-1
dp[i][u] = (ind0, d0)
# print(dp[10])
write("\n".join(map(str, ((qs[dp[10][u][0]][3] if dp[10][u][0]>=0 else 0) for u in range(n)))))
|
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
n,m = list(map(int, input().split()))
from collections import defaultdict
ns = defaultdict(list)
for _ in range(m):
u,v = list(map(int, input().split()))
u -= 1
v -= 1
ns[u].append(v)
ns[v].append(u)
dp = [[-1]*n for _ in range(11)]
q = int(eval(input()))
qs = [None]*q
for i in range(q):
v,d,c = tuple(map(int, input().split()))
v -= 1
qs[i] = (i,v,d,c)
dp[d][v] = i
from itertools import product
for i,u in product(list(range(10,0,-1)), list(range(n))):
if dp[i][u]>=0:
dp[i-1][u] = max(dp[i-1][u], dp[i][u])
for v in ns[u]:
dp[i-1][v] = max(dp[i-1][v], dp[i][u])
write("\n".join(map(str, ((qs[dp[0][u]][3] if dp[0][u]>=0 else 0) for u in range(n)))))
|
p03768
|
from collections import deque
n, m = map(int, input().split())
G = [list() for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
a -= 1; b -= 1
G[a].append(b)
G[b].append(a)
Q = int(input())
queries = [tuple(map(int, input().split())) for _ in range(Q)][::-1]
dp = [[Q]*11 for _ in range(n)]
for i, (v, d, _) in enumerate(queries):
if dp[v-1][d] == Q:
dp[v-1][d] = i
for d in range(10, 0, -1):
for v in range(n):
if dp[v][d] < Q:
dp[v][d-1] = min(dp[v][d-1], dp[v][d])
for x in G[v]:
dp[x][d-1] = min(dp[x][d-1], dp[v][d])
queries.append((-1, -1, 0))
color = [queries[dp[v][0]][2] for v in range(n)]
print(*color, sep='\n')
|
import sys
readline = sys.stdin.readline
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
def solve():
n, m = nm()
G = [list() for _ in range(n)]
for _ in range(m):
a, b = nm()
a -= 1; b -= 1
G[a].append(b)
G[b].append(a)
Q = int(input())
queries = [tuple(nm()) for _ in range(Q)][::-1]
dp = [[Q]*11 for _ in range(n)]
for i in range(Q-1, -1, -1):
v, d, _ = queries[i]
dp[v-1][d] = i
for d in range(10, 0, -1):
for v in range(n):
for x in G[v] + [v]:
if dp[x][d-1] > dp[v][d]:
dp[x][d-1] = dp[v][d]
queries.append((-1, -1, 0))
color = [queries[dp[v][0]][2] for v in range(n)]
print(*color, sep='\n')
return
solve()
|
p03768
|
from collections import defaultdict
def paint(v, d, c):
if (v, d) in memo:
return
else:
memo[(v, d)] = True
if d == 0:
color[v] = c
elif d > 0:
paint(v, d-1, c)
for nb in graph[v]:
paint(nb, d-1, c)
memo = {}
N, M = list(map(int, input().split()))
color = [0] * N
graph = defaultdict(set)
for _ in range(M):
i, j = list(map(int, input().split()))
graph[i-1].add(j-1)
graph[j-1].add(i-1)
Q = int(eval(input()))
vdcs = []
for _ in range(Q):
v, d, c = list(map(int, input().split()))
vdcs.append((v-1, d, c))
vdcs.reverse()
for v, d, c in vdcs:
paint(v, d, c)
for c in color:
print(c)
|
from collections import defaultdict
def paint(v, d, c):
if color[v] == 0:
color[v] = c
if dp[v] >= d or d == 0:
return
dp[v] = d
for nb in graph[v]:
paint(nb, d-1, c)
N, M = list(map(int, input().split()))
dp = [0] * N
color = [0] * N
graph = defaultdict(set)
for _ in range(M):
i, j = list(map(int, input().split()))
graph[i-1].add(j-1)
graph[j-1].add(i-1)
Q = int(eval(input()))
vdcs = []
for _ in range(Q):
v, d, c = list(map(int, input().split()))
vdcs.append((v-1, d, c))
vdcs.reverse()
for v, d, c in vdcs:
paint(v, d, c)
for c in color:
print(c)
|
p03768
|
from collections import deque
from heapq import heappop, heappush
N,M = list(map(int, input().split()))
edge = [[] for _ in range(N)]
for _ in range(M):
a,b = list(map(int, input().split()))
edge[a-1].append(b-1)
edge[b-1].append(a-1)
Q = int(eval(input()))
VDC = [[int(i) for i in input().split()] for _ in range(Q)]
VDC.reverse()
INF = 10 ** 3
color = [-1] * N
def dijkstra(n, d, c):
dist = [INF] * N
dist[n] = 0
que = [(0, n)]
while que:
dv, v = heappop(que)
if dist[v] < dv: continue
if color[v] < 0: color[v] = c
if d == dv: continue
for w in edge[v]:
if dist[w] > dv + 1:
dist[w] = dv + 1
heappush(que, (dist[w], w))
def main():
for v,d,c in VDC:
dijkstra(v-1, d, c)
for c in color:
print((max(c, 0)))
if __name__ == "__main__":
main()
|
# 写経AC
N,M = map(int, input().split())
edge = [[] for _ in range(N)]
for _ in range(M):
a,b = map(int, input().split())
edge[a-1].append(b-1)
edge[b-1].append(a-1)
Q = int(input())
VDC = [[int(i) for i in input().split()] for _ in range(Q)]
for i in range(Q):
VDC[i][0] -= 1
color = [0] * N
# dp[v][d]: 頂点vから距離dは塗装済みか
visited = [[False] * 11 for _ in range(N)]
for v,d,c in reversed(VDC):
if visited[v][d]: # 既に塗装済み
continue
if color[v] == 0:
color[v] = c
for dist in range(d + 1):
# 距離d以下は塗装済み
visited[v][dist] = True
q = [v]
for t in range(d - 1, -1, -1):
qq = []
for v in q:
for w in edge[v]:
if visited[w][t]:
continue
for dist in range(t + 1):
visited[w][dist] = True
if color[w] == 0:
color[w] = c
qq.append(w)
q = qq
print(*color, sep="\n")
|
p03768
|
import queue
N,M=list(map(int,input().split()))
G=[[] for i in range(N)]
for i in range(M):
a,b=list(map(int,input().split()))
G[a-1].append(b-1)
G[b-1].append(a-1)
Q=int(eval(input()))
v=[0 for i in range(Q)]
d=[0 for i in range(Q)]
c=[0 for i in range(Q)]
for i in range(Q):
v[-i-1],d[-i-1],c[-i-1]=list(map(int,input().split()));v[-i-1]-=1
q=queue.Queue()
color=[0 for i in range(N)]
dp=[-1 for i in range(N)]
for t in range(Q):
if dp[v[t]]>=d[t]:
continue
dp[v[t]]=d[t]
q.put((v[t],d[t]))
while(not(q.empty())):
vv,dd=q.get()
if color[vv]==0:
color[vv]=c[t]
dd-=1
for y in G[vv]:
if dp[y]>=dd:
continue
dp[y]=dd
q.put((y,dd))
for line in color:
print(line)
|
from collections import deque
N,M=list(map(int,input().split()))
G=[[] for i in range(N)]
for i in range(M):
a,b=list(map(int,input().split()))
G[a-1].append(b-1)
G[b-1].append(a-1)
Q=int(eval(input()))
v=[0 for i in range(Q)]
d=[0 for i in range(Q)]
c=[0 for i in range(Q)]
for i in range(Q):
v[-i-1],d[-i-1],c[-i-1]=list(map(int,input().split()));v[-i-1]-=1
q=deque()
color=[0 for i in range(N)]
dp=[-1 for i in range(N)]
for t in range(Q):
if dp[v[t]]>=d[t]:
continue
dp[v[t]]=d[t]
q.append((v[t],d[t]))
while(q):
vv,dd=q.popleft()
if color[vv]==0:
color[vv]=c[t]
dd-=1
for y in G[vv]:
if dp[y]>=dd:
continue
dp[y]=dd
q.append((y,dd))
for line in color:
print(line)
|
p03768
|
#!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()
return
#B
def B():
def dfs(k,d,x,c):
if not f[x]:
f[x] = c
if k == d:
return
for y in v[x]:
dfs(k+1,d,y,c)
n,m = LI()
f = [0]*n
v = [[] for i in range(n)]
for i in range(m):
a,b = LI()
a -= 1
b -= 1
v[a].append(b)
v[b].append(a)
q = I()
l = LIR(q)
l = l[::-1]
for x,d,c in l:
x -= 1
dfs(0,d,x,c)
for i in f:
print(i)
return
#C
def C():
n = I()
return
#D
def D():
n = I()
return
#E
def E():
n = I()
return
#F
def F():
n = I()
return
#Solve
if __name__ == "__main__":
B()
|
#!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()
return
#B
def B():
def dfs(d,x,c):
if dp[(d,x)] != None:
return
dp[(d,x)] = 1
if d == 0:
f[x] = c
else:
dfs(d-1,x,c)
for y in v[x]:
dfs(d-1,y,c)
n,m = LI()
f = [0]*n
v = [[] for i in range(n)]
for i in range(m):
a,b = LI()
a -= 1
b -= 1
v[a].append(b)
v[b].append(a)
dp = defaultdict(lambda : None)
q = I()
l = LIR(q)
l = l[::-1]
for x,d,c in l:
x -= 1
dfs(d,x,c)
for i in f:
print(i)
return
#C
def C():
n = I()
return
#D
def D():
n = I()
return
#E
def E():
n = I()
return
#F
def F():
n = I()
return
#Solve
if __name__ == "__main__":
B()
|
p03768
|
import sys
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt, ceil, floor
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache, reduce
from operator import xor
INF = float("inf")
sys.setrecursionlimit(10**7)
# 4近傍(右, 下, 左, 上)
dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]
def inside(y: int, x: int, H: int, W: int) -> bool: return 0 <= y < H and 0 <= x < W
color, depth, graph = [], [], {}
def func(v, d, c):
if not color[v]:
color[v] = c
if depth[v] >= d or d == 0:
return
for u in graph[v]:
func(u, d - 1, c)
def main():
global color, depth, graph
N, M = map(int, input().split())
graph = [[] for _ in range(N)]
for _ in range(M):
a, b = map(int, input().split())
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
Q = int(input())
q = []
for _ in range(Q):
v, d, c = map(int, input().split())
q.append((v - 1, d, c))
color = [0] * N
depth = [0] * N
for i in range(Q - 1, -1, -1):
func(q[i][0], q[i][1], q[i][2])
print(*color, sep="\n")
if __name__ == '__main__':
main()
|
import sys
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt, ceil, floor
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache, reduce
from operator import xor
INF = float("inf")
sys.setrecursionlimit(10**7)
# 4近傍(右, 下, 左, 上)
dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]
def inside(y: int, x: int, H: int, W: int) -> bool: return 0 <= y < H and 0 <= x < W
color, depth, graph = [], [], {}
def func(v, d, c):
if not color[v]:
color[v] = c
if depth[v] >= d or d == 0:
return
depth[v] = d
for u in graph[v]:
func(u, d - 1, c)
def main():
global color, depth, graph
N, M = map(int, input().split())
graph = [[] for _ in range(N)]
for _ in range(M):
a, b = map(int, input().split())
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
Q = int(input())
q = []
for _ in range(Q):
v, d, c = map(int, input().split())
q.append((v - 1, d, c))
color = [0] * N
depth = [0] * N
for i in range(Q - 1, -1, -1):
func(q[i][0], q[i][1], q[i][2])
print(*color, sep="\n")
if __name__ == '__main__':
main()
|
p03768
|
n, m = list(map(int, input().split()))
g = {}
used = {i:[False for _ in range(11)] for i in range(n)}
color = [0 for _ in range(n)]
for _ in range(m):
u, v = list(map(int, input().split()))
u-=1
v-=1
if u not in g:
g[u] = []
if v not in g:
g[v] = []
g[u].append(v)
g[v].append(u)
q = int(eval(input()))
Q = []
for _ in range(q):
node, dis, col = list(map(int, input().split()))
Q.append([node-1, dis, col])
Q = Q[::-1]
def bfs(node, dis, col):
if used[node][dis] == True:
return
used[node][dis] == True
if color[node] == 0:
color[node] = col
if node in g and dis > 0:
for v in g[node]:
bfs(v, dis-1, col)
for node, dis, col in Q:
bfs(node, dis, col)
for x in color:
print(x)
|
n, m = list(map(int, input().split()))
g = {}
used = {i:[False for _ in range(11)] for i in range(n)}
color = [0 for _ in range(n)]
for _ in range(m):
u, v = list(map(int, input().split()))
u-=1
v-=1
if u not in g:
g[u] = []
if v not in g:
g[v] = []
g[u].append(v)
g[v].append(u)
q = int(eval(input()))
Q = []
for _ in range(q):
node, dis, col = list(map(int, input().split()))
Q.append([node-1, dis, col])
Q = Q[::-1]
def bfs(now, dist, col):
if dist < 0:
return
if used[now][dist]:
return
used[now][dist] = True
if not color[now]:
color[now] = col
if now in g:
for x in g[now]:
bfs(x, dist - 1, col)
for node, dis, col in Q:
bfs(node, dis, col)
for x in color:
print(x)
|
p03768
|
from collections import deque
N, M, *L = list(map(int, open(0).read().split()))
AB, VDC = L[:2 * M], L[2 * M + 1:]
E = [[] for _ in range(N + 1)]
for a, b in zip(*[iter(AB)] * 2):
E[a].append(b)
E[b].append(a)
colors = [0] * (N + 1)
visited = [-1] * (N + 1)
for v, d, c in reversed(tuple(zip(*[iter(VDC)] * 3))):
Q = deque([(d, v)])
while Q:
cnt, v = Q.popleft()
if visited[v] >= cnt:
continue
if colors[v] == 0:
colors[v] = c
visited[v] = cnt
if cnt > 0:
Q.extend((cnt - 1, u) for u in E[v])
for c in colors[1:]:
print(c)
|
from collections import deque
def main():
N, M, *L = list(map(int, open(0).read().split()))
E = [[] for _ in range(N + 1)]
for a, b in zip(*[iter(L[:2 * M])] * 2):
E[a].append(b)
E[b].append(a)
colors = [0] * (N + 1)
visited = [-1] * (N + 1)
for v, d, c in reversed(tuple(zip(*[iter(L[2 * M + 1:])] * 3))):
Q = deque([(d, v)])
while Q:
cnt, v = Q.popleft()
if visited[v] >= cnt:
continue
if colors[v] == 0:
colors[v] = c
visited[v] = cnt
if cnt > 0:
Q.extend((cnt - 1, u) for u in E[v])
for c in colors[1:]:
print(c)
if __name__ == '__main__':
main()
|
p03768
|
from collections import deque
def main():
N, M, *L = list(map(int, open(0).read().split()))
E = [[] for _ in range(N + 1)]
for a, b in zip(*[iter(L[:2 * M])] * 2):
E[a].append(b)
E[b].append(a)
colors = [0] * (N + 1)
visited = [False] * (N + 1)
for v, d, c in reversed(tuple(zip(*[iter(L[2 * M + 1:])] * 3))):
Q = deque([(d, v)])
while Q:
cnt, v = Q.popleft()
if colors[v] == 0:
colors[v] = c
visited[v] = cnt
if cnt > 0:
Q.extend((cnt - 1, u) for u in E[v] if visited[u] < cnt)
for c in colors[1:]:
print(c)
if __name__ == '__main__':
main()
|
from collections import deque
def main():
N, M, *L = list(map(int, open(0).read().split()))
E = [[] for _ in range(N + 1)]
for a, b in zip(*[iter(L[:2 * M])] * 2):
E[a].append(b)
E[b].append(a)
colors = [0] * (N + 1)
visited = [-1] * (N + 1)
for v, d, c in reversed(tuple(zip(*[iter(L[2 * M + 1:])] * 3))):
Q = deque([(d, v)])
while Q:
cnt, v = Q.popleft()
if visited[v] >= cnt:
continue
if colors[v] == 0:
colors[v] = c
visited[v] = cnt
if cnt > 0:
Q.extend((cnt - 1, u) for u in E[v] if visited[u] < cnt - 1)
for c in colors[1:]:
print(c)
if __name__ == '__main__':
main()
|
p03768
|
def painting(N,A,v,d,c):
if d < 0:
return
if A[v][d] == 0:
A[v][d] = c
for ni,n in enumerate(N[v]):
if n == 1:
painting(N,A,ni,d-1,c)
N,M = list(map(int,input().split()))
nodes = [[0]*N for i in range(N)]
dp = [[0]*11 for i in range(N)]
for m in range(M):
a,b = list(map(int,input().split()))
nodes[a-1][b-1] = 1
nodes[b-1][a-1] = 1
for i in range(N):
nodes[i][i] = 1
Q = int(eval(input()))
paint = [list(map(int,input().split())) for q in range(Q)]
paint.reverse()
for q in paint:
v,d,c = q
v = v - 1
painting(nodes,dp,v,d,c)
print(("\n".join(list(map(str,[dp[i][0] for i in range(N)])))))
|
def painting(N,A,v,d,c):
if d < 0:
return
if A[v][d] == 0:
A[v][d] = c
i = 0
while i < len(N):
if 1 in N[v][i:]:
i = i + N[v][i:].index(1)
else:
break
painting(N,A,i,d-1,c)
i = i + 1
N,M = list(map(int,input().split()))
nodes = [[0]*N for i in range(N)]
dp = [[0]*11 for i in range(N)]
for m in range(M):
a,b = list(map(int,input().split()))
nodes[a-1][b-1] = 1
nodes[b-1][a-1] = 1
for i in range(N):
nodes[i][i] = 1
Q = int(eval(input()))
paint = [list(map(int,input().split())) for q in range(Q)]
paint.reverse()
for q in paint:
v,d,c = q
v = v - 1
painting(nodes,dp,v,d,c)
print(("\n".join(list(map(str,[dp[i][0] for i in range(N)])))))
|
p03768
|
#b
#naive (TLE)
n,m = [int(i) for i in input().split()]
edges = [[] for _ in range(n)]
colors = [0]*n
for _ in range(m):
a,b = [int(i) for i in input().split()]
edges[a-1].append(b-1)
edges[b-1].append(a-1)
q = int(eval(input()))
info = []
for _ in range(q):
v,d,c = [int(i) for i in input().split()]
info.append((v,d,c))
info.reverse()
for tupple in info:
v,d,c = tupple
#bfs
queue = [v-1]
while(d>=0):
next_queue = []
for p in queue:
if colors[p]==0:
colors[p] = c
nodes = edges[p]
next_queue += nodes
d -= 1
queue = next_queue
for i in range(n):
print((colors[i]))
|
#b
#by using the condition d<=10, we should memorize V*d whether the pair is already searched.
#if searched, we can stop.
n,m = [int(i) for i in input().split()]
edges = [[] for _ in range(n)]
colors = [0]*n
checker = [[0 for _ in range(11)] for _ in range(n)]
for _ in range(m):
a,b = [int(i) for i in input().split()]
edges[a-1].append(b-1)
edges[b-1].append(a-1)
def dfs(d,v,c):
if checker[v][d] != 0 or d<0:
return
#d>=0 and (v,d) is not checked
if colors[v]==0: #not colored yet
colors[v] = c
checker[v][d] = 1 #checked
dfs(d-1, v, c) #dが低いやつについて全て埋めておく必要がある。もう先着ありで無理ですよ、って宣言。
nodes=edges[v]
for u in nodes:
dfs(d-1, u, c)
q = int(eval(input()))
info = []
for _ in range(q):
v,d,c = [int(i) for i in input().split()]
info.append((v-1,d,c))
info.reverse()
for tupple in info:
v,d,c = tupple
#not bfs but dfs
dfs(d,v,c)
for i in range(n):
print((colors[i]))
|
p03768
|
import sys
sys.setrecursionlimit(10**7)
def main():
n, m = list(map(int, input().split()))
G = [[] for _ in range(n)]
for _ in range(m):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
G[a].append(b)
G[b].append(a)
q = int(eval(input()))
vdc = [list(map(int, input().split())) for _ in range(q)][::-1]
dp = [[0]*11 for _ in range(n)]
def dfs(v, d, c):
if dp[v][d]:
return dp[v][d]
if d == 0:
dp[v][d] = c
return
for u in G[v]:
dfs(u, d-1, c)
dfs(v, d-1, c)
dp[v][d] = c
for v, d, c in vdc:
dfs(v-1, d, c)
for i in range(n):
print((dp[i][0]))
if __name__ == "__main__":
main()
|
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
def main():
n, m = list(map(int, input().split()))
G = [[] for _ in range(n)]
for _ in range(m):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
G[a].append(b)
G[b].append(a)
q = int(eval(input()))
vdc = [list(map(int, input().split())) for _ in range(q)][::-1]
dp = [[0]*11 for _ in range(n)]
def dfs(v, d, c):
if dp[v][d]:
return dp[v][d]
if d == 0:
dp[v][d] = c
return
for u in G[v]:
dfs(u, d-1, c)
dfs(v, d-1, c)
dp[v][d] = c
for v, d, c in vdc:
dfs(v-1, d, c)
for i in range(n):
print((dp[i][0]))
if __name__ == "__main__":
main()
|
p03768
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
"""
agc012 C
"""
from collections import defaultdict
n, m = list(map(int, input().split()))
graph = defaultdict(list)
for i in range(m):
a, b = list(map(int, input().split()))
graph[a].append(b)
graph[b].append(a)
q = int(eval(input()))
qlist = [tuple(map(int, input().split())) for i in range(q)]
qlist.reverse()
dp = [[-1]*11 for i in range(n+1)]
col = [0]
def updatedp(v, t, d):
if dp[v][d] == -1:
dp[v][d] = t
if d > 0:
updatedp(v, t, d-1)
for u in graph[v]:
updatedp(u, t, d-1)
t = 0
for v, d, c in qlist:
col.append(c)
updatedp(v, t, d)
t += 1
for i in range(1, n+1):
print((col[dp[i][0]+1]))
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
"""
agc012 C
"""
n, m = list(map(int, input().split()))
graph = [[] for i in range(n+1)]
for i in range(m):
a, b = list(map(int, input().split()))
graph[a].append(b)
graph[b].append(a)
q = int(eval(input()))
qlist = [tuple(map(int, input().split())) for i in range(q)]
qlist.reverse()
dp = [[-1]*11 for i in range(n+1)]
col = [0]
def updatedp(v, t, d):
if dp[v][d] == -1:
dp[v][d] = t
if d > 0:
updatedp(v, t, d-1)
for u in graph[v]:
updatedp(u, t, d-1)
t = 0
for v, d, c in qlist:
col.append(c)
updatedp(v, t, d)
t += 1
for i in range(1, n+1):
print((col[dp[i][0]+1]))
|
p03768
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
"""
agc012 C
"""
n, m = list(map(int, input().split()))
graph = [[] for i in range(n+1)]
for i in range(m):
a, b = list(map(int, input().split()))
graph[a].append(b)
graph[b].append(a)
q = int(eval(input()))
qlist = [tuple(map(int, input().split())) for i in range(q)]
qlist.reverse()
dp = [[-1]*11 for i in range(n+1)]
col = [0]
def updatedp(v, t, d):
if dp[v][d] == -1:
dp[v][d] = t
if d > 0:
updatedp(v, t, d-1)
for u in graph[v]:
updatedp(u, t, d-1)
t = 0
for v, d, c in qlist:
col.append(c)
updatedp(v, t, d)
t += 1
for i in range(1, n+1):
print((col[dp[i][0]+1]))
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
"""
agc012 C
"""
n, m = list(map(int, input().split()))
graph = [[] for i in range(n+1)]
for i in range(m):
a, b = list(map(int, input().split()))
graph[a].append(b)
graph[b].append(a)
q = int(eval(input()))
qlist = [tuple(map(int, input().split())) for i in range(q)]
qlist.reverse()
dp = [[-1]*11 for i in range(n+1)]
col = [0]
def updatedp(v, t, d):
if dp[v][d] == -1:
for i in range(d+1):
if dp[v][i] == -1:
dp[v][i] = t
if d > 0:
for u in graph[v]:
updatedp(u, t, d-1)
t = 0
for v, d, c in qlist:
col.append(c)
updatedp(v, t, d)
t += 1
for i in range(1, n+1):
print((col[dp[i][0]+1]))
|
p03768
|
n,m = list(map(int,input().split()))
p = [list(map(int,input().split())) for i in range(m)]
q = int(eval(input()))
v = [list(map(int,input().split())) for i in range(q)]
v = v[::-1]
l = [[] for i in range(n+1)]
for pi in p:
l[pi[0]].append(pi[1])
l[pi[1]].append(pi[0])
mita = [-1]*(n+1)
tugi = [set() for i in range(n+1)]
iro = [0] *(n+1)
def dfs(x,y,z):
if iro[x] == 0:
iro[x] = z
if mita[x] >=y:
return
for i in l[x]:
if y-1>=0:
dfs(i,y-1,z)
for ch in v:
dfs(ch[0],ch[1],ch[2])
for i in range(1,n+1):
print((iro[i]))
|
n,m = list(map(int,input().split()))
p = [list(map(int,input().split())) for i in range(m)]
q = int(eval(input()))
v = [list(map(int,input().split())) for i in range(q)]
v = v[::-1]
l = [[] for i in range(n+1)]
for pi in p:
l[pi[0]].append(pi[1])
l[pi[1]].append(pi[0])
mita = [-1]*(n+1)
tugi = [set() for i in range(n+1)]
iro = [0] *(n+1)
def dfs(x,y,z):
if iro[x] == 0:
iro[x] = z
if mita[x] >=y:
return
for i in l[x]:
if y-1>=0:
dfs(i,y-1,z)
mita[x] = y
for ch in v:
dfs(ch[0],ch[1],ch[2])
for i in range(1,n+1):
print((iro[i]))
|
p03768
|
import sys
input = sys.stdin.readline
n, m = list(map(int,input().split()))
nei =[[i] for i in range(n)]
for i in range(m):
a, b = list(map(int,input().split()))
a -= 1
b -= 1
nei[a].append(b)
nei[b].append(a)
color = [0 for i in range(n)]
#print(nei)
def paint(v,d,c):
if color[v] == 0:
color[v] = c
if d == 0:
return
for i in nei[v]:
paint(i,d-1,c)
q = int(eval(input()))
vbc = [list(map(int,input().split())) for i in range(q)][::-1]
for i in range(q):
paint(vbc[i][0]-1,vbc[i][1],vbc[i][2])
#print(color)
for i in range(n):
print((color[i]))
|
import sys
input = sys.stdin.readline
n, m = list(map(int,input().split()))
nei =[[i] for i in range(n)]
for i in range(m):
a, b = list(map(int,input().split()))
a -= 1
b -= 1
nei[a].append(b)
nei[b].append(a)
color = [0 for i in range(n)]
depth = [-1 for i in range(n)]
def paint(v,d,c,pre):
if d <= depth[v]:
return
depth[v] = d
if color[v] == 0:
color[v] = c
if d == 0:
return
for next in nei[v]:
if next == pre:
continue
paint(next,d-1,c,v)
q = int(eval(input()))
vbc = [list(map(int,input().split())) for i in range(q)][::-1]
for i in range(q):
paint(vbc[i][0]-1,vbc[i][1],vbc[i][2],-1)
#print(color)
for co in color:
print(co)
|
p03768
|
import sys
N,K=list(map(int,input().split()))
A=sorted([int(i) for i in input().split()])
def f(x):
L=[set() for i in range(N+1)]
L[0].add(0)
for i in range(N):
s=A[i]
if i==x:
s=0
for k in L[i]:
L[i+1].add(k)
if k+s<K:
L[i+1].add(k+s)
for k in L[N]:
if k+A[x]>=K:
return True
return False
ma=N-1
mi=0
if not f(N-1):
print(N)
sys.exit()
if f(0):
print((0))
sys.exit()
while ma-mi>1:
#print(ma,mi)
a=(ma+mi)//2
if f(a):
ma=a
else:
mi=a
print(ma)
|
import sys
N,K=list(map(int,input().split()))
A=sorted([int(i) for i in input().split()])
sa=sum(A)
def f(x):
if A[x]>=K:
return True
L=set()
L.add(0)
for i in range(N):
T=set()
s=A[i]
if i==x:
s=0
for k in L:
T.add(k)
if k+s<K:
T.add(k+s)
L=T
for k in L:
if k+A[x]>=K:
return True
return False
ma=N-1
mi=0
if not f(N-1):
print(N)
sys.exit()
if f(0):
print((0))
sys.exit()
while ma-mi>1:
#print(ma,mi)
a=(ma+mi)//2
if f(a):
ma=a
else:
mi=a
print(ma)
|
p03782
|
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
A = sorted([a for a in A if a < K])
N = len(A)
S = sum(A)
l, r = -1, N
while r - l > 1:
m = (l + r) // 2
B = A[:m] + A[m + 1:]
if S - A[m] < K - A[m]:
l = m
continue
dp = [False] * (K + 1)
dp[0] = True
flg= False
for i in range(N - 1):
for j in range(K + 1)[::-1]:
if B[i] > j:
continue
else:
dp[j] = dp[j - B[i]]
if dp[j] and K-A[m] <= j < K:
r = m
flg = True
break
if flg:
flg = False
break
else:
l = m
print(r)
|
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
A = sorted([a for a in A if a < K])
N = len(A)
S = sum(A)
# あああああああああああああああああああ\(^o^)/
if S < K:
print(N)
exit()
elif S - A[0] < N:
print((0))
exit()
l, r = -1, N
while r - l > 1:
m = (l + r) // 2
B = A[:m] + A[m + 1:]
if S - A[m] < K - A[m]:
l = m
continue
dp = [False] * (K + 1)
dp[0] = True
flg= False
for i in range(N - 1):
for j in range(K + 1)[::-1]:
if B[i] > j:
continue
else:
dp[j] = dp[j - B[i]]
if dp[j] and K-A[m] <= j < K:
r = m
flg = True
break
if flg:
flg = False
break
else:
l = m
print(r)
|
p03782
|
N, K = list(map(int, input().split()))
a = list(map(int, input().split()))
a = sorted(a)
if N == 1:
if a[0] >= K:
print((0))
else:
print((1))
else:
def check(i):
if a[i] >= K:
return True
if i == 0:
b = a[1:]
elif i == N - 1:
b = a[:N - 1]
else:
b = a[:i] + a[i+1:]
#print(b)
#ok = False
dp = [[False] * K for _ in range(N - 1)]
if b[0] < K:
dp[0][b[0]] = True
if K - a[i] <= b[0] < K:
return True
for j in range(1, N - 1):
for k in range(1, K):
#if b[j] == K:
# return True
#elif dp[j - 1][k] == True:
if dp[j - 1][k] == True:
dp[j][k] = True
elif k > b[j]:
if dp[j - 1][k - b[j]] == True:
dp[j][k] = True
if dp[j][k] == True and K - a[i] <= k < K:
return True
return False
def bi_search(lower, upper):
#print(lower, upper)
mid = (lower + upper) // 2
#print(mid)
if mid == 0 and check(mid) == True:
return 0
elif mid == N - 2 and check(mid + 1) == False:
return N
elif check(mid) == False and check(mid + 1) == True:
#print("hoge")
return mid + 1
elif check(mid) == True:
return bi_search(lower, mid)
else:
return bi_search(mid + 1, upper)
print((bi_search(0, N - 1)))
|
N, K = list(map(int, input().split()))
a = list(map(int, input().split()))
a = sorted(a)
if N == 1:
if a[0] >= K:
print((0))
else:
print((1))
else:
def check(i):
if a[i] >= K:
return True
if i == 0:
b = a[1:]
elif i == N - 1:
b = a[:N - 1]
else:
b = a[:i] + a[i+1:]
#print(b)
#ok = False
#dp = [[False] * K for _ in range(N - 1)]
dp = [False] * K
#dp[0] = True
if b[0] < K:
#dp[0][b[0]] = True
dp[b[0]] = True
if K - a[i] <= b[0] < K:
return True
for j in range(1, N - 1):
dp2 = [False] * K
#if b[j] < K:
#dp[b[j]] = True
for k in range(1, K):
#if b[j] == K:
# return True
#elif dp[j - 1][k] == True:
if dp[k] == True:
dp2[k] = True
#elif k > b[j]:
if k >= b[j]:
#if dp[j - 1][k - b[j]] == True:
if dp[k - b[j]] == True:
#dp[j][k] = True
dp2[k] = True
#if dp[j][k] == True and K - a[i] <= k < K:
if dp2[k] == True and K - a[i] <= k:
return True
#print(dp)
dp = dp2
return False
def bi_search(lower, upper):
#print(lower, upper)
mid = (lower + upper) // 2
#print(mid)
if mid == 0 and check(mid) == True:
return 0
elif mid == N - 2 and check(mid + 1) == False:
return N
elif check(mid) == False and check(mid + 1) == True:
#print("hoge")
return mid + 1
elif check(mid) == True:
return bi_search(lower, mid)
else:
return bi_search(mid, upper)
print((bi_search(0, N - 1)))
|
p03782
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.