Hello everyone, I was solving this Problem 20C - Dijkstra? and wrote a code and submitted but it gave me a TLE on test 28. Can I still improve my code's efficiency? I am not able to figure it out how to do so. Thanks.
My code
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 151 |
Still Need to optimize my code for Dijkstra algo
Hello everyone, I was solving this Problem 20C - Dijkstra? and wrote a code and submitted but it gave me a TLE on test 28. Can I still improve my code's efficiency? I am not able to figure it out how to do so. Thanks.
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
typedef vector<pii> vii;
typedef vector<int> vi;
#define inf 0x3f3f3f3f
vii *G;
vi D,P;
void Dijkstra(int s,int N){
D.assign(N+1,inf);
P.assign(N+1,-1);
D[s]=0;
P[s]=-1;
set<pii> Q;
Q.insert({s,0});
while(!Q.empty()){
auto top=Q.begin();
int u=top->first;
Q.erase(top);
if(u==N)return ;
for(auto next:G[u]){
int v=next.first,wt=next.second;
if(D[v]>D[u]+wt){
P[v]=u;
Q.erase({v,D[v]});
D[v]=D[u]+wt;
Q.insert({v,D[v]});
}
}
}
}
void print_shortest_path(int to){
vi path;
for(int i=to;i!=-1;i=P[i])path.push_back(i);
reverse(path.begin(),path.end());
for(auto i:path)cout<<i<<" ";
}
int main(){
int N,m;cin>>N>>m;
G= new vii[N+1];
for(int i=0;i<m;i++){
int a,b,w;cin>>a>>b>>w;
G[a].push_back({b,w});
G[b].push_back({a,w});
}
Dijkstra(1,N);
if(D[N]==inf)cout<<-1;
else
print_shortest_path(N);
//cout<<D[N]<<"\n";
}
Name |
---|