import java.util.ArrayList;
import java.util.Scanner;

public class Solution {
    static ArrayList<Integer>[] adj;
    static int[] vis;
    static int cnt = 0;

    static long mod = (long)1e9+7;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        adj = new ArrayList[n];

        for(int i=0;i<n;i++){
            adj[i] = new ArrayList<Integer>();
        }

        for(int i=0;i<n-1;i++){
            int u = sc.nextInt()-1;
            int v = sc.nextInt()-1;
            int col = sc.nextInt();
            if(col==0){
                adj[u].add(v);
                adj[v].add(u);
            }
        }

        long ans = fast_pow(n,k);

        long remaining = 0;

        vis = new int[n];

        for(int i=0;i<n;i++){
            if(vis[i]==0){
                cnt = 0;
                dfs(i);
                remaining +=fast_pow(cnt,k);
            }
        }
        remaining = remaining % mod;
        System.out.println( (ans - remaining)%mod);
    }

    private static void dfs(int i) {
        vis[i] = 1;
        cnt++;
        for(int j: adj[i]){
            if(vis[j]==0){
                dfs(j);
            }
        }
    }

    static long fast_pow(long a, long b) {
        if(b == 0)
            return 1L;

        long val = fast_pow(a, b / 2);

        if(b % 2 == 0)
            return val * val % mod;
        else{
            return val * val % mod * a % mod;
        }

    }
}


import java.util.ArrayList;
import java.util.Scanner;

public class Solution {
    static ArrayList<Integer>[] adj;
    static int[] vis;
    static int cnt = 0;

    static long mod = (long)1e9+7;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        adj = new ArrayList[n];

        for(int i=0;i<n;i++){
            adj[i] = new ArrayList<Integer>();
        }

        for(int i=0;i<n-1;i++){
            int u = sc.nextInt()-1;
            int v = sc.nextInt()-1;
            int col = sc.nextInt();
            if(col==0){
                adj[u].add(v);
                adj[v].add(u);
            }
        }

        long ans = fast_pow(n,k);

        long remaining = 0;

        vis = new int[n];

        for(int i=0;i<n;i++){
            if(vis[i]==0){
                cnt = 0;
                dfs(i);
                remaining +=fast_pow(cnt,k);
            }
        }
        remaining %= mod;
        System.out.println( (ans - remaining+mod)%mod);
    }

    private static void dfs(int i) {
        vis[i] = 1;
        cnt++;
        for(int j: adj[i]){
            if(vis[j]==0){
                dfs(j);
            }
        }
    }

    static long fast_pow(long a, long b) {
        if(b == 0)
            return 1L;

        long val = fast_pow(a, b / 2);

        if(b % 2 == 0)
            return val * val % mod;
        else{
            return val * val % mod * a % mod;
        }

    }
}


import java.util.ArrayList;
import java.util.Scanner;

public class Solution {
    static ArrayList<Integer>[] adj;
    static int[] vis;
    static int cnt = 0;

    static long mod = (long)1e9+7;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        adj = new ArrayList[n];

        for(int i=0;i<n;i++){
            adj[i] = new ArrayList<Integer>();
        }

        for(int i=0;i<n-1;i++){
            int u = sc.nextInt()-1;
            int v = sc.nextInt()-1;
            int col = sc.nextInt();
            if(col==0){
                adj[u].add(v);
                adj[v].add(u);
            }
        }

        long ans = fast_pow(n,k);

        long remaining = 0;

        vis = new int[n];

        for(int i=0;i<n;i++){
            if(vis[i]==0){
                cnt = 0;
                dfs(i);
                remaining +=fast_pow(cnt,k) % mod;
            }
        }
        remaining = remaining % mod;
        System.out.println( (ans - remaining)%mod);
    }

    private static void dfs(int i) {
        vis[i] = 1;
        cnt++;
        for(int j: adj[i]){
            if(vis[j]==0){
                dfs(j);
            }
        }
    }

    static long fast_pow(long a, long b) {
        if(b == 0)
            return 1L;

        long val = fast_pow(a, b / 2);

        if(b % 2 == 0)
            return val * val % mod;
        else{
            return val * val % mod * a % mod;
        }

    }
}


//package com.company;
import java.io.*;
import java.util.*;
public class Main
{
	public static void main(String args[])
	{
		new Main().run();
	}
	static long power(long x, long y, long p)
	{
		// Initialize result
		long res = 1;

		// Update x if it is more
		// than or equal to p
		x = x % p;

		if (x == 0) return 0; // In case x is divisible by p;

		while (y > 0)
		{
			// If y is odd, multiply x
			// with result
			if((y & 1)==1)
				res = (res * x) % p;

			// y must be even now
			// y = y / 2
			y = y >> 1;
			x = (x * x) % p;
		}
		return res;
	}
	public void solve()throws IOException
	{
		int n=nextInt();
		long m=nextLong();
		Graph g=new Graph(n);
		int ans[]=new int[n];
		for (int i=0;i<n-1;i++)
		{
			int u=nextInt();
			int v=nextInt();
			int c=nextInt();
			if(c==0)
				g.addEdge(u-1,v-1);
		}
		int no=0;
		long mod=1000000007;
		long rem=0;
		for(int i=0;i<n;i++)
		{
			if (ans[i]!=0)
				continue;
			int s=g.DFS(i);
			g.DFSput(i,s,ans);
			rem+=power(s,m,mod);
			no+=s;
			if(no==n)
				break;
		}
		//System.out.println(rem);
		//System.out.println(power(n,m,mod));
		long tryu=power(n,m,mod)-rem;
		tryu=tryu%mod;
		if (tryu<0)
			tryu+=mod;
		System.out.print(tryu);
	}

	BufferedReader reader;
	StringTokenizer tokenizer;
	PrintWriter writer;

	public void run() {
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			tokenizer = null;
			writer = new PrintWriter(System.out);
			solve();
			reader.close();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	String nextToken() throws IOException {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}
}
class Graph
{
	private int V;
	private LinkedList<Integer> adj[];
	private boolean visited[];
	private boolean visited1[];
	int res=0;
	Graph(int v)
	{
		V = v;
		visited = new boolean[V];
		visited1 = new boolean[V];
		adj = new LinkedList[v];
		for (int i=0; i<v; i++)
		{   adj[i] = new LinkedList();
		}
	}

	void addEdge(int v, int w)
	{
		adj[v].add(w);
		adj[w].add(v);// Add w to v's list.
	}

	void DFSUtil(int v)
	{
		visited[v] = true;
		Iterator<Integer> i = adj[v].listIterator();
		res+=1;
		while (i.hasNext())
		{
			int n = i.next();
			if (!visited[n])
			{
				DFSUtil(n);
			}
		}

	}

	int DFS(int v)//,int dep[])
	{
		DFSUtil(v);
		return res;
	}

	void DFSUtilp(int v,int l,int ans[])
	{
		visited1[v] = true;
		Iterator<Integer> i = adj[v].listIterator();
		ans[v]=l;
		while (i.hasNext())
		{
			int n = i.next();
			if (!visited1[n])
			{
				DFSUtilp(n,l,ans);
			}
		}

	}

	int DFSput(int v,int l,int ans[])//,int dep[])
	{
		res=0;
		DFSUtilp(v,l,ans);
		return res;
	}
}


//package com.company;
import java.io.*;
import java.util.*;
public class Main
{
	public static void main(String args[])
	{
		new Main().run();
	}
	static long power(long x, long y, long p)
	{
		// Initialize result
		long res = 1;

		// Update x if it is more
		// than or equal to p
		x = x % p;

		if (x == 0) return 0; // In case x is divisible by p;

		while (y > 0)
		{
			// If y is odd, multiply x
			// with result
			if((y & 1)==1)
				res = (res * x) % p;

			// y must be even now
			// y = y / 2
			y = y >> 1;
			x = (x * x) % p;
		}
		return res;
	}
	public void solve()throws IOException
	{
		int n=nextInt();
		long m=nextLong();
		Graph g=new Graph(n);
		int ans[]=new int[n];
		for (int i=0;i<n-1;i++)
		{
			int u=nextInt();
			int v=nextInt();
			int c=nextInt();
			if(c==0)
				g.addEdge(u-1,v-1);
		}
		int no=0;
		long mod=1000000007;
		long rem=0;
		for(int i=0;i<n;i++)
		{
			if (ans[i]!=0)
				continue;
			int s=g.DFS(i);
			g.DFSput(i,s,ans);
			rem+=power(s,m,mod);
			no+=s;
			if(no==n)
				break;
		}
		long tryu=power(n,m,mod)-rem;
		tryu=tryu%mod;
		System.out.print(tryu);
	}

	BufferedReader reader;
	StringTokenizer tokenizer;
	PrintWriter writer;

	public void run() {
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			tokenizer = null;
			writer = new PrintWriter(System.out);
			solve();
			reader.close();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	String nextToken() throws IOException {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}
}
class Graph
{
	private int V;
	private LinkedList<Integer> adj[];
	private boolean visited[];
	private boolean visited1[];
	int res=0;
	Graph(int v)
	{
		V = v;
		visited = new boolean[V];
		visited1 = new boolean[V];
		adj = new LinkedList[v];
		for (int i=0; i<v; i++)
		{   adj[i] = new LinkedList();
		}
	}

	void addEdge(int v, int w)
	{
		adj[v].add(w);
		adj[w].add(v);// Add w to v's list.
	}

	void DFSUtil(int v)
	{
		visited[v] = true;
		Iterator<Integer> i = adj[v].listIterator();
		res+=1;
		while (i.hasNext())
		{
			int n = i.next();
			if (!visited[n])
			{
				DFSUtil(n);
			}
		}

	}

	int DFS(int v)//,int dep[])
	{
		DFSUtil(v);
		return res;
	}

	void DFSUtilp(int v,int l,int ans[])
	{
		visited1[v] = true;
		Iterator<Integer> i = adj[v].listIterator();
		ans[v]=l;
		while (i.hasNext())
		{
			int n = i.next();
			if (!visited1[n])
			{
				DFSUtilp(n,l,ans);
			}
		}

	}

