Problem solution [a person's] company

Portal

This question is  % 1 0 data is prepared for the storm to search.

The successful connection condition of the subject, can be seen that this is a problem minimum spanning tree, to minimize the cost by  n -1  connecting edges  n  points. Two minimum spanning tree algorithm,  Prim  and  K R & lt U S K A L.

  • About  Prim

It's dead.

Prim P R & lt I time complexity m is  O (n-2} ^)  , this title data is too large, only through  % 8 0 data. It is the intent of the question's card out to  Prim  . And  K R & lt U S K A time complexity l is  O ( E log E ), by this question.

This question focuses on server brand and determine whether the connection is successful.

Definition array  b each server store brand, both ends of the input side is determined whether or not the same brand, if the establishment of the right side is zero. Since the cable price is equal to the right side, so the total amount of money can be directly added to the right side.

According to the law of minimum spanning tree, if  n points connection is successful, it must spend  n - . 1 edges. Setting a counter  k the number of recording side spend if  k = n- - . 1, the connection is successful.

The title  S T D:

#include <bits/stdc++.h>
using namespace std;
struct edge {int x, y, v;} a[10000005];
int n, e, b[10000005], f[10000005], ans, k, m;
inline bool cmp(const edge &a, const edge &b) {return a.v < b.v;}
inline int find(int x) {if (f[x] != x) f[x] = find(f[x]); return f[x];}
int main()
{
    scanf("%d%d", &n, &e);
    for (register int i = 1; i <= n; i++) scanf("%d", &b[i]);
    for (register int i = 1; i <= e; i++)
    {
        scanf("%d%d%d", &a[i].x, &a[i].y, &a[i].v);
        // 预处理边权
        if (b[a[i].x] == b[a[i].y]) a[i].v = 0;
    }
    // kruskal
    sort(a + 1, a + 1 + n, cmp);
    for (register int i = 1; i <= n; i++) f[i] = i;
    for (register int i = 1; i <= e; i++)
    {
        if (find(a[i].x) != find(a[i].y))
        {
            ans += a[i].v;
            f[a[i].x] = a[i].y;
            k++;
        }
        if (k == n - 1) break;
    }
    if (k < n - 1) printf("Failed.\n");
    else printf("%d\n", ans);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/mhhx/p/11634933.html