Luogu P1340

スパイシーチキンcchがsb質問を書き直しました。
タイトルは最小全域木を示しています。
毎回順序並べ替えると、Tを飛行します(50ポイントのみ)。
マルチセットを使用してすべてのエッジを保存することを検討して
ください最初のn -2回グラフを
切断する必要があります。-1 出力し、クラスカルを実行します。
この複雑さはO(nwlogw)であり、合格できます。

#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define PB push_back
#define MP make_pair
typedef long long ll;
const int maxn = 205;
const int maxw = 6005;
int n, w;
struct edge
{
	int x, y, w;
	friend bool operator < (edge x, edge y) {return x.w<y.w;}
}a;
multiset<edge> e;
int fa[maxn];
int getfa(int x) {return x==fa[x]? x: fa[x] = getfa(fa[x]);}
int solve(int m)
{
	int ans=0, cnt=0;
	for (int i=1; i<=n; i++) fa[i] = i;
	auto it = e.begin();
	for (int i=1; i<=m&&it!=e.end(); i++, it++)
	{
		int fx = getfa(it->x), fy = getfa(it->y);
		if (fx!=fy)
		{
			ans+=it->w;
			fa[fx] = fy;
			cnt++;
			if (cnt==n-1) return ans;
		}
	}
	return -1;
}
int main()
{
	scanf("%d%d", &n, &w);
	for (int i=1; i<=w; i++)
	{
		scanf("%d%d%d", &a.x, &a.y, &a.w);
		e.insert(a);
		if (i>=n-1) printf("%d\n", solve(i));
		else puts("-1");
	}
	return 0;
}

おすすめ

転載: www.cnblogs.com/Saudi/p/12744620.html