	int DFSput(int v,int l,int ans[])//,int dep[])
	{
		res=0;
		DFSUtilp(v,l,ans);
		return res;
	}
}


package com.company;
import java.io.*;
import java.util.*;
public class Main
{
	public static void main(String args[])
	{
		new Main().run();
	}
	static long power(long x, long y, long p)
	{
		// Initialize result
		long res = 1;

		// Update x if it is more
		// than or equal to p
		x = x % p;

		if (x == 0) return 0; // In case x is divisible by p;

		while (y > 0)
		{
			// If y is odd, multiply x
			// with result
			if((y & 1)==1)
				res = (res * x) % p;

			// y must be even now
			// y = y / 2
			y = y >> 1;
			x = (x * x) % p;
		}
		return res;
	}
	public void solve()throws IOException
	{
		int n=nextInt();
		long m=nextLong();
		Graph g=new Graph(n);
		int ans[]=new int[n];
		for (int i=0;i<n-1;i++)
		{
			int u=nextInt();
			int v=nextInt();
			int c=nextInt();
			if(c==0)
				g.addEdge(u-1,v-1);
		}
		int no=0;
		long mod=1000000007;
		long rem=0;
		for(int i=0;i<n;i++)
		{
			if (ans[i]!=0)
				continue;
			int s=g.DFS(i);
			g.DFSput(i,s,ans);
			rem+=power(s,m,mod);
			no+=s;
			if(no==n)
				break;
		}
		long tryu=power(n,m,mod)-rem;
		tryu=tryu%mod;
		System.out.print(tryu);
	}

	BufferedReader reader;
	StringTokenizer tokenizer;
	PrintWriter writer;

	public void run() {
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			tokenizer = null;
			writer = new PrintWriter(System.out);
			solve();
			reader.close();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	String nextToken() throws IOException {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}
}
class Graph
{
	private int V;
	private LinkedList<Integer> adj[];
	private boolean visited[];
	private boolean visited1[];
	int res=0;
	Graph(int v)
	{
		V = v;
		visited = new boolean[V];
		visited1 = new boolean[V];
		adj = new LinkedList[v];
		for (int i=0; i<v; i++)
		{   adj[i] = new LinkedList();
		}
	}

	void addEdge(int v, int w)
	{
		adj[v].add(w);
		adj[w].add(v);// Add w to v's list.
	}

	void DFSUtil(int v)
	{
		visited[v] = true;
		Iterator<Integer> i = adj[v].listIterator();
		res+=1;
		while (i.hasNext())
		{
			int n = i.next();
			if (!visited[n])
			{
				DFSUtil(n);
			}
		}

	}

	int DFS(int v)//,int dep[])
	{
		DFSUtil(v);
		return res;
	}

	void DFSUtilp(int v,int l,int ans[])
	{
		visited1[v] = true;
		Iterator<Integer> i = adj[v].listIterator();
		ans[v]=l;
		while (i.hasNext())
		{
			int n = i.next();
			if (!visited1[n])
			{
				DFSUtilp(n,l,ans);
			}
		}

	}

	int DFSput(int v,int l,int ans[])//,int dep[])
	{
		res=0;
		DFSUtilp(v,l,ans);
		return res;
	}
}


import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.Math.*;

public class Main {
    static long mod = (long)1e9 + 7;
    static ArrayList<Integer> adj[];
    static int vis[];
    static long cnt = 0;

    private static void dfs(int i) {
        cnt++;
        vis[i] = 1;
        for(int j : adj[i]) {
            if(vis[j] == 0) {
                dfs(j);
            }
        }
    }
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        adj = new ArrayList[n];
        for(int i=0; i<n; i++) {
            adj[i] = new ArrayList<>();
        }
        for(int i=0; i<n-1; i++) {
            int u = sc.nextInt() - 1;
            int v = sc.nextInt() - 1;
            int col = sc.nextInt();

            if(col == 0) {
                adj[u].add(v);
                adj[v].add(u);
            }
        }

        long ans = (long)pow(n, k);
        long rem = 0;

        vis = new int[n];
        for(int i=0; i<n; i++) {
            if(vis[i] == 0) {
                if(vis[i] == 0) {
                    cnt = 0;
                    dfs(i);
                    rem += (long) pow(cnt, k);
                }
            }
        }
        ans = (ans - rem) % mod;
        System.out.println(ans);
    }
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    static long mod = (long)1e9 + 7;
    static ArrayList<Integer> adj[];
    static int vis[];
    static long cnt = 0;

    private static void dfs(int i) {
        cnt++;
        vis[i] = 1;
        for(int j : adj[i]) {
            if(vis[j] == 0) {
                dfs(j);
            }
        }
    }
    static long fast_pow(long a, long b) {
		if(b == 0)
			return 1L;

		long val = fast_pow(a, b / 2);

		if(b % 2 == 0)
			return val * val % mod;
		else
			return val * val % mod * a % mod;
	}
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        adj = new ArrayList[n];
        for(int i=0; i<n; i++) {
            adj[i] = new ArrayList<>();
        }
        for(int i=0; i<n-1; i++) {
            int u = sc.nextInt() - 1;
            int v = sc.nextInt() - 1;
            int col = sc.nextInt();

            if(col == 0) {
                adj[u].add(v);
                adj[v].add(u);
            }
        }

        long ans = fast_pow(n, k);
        long rem = 0;

        vis = new int[n];
        for(int i=0; i<n; i++) {
            if(vis[i] == 0) {
                cnt = 0;
                dfs(i);
                rem += fast_pow(cnt, k);
            }
        }
        rem %= mod;
        ans = (ans - rem + mod) % mod;
        System.out.println(ans);
    }
}


import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.Math.*;

public class Main {
    static long mod = (long)1e9 + 7;
    static ArrayList<Integer> adj[];
    static int vis[];
    static long cnt = 0;

    private static void dfs(int i) {
        cnt++;
        vis[i] = 1;
        for(int j : adj[i]) {
            if(vis[j] == 0) {
                dfs(j);
            }
        }
    }
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        adj = new ArrayList[n];
        for(int i=0; i<n; i++) {
            adj[i] = new ArrayList<>();
        }
        for(int i=0; i<n-1; i++) {
            int u = sc.nextInt() - 1;
            int v = sc.nextInt() - 1;
            int col = sc.nextInt();

            if(col == 0) {
                adj[u].add(v);
                adj[v].add(u);
            }
        }

        long ans = (long)pow(n, k);
        long rem = 0;

        vis = new int[n];
        for(int i=0; i<n; i++) {
            if(vis[i] == 0) {
                cnt = 0;
                dfs(i);
                rem += (long) pow(cnt, k);
            }
        }
        rem %= mod;
        ans = (ans - rem + mod) % mod;
        System.out.println(ans);
    }
}


// package codeForces;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
import java.text.*;

public class TEdgyTrees {

	static InputReader in = new InputReader(System.in);
	static OutputWriter out = new OutputWriter(System.out);
	static long count=0L;

	static void dfs(int s,ArrayList<ArrayList<Integer>> ar,boolean vis[]) {

		vis[s]=true;
		count++;
		for(int j:ar.get(s) ) {
			if(!vis[j]) {

				dfs(j,ar,vis);
			}
		}

	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int t = 1;
		while (t > 0) {
			int n=i();
			int k=i();
			int c1=0;
			int c0=0;
			ArrayList<ArrayList<Integer>> ar=new ArrayList<>();
			for(int i=0;i<=n;i++) {
				ar.add(new ArrayList<>());
			}
			for(int i=0;i<n-1;i++) {
				int a=i();
				int b=i();
				int x=i();
				if(x==0) {
					ar.get(a).add(b);
					ar.get(b).add(a);
				}
				if(x==0) {
					c0++;
				}
				else {
					c1++;
				}
			}
//			System.out.println(ar);

			long ans1=0L;
			long ans2=0L;
			ans1=pow(n,k);
			boolean vis[]=new boolean[n+1];
			for(int i=1;i<=n;i++) {
				if(!vis[i]) {
					count=0;
					dfs(i,ar,vis);
					ans2=ans2+pow(count,k);
//					System.out.println(ans2);
				}
			}
//			System.out.println(ans2);
			long ansf=0L;
			ansf=(ans1-ans2);
			System.out.println(ansf);

			t--;
		}

		//		long l=l();
		//		String s=s();     //	ONLY BEFORE SPACE IN STRING , ELSE USE BUFFER-READER

	}

	public static long pow(long a, long b) {
		long m = 1000000007;
		long result = 1;
		while (b > 0) {
			if (b % 2 != 0) {
				result = (result * a) % m;
				b--;
			}
			a = (a * a) % m;
			b /= 2;
		}
		return result % m;
	}

	public static long gcd(long a, long b) {
		if (a == 0) {
			return b;
		}
		return gcd(b % a, a);
	}

	public static long lcm(long a, long b) {
		return a * (b / gcd(a, b));
	}

	public static long l() {
		String s = in.String();
		return Long.parseLong(s);
	}

	public static void pln(String value) {
		System.out.println(value);
	}

	public static int i() {
		return in.Int();
	}

	public static String s() {
		return in.String();
	}

}

class pair {
	int x, y;

	pair(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

class CompareValue {

	static void compare(pair arr[], int n) {
		Arrays.sort(arr, new Comparator<pair>() {
			public int compare(pair p1, pair p2) {
				return p1.y - p2.y;
			}
		});
	}
}

class CompareKey {
	static void compare(pair arr[], int n) {
		Arrays.sort(arr, new Comparator<pair>() {
			public int compare(pair p1, pair p2) {
				return p2.x - p1.x;
			}
		});
	}
}

class InputReader {
	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int Int() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public String String() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public String next() {
		return String();
	}

	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}

	public double readDouble() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		double res = 0;
		while (!isSpaceChar(c) && c != '.') {
			if (c == 'e' || c == 'E') {
				return res * Math.pow(10, Int());
			}
			if (c < '0' || c > '9') {
				throw new InputMismatchException();
			}
			res *= 10;
			res += c - '0';
			c = read();
		}
		if (c == '.') {
			c = read();
			double m = 1;
			while (!isSpaceChar(c)) {
				if (c == 'e' || c == 'E') {
					return res * Math.pow(10, Int());
				}
				if (c < '0' || c > '9') {
					throw new InputMismatchException();
				}
				m /= 10;
				res += (c - '0') * m;
				c = read();
			}
		}
		return res * sgn;
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}

