hdu1874

Problem Description
某省自从实行了很多年的畅通工程计划后,终于修建了很多路。不过路多了也不好,每次要从一个城镇到另一个城镇时,都有许多种道路方案可以选择,而某些方案要比另一些方案行走的距离要短很多。这让行人很困扰。 现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。
 

Input
本题目包含多组数据,请处理到文件结束。 每组数据第一行包含两个正整数N和M(0
 

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
 这道题目清楚的给出了可以用最短路的思想解决,但是在实现的时候不能单看书上的模板,注意在处理起点非0的操作时要加上一个初始化操作
代码如下
#include
#include
#include 
#include 
using namespace std;
const int maxn=1010;
const int INF=1000000;
int vis[maxn];
int dis[maxn],w[maxn][maxn];
int n,m;
void dijkstra(int a)
{
    memset(vis,0,sizeof(vis));
    for(int i=0;idis[x]+w[x][y])
                dis[y]=dis[x]+w[x][y];
        }
    }
}
int main()
{
    int a,b,c,x,y;
   while(scanf("%d %d",&n,&m)!=EOF)
   {
       for(int i=0;ic)
                w[a][b]=w[b][a]=c;
       }

       scanf("%d %d",&x,&y);
       dijkstra(x);
       if(dis[y]!=INF)
       {
           printf("%d\n",dis[y]);
       }
       else
        printf("-1\n");
   }
    return 0;
}


你可能感兴趣的:(acm程序设计题目)