0

I am trying to solve a dijkstra related problem in hackerank. There are total of 9 test cases. My code works fine in all the test cases except test case 7 where the code exceeds the time limit. In this test case, there are 2499 nodes and 3121251 edges. How can I execute it within the time limit? Here is my code:

#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

   int query;
   cin>>query;

   for(int i=0;i<query;i++)
   {

    vector<int> edges[3009];
    vector<int> cost[3009];
    int node,edge,u,v,x,source;

    cin>>node>>edge;

    for(int i=0;i<edge;i++)
    {
        cin>>u>>v>>x;
        edges[u].push_back(v);
        edges[v].push_back(u);
        cost[u].push_back(x);
        cost[v].push_back(x);
    }
    cin>>source;
    int level[node+1];
    memset(level,10000,sizeof(level));

    level[source]=0;
priority_queue<PII,vector<PII>,greater<PII> >qu;

    qu.push(make_pair(level[source],source));
    while(!qu.empty())
    {
      PII P=qu.top();
      int  first=P.second;
        qu.pop();
        for(int i=first, j=0;j<edges[i].size();j++)
        {
            if(level[i] + cost[i][j] < level[edges[i][j]] )
            {
                level[edges[i][j]] = level[i] + cost[i][j];
                qu.push(make_pair(level[edges[i][j]],edges[i][j]));

            }
        }
    }

    for(int i=1;i<node+1;i++)
    {
        if(level[i]>10000)
        {
            level[i]=-1;
        }
    }

    for(int i=1;i<node+1;i++)
    {
        if(i!=source)
        {
            cout<<level[i]<<' ';
        }

    }
    cout<<endl;
   }

}
imtinan
  • 15
  • 5
  • 1
    `int level[node+1];` is not standard c++, see here for more details: [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – 463035818_is_not_an_ai Nov 30 '20 at 09:05
  • 1
    The `memset` does not do what you think it does. Use `std::vector`. – molbdnilo Nov 30 '20 at 09:06
  • 1
    also useful reading: [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) and [Why should I not `#include `?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – 463035818_is_not_an_ai Nov 30 '20 at 09:06

0 Answers0