I'm trying to solve a SPOJ problem, which is code SAMER08A at this link.
The problem is that when I ran my code in my IDE with all the examples given in the problem, the code works perfectly. But when running it in SPOJ, it exceeds the time limit of 2 seconds.
I am frustrated because I have worked so hard on it. I would love some advice and help.
#include <vector>
#include <iostream>
#include <queue>
using namespace std;
typedef pair <int, int> dist_node;
typedef pair <int, int> edge;
const int MAXN = 500;
const int INF = 1 << 30;
vector <edge> g[MAXN];
int d[MAXN];
vector<int> p[MAXN];
int answer[MAXN];
int last_node;
vector<vector<int> > paths;
int dijkstra(int s, int n,int t){
for (int i = 0; i <= n; ++i){
d[i] = INF; p[s].push_back(-1);
}
priority_queue < dist_node, vector <dist_node>,greater<dist_node> > q;
d[s] = 0;
q.push(dist_node(0, s));
while (!q.empty()){
int dist = q.top().first;
int cur = q.top().second;
q.pop();
if (dist > d[cur]) continue;
for (int i = 0; i < g[cur].size(); ++i){
int next = g[cur][i].first;
int w_extra = g[cur][i].second;
if (d[cur] + w_extra < d[next]){
d[next] = d[cur] + w_extra;
p[next].clear();
p[next].push_back(cur);
q.push(dist_node(d[next], next));
}
else if(d[cur] + w_extra == d[next]){
p[next].push_back(cur);
}
}
}
return d[t];
}
void findpath (int t, int depth){
if(t == 0){
vector<int> camino;
for(int i = depth-1; i >= 0; --i){
camino.push_back(answer[i]);
}
camino.push_back(last_node);
paths.push_back(camino);
return;
}
for(int i = (int)p[t].size()-1; i >= 0; --i){
answer[depth] = p[t][i];
findpath(p[t][i], depth+1);
}
}
void findAlmostShortestPath(){
for(int k = 0; k<paths.size();k++){
vector<int> camino = paths[k];
for(int i = 0;i<camino.size()-1;i++){
int x = camino[i];
int y = camino[i+1];
for(int j = 0; j < g[x].size() ; j++){
if(g[x][j].first == y){
g[x][j].second =INF;
break;
}
}
break;
}
}
}
int main(){
int n,m;
int w,s;
bool seguir = true;
while(seguir){
cin>>n>>m;
cin>>w>>s;
last_node=s;
if(n == 0 & m == 0){
break;
}
for (int i = 0; i < m; ++i){
int u, v, w;
cin >> u >> v >> w;
g[u].push_back(edge(v, w));
}
int i;
i = dijkstra(w, n,s);
findpath(s, 0);
findAlmostShortestPath();
i = dijkstra(w, n, s);
if(i==INF){
i =-1;
}
cout<<i<<endl;
for(int i = 0; i < g[i].size(); i++){
g[i].clear();
}
}
return 0;
}
I would be so grateful if you could help me since I've worked on this for hours, and it's my first SPOJ problem that I have tried to solve.