下面展示一些 内联代码片
。
哎会超时
#include<iostream>
#include<cstring>
using namespace std;
const int MAX = 1000000+5;
int max(int a,int b){
return a>b ? a : b;
}
int father[MAX];
int people[MAX];
int rankw[MAX];
int a[MAX];
int res[MAX]; //max为祖宗节点最大值;
int cn[MAX];//每个集合祖宗节点位置
int rrr=0;//标记第几个集合
long long s=0;
int find(int x)
{
if (x != father[x])
father[x] = find(father[x]);
return father[x];
}
//合并并返回合并后的祖先序号
void Union(int x, int y)
{
x = find(x);
y = find(y);
if (rankw[x] > rankw[y])
{
father[y] = x;
if (x != y)
people[x] += people[y];
}
else
{
father[x] = y;
//两者祖先相同时,实际没发生合并,只考虑祖先不同的情况
if (x != y)
people[y] += people[x];
if (rankw[x] == rankw[y]) //树高相同时让父节点的树高值加一
rankw[y] += 1;
}
}
//计算集合的个数
int count_sets(int n)
{
int cnt = 0;
for (int i = 1; i <= n; i++)
if (find(i) == i){
cnt++;
cn[cnt] = i;
// cout<<i<<" "<<cnt<<" "<<cn[cnt]<<endl;
}
return cnt;
}
int main()
{
int n, m;
cin>>n>>m;
for (int i = 1; i <= n; i++)
{
father[i] = i;
people[i] = 1;
rankw[i] = 0;
}
for(int i=1 ;i<=n;i++) scanf("%d",&a[i] );
long long qq=0;
for(int i=1;i<=n;i++) qq+=a[i];
if(m==0){
cout<<qq;
return 0;
}
int x, y;
while (m--)
{
scanf("%d %d", &x, &y);
Union(x, y);
res[find(x)] =max(res[find(x)] ,max(a[x],a[y]) );
}
int wwe=0;
for(int i=1;i<=count_sets(n) ;i++){
if(res[cn[i]]==0) wwe = a[cn[i]];
else wwe=res[cn[i]];
s=s+(people[cn[i]]*wwe );
//cout<<s<<endl;
}
printf("%lld",s);
return 0;
}