2020 Multi-University Training Contest 2:Total Eclipse【贪心】【并查集】

2020 Multi-University Training Contest 2:Total Eclipse【贪心】【并查集】_第1张图片
思路:对于一个连通块来说,一定是点按照权值从小到大被删。把操作顺序倒过来,就是把大的结点减小成和小的结点相同,然后一起删掉。

#pragma warning (disable:4996)
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define inf 0X3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e5 + 20;
const int maxm = 2e5 + 20;

int n, m;
struct node {
 int b, pos;
};
node p[maxn];
vector<int> g[maxn];
bool vis[maxn];
int fa[maxn], f[maxn];

int get(int x)
{
 if (fa[x] == x)
  return x;
 return fa[x] = get(fa[x]);
}

bool cmp(node& u, node& v)
{
 return u.b > v.b;
}

void init()
{
 for (int i = 1; i <= n; i++)
 {
  fa[i] = i;
  f[i] = 0;
  vis[i] = 0;
  g[i].clear();
 }
}

int main()
{
 int t;
 scanf("%d", &t);
 while (t--)
 {
  scanf("%d%d", &n, &m);
  init();
  for (int i = 1; i <= n; i++)
  {
   scanf("%d", &p[i].b);
   p[i].pos = i;
  }
  sort(p + 1, p + n + 1, cmp);
  for (int i = 1; i <= m; i++)
  {
   int u, v;
   scanf("%d%d", &u, &v);
   g[u].push_back(v);
   g[v].push_back(u);
  }
  ll ans = 0;
  for (int i = 1; i <= n; i++)
  {
   int x = p[i].pos;
   vis[x] = 1;
   for (int j = 0; j < g[x].size(); j++)
   {
    int y = g[x][j];
    if (!vis[y])
     continue;
    y = get(y);
    x = get(x);
    if (x == y)
     continue;
    fa[y] = x;
    f[y] = i;
   }
  }
  for (int i = 1; i <= n; i++)
   ans += (ll)p[i].b - p[f[i]].b;
  printf("%lld\n", ans);
 }
}

你可能感兴趣的:(acm竞赛)