	public OutputWriter(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

	public void print(Object... objects) {
		for (int i = 0; i < objects.length; i++) {
			if (i != 0) {
				writer.print(' ');
			}
			writer.print(objects[i]);
		}
		writer.flush();
	}

	public void printLine(Object... objects) {
		print(objects);
		writer.println();
		writer.flush();
	}

	public void close() {
		writer.close();
	}

	public void flush() {
		writer.flush();
	}
}

class IOUtils {
	public static int[] readIntArray(InputReader in, int size) {
		int[] array = new int[size];
		for (int i = 0; i < size; i++)
			array[i] = in.Int();
		return array;
	}
}

/**
 * TO SORT VIA TWO KEYS , HERE IT IS ACCORDING TO ASCENDING ORDER OF FIRST AND
 * DESC ORDER OF SECOND
 * LIST name-list
 * ARRAYLIST
 * COPY PASTE
 *
 * Collections.sort(list, (first,second) ->{
		    	if(first.con >second.con)
		    		return -1;
		    	else if(first.con<second.con)
		    		return 1;
		    	else {
		    		if(first.index >second.index)
		    			return 1;
		    		else
		    			return -1;
		    	}

		    });
 *
 */

/**
 *

  DECIMAL FORMATTER
Double k = in.readDouble();

System.out.println(k);
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(k));
out.printLine(k);
*
* */


// package codeForces;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
import java.text.*;

public class TEdgyTrees {

	static InputReader in = new InputReader(System.in);
	static OutputWriter out = new OutputWriter(System.out);
	static long count=0L;

	static void dfs(int s,ArrayList<ArrayList<Integer>> ar,boolean vis[]) {

		vis[s]=true;
		count++;
		for(int j:ar.get(s) ) {
			if(!vis[j]) {

				dfs(j,ar,vis);
			}
		}

	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int t = 1;
		while (t > 0) {
			int n=i();
			int k=i();
			int c1=0;
			int c0=0;
			ArrayList<ArrayList<Integer>> ar=new ArrayList<>();
			for(int i=0;i<=n;i++) {
				ar.add(new ArrayList<>());
			}
			for(int i=0;i<n-1;i++) {
				int a=i();
				int b=i();
				int x=i();
				if(x==0) {
					ar.get(a).add(b);
					ar.get(b).add(a);
				}
				if(x==0) {
					c0++;
				}
				else {
					c1++;
				}
			}
//			System.out.println(ar);

			long ans1=0L;
			long ans2=0L;
			ans1=pow(n,k);
			boolean vis[]=new boolean[n+1];
			for(int i=1;i<=n;i++) {
				if(!vis[i]) {
					count=0;
					dfs(i,ar,vis);
					ans2=ans2+pow(count,k);
//					System.out.println(ans2);
				}
			}
//			System.out.println(ans1);
//			System.out.println(ans2);
			long ansf=0L;
			ansf=(ans1-ans2+1000000007)%1000000007;
			System.out.println(ansf);

			t--;
		}

		//		long l=l();
		//		String s=s();     //	ONLY BEFORE SPACE IN STRING , ELSE USE BUFFER-READER

	}

	public static long pow(long a, long b) {
		long m = 1000000007;
		long result = 1;
		while (b > 0) {
			if (b % 2 != 0) {
				result = (result * a) % m;
				b--;
			}
			a = (a * a) % m;
			b /= 2;
		}
		return result % m;
	}

	public static long gcd(long a, long b) {
		if (a == 0) {
			return b;
		}
		return gcd(b % a, a);
	}

	public static long lcm(long a, long b) {
		return a * (b / gcd(a, b));
	}

	public static long l() {
		String s = in.String();
		return Long.parseLong(s);
	}

	public static void pln(String value) {
		System.out.println(value);
	}

	public static int i() {
		return in.Int();
	}

	public static String s() {
		return in.String();
	}

}

class pair {
	int x, y;

	pair(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

class CompareValue {

	static void compare(pair arr[], int n) {
		Arrays.sort(arr, new Comparator<pair>() {
			public int compare(pair p1, pair p2) {
				return p1.y - p2.y;
			}
		});
	}
}

class CompareKey {
	static void compare(pair arr[], int n) {
		Arrays.sort(arr, new Comparator<pair>() {
			public int compare(pair p1, pair p2) {
				return p2.x - p1.x;
			}
		});
	}
}

class InputReader {
	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int Int() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public String String() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public String next() {
		return String();
	}

	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}

	public double readDouble() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		double res = 0;
		while (!isSpaceChar(c) && c != '.') {
			if (c == 'e' || c == 'E') {
				return res * Math.pow(10, Int());
			}
			if (c < '0' || c > '9') {
				throw new InputMismatchException();
			}
			res *= 10;
			res += c - '0';
			c = read();
		}
		if (c == '.') {
			c = read();
			double m = 1;
			while (!isSpaceChar(c)) {
				if (c == 'e' || c == 'E') {
					return res * Math.pow(10, Int());
				}
				if (c < '0' || c > '9') {
					throw new InputMismatchException();
				}
				m /= 10;
				res += (c - '0') * m;
				c = read();
			}
		}
		return res * sgn;
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}

	public OutputWriter(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

	public void print(Object... objects) {
		for (int i = 0; i < objects.length; i++) {
			if (i != 0) {
				writer.print(' ');
			}
			writer.print(objects[i]);
		}
		writer.flush();
	}

	public void printLine(Object... objects) {
		print(objects);
		writer.println();
		writer.flush();
	}

	public void close() {
		writer.close();
	}

	public void flush() {
		writer.flush();
	}
}

class IOUtils {
	public static int[] readIntArray(InputReader in, int size) {
		int[] array = new int[size];
		for (int i = 0; i < size; i++)
			array[i] = in.Int();
		return array;
	}
}

/**
 * TO SORT VIA TWO KEYS , HERE IT IS ACCORDING TO ASCENDING ORDER OF FIRST AND
 * DESC ORDER OF SECOND
 * LIST name-list
 * ARRAYLIST
 * COPY PASTE
 *
 * Collections.sort(list, (first,second) ->{
		    	if(first.con >second.con)
		    		return -1;
		    	else if(first.con<second.con)
		    		return 1;
		    	else {
		    		if(first.index >second.index)
		    			return 1;
		    		else
		    			return -1;
		    	}

		    });
 *
 */

/**
 *

  DECIMAL FORMATTER
Double k = in.readDouble();

System.out.println(k);
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(k));
out.printLine(k);
*
* */


// package codeForces;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
import java.text.*;

public class TEdgyTrees {

	static InputReader in = new InputReader(System.in);
	static OutputWriter out = new OutputWriter(System.out);

	public static void main(String[] args) throws NumberFormatException, IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int t = 1;
		while (t > 0) {
			int n=i();
			int k=i();
			int c1=0;
			int c0=0;
			for(int i=0;i<n-1;i++) {
				int a=i();
				int b=i();
				int x=i();
				if(x==0) {
					c0++;
				}
				else {
					c1++;
				}
			}
			if(c1==0) {
				System.out.println(0);
			}
			else {

					System.out.println(pow(n,k)-pow((c0+1),k)-c1);

			}

			t--;
		}

		//		long l=l();
		//		String s=s();     //	ONLY BEFORE SPACE IN STRING , ELSE USE BUFFER-READER

	}

	public static long pow(long a, long b) {
		long m = 1000000007;
		long result = 1;
		while (b > 0) {
			if (b % 2 != 0) {
				result = (result * a) % m;
				b--;
			}
			a = (a * a) % m;
			b /= 2;
		}
		return result % m;
	}

	public static long gcd(long a, long b) {
		if (a == 0) {
			return b;
		}
		return gcd(b % a, a);
	}

	public static long lcm(long a, long b) {
		return a * (b / gcd(a, b));
	}

	public static long l() {
		String s = in.String();
		return Long.parseLong(s);
	}

	public static void pln(String value) {
		System.out.println(value);
	}

	public static int i() {
		return in.Int();
	}

	public static String s() {
		return in.String();
	}

}

class pair {
	int x, y;

	pair(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

class CompareValue {

	static void compare(pair arr[], int n) {
		Arrays.sort(arr, new Comparator<pair>() {
			public int compare(pair p1, pair p2) {
				return p1.y - p2.y;
			}
		});
	}
}

class CompareKey {
	static void compare(pair arr[], int n) {
		Arrays.sort(arr, new Comparator<pair>() {
			public int compare(pair p1, pair p2) {
				return p2.x - p1.x;
			}
		});
	}
}

class InputReader {
	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int Int() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public String String() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public String next() {
		return String();
	}

	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}

	public double readDouble() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		double res = 0;
		while (!isSpaceChar(c) && c != '.') {
			if (c == 'e' || c == 'E') {
				return res * Math.pow(10, Int());
			}
			if (c < '0' || c > '9') {
				throw new InputMismatchException();
			}
			res *= 10;
			res += c - '0';
			c = read();
		}
		if (c == '.') {
			c = read();
			double m = 1;
			while (!isSpaceChar(c)) {
				if (c == 'e' || c == 'E') {
					return res * Math.pow(10, Int());
				}
				if (c < '0' || c > '9') {
					throw new InputMismatchException();
				}
				m /= 10;
				res += (c - '0') * m;
				c = read();
			}
		}
		return res * sgn;
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}

	public OutputWriter(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

	public void print(Object... objects) {
		for (int i = 0; i < objects.length; i++) {
			if (i != 0) {
				writer.print(' ');
			}
			writer.print(objects[i]);
		}
		writer.flush();
	}

	public void printLine(Object... objects) {
		print(objects);
		writer.println();
		writer.flush();
	}

	public void close() {
		writer.close();
	}

	public void flush() {
		writer.flush();
	}
}

class IOUtils {
	public static int[] readIntArray(InputReader in, int size) {
		int[] array = new int[size];
		for (int i = 0; i < size; i++)
			array[i] = in.Int();
		return array;
	}
}

/**
 * TO SORT VIA TWO KEYS , HERE IT IS ACCORDING TO ASCENDING ORDER OF FIRST AND
 * DESC ORDER OF SECOND
 * LIST name-list
 * ARRAYLIST
 * COPY PASTE
 *
 * Collections.sort(list, (first,second) ->{
		    	if(first.con >second.con)
		    		return -1;
		    	else if(first.con<second.con)
		    		return 1;
		    	else {
		    		if(first.index >second.index)
		    			return 1;
		    		else
		    			return -1;
		    	}

		    });
 *
 */

/**
 *

  DECIMAL FORMATTER
Double k = in.readDouble();

System.out.println(k);
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(k));
out.printLine(k);
*
* */


// package codeForces;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
import java.text.*;

public class TEdgyTrees {

