堆优板子求助

P4779 【模板】单源最短路径(标准版)

Furina_Hate_Comma @ 2023-03-09 22:31:04

#include<bits/stdc++.h>
using namespace std;
struct lsqxx{
    int nxt,to,from,value;
    lsqxx(){
        value=114514;
    } 
}e[114514];int tail=0;
int num[114514],ans[114514];
void addedge(int f,int t,int v){
    e[++tail].from=f;
    e[tail].nxt=num[f];
    e[tail].value=v;
    e[tail].to=t;
    num[f]=tail;
}
bool check[114514];
priority_queue<pair<int,int> >q;
int main(){
    int n,m,s;
    cin>>n>>m>>s;
    memset(num,-1,sizeof num);
    for(int i=1;i<=m;i++){
        int a,b,c;
        cin>>a>>b>>c;
        addedge(a,b,c);
    }
    q.push(make_pair(0,s));
    while(!q.empty()){
        int k=q.top().second;
        check[k]=1;
        ans[k]=q.top().first;
        q.pop();
        for(int i=num[k];i!=-1;i=e[i].nxt){
            if(!check[e[i].to]){
                if(ans[k]+e[i].value<ans[e[i].to]){
                    ans[e[i].to]=ans[k]+e[i].value;
                    q.push(make_pair(ans[e[i].to],e[i].to));
                }
            }
        }
    }
    for(int i=1;i<=n;i++)
        cout<<ans[i]<<" ";
}

样例输出0 0 0 0


by Stevehim @ 2023-03-09 23:01:37

@jasonsuri1424 提供一个错误:没有初始化

剩下的没看出来QAQ


by Furina_Hate_Comma @ 2023-03-09 23:14:44

thx 目前有弄错堆了,没初始化

#include<bits/stdc++.h>
using namespace std;
struct lsqxx{
    int nxt,to,from,value;
}e[114514];int tail=0;
int num[114514],ans[114514];
void addedge(int f,int t,int v){
    e[++tail].from=f;
    e[tail].nxt=num[f];
    e[tail].value=v;
    e[tail].to=t;
    num[f]=tail;
}
bool check[114514];
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > >q;
int main(){
    int n,m,s;
    cin>>n>>m>>s;
    memset(num,-1,sizeof num);
    memset(ans,0x7f,sizeof ans);
    for(int i=1;i<=m;i++){
        int a,b,c;
        cin>>a>>b>>c;
        addedge(a,b,c);
    }
    q.push(make_pair(0,s));
    while(!q.empty()){
        int k=q.top().second;
        check[k]=1;
        ans[k]=q.top().first;
        q.pop();
        cout<<k<<endl;
        for(int i=num[k];i!=-1;i=e[i].nxt){
            cout<<"___"<<e[i].from<<" "<<e[i].to<<" "<<e[i].value<<endl;
            if(!check[e[i].to]){
                if(ans[k]+e[i].value<ans[e[i].to]){
                    cout<<e[i].to<<" "<<ans[e[i].to]<<"->";
                    ans[e[i].to]=ans[k]+e[i].value;
                    cout<<ans[e[i].to]<<endl;
                    q.push(make_pair(ans[e[i].to],e[i].to));
                }
            }
        }
    }
    for(int i=1;i<=n;i++)
        cout<<ans[i]<<" ";
}

|