为什么dij数组初始化位置不同,得到结果不同 AC:
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
int n,m,s;
int u,v,W;
int to[1000000],tot,nex[1000000],w[1000000],head[1000000];
void add(int a,int b,int W){
to[tot]=b;
nex[tot]=head[a];
w[tot]=W;
head[a]=tot++;
}
int dij[1000000];
bool vis[10000000];
void di(){
for(int i=1;i<=n;i++) dij[i]=1e9;
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > q;
q.push({0,s});
dij[s]=0;
while(!q.empty()){
auto t=q.top();
q.pop();
if(vis[t.second]){
continue;
}
vis[t.second]=1;
for(int i=head[t.second];i!=-1;i=nex[i]){
int j=to[i];
if(dij[j]>t.first+w[i]){
// cout<<j<<"\n";
dij[j]=t.first+w[i];
if(!vis[j])
q.push({dij[j],j});
}
}
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
memset(head,-1,sizeof head);
cin>>n>>m>>s;
for(int i=1;i<=m;i++){
cin>>u>>v>>W;
add(u,v,W);
}
di();
for(int i=1;i<=n;i++){
cout<<dij[i]<<" ";
}
return 0;
}
WA:
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
int n,m,s;
int u,v,W;
int to[1000000],tot,nex[1000000],w[1000000],head[1000000];
void add(int a,int b,int W){
to[tot]=b;
nex[tot]=head[a];
w[tot]=W;
head[a]=tot++;
}
int dij[1000000];
bool vis[10000000];
void di(){
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > q;
q.push({0,s});
dij[s]=0;
while(!q.empty()){
auto t=q.top();
q.pop();
if(vis[t.second]){
continue;
}
vis[t.second]=1;
for(int i=head[t.second];i!=-1;i=nex[i]){
int j=to[i];
if(dij[j]>t.first+w[i]){
// cout<<j<<"\n";
dij[j]=t.first+w[i];
if(!vis[j])
q.push({dij[j],j});
}
}
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
memset(head,-1,sizeof head);
for(int i=1;i<=n;i++) dij[i]=1e9;
cin>>n>>m>>s;
for(int i=1;i<=m;i++){
cin>>u>>v>>W;
add(u,v,W);
}
di();
for(int i=1;i<=n;i++){
cout<<dij[i]<<" ";
}
return 0;
}