	static InputReader in = new InputReader(System.in);
	static OutputWriter out = new OutputWriter(System.out);
	static long count=0L;

	static void dfs(int s,ArrayList<ArrayList<Integer>> ar,boolean vis[]) {

		vis[s]=true;
		count++;
		for(int j:ar.get(s) ) {
			if(!vis[j]) {

				dfs(j,ar,vis);
			}
		}

	}
	static int mod=1000000007;

	public static void main(String[] args) throws NumberFormatException, IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int t = 1;
		while (t > 0) {
			int n=i();
			int k=i();
			int c1=0;
			int c0=0;
			ArrayList<ArrayList<Integer>> ar=new ArrayList<>();
			for(int i=0;i<=n;i++) {
				ar.add(new ArrayList<>());
			}
			for(int i=0;i<n-1;i++) {
				int a=i();
				int b=i();
				int x=i();
				if(x==0) {
					ar.get(a).add(b);
					ar.get(b).add(a);
				}
				if(x==0) {
					c0++;
				}
				else {
					c1++;
				}
			}
//			System.out.println(ar);

			long ans1=0L;
			long ans2=0L;
			ans1=pow(n,k);
			boolean vis[]=new boolean[n+1];
			for(int i=1;i<=n;i++) {
				if(!vis[i]) {
					count=0;
					dfs(i,ar,vis);
					ans2=ans2+pow(count,k);
//					System.out.println(ans2);
				}
			}
//			System.out.println(ans1);
//			System.out.println(ans2);
			ans2=ans2%mod;
			long ansf=0L;
			ansf=(ans1-ans2+mod)%mod;
			System.out.println(ansf);

			t--;
		}

		//		long l=l();
		//		String s=s();     //	ONLY BEFORE SPACE IN STRING , ELSE USE BUFFER-READER

	}

	public static long pow(long a, long b) {
		long m = 1000000007;
		long result = 1;
		while (b > 0) {
			if (b % 2 != 0) {
				result = (result * a) % m;
				b--;
			}
			a = (a * a) % m;
			b /= 2;
		}
		return result % m;
	}

	public static long gcd(long a, long b) {
		if (a == 0) {
			return b;
		}
		return gcd(b % a, a);
	}

	public static long lcm(long a, long b) {
		return a * (b / gcd(a, b));
	}

	public static long l() {
		String s = in.String();
		return Long.parseLong(s);
	}

	public static void pln(String value) {
		System.out.println(value);
	}

	public static int i() {
		return in.Int();
	}

	public static String s() {
		return in.String();
	}

}

class pair {
	int x, y;

	pair(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

class CompareValue {

	static void compare(pair arr[], int n) {
		Arrays.sort(arr, new Comparator<pair>() {
			public int compare(pair p1, pair p2) {
				return p1.y - p2.y;
			}
		});
	}
}

class CompareKey {
	static void compare(pair arr[], int n) {
		Arrays.sort(arr, new Comparator<pair>() {
			public int compare(pair p1, pair p2) {
				return p2.x - p1.x;
			}
		});
	}
}

class InputReader {
	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int Int() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public String String() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public String next() {
		return String();
	}

	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}

	public double readDouble() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		double res = 0;
		while (!isSpaceChar(c) && c != '.') {
			if (c == 'e' || c == 'E') {
				return res * Math.pow(10, Int());
			}
			if (c < '0' || c > '9') {
				throw new InputMismatchException();
			}
			res *= 10;
			res += c - '0';
			c = read();
		}
		if (c == '.') {
			c = read();
			double m = 1;
			while (!isSpaceChar(c)) {
				if (c == 'e' || c == 'E') {
					return res * Math.pow(10, Int());
				}
				if (c < '0' || c > '9') {
					throw new InputMismatchException();
				}
				m /= 10;
				res += (c - '0') * m;
				c = read();
			}
		}
		return res * sgn;
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}

	public OutputWriter(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

	public void print(Object... objects) {
		for (int i = 0; i < objects.length; i++) {
			if (i != 0) {
				writer.print(' ');
			}
			writer.print(objects[i]);
		}
		writer.flush();
	}

	public void printLine(Object... objects) {
		print(objects);
		writer.println();
		writer.flush();
	}

	public void close() {
		writer.close();
	}

	public void flush() {
		writer.flush();
	}
}

class IOUtils {
	public static int[] readIntArray(InputReader in, int size) {
		int[] array = new int[size];
		for (int i = 0; i < size; i++)
			array[i] = in.Int();
		return array;
	}
}

/**
 * TO SORT VIA TWO KEYS , HERE IT IS ACCORDING TO ASCENDING ORDER OF FIRST AND
 * DESC ORDER OF SECOND
 * LIST name-list
 * ARRAYLIST
 * COPY PASTE
 *
 * Collections.sort(list, (first,second) ->{
		    	if(first.con >second.con)
		    		return -1;
		    	else if(first.con<second.con)
		    		return 1;
		    	else {
		    		if(first.index >second.index)
		    			return 1;
		    		else
		    			return -1;
		    	}

		    });
 *
 */

/**
 *

  DECIMAL FORMATTER
Double k = in.readDouble();

System.out.println(k);
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(k));
out.printLine(k);
*
* */


import java.util.*;
import static java.lang.Math.*;

public class SolutionB {
       public static final long BASE = 100001;
       public static final int MOD = 1000000007;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		Map<Long, Integer> colors = new HashMap<Long, Integer>();
		Map<Integer, List<Integer>> tree = new HashMap<Integer, List<Integer>>();
		for(int m = 0; m < n-1; m++){
		       int u = sc.nextInt();
		       int v = sc.nextInt();
		       int c = sc.nextInt();
		       if(!tree.containsKey(u))tree.put(u, new ArrayList<Integer>());
		       tree.get(u).add(v);
		       if(!tree.containsKey(v))tree.put(v, new ArrayList<Integer>());
		       tree.get(v).add(u);
		       long key = (long)u + (long)v * BASE;
		       colors.put(key, c);
		       key = (long)v + (long)u * BASE;
		       colors.put(key, c);
		}
		long ans = n;
		for(int i = 0; i < k-1; i++){
		       ans *= n;
		       ans %= MOD;
		}
		ans -= n;
		//System.out.println("ans " + ans);
		boolean visited[] = new boolean[n + 1];
		for(int i = 1; i <= n; i++){
		       if(visited[i])continue;
		       Queue<Integer> bfs = new LinkedList<Integer>();
		       visited[i] = true;
		       bfs.offer(i);
		       int amnt = 0;
		       //System.out.print(i + " ");
		       while(!bfs.isEmpty()){
		              int father = bfs.remove();
		              amnt++;
		              for(int child : tree.get(father)){
		                     if(visited[child])continue;
		                     long key = (long)father + (long)child * BASE;
		                     if(colors.get(key) == 0){
		                            visited[child] = true;
		                            bfs.offer(child);
		                     }
		              }
		       }
		       if(amnt < 2)continue;
		       //System.out.print( "amount " + amnt);
		       long comb = amnt;
		       for(int j = 0; j < k - 1; j++){
		              comb *= amnt;
		              comb %= MOD;
		       }
		       comb -= amnt;
		       //System.out.println(" " + comb);
		       ans -= comb;
		       ans = (ans + MOD) % MOD;
		}
		System.out.println(ans);
	}
}


import java.util.*;
import static java.lang.Math.*;

public class SolutionB {
       public static final long BASE = 100001;
       public static final int MOD = 1000000007;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		Map<Long, Integer> colors = new HashMap<Long, Integer>();
		Map<Integer, List<Integer>> tree = new HashMap<Integer, List<Integer>>();
		for(int m = 0; m < n-1; m++){
		       int u = sc.nextInt();
		       int v = sc.nextInt();
		       int c = sc.nextInt();
		       if(!tree.containsKey(u))tree.put(u, new ArrayList<Integer>());
		       tree.get(u).add(v);
		       if(!tree.containsKey(v))tree.put(v, new ArrayList<Integer>());
		       tree.get(v).add(u);
		       long key = (long)u + (long)v * BASE;
		       colors.put(key, c);
		       key = (long)v + (long)u * BASE;
		       colors.put(key, c);
		}
		long ans = n;
		for(int i = 0; i < k-1; i++){
		       ans *= n;
		       ans %= MOD;
		}
		ans -= n;
		//System.out.println("ans " + ans);
		boolean visited[] = new boolean[n + 1];
		for(int i = 1; i <= n; i++){
		       if(visited[i])continue;
		       Queue<Integer> bfs = new LinkedList<Integer>();
		       visited[i] = true;
		       bfs.offer(i);
		       int amnt = 0;
		       while(!bfs.isEmpty()){
		              int father = bfs.remove();
		              amnt++;
		              for(int child : tree.get(father)){
		                     if(visited[child])continue;
		                     long key = (long)father + (long)child * BASE;
		                     if(colors.get(key) == 0){
		                            visited[child] = true;
		                            bfs.offer(child);
		                     }
		              }
		       }
		       //System.out.println( "amount " + amnt);
		       if(amnt < 2)continue;
		       long comb = amnt;
		       for(int j = 0; j < k - 1; j++){
		              comb *= amnt;
		              comb %= MOD;
		       }
		       comb -= amnt;
		       ans -= comb;
		}
		System.out.println(ans);
	}
}


import java.util.*;
import static java.lang.Math.*;

