1 条题解

  • 0
    @ 2024-2-21 16:55:46
    #include<iostream>
    #include<cstdio>
    #include<queue>
    
    using namespace std;
    
    #define int long long 
    int read(){
        int x=0,k=1; char c=getchar();
        while(c<'0'||c>'9'){if(c=='-')k=-1;c=getchar();}
        while(c>='0'&&c<='9')x=(x<<3)+(x<<1)+(c^48),c=getchar();
        return x*k;
    }
    
    const int inf=0x7fffffffffffffff; 
    int n,m,s,tot,dis[300005],head[300005];
    bool vis[300005];
    struct node{
    	int next,to,w;
    }h[1000005];
    struct qwq{
    	int dis,now;
    	bool operator<(const qwq &x)const{return x.dis<dis;}
    }f,v;
    priority_queue<qwq>pq;
    
    void add(int u,int v,int w){
    	
    	tot++;
    	h[tot].next=head[u];
    	h[tot].to=v;
    	h[tot].w=w;
    	head[u]=tot;
    	
    }
    
    void Dijkstra(int s){
    	
    	dis[s]=0;
    	pq.push((qwq){0,s});
    	
    	while(!pq.empty()){
    		
    		f=pq.top();
    		pq.pop();
    		int u=f.now;
    		if(vis[u])continue;	
    		vis[u]=1;
    		
    		for(int i=head[u];i;i=h[i].next){
    			int v=h[i].to;
    			if(dis[v]>dis[u]+h[i].w){
    				dis[v]=dis[u]+h[i].w;
    				if(!vis[v])
    					pq.push((qwq){dis[v],v});
    			}
    		}
    			
    	}
    	
    }
    
    signed main(){
    	
    	n=read();
    	m=read();
    	
    	for(int i=1;i<=n;i++)
    		dis[i]=inf; 
    	
    	int u,v,w;
    	
    	for(int i=1;i<=m;i++){
    		u=read();
    		v=read();
    		w=read();
    		add(u,v,w);
    	}
    	
    	Dijkstra(1);
    	
    	for(int i=1;i<=n;i++)
    		printf("%lld ",dis[i]==inf?-1:dis[i]); 
    	return 0;
    	
    }
    

    1个小时,6次尝试😕...

    终于对了😄

    • 1

    信息

    ID
    1
    时间
    2000ms
    内存
    512MiB
    难度
    8
    标签
    (无)
    递交数
    12
    已通过
    8
    上传者