HDU 2544 - Shortest Path - [Heap Optimization dijkstra] [Shortest Path Template Question]

Topic link: http://acm.hdu.edu.cn/showproblem.php?pid=2544

Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Problem Description
In the annual school competition, all the finalists will receive a beautiful t-shirt. But every time our staff transports hundreds of clothes from the store back to the arena, it's very tiring! So now they want to find the shortest route from the store to the arena, can you help them?

Input
The input includes multiple sets of data. The first line of each set of data is two integers N and M (N<=100, M<=10000). N represents how many intersections there are on the streets of Chengdu. The intersection marked with 1 is where the store is located, and the intersection marked with N It is the location of the stadium, and M means that there are several roads in Chengdu. N=M=0 means the end of input. Next M lines, each line includes 3 integers A, B, C (1<=A, B<=N, 1<=C<=1000), indicating that there is a road between intersection A and intersection B, we The staff takes C minutes to walk this way.
Enter a route that guarantees there is at least 1 store to the arena.
 
Output
For each set of inputs, output a line representing the minimum time for a worker to walk from the store to the arena
 
Sample Input
2 1
1 2 3
3 3
1 2 5
2 3 5
3 1 2
0 0
 
Sample Output
3
2

 

AC code:

#include<bits/stdc++.h>
using namespace std;
const int maxn=110;
const int INF=0x3f3f3f3f;

int n,m;

struct Edge
{
    int u,v,w;
    Edge(int u,int v,int w){this->u=u,this->v=v,this->w=w;}
};
vector<Edge> E;
vector<int> G[maxn];
void init(int l,int r)
{
    E.clear();
    for(int i=l;i<=r;i++) G[i].clear();
}
void addedge(int u,int v,int w)
{
    E.push_back(Edge(u,v,w));
    G[u].push_back(E.size()-1);
}

bool vis[maxn];
int d[maxn];
void dijkstra(int st)
{
    for(int i=1;i<=n;i++) d[i]=(i==st)?0:INF;
    memset(vis,0,sizeof(vis));

    priority_queue< pair<int,int> > Q;
    Q.push(make_pair(0,st));
    while(!Q.empty())
    {
        int now=Q.top().second; Q.pop();
        if(vis[now]) continue;
        vis[now]=1;
        for(int i=0;i<G[now].size();i++)
        {
            Edge &e=E[G[now][i]]; int nxt=e.v;
            if(vis[nxt]) continue;
            if(d[nxt]>d[now]+e.w)
            {
                d[nxt]=d[now]+e.w;
                Q.push(make_pair(-d[nxt],nxt));
            }
        }
    }
}

intmain ()
{
    while(scanf("%d%d",&n,&m) && n+m>0)
    {
        init(1,n);
        for(int i=1,u,v,w;i<=m;i++)
        {
            scanf("%d%d%d",&u,&v,&w);
            addedge(u,v,w);
            addedge(v,u,w);
        }

        dijkstra(1);
        printf("%d\n",d[n]);
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325977727&siteId=291194637
Recommended