Description
CX是要赶去上课,为了不迟到必须要以最短的路径到达教室,同时CX希望经过的路上能看到的学妹越多越好。现在把地图抽象成一个无向图,CX从1点出发,教室在N号点,告诉每个点上学妹的数量,每条边的长度。请你求出CX以最短路径赶到教室最多能看到多少学妹。
Input
多组输入数据(最多20组),输入到文件结束。
每组数据第一行两个正整数N,M其中N代表点的个数(2<=N<=1000),M代表边的个数(1<=M<=10000)。
接下来一行N个数,代表着1~N每个点上学妹的个数,(0<=Ni<=50)。 接下来M行,每行三个数A B C(1<=A,B<=N,0<c<=100)代表A,B间有边,长度为C。(可能存在重边)
Output
输出CX以最短距离从1到n的情况下能看到的最多学妹数量,若从点1无法到达点N输出-1。
Sample Input
4 4
1 2 3 4
1 2 1
1 3 1
2 4 2
3 4 2
Sample Output
8
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#define MAXN 1010
#define MAXM 10100
#define INF 0x3f3f3f3f
using namespace std;
int n, m;
int dis[MAXN], vis[MAXN], map[MAXN][MAXN], cost[MAXN], total[MAXN];
int dijkstra()
{
for(int i = 2; i <= n; i++)
dis[i] = map[1][i];
vis[1] = 1;
dis[1] = 0;
total[1] = cost[1];
for(int i = 2; i <= n; i++)
total[i] = cost[i] + cost[1];
for(int i = 2; i <= n; i++)
{
int k = -1, minx = INF;
for(int j = 1; j <= n; j++)
{
if(!vis[j] && dis[j] < minx)
{
minx = dis[j];
k = j;
}
}
if(k == -1) break;
vis[k] = 1;
for(int j = 1; j <= n; j++)
{
if(vis[j]) continue;
if(dis[j] > dis[k] + map[k][j])
{
dis[j] = dis[k] + map[k][j];
total[j] = total[k] + cost[j];
}
else if(dis[j] == dis[k] + map[k][j])
{
if(total[j] < total[k] + cost[j])
total[j] = total[k] + cost[j];
}
}
}
return dis[n];
}
int main()
{
int a, b, c;
while(scanf("%d%d", &n, &m) != EOF)
{
memset(vis, 0, sizeof(vis));
memset(map, 0x3f, sizeof(map));
for(int i = 1; i <= n; i++)
{
scanf("%d", &cost[i]);
map[i][i] = 0;
}
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d", &a, &b, &c);
if(c < map[a][b])
map[a][b] = map[b][a] = c;
}
int ans = dijkstra();
if(ans == INF) printf("-1\n");
else printf("%d\n", total[n]);
}
return 0;
}