題目:
Description
Input
輸入保證至少存在1條商店到賽場的路線。
Output
Sample Input
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
Sample Output
3 2
題意:裸的單源最短路。
實現:由於很久沒寫,所以幾乎都忘了,因此最近熟悉一下,然後用鄰接表和鄰接矩陣寫了一下,其實也熟悉了一下vector數組把。
鄰接表:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <math.h>
using namespace std;
const int MAX = 105;
const int INF = 0x3f3f3f3f;
int n, m;
struct graph {
int vv, key;
};
struct node {
int v;
int value;
bool friend operator < (node n1, node n2) {
return n1.value > n2.value;
}
}visit[MAX];
vector <graph> path[MAX];
void Dij() {
priority_queue <node> q;
q.push(visit[1]);
while (!q.empty()) {
node head = q.top();
q.pop();
for (int i = 0; i < path[head.v].size(); i++) {
if (visit[head.v].value + path[head.v][i].key < visit[path[head.v][i].vv].value) {
visit[path[head.v][i].vv].value = visit[head.v].value + path[head.v][i].key;
q.push(visit[path[head.v][i].vv]);
}
}
}
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
if (n == 0 && m == 0)
break;
for (int i = 1; i <= n; i++)
path[i].clear();
int v1, v2, key;
graph g1, g2;
for (int i = 0; i < m; i++) {
scanf("%d%d%d", &v1, &v2, &key);
g1.vv = v2;
g1.key = key;
g2.vv = v1;
g2.key = key;
path[v1].push_back(g1);
path[v2].push_back(g2);
}
for (int i = 1; i <= n; i++) {
visit[i].v = i;
visit[i].value = INF;
}
visit[1].value = 0;
Dij();
printf("%d\n", visit[n].value);
}
return 0;
}
鄰接矩陣:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <math.h>
using namespace std;
const int MAX = 105;
const int INF = 0x3f3f3f3f;
int graph[MAX][MAX];
int n, m;
struct node {
int v;
int value;
bool friend operator < (node n1, node n2) {
return n1.value > n2.value;
}
}visit[MAX];
void Dij() {
priority_queue <node> q;
for (int i = 1; i <= n; i++) {
q.push(visit[i]);
}
while (!q.empty()) {
node head = q.top();
q.pop();
for (int j = 1; j <= n; j++) {
if (graph[head.v][j] + head.value < visit[j].value) {
visit[j].value = graph[head.v][j] + head.value;
q.push(visit[j]);
}
}
}
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
if (n == 0 && m == 0)
break;
memset(graph, 0, sizeof(graph));
int v1, v2, key;
for (int i = 0; i < m; i++) {
scanf("%d%d%d", &v1, &v2, &key);
if (graph[v1][v2] == 0 || graph[v1][v2] > key) {
graph[v1][v2] = key;
graph[v2][v1] = key;
}
}
for (int i = 1; i <= n; i++) {
visit[i].v = i;
visit[i].value = INF;
}
visit[1].value = 0;
Dij();
printf("%d\n", visit[n].value);
}
return 0;
}