public class SolutionB {
       public static final long BASE = 100001;
       public static final int MOD = 1000000007;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		Map<Long, Integer> colors = new HashMap<Long, Integer>();
		Map<Integer, List<Integer>> tree = new HashMap<Integer, List<Integer>>();
		for(int m = 0; m < n-1; m++){
		       int u = sc.nextInt();
		       int v = sc.nextInt();
		       int c = sc.nextInt();
		       if(!tree.containsKey(u))tree.put(u, new ArrayList<Integer>());
		       tree.get(u).add(v);
		       if(!tree.containsKey(v))tree.put(v, new ArrayList<Integer>());
		       tree.get(v).add(u);
		       long key = (long)u + (long)v * BASE;
		       colors.put(key, c);
		       key = (long)v + (long)u * BASE;
		       colors.put(key, c);
		}
		long ans = n;
		for(int i = 0; i < k-1; i++){
		       ans *= n;
		       ans %= MOD;
		}
		ans -= n;
		//System.out.println("ans " + ans);
		boolean visited[] = new boolean[n + 1];
		for(int i = 1; i <= n; i++){
		       if(visited[i])continue;
		       Queue<Integer> bfs = new LinkedList<Integer>();
		       visited[i] = true;
		       bfs.offer(i);
		       int amnt = 0;
		       while(!bfs.isEmpty()){
		              int father = bfs.remove();
		              amnt++;
		              for(int child : tree.get(father)){
		                     if(visited[child])continue;
		                     long key = (long)father + (long)child * BASE;
		                     if(colors.get(key) == 0){
		                            visited[child] = true;
		                            bfs.offer(child);
		                     }
		              }
		       }
		       //System.out.println( "amount " + amnt);
		       if(amnt < 2)continue;
		       System.out.println(amnt);
		       long comb = amnt;
		       for(int j = 0; j < k - 1; j++){
		              comb *= amnt;
		              comb %= MOD;
		       }
		       comb -= amnt;
		       //System.out.println("comb " + comb);
		       ans -= comb;
		      // System.out.println(ans);
		}
		System.out.println(ans);
	}
}


import java.util.*;
import static java.lang.Math.*;

public class SolutionB {
       public static final long BASE = 100001;
       public static final int MOD = 1000000007;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		Map<Long, Integer> colors = new HashMap<Long, Integer>();
		Map<Integer, List<Integer>> tree = new HashMap<Integer, List<Integer>>();
		for(int m = 0; m < n-1; m++){
		       int u = sc.nextInt();
		       int v = sc.nextInt();
		       int c = sc.nextInt();
		       if(!tree.containsKey(u))tree.put(u, new ArrayList<Integer>());
		       tree.get(u).add(v);
		       if(!tree.containsKey(v))tree.put(v, new ArrayList<Integer>());
		       tree.get(v).add(u);
		       long key = (long)u + (long)v * BASE;
		       colors.put(key, c);
		       key = (long)v + (long)u * BASE;
		       colors.put(key, c);
		}
		long ans = n;
		for(int i = 0; i < k-1; i++){
		       ans *= n;
		       ans %= MOD;
		}
		ans -= n;
		//System.out.println("ans " + ans);
		boolean visited[] = new boolean[n + 1];
		for(int i = 1; i <= n; i++){
		       if(visited[i])continue;
		       Queue<Integer> bfs = new LinkedList<Integer>();
		       visited[i] = true;
		       bfs.offer(i);
		       int amnt = 0;
		       while(!bfs.isEmpty()){
		              int father = bfs.remove();
		              amnt++;
		              for(int child : tree.get(father)){
		                     if(visited[child])continue;
		                     long key = (long)father + (long)child * BASE;
		                     if(colors.get(key) == 0){
		                            visited[child] = true;
		                            bfs.offer(child);
		                     }
		              }
		       }
		       //System.out.println( "amount " + amnt);
		       if(amnt < 2)continue;
		       int comb = amnt;
		       for(int j = 0; j < k - 1; j++){
		              comb *= amnt;
		              comb %= MOD;
		       }
		       comb -= amnt;
		       ans -= comb;
		}
		System.out.println(ans);
	}
}


import java.util.*;
import static java.lang.Math.*;

public class SolutionB {
       public static final long BASE = 100001;
       public static final int MOD = 1000000007;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		Map<Long, Integer> colors = new HashMap<Long, Integer>();
		Map<Integer, List<Integer>> tree = new HashMap<Integer, List<Integer>>();
		for(int m = 0; m < n-1; m++){
		       int u = sc.nextInt();
		       int v = sc.nextInt();
		       int c = sc.nextInt();
		       if(!tree.containsKey(u))tree.put(u, new ArrayList<Integer>());
		       tree.get(u).add(v);
		       if(!tree.containsKey(v))tree.put(v, new ArrayList<Integer>());
		       tree.get(v).add(u);
		       long key = (long)u + (long)v * BASE;
		       colors.put(key, c);
		       key = (long)v + (long)u * BASE;
		       colors.put(key, c);
		}
		int ans = n;
		for(int i = 0; i < k-1; i++){
		       ans *= n;
		       ans %= MOD;
		}
		ans -= n;
		boolean visited[] = new boolean[n + 1];
		for(int i = 1; i <= n; i++){
		       if(visited[i])continue;
		       Queue<Integer> bfs = new LinkedList<Integer>();
		       visited[i] = true;
		       bfs.offer(i);
		       int amnt = 0;
		       while(!bfs.isEmpty()){
		              int father = bfs.remove();
		              amnt++;
		              for(int child : tree.get(father)){
		                     if(visited[child])continue;
		                     long key = (long)father + (long)child * BASE;
		                     if(colors.get(key) == 0){
		                            visited[child] = true;
		                            bfs.offer(child);
		                     }
		              }
		       }
		       //System.out.println( "amount " + amnt);
		       if(amnt < 2)continue;
		       int comb = amnt;
		       for(int j = 0; j < k - 1; j++){
		              comb *= amnt;
		              comb %= MOD;
		       }
		       comb -= amnt;
		       ans -= comb;
		}
		System.out.println(ans);
	}
}


import java.io.*;
import java.util.*;

public class EdgyTrees {
	public static void main (String [] args) throws IOException{
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			StringTokenizer st = new StringTokenizer(in.readLine());

			final long M = (long) Math.pow(10, 9) + 7;
			int n = Integer.parseInt(st.nextToken());
			int k = Integer.parseInt(st.nextToken());
			Node [] nod = new Node [n];
			for (int i = 0; i < n; i++)
				nod[i] = new Node();

			for (int i = 0; i < n - 1; i++) {
				st = new StringTokenizer(in.readLine());
				int u = Integer.parseInt(st.nextToken()) - 1;
				int v = Integer.parseInt(st.nextToken()) - 1;
				int x = Integer.parseInt(st.nextToken());
				if (x == 0) {
					nod[u].rcon.add(nod[v]);
					nod[v].rcon.add(nod[u]);
				}
			}

			long ans = 1;
			for (int i = 0; i < k; i++)
				ans = (ans * n) % M;

			for (int i = 0; i < n; i++) {
				if (nod[i].group == false) {
					ans -= Math.pow(form(nod[i]), k);
					ans %= M;
				}
			}
			if (ans < 0)
				System.out.println(ans + M);
			else
				System.out.println(ans);
	}
	public static int form (Node n) {
		n.group = true;
		int size = 1;
		for (Node newNode: n.rcon) {
			if (newNode.group == false)
				size += form(newNode);
		}
		return size;
	}
	static class Node {
		boolean group = false;
		ArrayList<Node> rcon = new ArrayList<Node>();

	}
}


import java.io.*;
import java.util.*;

public class EdgyTrees {
	public static void main (String [] args) throws IOException{
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			StringTokenizer st = new StringTokenizer(in.readLine());

			final long M = (long) Math.pow(10, 9) + 7;
			int n = Integer.parseInt(st.nextToken());
			int k = Integer.parseInt(st.nextToken());
			Node [] nod = new Node [n];
			for (int i = 0; i < n; i++)
				nod[i] = new Node();

			for (int i = 0; i < n - 1; i++) {
				st = new StringTokenizer(in.readLine());
				int u = Integer.parseInt(st.nextToken()) - 1;
				int v = Integer.parseInt(st.nextToken()) - 1;
				int x = Integer.parseInt(st.nextToken());
				if (x == 0) {
					nod[u].rcon.add(nod[v]);
					nod[v].rcon.add(nod[u]);
				}
			}

			long ans = 1;
			for (int i = 0; i < k; i++)
				ans = (ans * n) % M;

			for (int i = 0; i < n; i++) {
				if (nod[i].group == false) {
					ans -= Math.pow(form(nod[i]), k) % M;
					ans %= M;
				}
			}
			System.out.println(ans);
	}
	public static int form (Node n) {
		n.group = true;
		int size = 1;
		for (Node newNode: n.rcon) {
			if (newNode.group == false)
				size += form(newNode);
		}
		return size;
	}
	static class Node {
		boolean group = false;
		ArrayList<Node> rcon = new ArrayList<Node>();

	}
}


import java.io.*;
import java.util.*;

public class EdgyTrees {
	static final long M = (long) Math.pow(10, 9) + 7;
	public static void main (String [] args) throws IOException{
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			StringTokenizer st = new StringTokenizer(in.readLine());

			int n = Integer.parseInt(st.nextToken());
			int k = Integer.parseInt(st.nextToken());
			Node [] nod = new Node [n];
			for (int i = 0; i < n; i++)
				nod[i] = new Node();

			for (int i = 0; i < n - 1; i++) {
				st = new StringTokenizer(in.readLine());
				int u = Integer.parseInt(st.nextToken()) - 1;
				int v = Integer.parseInt(st.nextToken()) - 1;
				int x = Integer.parseInt(st.nextToken());
				if (x == 0) {
					nod[u].rcon.add(nod[v]);
					nod[v].rcon.add(nod[u]);
				}
			}

			long ans = pow (n, k);

			for (int i = 0; i < n; i++) {
				if (nod[i].group == false) {
					ans -= pow(form(nod[i]), k);
					ans %= M;
				}
			}
			if (ans < 0)
				System.out.println(ans + M);
			else
				System.out.println(ans);
	}
	public static long pow (long a, long b) {
		long p = 1;
		for (int i = 0; i < b; i++)
			p = (p * a) % M;
		return p;
	}
	public static int form (Node n) {
		n.group = true;
		int size = 1;
		for (Node newNode: n.rcon) {
			if (newNode.group == false)
				size += form(newNode);
		}
		return size;
	}
	static class Node {
		boolean group = false;
		ArrayList<Node> rcon = new ArrayList<Node>();

	}
}


