【悬关】堆优化prim算法30分TLE求调
查看原帖
【悬关】堆优化prim算法30分TLE求调
1023793
yaodiguoan楼主2024/6/20 13:56

记录

#include <bits/stdc++.h>
using namespace std;
//#pragma GCC optimize(2)
//#pragma GCC optimize(3, "Ofast", "inline")
#define hh putchar('\n')
#define kg putchar(' ')
#define debug puts("debug")
//#define int long long
//#define int __int128
namespace quickread{
	inline int read(){
		int x=0,f=1;char ch=getchar();
		while (ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
		while (ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
		return x*f;
	}
	inline void write(int x){
	    if(x<0){putchar('-');x=-x;}
	    if(x>9)write(x/10);
	    putchar(x%10+'0');
	}
	inline string readstr(){
    	char ch=getchar();string str="";
		while(!(ch>='0'&&ch<='9')&&!(ch>='a'&&ch<='z')&&!(ch>='A'&&ch<='Z')) ch=getchar();
		while((ch>='0'&&ch<='9')||(ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')){str+=ch;ch=getchar();}
		return str;
	}
	inline char readchar(){
		char ch=getchar();
		while(!(ch>='0'&&ch<='9')&&!(ch>='a'&&ch<='z')&&!(ch>='A'&&ch<='Z')) ch=getchar();
		return ch;
	}
}
using namespace quickread;
const int N=1e5+10,inf=2147483647;
int n,m,cnt,ans,dis[N];
bool vis[N];
struct edge{int v,w;};
vector<edge> g[N];
struct node{int u,w;};
bool operator > (const node A,const node B){return A.w>B.w;}
void prim(int u,int w){
	memset(dis,0x3f,sizeof(dis));
	dis[u]=w;
	priority_queue<node ,vector<node> ,greater<node> >q;
	q.push(node{u,w});
	while(!q.empty()){
		if(cnt>=n) return;
		int u=q.top().u;
		if(vis[u]) continue;
		vis[u]=1;
		++cnt,ans+=q.top().w;q.pop();
		for(edge to:g[u]){
			int v=to.v;w=to.w;
			if(w<dis[v]){
				dis[v]=w;
				q.push(node{v,w});
			}
		}
	} 
}
signed main(){
//	ios::sync_with_stdio(0);
//	cin.tie(0);cout.tie(0);
	n=read(),m=read();
	for(int i=1;i<=m;i++){
		int u=read(),v=read(),w=read();
		g[u].push_back(edge{v,w});
		g[v].push_back(edge{u,w});
	} 
	prim(1,0);
	if(cnt==n) write(ans);
	else puts("orz");
	return 0;
}
2024/6/20 13:56
加载中...