每日一題(牛客) — 2020 - 05 -10

最小生成樹的題目,其實發現自己對一些算法的時間複雜度的計算不怎麼好,還是要練一下,不過這題挺不錯,是最小生成樹的加強版

題目鏈接

自己的想法

  • 這題自己看大體知道是最小生成樹,也知道是找與1相連的圖,但是不太會整
  • 一部分是忘記最小生成樹他的排序(知道是從小到大,但是那是裸最小生成樹),然後就是不太會處理他的集合
  • 看大佬的思路和代碼後才能白了

解題思路:

  • 首先我們存儲的時候要注意他是個有向圖,從高到低才能走過
  • 然後是找出他們的集合,然後存儲起來,這裏我們要記錄他的個數,因爲要輸出他最多到達的地方
  • 然後我們就進入kruskal, 這裏的排序我們按照y的排即可,因爲x --> y 肯定是從高到低,因此我們按照y的高度排,那麼肯定都是到低的,如果高度相同,那麼我們就按照路程的長短排序,小的排在前面(這裏需要思考理解一下)
  • 然後套板子即可。

代碼:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>

using namespace std;

const int N = 1000010, M = 2000010;

int h[N], ne[M], e[M], ww[M], p[N], a[N], cnt, idx;

bool st[N];

void add(int x, int y, int z){
	e[idx] = y, ne[idx] = h[x], ww[idx] = z, h[x] = idx++;
}

struct Edge{
    int x, y, w;
}edges[M];

bool cmp(Edge xx, Edge yy){
	if (a[xx.y] == a[yy.y]){
		return xx.w < yy.w;
	}
	return a[xx.y] > a[yy.y];
}

void add1(int x, int y, int z){
	edges[cnt].x = x, edges[cnt].y = y,edges[cnt++].w = z;
}

int Find(int x ){
    if (p[x] != x) p[x] = Find(p[x]);
    return p[x];
}

void bfs(){
	queue<int> q;
	q.push(1);
	int res1 = 1;
	st[1] = true;
	while(!q.empty()){
		int t = q.front();
		q.pop();
		for (int i = h[t];i != -1; i = ne[i]){
			int j = e[i];
			add1(t,j,ww[i]); 
			if (!st[j]){
				q.push(j);
				res1++;
				st[j] = true;
			}
		}
	} 
	printf("%d ",res1);
}

void kruskal(){
    sort(edges,edges + cnt,cmp);
    long long res = 0;
    int num = 0;
      
    for (int i = 0; i < cnt; i++){
        int x = edges[i].x, y = edges[i].y, w = edges[i].w;
        if (Find(x) != Find(y)){
            p[Find(x)] = Find(y);
            num ++;
            res += w;
        }
    }
    
    printf("%lld\n",res);
}

int main(){
	
	memset(h,-1,sizeof h);

	int n, m;
	scanf("%d%d",&n,&m);
	for (int i = 1; i <= n; i++){
		scanf("%d",&a[i]);
	}

	for (int i = 1; i <= n ;i ++){
		p[i] = i;
	}

	for (int i = 0; i < m; i++){
		int x, y, z;
		scanf("%d%d%d",&x,&y,&z);
		if (a[x] > a[y]) add(x,y,z);
		else if (a[x] == a[y]){
			add(x,y,z);
			add(y,x,z);
		}
		else add(y,x,z);
	}
	bfs();
	kruskal();
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章