OR50. 旅途
描述
原来是要到醋溜站台乘坐醋溜快车到醋溜港”,亮亮解出了地图隐藏的秘密,赶紧奔向醋溜站台,但到了之后,亮亮忧桑地发现,从醋溜站台到醋溜港沿途的每个车站都有很多美女被他飒爽的英姿所吸引,只要经过车站就会被这些漂亮的女孩搭讪,但是现在亮亮一心想要寻找楚楚街而没空去搭理她们,所以亮亮希望在抵达醋溜港的时候被搭讪的次数最少。问亮亮抵达醋溜港最少会被搭讪多少次?输入描述
第一行包含两个整数N(2<=N<=5000),M(1<=M<=50000)。N表示公有N个汽车站,M表示公有M条公路,起点为1,终点为N。 第二行包含N个整数(0<=K<=10000),第i个整数表示在第i站有K个美女想要搭讪亮亮。 接下来M行,每行包含两个整数P(1<=P<=N),Q(1<=Q<=N),代表P,Q两个站是有班车直达的。输出描述
一个整数,即亮亮抵达醋溜港最少需要被搭讪的次数。示例1
输入:
5 5 0 1 1 3 6 1 2 1 4 2 3 3 5 4 5
输出:
8
C++ 解法, 执行用时: 1ms, 内存消耗: 372KB, 提交时间: 2017-06-14
#include<iostream> #include<vector> using namespace std; int main() { int INF_MAX = INT32_MAX; int N, M; cin >> N >> M; vector<int> people(N + 1, 0); vector<vector<int>> map(N + 1); for (int i = 1;i < N + 1;i++) { cin >> people[i]; } for (int i = 0;i < M;i++) { int x, y; cin >> x >> y; map[x].push_back(y); map[y].push_back(x); } vector<int> dist(N + 1, INF_MAX), visited(N + 1, 0); dist[1] = people[1]; visited[1] = 1; for (int i = 1;i < N + 1;i++) { for (int i = 0;i < map[1].size();i++) dist[map[1][i]] = dist[1] + people[map[1][i]]; } for (int i = 2;i < N + 1;i++) { int min = INF_MAX, pos; for (int k = 1;k < N + 1;k++) { if (visited[k] == 0 && dist[k] < min) { min = dist[k]; pos = k; } } visited[pos] = 1; if (pos == N) break; for (int s = 0;s < map[pos].size();s++) { int p = map[pos][s]; if ((visited[p] == 0) && ((min + people[p]) < dist[p])) { dist[p] = min + people[p]; } } } cout << dist[N] << endl; return 0; }
C++ 解法, 执行用时: 1ms, 内存消耗: 376KB, 提交时间: 2017-06-13
#include <iostream> using namespace std; void dijstl(int start,int end,int **gonglu,int *cost,int *zhan,int m) { int *s = new int[end]; int *dis = new int[end]; for (int i = 0; i < end; i++) { s[i] = 0; dis[i] = 99999; } s[start] = 1; dis[start] = zhan[start]; int index = start; for (int j = 0; j < end; j++) { int minn = 99999; for (int i = 0; i < end; i++) { if (s[i] == 0) { if (dis[i] < minn) { minn = dis[i]; index = i; } } } s[index] = 1; for (int i = 0; i < m; i++) { if (gonglu[i][0] == index) { if (dis[gonglu[i][0]] + zhan[gonglu[i][1]] < dis[gonglu[i][1]]) dis[gonglu[i][1]] = dis[gonglu[i][0]] + zhan[gonglu[i][1]]; } else if(gonglu[i][1] == index) { if (dis[gonglu[i][1]] + zhan[gonglu[i][0]] < dis[gonglu[i][0]]) dis[gonglu[i][0]] = dis[gonglu[i][1]] + zhan[gonglu[i][0]]; } } } for (int i = 0; i < end; i++) cost[i] = dis[i]; } int main() { int n, m; while (cin >> n >> m) { //int zhan[5]; int *zhan = new int[n]; int index=0; for (int i = 0; i<n; i++) { cin >> zhan[i];; index += zhan[i]; } int **gonglu = new int*[m]; //int gonglu[6][2]; for (int i = 0; i<m; i++) { gonglu[i] = new int[2]; cin >> gonglu[i][0] >> gonglu[i][1]; gonglu[i][0]--; gonglu[i][1]--; } //int cost[5]; int *cost=new int[n]; dijstl(0, n, gonglu, cost, zhan,m); cout << cost[n-1] << endl; } return 0; }