An undirected connected graph has nn nodes and mm edges, The ii-th edge’s length is 2i2i. Each node ii has a value aiai, which is either 00 or 11. You need to calculate:
∑i=1n∑j=1nd(i,j)×[ai=1∧aj=0]∑i=1n∑j=1nd(i,j)×[ai=1∧aj=0]
d(i,j)d(i,j) indicates the shortest distance between ii and jj. [ ][ ] is the Iverson bracket. ∧∧ indicates ANDAND.
Because the answer may be too large, please output the answer modulo 109+7109+7.
Input
The first line contains one integer TT(1≤T≤81≤T≤8),indicating the number of test cases.
The second line contains two ingeters n,mn,m(1≤n≤105,1≤m≤2×1051≤n≤105,1≤m≤2×105).
The third line contains nn positive integers a1,a2,...,an(ai=0a1,a2,...,an(ai=0 or 11) —— the value of the nodes.
The following mm lines contain two ingeters u,v(1≤u,v≤n)u,v(1≤u,v≤n), and the ii-th line represents the i-th undirected edge’s length is 2i2i, between node uu and vv.
The sum of n,mn,m is no more than 2×1052×105.
Output
Print a single integer—— the value of the answer modulo 109+7109+7.
Sample Input
1 3 2 0 1 0 3 1 3 2
Sample Output
10
Sponsor
因为2^i > 2^i - 1 + 2^i - 2 + .......2;
容易想到并查集缩边
把图变成一个无向无环图(树)
在进行一次dfs对0, 1数进行统计就可得到结果
#include<bits/stdc++.h>
#define ll long long
const int maxn = 4e5 + 10;
const ll md = 1e9 + 7;
using namespace std;
int val[maxn];
int fa[maxn];
int pre[maxn];
int s0[maxn];
int s1[maxn];
int ss0, ss1;
ll ans = 0;
vector<int> G[maxn];
int find(int x){
if(x == fa[x])
return x;
return fa[x] = find(fa[x]);
}
void init(int x){
for(int i = 1; i <= x; i++){
fa[i] = i;
G[i].clear();
s0[i] = s1[i] = 0;
pre[i] = i;
}
ss0 = 0; ss1 = 0;
ans = 0;
}
struct node{
int a, b;
ll w;
}e[maxn];
void dfs(int x, int f){
pre[x] = f;
for(auto i : G[x]){
if(i != f){
dfs(i, x);
s1[x] += s1[i];
s0[x] += s0[i];
}
}
}
void solve(){
int n, m;
cin >> n >> m;
init(n);
ll cnt = 1;
for(int i = 1; i <= n; i++){
cin >> val[i];
if(val[i])
s1[i]++, ss1++;
else
s0[i]++, ss0++;
}
for(int i = 1; i <= m; i++){
cin >> e[i].a >> e[i].b;
cnt = 2 * cnt % md;
e[i].w = cnt;
}
int cntt = 0;
for(int i = 1; i <= m; i++){
int finda = find(e[i].a);
int findb = find(e[i].b);
if(finda != findb){
fa[finda] = findb;
++cntt;
e[cntt].a = e[i].a;
e[cntt].b = e[i].b;
e[cntt].w = e[i].w;
G[e[cntt].a].push_back(e[cntt].b);
G[e[cntt].b].push_back(e[cntt].a);
}
}
//cout << cntt << endl;
dfs(1, 0);
for(int i = 1; i <= cntt; i++){
int ta = e[i].a;
int tb = e[i].b;
ll quan = e[i].w;
if(pre[ta]==tb)
swap(ta, tb);
ans += ((ss1 - s1[tb]) * (s0[tb]) % md * quan)%md;
ans %= md;
ans += ((ss0 - s0[tb]) * (s1[tb]) % md * quan)%md;
ans %= md;
}
cout << ans % md << endl;
}
int main(){
int t;
cin >> t;
while(t--){
solve();
}
}