Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1e5 + 7, mod = 1e9 + 7;
- int n, m, ans = 1, dsu[N], sz[N];
- map<int, vector<pair<int, int>>> edges;
- int get(int v) {
- if (dsu[v] == v) {
- return v;
- }
- return dsu[v] = get(dsu[v]);
- }
- void merge(int a, int b) {
- if (a == -1 || b == -1) {
- return;
- }
- a = get(a);
- b = get(b);
- if (a == b) {
- return;
- }
- if (sz[a] < sz[b]) {
- swap(a, b);
- }
- dsu[b] = a;
- sz[a] += sz[a] == sz[b];
- }
- bool eq(pair<int, int> a, pair<int, int> b) {
- return (get(a.first) == get(b.first) && get(a.second) == get(b.second)) || (get(a.first) == get(b.second) && get(a.second) == get(b.first));
- }
- int main() {
- ios::sync_with_stdio(0);
- cin.tie(0); cout.tie(0);
- cin >> n >> m;
- for (int i = 0; i < m; ++i) {
- int a, b, c;
- cin >> a >> b >> c;
- a--; b--;
- edges[c].emplace_back(a, b);
- }
- iota(dsu, dsu + n, 0);
- for (auto i : edges) {
- pair<int, int> a = { -1, -1 }, b = { -1, -1 }, c = { -1, -1 };
- if (i.second.size() >= 1) {
- a = i.second[0];
- if (get(a.first) == get(a.second)) {
- a = { -1, -1 };
- }
- }
- if (i.second.size() >= 2) {
- b = i.second[1];
- if (get(b.first) == get(b.second)) {
- b = { -1, -1 };
- }
- }
- if (i.second.size() >= 3) {
- c = i.second[2];
- if (get(c.first) == get(c.second)) {
- c = { -1, -1 };
- }
- }
- int cnt = (a.first != -1) + (b.first != -1) + (c.first != -1);
- if (cnt == 3) {
- set<int> LOL;
- LOL.insert(get(a.first));
- LOL.insert(get(a.second));
- LOL.insert(get(b.first));
- LOL.insert(get(b.second));
- LOL.insert(get(c.first));
- LOL.insert(get(c.second));
- if (eq(a, b) && eq(a, c)) {
- ans = (1ll * ans * 3) % mod;
- } else if (eq(a, b) || eq(a, c) || eq(b, c)) {
- ans = (1ll * ans * 2) % mod;
- } else if ((int) LOL.size() == 3) {
- ans = (1ll * ans * 3) % mod;
- }
- } else if (cnt == 2) {
- if (a.first == -1) {
- swap(a, c);
- } else if (b.first == -1) {
- swap(b, c);
- }
- if (eq(a, b)) {
- ans = (1ll * ans * 2) % mod;
- }
- }
- merge(a.first, a.second);
- merge(b.first, b.second);
- merge(c.first, c.second);
- }
- bool flag = true;
- for (int i = 0; i < n; ++i) {
- flag &= get(i) == get(0);
- }
- if (flag) {
- cout << ans << "\n";
- } else {
- cout << 0 << "\n";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement