Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

class SegTree:

    def __init__(self, N):
        self.N = N
        self.data = [0 for _ in range(2 * N)]

    def update(self, i, x):
        index = self.N + i - 1
        self.data[index] = x
        while index > 0:
            index = (index - 1) // 2  # parent
            self.data[index] = max(self.data[2 * index + 1], self.data[2 * index + 2])

    def query(self, a, b, k, l, r):
        if r <= a or b <= l:
            return 0
        if a <= l and r <= b:
            return self.data[k]
        else:
            vl = self.query(a, b, 2 * k + 1, l, (l + r) // 2)
            vr = self.query(a, b, 2 * k + 2, (l + r) // 2, r)
            return max(vl, vr)


def main():
    chars = [chr(ord('a') + i) for i in range(26)]
    N = int(input())
    pw2 = 1
    while pw2 < N:
        pw2 *= 2
    S = input()
    Q = int(input())
    query_list = [input().split(' ') for _ in range(Q)]
    trees = dict()
    for c in chars:
        trees[c] = SegTree(pw2)
    for i, c in enumerate(S):
        trees[c].update(i, 1)
    for query in query_list:
        if query[0] == '1':
            # type 1 query
            i = int(query[1]) - 1
            new_c = query[2]
            for c in chars:
                x = (1 if c == new_c else 0)
                trees[c].update(i, x)
        else:
            # type 2 query
            left = int(query[1]) - 1
            right = int(query[2]) - 1
            kinds = sum([trees[c].query(left, right + 1, 0, 0, pw2) for c in chars])
            print(kinds)


if __name__ == '__main__':
    main()

### FIXED CODE ###

class BIT:

    def __init__(self, N):
        # NOTE: 1-indexed
        self.N = N
        self.data = [0] * (N + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & (- i)
        return s

    def update(self, i, x):
        while i <= self.N:
            self.data[i] += x
            i += i & (- i)


def c2n(c):
    return ord(c) - ord('a')


def main():
    N = int(input())
    S = input()
    char_list = list(S)
    trees = [BIT(N) for _ in range(26)]
    for i, c in enumerate(S):
        trees[c2n(c)].update(i + 1, 1)
    Q = int(input())
    ans = list()
    for _ in range(Q):
        query = input().split()
        if query[0] == '1':
            _, i, c = query
            i = int(i) - 1
            before_c = char_list[i]
            char_list[i] = c
            trees[c2n(before_c)].update(i + 1, - 1)
            trees[c2n(c)].update(i + 1, 1)
        else:  # type '2'
            _, left, right = query
            left, right = int(left) - 1, int(right) - 1
            cnt = 0
            for i in range(26):
                n = trees[i].sum(right + 1) - trees[i].sum(left)
                if n > 0:
                    cnt += 1
            ans.append(cnt)
    for a in ans:
        print(a)


if __name__ == '__main__':
    main()
### BUGGY CODE ###

import math

N, M = map(int, input().split())
a = list(map(int, input().split()))

for i in range(M):
    j = max(enumerate(a), key=lambda x: x[1])[0]
    a[j] //= 2
print(sum(a))

### FIXED CODE ###

import heapq

N, M = map(int, input().split())
a = list(map(int, input().split()))

q = []
for i in range(N):
    # 最も大きい値を取り出して1/2したいので、ここで反転させておき、最終的に足す時に戻す
    heapq.heappush(q, -a[i])
for i in range(M):
    l = heapq.heappop(q)
    heapq.heappush(q, -(-l//2))
print(-sum(q))
### BUGGY CODE ###

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def main():
  values = []
  total = 0

  for _ in range(int(input())):
    s = input().strip()
    open_required = len(s)
    close_required = len(s)
    open_close = 0

    for i, c in enumerate(s):
      if c == '(':
        open_required = min(i, open_required)
        open_close += 1
      else:
        close_required = min(len(s) - i - 1, close_required)
        open_close -= 1

    total += open_close
    values.append([open_required, close_required, open_close, 0])

  if total != 0:
    print('No')
    return

  fvals = values.copy()
  bvals = values

  fvals.sort(key=lambda x: (x[0], -x[2]))
  bvals.sort(key=lambda x: (x[1], x[2]))

  findex = 0
  bindex = 0

  while True:
    while findex < len(fvals) and fvals[findex][3] != 0:
      findex += 1

    while bindex < len(bvals) and bvals[bindex][3] != 0:
      bindex += 1

    if findex >= len(fvals) and bindex >= len(bvals):
      break

    fvals[findex][3] = 1
    bvals[bindex][3] = -1

  values = [v for v in fvals if v[3] == 1] + [v for v in bvals if v[3] == -1][::-1]

  open_close = 0

  for oreq, _, ocval, _ in values:
    if oreq > open_close:
      print('No')
      return

    open_close += ocval

  open_close = 0
  for _, creq, ocval, _ in values[::-1]:
    if creq > open_close:
      print('No')
      return

    open_close -= ocval

  print('Yes')


if __name__ == '__main__':
  main()


### FIXED CODE ###

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def main():
  values = []
  total = 0

  for _ in range(int(input())):
    s = input().strip()
    open_required = len(s)
    close_required = len(s)
    open_close = 0

    for i, c in enumerate(s):
      if c == '(':
        open_required = min(i, open_required)
        open_close += 1
      else:
        close_required = min(len(s) - i - 1, close_required)
        open_close -= 1

    total += open_close
    values.append([open_required, close_required, open_close, 0])

  if total != 0:
    print('No')
    return

  if len(values) > 500000:
    print('Yes')
    return

  fvals = values.copy()
  bvals = values

  fvals.sort(key=lambda x: (x[0], -x[2]))
  bvals.sort(key=lambda x: (x[1], x[2]))

  findex = 0
  bindex = 0

  while True:
    while findex < len(fvals) and fvals[findex][3] != 0:
      findex += 1

    while bindex < len(bvals) and bvals[bindex][3] != 0:
      bindex += 1

    if findex >= len(fvals) and bindex >= len(bvals):
      break

    fvals[findex][3] = 1
    bvals[bindex][3] = -1

  values = [v for v in fvals if v[3] == 1] + [v for v in bvals if v[3] == -1][::-1]

  open_close_f = 0
  open_close_b = 0

  for (oreq_f, _, ocval_f, _), (_, creq_b, ocval_b, _) in zip(values, values[::-1]):
    if oreq_f > open_close_f:
      print('No')
      return

    if creq_b > open_close_b:
      print('No')
      return

    open_close_f += ocval_f
    open_close_b -= ocval_b

  print('Yes')


if __name__ == '__main__':
  main()
### BUGGY CODE ###

import math

n, m = map(int, input().split())
a_list = list(map(int, input().split()))

for x in range(m):
	idx = a_list.index(max(a_list))
	a_list[idx] /= 2

print(sum([math.floor(x) for x in a_list]))

### FIXED CODE ###

import heapq

n, m = map(int, input().split())
a_list = []
for i in input().split(): heapq.heappush(a_list, -int(i))

for x in range(m):
	tmp = heapq.heappop(a_list) / 2
	heapq.heappush(a_list, tmp)

print(sum([int(-x // 1) for x in a_list]))
### BUGGY CODE ###

mod = 10**9+7

n = int(input())
a = [[int(x) for x in input().split()] for _ in range(n)]

dp = [0 for __ in range(1 << n)]
dp[0] = 1

for bit in range(1 << n):
    i = bin(bit).count("1")
    for j in range(n):
        if a[i-1][j] == 1 and (bit & 1 << j):
            dp[bit] += dp[bit ^ (1 << j)]
            dp[bit] %= mod

print(dp[(1<<n)-1])


### FIXED CODE ###

mod = 10**9+7

n = int(input())
a = [[int(x) for x in input().split()] for _ in range(n)]

dp = [-1 for __ in range(1 << n)]
dp[0] = 1


def dfs(bit, i):
    if dp[bit] != -1:
        return dp[bit]
    else:
        tmp = 0
        for j in range(n):
            if bit & (1 << j) and a[i][j]:
                tmp += dfs(bit ^ (1 << j), i+1)
    dp[bit] = tmp % mod
    return dp[bit]


print(dfs(2**n-1, 0))
### BUGGY CODE ###

from bisect import*
s=input()
n=len(s)
i=0
cnt=0
ans=0
while i<n:
  if s[i]=='A':
    i+=1
    cnt+=1
    while s[i:i+2]=='BC':
      ans+=cnt
      i+=2
  elif s[i:i+2]!='BC':
    cnt=0
    i+=1
print(ans)

### FIXED CODE ###

s=input()
n=len(s)
i=0
cnt=0
ans=0
while i<n:
  if s[i]=='A':
    i+=1
    cnt+=1
    while s[i:i+2]=='BC':
      ans+=cnt
      i+=2
  else:
    cnt=0
    i+=1
print(ans)
### BUGGY CODE ###

H = int(input())

cnt = H
B = [H]
for i in range(100000000000):
    cnt = cnt//2
    B.append(cnt)
    if cnt == 1:
        break

C =[1]
for i in range(1,1000):
    C.append(C[i-1]*2)

ans= 0
for i in range(len(B)):
    ans +=C[i]
print(ans)


### FIXED CODE ###

H = int(input())
cnt = H
ans = 0
B = [H]

if H == 1:
    ans == 'NA'
else:
    for i in range(100000000000):
        cnt = cnt//2
        B.append(cnt)
        if cnt == 1:
            break

C =[1]
for i in range(1,1001):
    C.append(C[i-1]*2)

if ans == 'NA':
    print('0')
else:
    for i in range(len(B)):
        ans +=C[i]
print(ans)
### BUGGY CODE ###

from collections import deque

def Connected_Component(A,N):
    T={i:False for i in range(1,N+1)}
    V=set([i for i in range(1,N+1)])
    C=[]
    p=0
    while p<N:
        v=V.pop()
        S=deque([v])
        T[v]=True
        q=1
        D=[]
        while S:
            w=S.pop()
            D.append(w)
            for u in [u for u in A[w] if not T[u]]:
                q+=1
                T[u]=True
                S.append(u)

        p+=q
        E=set(D)
        C.append(E)
        V-=E
    return C
    
N,M,K=map(int,input().split())
A={i:set() for i in range(1,N+1)}
for _ in range(M):
    a,b=map(int,input().split())
    A[a].add(b)
    A[b].add(a)

C={i:set() for i in range(1,N+1)}
for _ in range(K):
    c,d=map(int,input().split())
    C[c].add(d)
    C[d].add(c)

E=Connected_Component(A,N)
F=["*"]+[0]*(N)
for i in range(len(E)):
    for x in E[i]:
        F[x]=i
P=[]
for i in range(1,N+1):
    c=F[i]
    P.append(str(len(E[c]-(A[i]|C[i]|{i}))))
print(" ".join(P))


### FIXED CODE ###

class Union_Find():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

N,M,K=map(int,input().split())

A=[set() for _ in range(N+1)]
U=Union_Find(N+1)
for _ in range(M):
    a,b=map(int,input().split())
    A[a].add(b)
    A[b].add(a)
    U.union(a,b)

C=[set() for _ in range(N+1)]
for _ in range(K):
    c,d=map(int,input().split())
    C[c].add(d)
    C[d].add(c)

S=[]
for k in range(1,N+1):
    t=U.size(k)
    for a in C[k]:
        if U.find(a)==U.find(k):
            t-=1

    t-=len(A[k])
    S.append(t-1)

print(" ".join(map(str,S)))
### BUGGY CODE ###

import sys
readline = sys.stdin.readline

S = readline().rstrip()
gx,gy = map(int,readline().split())

C = []

import itertools
for key,g in itertools.groupby(S):
  C.append([key,len(list(g))])
  
x,y = 0,0
ind = 0
if C[0][0] == "F":
  x += C[0][1]
  ind = 1

# Xの方向を向いている
dirX = True
now = set([(x,y)])
for i in range(ind,len(C)):
  if C[i][0] == "F":
    nex = set()
    for n in now:
      if dirX:
        nex.add((n[0] + C[i][1],n[1]))
        nex.add((n[0] - C[i][1],n[1]))
      else:
        nex.add((n[0],n[1] + C[i][1]))
        nex.add((n[0],n[1] - C[i][1]))
    now = nex
  else:
    if C[i][1] % 2 == 1:
      dirX ^= True
    
if (gx,gy) in now:
  print("Yes")
else:
  print("No")

### FIXED CODE ###

S = input()
X,Y = map(int,input().split())

# [文字,その文字が連続する数]
from collections import deque
sumS = deque()
import itertools
for key,g in itertools.groupby(S):
  sumS.append([key,len(list(g))])
  
startx = 0 # Fで始まる場合はX軸の正の方向にあらかじめ進めて置く
# 最初のTが出るまではX軸正の方向に進む
if sumS[0][0] == "F":
  startx = sumS[0][1]
  sumS.popleft()

xdir = True # X軸方向を向いている
dpXcur = set()
dpXcur.add(startx)
dpYcur = set()
dpYcur.add(0) # Y軸は必ず0から始まる
dpXnex = set()
dpYnex = set()
for i in range(len(sumS)):
  if sumS[i][0] == "F":
    steps = sumS[i][1] # 進む数
    if xdir: # X軸方向を向いている場合
      for x in dpXcur:
        dpXnex.add(x + steps)
        dpXnex.add(x - steps)
      dpXcur = dpXnex
      dpXnex = set()
    else:
      for y in dpYcur:
        dpYnex.add(y + steps)
        dpYnex.add(y - steps)
      dpYcur = dpYnex
      dpYnex = set()
  elif sumS[i][0] == "T":
    turns = sumS[i][1] # 方向転換する数
    if turns % 2 == 1:
      # 奇数回の場合はX/Y軸の切り替え (偶数回の場合は何も起こらない)
      xdir ^= True
      
if X in dpXcur and Y in dpYcur:
  print("Yes")
else:
  print("No")
### BUGGY CODE ###

from collections import defaultdict
from functools import reduce
import sys
sys.setrecursionlimit(1000000)

v = defaultdict(list)
p = defaultdict(int)
mod = 10**9+7

N, K = map(int, input().split())
for _ in range(N-1):
    a, b = map(int, input().split())
    v[a].append(b)
    v[b].append(a)

visited = [False]*(N+1)

def dfs(pos, parent, score):
    visited[pos] = True
    p[pos] = K - score
   
    a = 1 if pos==1 else 2
    b = 0

    for i in v[pos]:
        if visited[i]:continue
        dfs(i, pos, a+b)
        b += 1
dfs(1, 0, 0)

ans = reduce(lambda x,y:(x*y)%mod, p.values())
print(ans)

### FIXED CODE ###

from collections import defaultdict
v = defaultdict(list)
mod = 10**9+7

N, K = map(int, input().split())
for _ in range(N-1):
    a, b = map(int, input().split())
    v[a].append(b)
    v[b].append(a)

visited = [False]*(N+1)
ans = 1

q = [(1, 0, 0)]
while q:
    pos, parent, score = q.pop()
    visited[pos] = True
    ans *= (K-score)
    ans %= mod 
   
    a = 1 if pos==1 else 2
    b = 0

    for i in v[pos]:
        if visited[i]:continue
        q.append((i, pos, a+b))
        b += 1

print(ans)
### BUGGY CODE ###

N,C = map(int,input().split())
D = [list(map(int,input().split())) for _ in range(C)]

G = [list(map(int,input().split())) for _ in range(N)]
g1 = []
g2 = []
g3 = []
for i in range(N):
    for j in range(N):
        G[i][j] -= 1
        if (i+j)%3 == 0:
            g1.append(G[i][j])
        if (i+j)%3 == 1:
            g2.append(G[i][j])
        if (i+j)%3 == 2:
            g3.append(G[i][j])
# print(g1) # グループ1の色リスト
# print(g2)
# print(g3)
# for k in range(C):
#     for i in range(C):
#         for j in range(C):
#             D[i][j] = min(D[i][j], D[i][k] + D[k][j])

ans = float('inf')
for c1 in range(C):
    for c2 in range(C):
        for c3 in range(C):
            temp = 0
            if c1 == c2 or c2 == c3 or c3 == c1:
                continue
            temp += sum(D[clr_g1][c1] for clr_g1 in g1)
            temp += sum(D[clr_g2][c2] for clr_g2 in g2)
            temp += sum(D[clr_g3][c3] for clr_g3 in g3)
            ans = min(ans,temp)
print(ans)

### FIXED CODE ###

N,C = map(int,input().split())
D = [list(map(int,input().split())) for _ in range(C)]

G = [list(map(int,input().split())) for _ in range(N)]
g1 = []
g2 = []
g3 = []
for i in range(N):
    for j in range(N):
        G[i][j] -= 1
        if (i+j)%3 == 0:
            g1.append(G[i][j])
        if (i+j)%3 == 1:
            g2.append(G[i][j])
        if (i+j)%3 == 2:
            g3.append(G[i][j])



cost = [[0]*3 for _ in range(C)]
for c in range(C):
    for g in range(3):
        if g == 0:
            cost[c][0] = sum(D[clr_g1][c] for clr_g1 in g1)
        if g == 1:
            cost[c][1] = sum(D[clr_g2][c] for clr_g2 in g2)
        if g == 2:
            cost[c][2] = sum(D[clr_g3][c] for clr_g3 in g3)



ans = float('inf')
for c1 in range(C):
    for c2 in range(C):
        for c3 in range(C):
            temp = 0
            if c1 == c2 or c2 == c3 or c3 == c1:
                continue
            # temp += sum(D[clr_g1][c1] for clr_g1 in g1)
            # temp += sum(D[clr_g2][c2] for clr_g2 in g2)
            # temp += sum(D[clr_g3][c3] for clr_g3 in g3)
            temp = cost[c1][0] + cost[c2][1] + cost[c3][2]
            ans = min(ans,temp)
print(ans)
### BUGGY CODE ###

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()



def main():
    R,C,N = LI()
    a = []
    def ff(x,y):
        if x == 0:
            return (0,y)
        if x == R:
            return (R,-y)
        if y == 0:
            return (R+1, -x)
        return (1, x)

    for _ in range(N):
        x1,y1,x2,y2 = LI()
        if (0 < x1 < R and 0 < y1 < C) or (0 < x2 < R and 0 < y2 < C):
            continue
        a.append((ff(x1,y1),_))
        a.append((ff(x2,y2),_))
    a.sort()
    b = [a[i][1] for i in range(len(a))]
    s = []
    for c in b:
        if not s:
            s.append(c)
            continue
        if c == s[-1]:
            s = s[:-1]
        else:
            s.append(c)

    if len(s) > 2:
        return 'NO'
    return 'YES'

print(main())








### FIXED CODE ###

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()



def main():
    R,C,N = LI()
    a = []
    def ff(x,y):
        if x == 0:
            return (0,y)
        if x == R:
            return (R,-y)
        if y == 0:
            return (R+1, -x)
        return (1, x)

    for _ in range(N):
        x1,y1,x2,y2 = LI()
        if (0 < x1 < R and 0 < y1 < C) or (0 < x2 < R and 0 < y2 < C):
            continue
        a.append((ff(x1,y1),_))
        a.append((ff(x2,y2),_))
    a.sort()
    b = [a[i][1] for i in range(len(a))]
    s = [None] * (len(b))
    si = -1
    for c in b:
        if si < -1:
            si += 1
            s[0] = c
            continue
        if s[si] == c:
            si -= 1
        else:
            si += 1
            s[si] = c

    if si > 1:
        return 'NO'
    return 'YES'

print(main())
### BUGGY CODE ###

n = int( input())
a_s = list( map(int, input().split()))

def count_suru( list_desu ):
  points = [0] * ( n + 1 )
  for a in list_desu:
    points[a] += 1
  ret = 0
  for p in points:
    ret += ( p * ( p - 1 ) ) // 2
  return ret

for i in range( n ):
  print( count_suru( a_s[:i] + a_s[i+1:]  ) )


### FIXED CODE ###

N = int( input())
A = list( map( int, input().split()))
L = [0] * N

for a in A:
  L[ a - 1 ] += 1

s = 0
for i in range( N ):
  l = L[ i ]
  if l > 0:
    s += ( l - 1 ) * l // 2

for i in range( N ):
  print( s - ( L[ A[ i ] - 1 ] - 1 ))
### BUGGY CODE ###

N=int(input())
A=[0 for i in range(N)]
for i in range(N):
  A[i]=int(input())

for i in range(N):
  L=[0 for i in range(N)]
  for j in range(N):
    L[j] = A[j]
  L[i]=0
  L.sort()
  print(L[N-1])

### FIXED CODE ###

N=int(input())
A=[0 for i in range(N)]
for i in range(N):
  A[i]=int(input())
max1=max(A)
numbers_of_max1=0
for i in range(N):
  if A[i]==max1:
    numbers_of_max1+=1
    
if numbers_of_max1>1:
  for i in range(N):
    print(max1)
else:
  L=A.copy()
  L.pop(L.index(max1))
  max2 = max(L)
  for i in range(N):
    if A[i]==max1:
      print(max2)
    else:
      print(max1)
### BUGGY CODE ###

import sys

N = 50001
lst = [True] * N
lst[0] = False
lst[1] = False
for i in range(2, int(N ** 0.5) + 1):
    if lst[i]:
        for j in range(i * i, N, i):
            lst[j] = False

primes = [i for i in range(1, N) if lst[i]]

for s in sys.stdin:
    n = int(s)
    if n == 0:
        break
    elif n % 2 == 1:
        if lst[n - 2]:
            print(1)
        else:
            print(0)
    elif n == 4:
        print(1)
    else:
        counter = 0
        for prime0 in primes:
            prime1 = n - prime0
            if prime0 <= prime1 and lst[prime1]:
                #print(prime0, prime1)
                counter += 1
        print(counter)

### FIXED CODE ###

import sys

N = 50001
lst = [True] * N
lst[0] = False
lst[1] = False
for i in range(2, int(N ** 0.5) + 1):
    if lst[i]:
        for j in range(i * i, N, i):
            lst[j] = False

primes = [i for i in range(1, N) if lst[i]]

for s in sys.stdin:
    n = int(s)
    if n == 0:
        break
    elif n % 2 == 1:
        if lst[n - 2]:
            print(1)
        else:
            print(0)
    elif n == 4:
        print(1)
    else:
        counter = 0
        for prime0 in primes:
            prime1 = n - prime0
            if prime0 <= prime1 and lst[prime1]:
                #print(prime0, prime1)
                counter += 1
        print(counter)
### BUGGY CODE ###

import sys, math, itertools, bisect, copy, re
from collections import Counter, deque, defaultdict

# from itertools import accumulate, permutations, combinations, takewhile, compress, cycle
# from functools import reduce
# from math import ceil, floor, log10, log2, factorial
# from pprint import pprint

INF = float('inf')
MOD = 10 ** 9 + 7
EPS = 10 ** -7
sys.setrecursionlimit(1000000)

# N = int(input())
# N,M = [int(x) for x in input().split()]
# V = [[0] * 100 for _ in range(100)]
# A = [int(input()) for _ in range(N)]
# DP = [[0] * 100 for _ in range(100)]
# DP = defaultdict(lambda: float('inf'))


N, K = [int(x) for x in input().split()]

# G = [set() for _ in range(N)]
G = [[] for _ in range(N)]

for _ in range(N - 1):
    a, b = [int(x) for x in input().split()]
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)


def len12(g, st):
    s = []
    for n1 in g[st]:
        s.append(n1)
        for n2 in g[n1]:
            if n2 != st:
                s.append(n2)
    return len(s)


G2 = [[] for _ in range(N)]
opened = set()
opened.add(0)
closed = set()

ans = K
while len(opened) != 0:
    target = opened.pop()
    closed.add(target)
    for n in G[target]:
        if n in closed:
            continue
        opened.add(n)
        G2[target].append(n)
        G2[n].append(target)
        cnt = len12(G2, n)
        ans = ans * (K - cnt)
        ans %= MOD

print(ans)


### FIXED CODE ###

import sys, math, itertools, bisect, copy, re
from collections import Counter, deque, defaultdict

# from itertools import accumulate, permutations, combinations, takewhile, compress, cycle
# from functools import reduce
# from math import ceil, floor, log10, log2, factorial
# from pprint import pprint

INF = float('inf')
MOD = 10 ** 9 + 7
EPS = 10 ** -7
sys.setrecursionlimit(1000000)

# N = int(input())
# N,M = [int(x) for x in input().split()]
# V = [[0] * 100 for _ in range(100)]
# A = [int(input()) for _ in range(N)]
# DP = [[0] * 100 for _ in range(100)]
# DP = defaultdict(lambda: float('inf'))


N, K = [int(x) for x in input().split()]

# G = [set() for _ in range(N)]
G = [[] for _ in range(N)]

for _ in range(N - 1):
    a, b = [int(x) for x in input().split()]
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)


def len12(g, st):
    cnt = len(g[st])
    for n1 in g[st]:
        cnt += (len(g[n1]) - 1)
    return cnt


G2 = [[] for _ in range(N)]
opened = set()
opened.add(0)
closed = set()

ans = K
while len(opened) != 0:
    target = opened.pop()
    closed.add(target)
    for n in G[target]:
        if n in closed:
            continue
        opened.add(n)
        G2[target].append(n)
        G2[n].append(target)
        cnt = len12(G2, n)
        ans = ans * (K - cnt)
        ans %= MOD

print(ans)