zoukankan      html  css  js  c++  java
  • HDU 1874-畅通project续(最短路Dijkstra+优先队列)

    畅通project续

    Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
    Total Submission(s): 28578    Accepted Submission(s): 10382


    Problem Description
    某省自从实行了非常多年的畅通project计划后。最终修建了非常多路。

    只是路多了也不好,每次要从一个城镇到还有一个城镇时。都有很多种道路方案能够选择,而某些方案要比还有一些方案行走的距离要短非常多。

    这让行人非常困扰。

    如今,已知起点和终点。请你计算出要从起点到终点,最短须要行走多少距离。

     

    Input
    本题目包括多组数据。请处理到文件结束。


    每组数据第一行包括两个正整数N和M(0<N<200,0<M<1000)。分别代表现有城镇的数目和已修建的道路的数目。

    城镇分别以0~N-1编号。
    接下来是M行道路信息。每一行有三个整数A,B,X(0<=A,B<N,A!=B,0<X<10000),表示城镇A和城镇B之间有一条长度为X的双向道路。
    再接下一行有两个整数S,T(0<=S,T<N),分别代表起点和终点。

     

    Output
    对于每组数据,请在一行里输出最短须要行走的距离。

    假设不存在从S到T的路线,就输出-1.

     

    Sample Input
    3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
     

    Sample Output
    2 -1
    优先队列水过。注意推断路不通
    #include <cstdio>
    #include <iostream>
    #include <algorithm>
    #include <cstring>
    #include <vector>
    #include <queue>
    #include <set>
    using namespace std;
    const int INF=1<<27;
    const int maxn=1000;
    int dis[maxn],m,n;
    typedef struct node
    {
    	int p,w;
    	node (int a,int b){p=a;w=b;}
    	friend bool operator <(node a,node b)
    	{
    		if(a.w!=b.w) return a.w>b.w;
    		return a.p>b.p;
    	}
    };
    vector <node> eg[maxn];
    void Dijkstra(int src)
    {
    	for(int i=0;i<n;i++) dis[i]=INF;
    	dis[src]=0;
    	priority_queue <node> Q;
    	Q.push(node(src,dis[src]));
    	while(!Q.empty())
    	{
    		node v=Q.top();Q.pop();
    		for(int i=0;i<eg[v.p].size();i++)
    		{
    			node t=eg[v.p][i];
    			if(dis[t.p]>t.w+v.w)
    			{
    				dis[t.p]=t.w+v.w;
    				Q.push(node(t.p,dis[t.p]));
    			}
    		}
    	}
    }
    int main()
    {
    	int u,v,w;
    	while(cin>>n>>m)
    	{
    		for(int i=0;i<n;i++)
    			eg[i].clear();
    		while(m--)
    		{
    			cin>>u>>v>>w;
    			eg[u].push_back(node(v,w));
    			eg[v].push_back(node(u,w));
    		}
    		int src,en;
    		cin>>src>>en;
    		Dijkstra(src);
    		if(dis[en]<INF)
    		cout<<dis[en]<<endl;
    		else
    		cout<<"-1"<<endl;
    	}
    	return 0;
    }
    



  • 相关阅读:
    Chrome快捷键统计
    数据封装
    数据抽象
    linux c++ 服务器端开发面试必看书籍(转载)
    闭包和高阶函数
    this,call,apply,bind
    DOM浏览器window对象模型
    jquery滚动条
    xml教程
    多态
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5241315.html
Copyright © 2011-2022 走看看