1,2,3,6个tle,求助大佬

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

with_my_moon @ 2024-06-02 10:31:14


#define inf 2147483647
using namespace std;

int d[1000001];
bool v[1000001];
int hea[1000001];
int m,n;
int x,y,z,cnt=0;
int s;

inline 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;
}

struct Edge{
    int next,to,dis;
}e[1000001];

void add(int x,int y,int z)
{
    e[++cnt].next=hea[x];
    e[cnt].to=y;
    e[cnt].dis=z;
    hea[x]=cnt;
}   
queue<int> q;
int main()
{
    n=read();
    m=read();
    s=read();
    for(int i=1;i<=m;i++)
    {
        x=read();
        y=read();
        z=read();
        add(x,y,z);
    }
    for(int i=1;i<=n;i++)
    {
        d[i]=inf;
        v[i]=0;
    }
    q.push(s);
    d[s]=0;
    v[s]=1;
    while(!q.empty()){
        x=q.front();
        q.pop();
        v[x]=0;
        for(int i=hea[x];i;i=e[i].next){
            y=e[i].to;
            if(d[y]>d[x]+e[i].dis){
                d[y]=d[x]+e[i].dis;
                if(v[y]==0){
                    v[y]=1;
                    q.push(y);
                }
            }
        }
    }
    for(int i=1;i<=n;i++) cout<<d[i]<<" ";
    return 0;
}

by Mathew_Miao @ 2024-06-02 10:59:28

这题卡SPFA,换Dijkstra吧


by with_my_moon @ 2024-06-06 08:33:55

@Mathew_Miao 好的,谢谢大佬


|