#include <iostream> #include <vector> typedef long long ll; int pow(int a, int b, int m) { if (b == 0) return 1; if (b&1) return (ll) pow(a, b-1, m) * a % m; int p = pow(a, b>>1, m); return (ll) p * p % m; } int dfs(int v, std::vector<std::vector<int>>& graph, std::vector<bool>& visited) { int cnt = 1; visited[v] = true; for (auto w : graph[v]) if (!visited[w]) cnt += dfs(w, graph, visited); return cnt; } void solve() { int n, m; std::cin >> n >> m; std::vector<int> B(n+1); for (int i = 1; i <= n; i++) std::cin >> B[i]; std::vector<std::vector<int>> graph(n+1); std::vector<int> start; for (int i = 0; i < m; i++) { int a, b; std::cin >> a >> b; graph[a].push_back(b); graph[b].push_back(a); if (B[a] == B[b]) start.push_back(a); } std::vector<bool> visited(n+1, false); int res = 1; int mod = 1e9+7; for (auto s : start) if (!visited[s]) res = (ll) res * pow(2, dfs(s, graph, visited)-1, mod) % mod; std::cout << res << '\n'; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); solve(); return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <iostream> #include <vector> typedef long long ll; int pow(int a, int b, int m) { if (b == 0) return 1; if (b&1) return (ll) pow(a, b-1, m) * a % m; int p = pow(a, b>>1, m); return (ll) p * p % m; } int dfs(int v, std::vector<std::vector<int>>& graph, std::vector<bool>& visited) { int cnt = 1; visited[v] = true; for (auto w : graph[v]) if (!visited[w]) cnt += dfs(w, graph, visited); return cnt; } void solve() { int n, m; std::cin >> n >> m; std::vector<int> B(n+1); for (int i = 1; i <= n; i++) std::cin >> B[i]; std::vector<std::vector<int>> graph(n+1); std::vector<int> start; for (int i = 0; i < m; i++) { int a, b; std::cin >> a >> b; graph[a].push_back(b); graph[b].push_back(a); if (B[a] == B[b]) start.push_back(a); } std::vector<bool> visited(n+1, false); int res = 1; int mod = 1e9+7; for (auto s : start) if (!visited[s]) res = (ll) res * pow(2, dfs(s, graph, visited)-1, mod) % mod; std::cout << res << '\n'; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); solve(); return 0; } |