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
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 166 |
2 | maomao90 | 163 |
2 | Um_nik | 163 |
4 | atcoder_official | 161 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | nor | 153 |
9 | Dominater069 | 153 |
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";
}
Название |
---|