// 三元环计数
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
const int N = 1e5 + 10, M = 2e5 + 10;
int n, m;
int deg[N];
tuple<int, int, int> e[M];
vector<pii> G[N];
bool st[N][2];
ll cnt[M];
int dfs(int u, int o) {
if (st[u][o]) return 0;
st[u][o] = 1;
int res = 1;
for (auto[v, c]: G[u]) {
if (c == o) res += dfs(v, c);
}
return res;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
cin >> n >> m;
int ans = n;
for (int i = 0; i < m; ++i) {
int a, b, c;
cin >> a >> b >> c;
e[i] = {a, b, c};
++deg[a], ++deg[b];
}
set<pii> S[2];
for (int i = 0; i < m; ++i) {
auto&[a, b, c] = e[i];
if (deg[a] < deg[b] || deg[a] == deg[b] && a < b) swap(a, b);
G[a].emplace_back(b, c);
G[b].emplace_back(a, c);
ans += S[c ^ 1].count({a, b});
S[c].insert({a, b});
}
set<array<int, 3>> valid;
for (int i = 1; i <= n; ++i) {
for (auto[j, c1]: G[i]) for (auto[k, c2]: G[i]) {
if (j == k) continue;
array g{i, j, k};
sort(g.begin(), g.end(), [&](int a, int b) {
return deg[a] < deg[b] || deg[a] == deg[b] && a < b;
});
if (S[0].count({i, j}) + S[0].count({i, k}) + S[0].count({j, k}) >= 2 &&
S[1].count({i, j}) + S[1].count({i, k}) + S[1].count({j, k}) >= 2) valid.insert({i, j, k});
}
}
// for (auto a: valid) cout << a[0] << ' ' << a[1] << ' ' << a[2] << el;
ans += valid.size();
for (int i = 1; i <= n; ++i) {
if (st[i][0] || st[i][1]) continue;
int a = dfs(i, 0), b = dfs(i, 1);
if (a == 4 && b == 4) ++ans;
}
cout << ans << '\n';
}