// C++ code for the above approach:
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// Define the modulo constant
const long long modulo = 1000000007;
// Function prototypes
long long power(long long a, long long b,
long long curr_mod);
void dfs(int i, vector<vector<int> >& adj,
vector<bool>& vis, vector<long long>& ar,
unordered_map<long long, long long>& hm);
void Count_sequences(int N, int M, vector<long long>& A,
vector<vector<int> >& B,
vector<long long>& fac);
int main()
{
// Precompute factorials up to 2e5
vector<long long> fac(200001, 0);
fac[0] = 1;
for (int i = 1; i <= 200000; i++)
fac[i] = (fac[i - 1] * i) % modulo;
// Read the number of nodes and edges
int N = 5;
int M = 5;
vector<long long> A = { 10, 12, 15, 20, 15 };
vector<vector<int> > B = {
{ 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 2 }, { 3, 1 }
};
// Function call
Count_sequences(N, M, A, B, fac);
return 0;
}
// Function to output the
// number of sequences
void Count_sequences(int N, int M, vector<long long>& A,
vector<vector<int> >& B,
vector<long long>& fac)
{
// Initialize adjacency list,
// visited array, and ar array
vector<vector<int> > adj(N);
// Visiting array created for DFS
vector<bool> Vis(N, false);
// Constructing the graph
for (int i = 0; i < N; i++)
adj[i] = vector<int>();
// Creating adjacency list
for (int i = 0; i < M; i++) {
int u = B[i][0] - 1;
int v = B[i][1] - 1;
adj[u].push_back(v);
adj[v].push_back(u);
}
// Initialize result and x
long long res = 1;
int x = 0;
// Perform DFS and calculate
// result for each node
for (int i = 0; i < N; i++) {
if (!Vis[i]) {
unordered_map<long long, long long> Map;
dfs(i, adj, Vis, A, Map);
long long mul = 1, cn = 0;
for (const auto& set : Map) {
cn += set.second;
long long xx = set.second;
mul = (mul * fac[xx]) % modulo;
}
int inn = static_cast<int>(cn);
long long y = fac[x + inn];
long long d1
= (power(fac[x], modulo - 2, modulo)
* power(fac[inn], modulo - 2, modulo))
% modulo;
long long fraction = (y * d1) % modulo;
res = (res * ((fraction * mul) % modulo))
% modulo;
x += inn;
}
}
// Print the result
cout << res << endl;
}
// Function to calculate (a^b) mod curr_mod
// using binary exponentiation
long long power(long long a, long long b,
long long curr_mod)
{
if (b == 0)
return 1;
long long temp = power(a, b / 2, curr_mod) % curr_mod;
if ((b & 1) == 0)
return (temp * temp) % curr_mod;
else
return (((temp * temp) % curr_mod) * a) % curr_mod;
}
// DFS function to traverse the graph
// and update HashMap and Visiting array
void dfs(int i, vector<vector<int> >& adj,
vector<bool>& vis, vector<long long>& ar,
unordered_map<long long, long long>& hm)
{
vis[i] = true;
hm[ar[i]] += 1;
for (int it : adj[i]) {
if (!vis[it])
dfs(it, adj, vis, ar, hm);
}
}