Example

Input

2 2
1 2 0
3 4 1


Output

2
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define N 3000005
#define ll long long
#define mod 1000000009
int n, m, k, ans;
int A[20], B[20], C[20];
int bel[N], sum[N], siz[N];
int fac[N], inv[N];
int Getbel(int x)
{
	if (!bel[x])
		return x;
	return bel[x] = Getbel(bel[x]);
}
int ksm(int a, int k)
{
	if (!k)
		return 1;
	int p = ksm(a, k / 2);
	if (k & 1)
		return (ll)p * p % mod * a % mod;
	return (ll)p * p % mod;
}
int main()
{
	fac[0] = 1;
	for (int i = 1; i <= N - 5; i++)
		fac[i] = (ll)fac[i - 1] * i % mod;
	inv[N - 5] = ksm(fac[N - 5], mod - 2);
	for (int i = N - 5; i >= 1; i--)
		inv[i - 1] = (ll)inv[i] * i % mod;
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= m; i++)
	{
		scanf("%d%d%d", &A[i], &B[i], &C[i]);
		k += C[i];
	}
	for (int i = 0; i < (1 << k); i++)
	{
		sum[1] = n * 3;
		sum[2] = sum[3] = 0;
		int w = 0;
		for (int j = 1; j <= m; j++)
		{
			bel[A[j]] = bel[B[j]] = 0;
			siz[A[j]] = siz[B[j]] = 1;
		}
		int flg = 0, bit = 0;
		for (int j = 1; j <= m; j++)
		{
			if (C[j] == 1 && i & (1 << w))
				bit++;
			if (C[j] == 0 || (i & (1 << w)))
			{
				int x = Getbel(A[j]), y = Getbel(B[j]);
				if (x != y)
				{
					bel[x] = y;
					sum[siz[y]]--;
					sum[siz[x]]--;
					siz[y] += siz[x];
					if (siz[y] > 3)
					{
						flg = 1;
						break;
					}
					sum[siz[y]]++;
				}
			}
			w += C[j];
		}
		if (!flg)
		{
			int x = sum[1], y = sum[2];
			if (x >= y)
			{
				int now = fac[x];
				now = (ll)now * ksm(inv[3], (x - y) / 3) % mod * inv[(x - y) / 3] % mod;
				if (bit & 1)
					ans = (ans - now) % mod;
				else
					ans = (ans + now) % mod;
			}
		}
	}
	if (ans < 0)ans += mod;
	printf("%d\n", ans);
}