import java.io.*;
import java.util.*;

public class EdgyTrees {
	public static void main (String [] args) throws IOException{
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			StringTokenizer st = new StringTokenizer(in.readLine());

			final long M = (long) Math.pow(10, 9) + 7;
			int n = Integer.parseInt(st.nextToken());
			int k = Integer.parseInt(st.nextToken());
			Node [] nod = new Node [n];
			for (int i = 0; i < n; i++)
				nod[i] = new Node();

			for (int i = 0; i < n - 1; i++) {
				st = new StringTokenizer(in.readLine());
				int u = Integer.parseInt(st.nextToken()) - 1;
				int v = Integer.parseInt(st.nextToken()) - 1;
				int x = Integer.parseInt(st.nextToken());
				if (x == 0) {
					nod[u].rcon.add(nod[v]);
					nod[v].rcon.add(nod[u]);
				}
			}

			long ans = 1;
			for (int i = 0; i < k; i++)
				ans = (ans * n) % M;

			for (int i = 0; i < n; i++) {
				if (nod[i].group == false) {
					ans -= Math.pow(form(nod[i]), k) % M;
					ans %= M;
				}
			}
			if (ans < 0)
				System.out.println(ans + M);
			else
				System.out.println(ans);
	}
	public static int form (Node n) {
		n.group = true;
		int size = 1;
		for (Node newNode: n.rcon) {
			if (newNode.group == false)
				size += form(newNode);
		}
		return size;
	}
	static class Node {
		boolean group = false;
		ArrayList<Node> rcon = new ArrayList<Node>();

	}
}


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class G {
	static int MOD = 1000000007;
	public static void main(String[] args) throws Exception {
		InputReader scan = new InputReader(new BufferedInputStream(System.in));
		int n = scan.nextInt(), k = scan.nextInt();
		Node[] arr = new Node[n];
		for(int i=0;i<n;i++)arr[i]=new Node();
		for (int i=0;i<n-1;i++) {
			int s = scan.nextInt() - 1, v = scan.nextInt() - 1, color = scan.nextInt();
			if (color == 0)
				arr[s].adjacentNodes.add(arr[v]);
		}
		List<Integer> nodeGroups = dfs(arr);
		long ans=0L;
		for (Integer key: nodeGroups) {
			ans = Math.floorMod(ans+pow(key, k), MOD);
		}
		ans = Math.floorMod((pow(n, k) - ans),MOD);
		if (ans<0)ans+=MOD;
		System.out.println(ans);
		scan.close();
	}

	private static List<Integer> dfs(Node[] arr) {
		List<Integer> nodes = new LinkedList<>();
		for (int i=0;i<arr.length;i++) {
			if (!arr[i].visited)
				nodes.add(dfs(arr[i]).size());

		}
		return nodes;
	}

	private static List<Node> dfs(Node node) {
		List<Node> nodes = new LinkedList<>();
		nodes.add(node);
		node.visited=true;
		for (Node n: node.adjacentNodes) {
			if (!n.visited)
				nodes.addAll(dfs(n));
		}
		return nodes;
	}

	static class Node {
		int key;boolean visited=false;
		List<Node> adjacentNodes = new LinkedList<G.Node>();
	}

	private static long pow(int base, int exponent) {
		/*if (n==1)return 1l;
		if (k==1)return (long)n;
		if (k==0)return 1l;
		return Math.floorMod(((long)n*(long)pow(n,k-1)),MOD);*/
		long result = 1;
        base = base % MOD;
        while (exponent > 0) {
            if (exponent % 2 == 1) {
                result = result * base;
                result %= MOD;
            }
            exponent = exponent / 2;
            base = (base * base) % MOD;
        }
        return result;
	}

	static class UF {

		private int[] parent;  // parent[i] = parent of i
		private byte[] rank;   // rank[i] = rank of subtree rooted at i (never more than 31)
		private int count;     // number of components

		public UF(int n) {
			if (n < 0) throw new IllegalArgumentException();
			count = n;
			parent = new int[n];
			rank = new byte[n];
			for (int i = 0; i < n; i++) {
				parent[i] = i;
				rank[i] = 0;
			}
		}

		public Map<Integer, Integer> getCounts() {
			Map<Integer, Integer> map = new HashMap<>(count);
			for (int i:parent)
				map.put(i, 1+map.getOrDefault(i, 0));
			return map;
		}

		public void print() {
			System.out.println(Arrays.toString(parent));
			System.out.println(Arrays.toString(rank));
		}

		public int find(int p) {
			while (p != parent[p]) {
				parent[p] = parent[parent[p]];    // path compression by halving
				p = parent[p];
			}
			return p;
		}

		public int count() {
			return count;
		}

		public boolean connected(int p, int q) {
			return find(p) == find(q);
		}

		public void union(int p, int q) {
			int rootP = find(p);
			int rootQ = find(q);
			if (rootP == rootQ) return;
			// make root of smaller rank point to root of larger rank
			if      (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
			else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
			else {
				parent[rootQ] = rootP;

				rank[rootP]++;
			}
			count--;
		}
	}

	static class InputReader {

		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		public void close() throws IOException {
			this.stream.close();
		}

		public static boolean isWhitespace(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public int read() {
			if (numChars == -1) {
				throw new InputMismatchException();
			}
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0) {
					return -1;
				}
			}
			return buf[curChar++];
		}

		public boolean isSpaceChar(int c) {
			if (filter != null) {
				return filter.isSpaceChar(c);
			}
			return isWhitespace(c);
		}

		public interface SpaceCharFilter {

			public boolean isSpaceChar(int ch);
		}

		public String next() {
			return nextString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9') {
					throw new InputMismatchException();
				}
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public Long nextLong() {
			return Long.parseLong(nextString());
		}

		public Double nextDouble() {
			return Double.parseDouble(nextString());
		}

		public char nextCharacter() {
			return nextString().charAt(0);
		}

		public int[] nextIntArray(int N) {
			int A[] = new int[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextInt();
			}
			return A;
		}

		public long[] nextLongArray(int N) {
			long A[] = new long[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextLong();
			}
			return A;
		}

		public double[] nextDoubleArray(int N) {
			double A[] = new double[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextDouble();
			}
			return A;
		}
	}

	int min(int... a) {
		int min = Integer.MAX_VALUE;
		for (int v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	long min(long... a) {
		long min = Long.MAX_VALUE;
		for (long v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	double min(double... a) {
		double min = Double.MAX_VALUE;
		for (double v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	int max(int... a) {
		int max = Integer.MIN_VALUE;
		for (int v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	long max(long... a) {
		long max = Long.MIN_VALUE;
		for (long v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	double max(double... a) {
		double max = Double.MIN_VALUE;
		for (double v : a) {
			max = Math.max(max, v);
		}
		return max;
	}
}


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class G {
	static int MOD = 1000000007;
	public static void main(String[] args) throws Exception {
		InputReader scan = new InputReader(new BufferedInputStream(System.in));
		int n = scan.nextInt(), k = scan.nextInt();
		Node[] arr = new Node[n];
		for(int i=0;i<n;i++)arr[i]=new Node();
		for (int i=0;i<n-1;i++) {
			int s = scan.nextInt() - 1, v = scan.nextInt() - 1, color = scan.nextInt();
			if (color == 0) {
				arr[s].adjacentNodes.add(arr[v]);
				arr[v].adjacentNodes.add(arr[s]);
			}
		}
		List<Integer> nodeGroups = dfs(arr);
		long ans=0L;
		for (Integer key: nodeGroups) {
			ans = Math.floorMod(ans+pow(key, k), MOD);
		}
		ans = Math.floorMod((pow(n, k) - ans),MOD);
		if (ans<0)ans+=MOD;
		System.out.println(ans);
		scan.close();
	}

	private static List<Integer> dfs(Node[] arr) {

		List<Integer> nodes = new LinkedList<>();
		for (int i=0;i<arr.length;i++) {
			if (!arr[i].visited)
				nodes.add(dfs(arr[i]).size());

		}
		//System.out.println(nodes);
		return nodes;
	}

	private static List<Node> dfs(Node node) {
		List<Node> nodes = new LinkedList<>();
		nodes.add(node);
		node.visited=true;
		for (Node n: node.adjacentNodes) {
			if (!n.visited)
				nodes.addAll(dfs(n));
		}
		return nodes;
	}

	static class Node {
		int key;boolean visited=false;
		List<Node> adjacentNodes = new LinkedList<G.Node>();
	}

	private static long pow(int base, int exponent) {
		/*if (n==1)return 1l;
		if (k==1)return (long)n;
		if (k==0)return 1l;
		return Math.floorMod(((long)n*(long)pow(n,k-1)),MOD);*/
		long result = 1;
		base = base % MOD;
		while (exponent > 0) {
			if (exponent % 2 == 1) {
				result = result * base;
				result %= MOD;
			}
			exponent = exponent / 2;
			base = (base * base) % MOD;
		}
		return result;
	}

	static class UF {

		private int[] parent;  // parent[i] = parent of i
		private byte[] rank;   // rank[i] = rank of subtree rooted at i (never more than 31)
		private int count;     // number of components

		public UF(int n) {
			if (n < 0) throw new IllegalArgumentException();
			count = n;
			parent = new int[n];
			rank = new byte[n];
			for (int i = 0; i < n; i++) {
				parent[i] = i;
				rank[i] = 0;
			}
		}

		public Map<Integer, Integer> getCounts() {
			Map<Integer, Integer> map = new HashMap<>(count);
			for (int i:parent)
				map.put(i, 1+map.getOrDefault(i, 0));
			return map;
		}

		public void print() {
			System.out.println(Arrays.toString(parent));
			System.out.println(Arrays.toString(rank));
		}

		public int find(int p) {
			while (p != parent[p]) {
				parent[p] = parent[parent[p]];    // path compression by halving
				p = parent[p];
			}
			return p;
		}

		public int count() {
			return count;
		}

		public boolean connected(int p, int q) {
			return find(p) == find(q);
		}

		public void union(int p, int q) {
			int rootP = find(p);
			int rootQ = find(q);
			if (rootP == rootQ) return;
			// make root of smaller rank point to root of larger rank
			if      (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
			else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
			else {
				parent[rootQ] = rootP;

				rank[rootP]++;
			}
			count--;
		}
	}

	static class InputReader {

		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		public void close() throws IOException {
			this.stream.close();
		}

		public static boolean isWhitespace(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public int read() {
			if (numChars == -1) {
				throw new InputMismatchException();
			}
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0) {
					return -1;
				}
			}
			return buf[curChar++];
		}

		public boolean isSpaceChar(int c) {
			if (filter != null) {
				return filter.isSpaceChar(c);
			}
			return isWhitespace(c);
		}

		public interface SpaceCharFilter {

			public boolean isSpaceChar(int ch);
		}

		public String next() {
			return nextString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9') {
					throw new InputMismatchException();
				}
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public Long nextLong() {
			return Long.parseLong(nextString());
		}

		public Double nextDouble() {
			return Double.parseDouble(nextString());
		}

		public char nextCharacter() {
			return nextString().charAt(0);
		}

		public int[] nextIntArray(int N) {
			int A[] = new int[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextInt();
			}
			return A;
		}

		public long[] nextLongArray(int N) {
			long A[] = new long[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextLong();
			}
			return A;
		}

		public double[] nextDoubleArray(int N) {
			double A[] = new double[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextDouble();
			}
			return A;
		}
	}

	int min(int... a) {
		int min = Integer.MAX_VALUE;
		for (int v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	long min(long... a) {
		long min = Long.MAX_VALUE;
		for (long v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	double min(double... a) {
		double min = Double.MAX_VALUE;
		for (double v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	int max(int... a) {
		int max = Integer.MIN_VALUE;
		for (int v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	long max(long... a) {
		long max = Long.MIN_VALUE;
		for (long v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	double max(double... a) {
		double max = Double.MIN_VALUE;
		for (double v : a) {
			max = Math.max(max, v);
		}
		return max;
	}
}


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class G {
	static int MOD = 1000000007;
	public static void main(String[] args) throws Exception {
		InputReader scan = new InputReader(new BufferedInputStream(System.in));
		int n = scan.nextInt(), k = scan.nextInt();
		Node[] arr = new Node[n];
		for(int i=0;i<n;i++)arr[i]=new Node();
		for (int i=0;i<n-1;i++) {
			int s = scan.nextInt() - 1, v = scan.nextInt() - 1, color = scan.nextInt();
			if (color == 0) {
				arr[s].adjacentNodes.add(arr[v]);
				arr[v].adjacentNodes.add(arr[s]);
			}
		}
		List<Integer> nodeGroups = dfs(arr);
		long ans=0L;
		for (Integer key: nodeGroups) {
			ans = Math.floorMod(ans+pow(key, k), MOD);
		}
		ans = Math.floorMod((pow(n, k) - ans),MOD);
		if (ans<0)ans+=MOD;
		System.out.println(ans);
		scan.close();
	}

	private static List<Integer> dfs(Node[] arr) {

		List<Integer> nodes = new LinkedList<>();
		for (int i=0;i<arr.length;i++) {
			if (!arr[i].visited)
				nodes.add(dfs(arr[i]).size());

		}
		//System.out.println(nodes);
		return nodes;
	}

	private static List<Node> dfs(Node node) {
		List<Node> nodes = new LinkedList<>();
		nodes.add(node);
		node.visited=true;
		for (Node n: node.adjacentNodes) {
			if (!n.visited)
				nodes.addAll(dfs(n));
		}
		return nodes;
	}

	static class Node {
		int key;boolean visited=false;
		List<Node> adjacentNodes = new LinkedList<G.Node>();
	}

	private static long pow(int base, int exponent) {
		if (base==1)return 1l;
		if (exponent==1)return (long)base;
		if (exponent==0)return 1l;
		return Math.floorMod(((long)base*(long)pow(base,exponent-1)),MOD);
/*		long result = 1;
		base = base % MOD;
		while (exponent > 0) {
			if (exponent % 2 == 1) {
				result = result * base;
				result %= MOD;
			}
			exponent = exponent / 2;
			base = (base * base) % MOD;
		}
		return result;*/
	}

	static class UF {

		private int[] parent;  // parent[i] = parent of i
		private byte[] rank;   // rank[i] = rank of subtree rooted at i (never more than 31)
		private int count;     // number of components

		public UF(int n) {
			if (n < 0) throw new IllegalArgumentException();
			count = n;
			parent = new int[n];
			rank = new byte[n];
			for (int i = 0; i < n; i++) {
				parent[i] = i;
				rank[i] = 0;
			}
		}

		public Map<Integer, Integer> getCounts() {
			Map<Integer, Integer> map = new HashMap<>(count);
			for (int i:parent)
				map.put(i, 1+map.getOrDefault(i, 0));
			return map;
		}

		public void print() {
			System.out.println(Arrays.toString(parent));
			System.out.println(Arrays.toString(rank));
		}

		public int find(int p) {
			while (p != parent[p]) {
				parent[p] = parent[parent[p]];    // path compression by halving
				p = parent[p];
			}
			return p;
		}

		public int count() {
			return count;
		}

		public boolean connected(int p, int q) {
			return find(p) == find(q);
		}

		public void union(int p, int q) {
			int rootP = find(p);
			int rootQ = find(q);
			if (rootP == rootQ) return;
			// make root of smaller rank point to root of larger rank
			if      (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
			else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
			else {
				parent[rootQ] = rootP;

				rank[rootP]++;
			}
			count--;
		}
	}

	static class InputReader {

		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		public void close() throws IOException {
			this.stream.close();
		}

		public static boolean isWhitespace(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public int read() {
			if (numChars == -1) {
				throw new InputMismatchException();
			}
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0) {
					return -1;
				}
			}
			return buf[curChar++];
		}

		public boolean isSpaceChar(int c) {
			if (filter != null) {
				return filter.isSpaceChar(c);
			}
			return isWhitespace(c);
		}

		public interface SpaceCharFilter {

			public boolean isSpaceChar(int ch);
		}

		public String next() {
			return nextString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9') {
					throw new InputMismatchException();
				}
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public Long nextLong() {
			return Long.parseLong(nextString());
		}

		public Double nextDouble() {
			return Double.parseDouble(nextString());
		}

		public char nextCharacter() {
			return nextString().charAt(0);
		}

		public int[] nextIntArray(int N) {
			int A[] = new int[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextInt();
			}
			return A;
		}

		public long[] nextLongArray(int N) {
			long A[] = new long[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextLong();
			}
			return A;
		}

		public double[] nextDoubleArray(int N) {
			double A[] = new double[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextDouble();
			}
			return A;
		}
	}

	int min(int... a) {
		int min = Integer.MAX_VALUE;
		for (int v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	long min(long... a) {
		long min = Long.MAX_VALUE;
		for (long v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	double min(double... a) {
		double min = Double.MAX_VALUE;
		for (double v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	int max(int... a) {
		int max = Integer.MIN_VALUE;
		for (int v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	long max(long... a) {
		long max = Long.MIN_VALUE;
		for (long v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	double max(double... a) {
		double max = Double.MIN_VALUE;
		for (double v : a) {
			max = Math.max(max, v);
		}
		return max;
	}
}


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.Map.Entry;

public class C {
	static int MOD = 1000000007;
	public static void main(String[] args) throws Exception {
		InputReader scan = new InputReader(new BufferedInputStream(System.in));
		int n = scan.nextInt(), k = scan.nextInt();
		UF uf = new UF(n);
		for (int i=0;i<n-1;i++) {
			int s = scan.nextInt() - 1, v = scan.nextInt() - 1, color = scan.nextInt();
			if (color == 0)
				uf.union(s, v);
		}
		//uf.print();
		Map<Integer, Integer> counts = uf.getCounts();
		//System.out.println(counts);
		long ans=0L;
		for (Entry<Integer, Integer> key: counts.entrySet()) {
			ans = Math.floorMod(ans+pow(key.getValue(), k), MOD);
		}
		ans = Math.floorMod((pow(n, k) - ans),MOD);
		if (ans<0)ans+=MOD;
		System.out.println(ans);
		scan.close();
	}

	private static long pow(int base, int exponent) {
		/*if (n==1)return 1l;
		if (k==1)return (long)n;
		if (k==0)return 1l;
		return Math.floorMod(((long)n*(long)pow(n,k-1)),MOD);*/
		long result = 1;
        base = base % MOD;
        while (exponent > 0) {
            if (exponent % 2 == 1) {
                result = result * base;
                result %= MOD;
            }
            exponent = exponent / 2;
            base = (base * base) % MOD;
        }
        return result;
	}

	static class UF {

		private int[] parent;  // parent[i] = parent of i
		private byte[] rank;   // rank[i] = rank of subtree rooted at i (never more than 31)
		private int count;     // number of components

		public UF(int n) {
			if (n < 0) throw new IllegalArgumentException();
			count = n;
			parent = new int[n];
			rank = new byte[n];
			for (int i = 0; i < n; i++) {
				parent[i] = i;
				rank[i] = 0;
			}
		}

		public Map<Integer, Integer> getCounts() {
			Map<Integer, Integer> map = new HashMap<>(count);
			for (int i:parent)
				map.put(i, 1+map.getOrDefault(i, 0));
			return map;
		}

		public void print() {
			System.out.println(Arrays.toString(parent));
		}

		public int find(int p) {
			while (p != parent[p]) {
				parent[p] = parent[parent[p]];    // path compression by halving
				p = parent[p];
			}
			return p;
		}

		public int count() {
			return count;
		}

		public boolean connected(int p, int q) {
			return find(p) == find(q);
		}

		public void union(int p, int q) {
			int rootP = find(p);
			int rootQ = find(q);
			if (rootP == rootQ) return;
			// make root of smaller rank point to root of larger rank
			if      (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
			else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
			else {
				parent[rootQ] = rootP;

				rank[rootP]++;
			}
			count--;
		}
	}

	static class InputReader {

		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		public void close() throws IOException {
			this.stream.close();
		}

		public static boolean isWhitespace(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public int read() {
			if (numChars == -1) {
				throw new InputMismatchException();
			}
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0) {
					return -1;
				}
			}
			return buf[curChar++];
		}

		public boolean isSpaceChar(int c) {
			if (filter != null) {
				return filter.isSpaceChar(c);
			}
			return isWhitespace(c);
		}

		public interface SpaceCharFilter {

			public boolean isSpaceChar(int ch);
		}

		public String next() {
			return nextString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9') {
					throw new InputMismatchException();
				}
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public Long nextLong() {
			return Long.parseLong(nextString());
		}

		public Double nextDouble() {
			return Double.parseDouble(nextString());
		}

		public char nextCharacter() {
			return nextString().charAt(0);
		}

		public int[] nextIntArray(int N) {
			int A[] = new int[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextInt();
			}
			return A;
		}

		public long[] nextLongArray(int N) {
			long A[] = new long[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextLong();
			}
			return A;
		}

		public double[] nextDoubleArray(int N) {
			double A[] = new double[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextDouble();
			}
			return A;
		}
	}

	int min(int... a) {
		int min = Integer.MAX_VALUE;
		for (int v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	long min(long... a) {
		long min = Long.MAX_VALUE;
		for (long v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	double min(double... a) {
		double min = Double.MAX_VALUE;
		for (double v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	int max(int... a) {
		int max = Integer.MIN_VALUE;
		for (int v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	long max(long... a) {
		long max = Long.MIN_VALUE;
		for (long v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	double max(double... a) {
		double max = Double.MIN_VALUE;
		for (double v : a) {
			max = Math.max(max, v);
		}
		return max;
	}
}


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.Map.Entry;

public class C {
	static int MOD = 1000000007;
	public static void main(String[] args) throws Exception {
		InputReader scan = new InputReader(new BufferedInputStream(System.in));
		int n = scan.nextInt(), k = scan.nextInt();
		UF uf = new UF(n);
		for (int i=0;i<n-1;i++) {
			int s = scan.nextInt() - 1, v = scan.nextInt() - 1, color = scan.nextInt();
			if (color == 0)
				uf.union(s, v);
		}
		//uf.print();
		Map<Integer, Integer> counts = uf.getCounts();
		//System.out.println(counts);
		long ans=0L;
		for (Entry<Integer, Integer> key: counts.entrySet()) {
			ans = Math.floorMod(ans+pow(key.getValue(), k), MOD);
		}
		ans = Math.floorMod((pow(n, k) - ans),MOD);
		if (ans<0)ans+=MOD;
		System.out.println(ans);
		scan.close();
	}

	private static long pow(int n, int k) {
		if (n==1)return 1l;
		if (k==1)return (long)n;
		if (k==0)return 1l;
		return Math.floorMod(((long)n*(long)pow(n,k-1)),MOD);
	}

	static class UF {

		private int[] parent;  // parent[i] = parent of i
		private byte[] rank;   // rank[i] = rank of subtree rooted at i (never more than 31)
		private int count;     // number of components

		public UF(int n) {
			if (n < 0) throw new IllegalArgumentException();
			count = n;
			parent = new int[n];
			rank = new byte[n];
			for (int i = 0; i < n; i++) {
				parent[i] = i;
				rank[i] = 0;
			}
		}

		public Map<Integer, Integer> getCounts() {
			Map<Integer, Integer> map = new HashMap<>(count);
			for (int i:parent)
				map.put(i, 1+map.getOrDefault(i, 0));
			return map;
		}

		public void print() {
			System.out.println(Arrays.toString(parent));
		}

		public int find(int p) {
			while (p != parent[p]) {
				parent[p] = parent[parent[p]];    // path compression by halving
				p = parent[p];
			}
			return p;
		}

		public int count() {
			return count;
		}

		public boolean connected(int p, int q) {
			return find(p) == find(q);
		}

		public void union(int p, int q) {
			int rootP = find(p);
			int rootQ = find(q);
			if (rootP == rootQ) return;
			// make root of smaller rank point to root of larger rank
			if      (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
			else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
			else {
				parent[rootQ] = rootP;

				rank[rootP]++;
			}
			count--;
		}
	}

	static class InputReader {

		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		public void close() throws IOException {
			this.stream.close();
		}

		public static boolean isWhitespace(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public int read() {
			if (numChars == -1) {
				throw new InputMismatchException();
			}
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0) {
					return -1;
				}
			}
			return buf[curChar++];
		}

		public boolean isSpaceChar(int c) {
			if (filter != null) {
				return filter.isSpaceChar(c);
			}
			return isWhitespace(c);
		}

		public interface SpaceCharFilter {

			public boolean isSpaceChar(int ch);
		}

		public String next() {
			return nextString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9') {
					throw new InputMismatchException();
				}
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public Long nextLong() {
			return Long.parseLong(nextString());
		}

		public Double nextDouble() {
			return Double.parseDouble(nextString());
		}

		public char nextCharacter() {
			return nextString().charAt(0);
		}

		public int[] nextIntArray(int N) {
			int A[] = new int[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextInt();
			}
			return A;
		}

		public long[] nextLongArray(int N) {
			long A[] = new long[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextLong();
			}
			return A;
		}

		public double[] nextDoubleArray(int N) {
			double A[] = new double[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextDouble();
			}
			return A;
		}
	}

	int min(int... a) {
		int min = Integer.MAX_VALUE;
		for (int v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	long min(long... a) {
		long min = Long.MAX_VALUE;
		for (long v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	double min(double... a) {
		double min = Double.MAX_VALUE;
		for (double v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	int max(int... a) {
		int max = Integer.MIN_VALUE;
		for (int v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	long max(long... a) {
		long max = Long.MIN_VALUE;
		for (long v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	double max(double... a) {
		double max = Double.MIN_VALUE;
		for (double v : a) {
			max = Math.max(max, v);
		}
		return max;
	}
}


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.Map.Entry;

public class C {
	static int MOD = 1000000007;
	public static void main(String[] args) throws Exception {
		InputReader scan = new InputReader(new BufferedInputStream(System.in));
		int n = scan.nextInt(), k = scan.nextInt();
		UF uf = new UF(n);
		for (int i=0;i<n-1;i++) {
			int s = scan.nextInt() - 1, v = scan.nextInt() - 1, color = scan.nextInt();
			if (color == 0)
				uf.union(s, v);
		}
		//uf.print();
		Map<Integer, Integer> counts = uf.getCounts();
		//System.out.println(counts);
		long ans=0L;
		for (Entry<Integer, Integer> key: counts.entrySet()) {
			ans = (ans+pow(key.getValue(), k)) % MOD;
		}
		ans = pow(n, k) - ans;
		System.out.println(ans%MOD);
		scan.close();
	}

	private static long pow(int n, int k) {
		if (k==1)return n;
		if (k==0)return 1;
		return (n*pow(n,k-1))%MOD;
	}

	static class UF {

		private int[] parent;  // parent[i] = parent of i
		private byte[] rank;   // rank[i] = rank of subtree rooted at i (never more than 31)
		private int count;     // number of components

		public UF(int n) {
			if (n < 0) throw new IllegalArgumentException();
			count = n;
			parent = new int[n];
			rank = new byte[n];
			for (int i = 0; i < n; i++) {
				parent[i] = i;
				rank[i] = 0;
			}
		}

		public Map<Integer, Integer> getCounts() {
			Map<Integer, Integer> map = new HashMap<>();
			for (int i:parent)
				map.put(i, 1+map.getOrDefault(i, 0));
			return map;
		}

		public void print() {
			System.out.println(Arrays.toString(parent));
		}

		public int find(int p) {
			while (p != parent[p]) {
				parent[p] = parent[parent[p]];    // path compression by halving
				p = parent[p];
			}
			return p;
		}

		public int count() {
			return count;
		}

		public boolean connected(int p, int q) {
			return find(p) == find(q);
		}

		public void union(int p, int q) {
			int rootP = find(p);
			int rootQ = find(q);
			if (rootP == rootQ) return;
			// make root of smaller rank point to root of larger rank
			if      (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
			else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
			else {
				parent[rootQ] = rootP;

				rank[rootP]++;
			}
			count--;
		}
	}

	static class InputReader {

		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		public void close() throws IOException {
			this.stream.close();
		}

		public static boolean isWhitespace(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public int read() {
			if (numChars == -1) {
				throw new InputMismatchException();
			}
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0) {
					return -1;
				}
			}
			return buf[curChar++];
		}

		public boolean isSpaceChar(int c) {
			if (filter != null) {
				return filter.isSpaceChar(c);
			}
			return isWhitespace(c);
		}

		public interface SpaceCharFilter {

			public boolean isSpaceChar(int ch);
		}

		public String next() {
			return nextString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9') {
					throw new InputMismatchException();
				}
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public Long nextLong() {
			return Long.parseLong(nextString());
		}

		public Double nextDouble() {
			return Double.parseDouble(nextString());
		}

		public char nextCharacter() {
			return nextString().charAt(0);
		}

		public int[] nextIntArray(int N) {
			int A[] = new int[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextInt();
			}
			return A;
		}

		public long[] nextLongArray(int N) {
			long A[] = new long[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextLong();
			}
			return A;
		}

		public double[] nextDoubleArray(int N) {
			double A[] = new double[N];
			for (int i = 0; i < N; i++) {
				A[i] = nextDouble();
			}
			return A;
		}
	}

	int min(int... a) {
		int min = Integer.MAX_VALUE;
		for (int v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	long min(long... a) {
		long min = Long.MAX_VALUE;
		for (long v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	double min(double... a) {
		double min = Double.MAX_VALUE;
		for (double v : a) {
			min = Math.min(min, v);
		}
		return min;
	}

	int max(int... a) {
		int max = Integer.MIN_VALUE;
		for (int v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	long max(long... a) {
		long max = Long.MIN_VALUE;
		for (long v : a) {
			max = Math.max(max, v);
		}
		return max;
	}

	double max(double... a) {
		double max = Double.MIN_VALUE;
		for (double v : a) {
			max = Math.max(max, v);
		}
		return max;
	}
}