hdu 1142 最短路 + DP
这题题意好纠结,半天没看懂,后来打完过不了样例,让海峰读题,最后按他的思路打完了,居然在他之前AC,哈哈~
读懂了题目还是挺简单的,首先求出所有点到终点的最短路,然后DP一下,就能求出路径条数。
/*
* hdu1142/linux.cpp
* Created on: 2011-9-17
* Author : ben
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int SIZE = 1005;
const int MAX = 0x7fffffff;
typedef struct {
int index;
int pathlen;
int routes;
} MyPoint;
int N, M;
int map[SIZE][SIZE];
int D[SIZE];
MyPoint mypoints[SIZE];
bool operator<(const MyPoint &p1, const MyPoint &p2) {
if (p1.pathlen != p2.pathlen) {
return p1.pathlen > p2.pathlen;
} else {
return p1.index < p2.index;
}
}
void dijistra(int s) {
int i, j, k, mind, minf;
int visited[SIZE];
for (i = 0; i < N; i++) {
visited[i] = 0;
D[i] = map[s][i];
}
visited[s] = 1;
D[s] = 0;
for (i = 1; i < N; i++) {
mind = MAX;
minf = MAX;
k = 0;
for (j = 0; j < N; j++) {
if (visited[j]) {
continue;
}
if (D[j] < mind) {
k = j;
mind = D[j];
}
}
visited[k] = 1;
for (j = 0; j < N; j++) {
if (!visited[j]) {
if (D[k] < D[j] - map[k][j]) {
D[j] = D[k] + map[k][j];
}
}
}
}
}
void Buildmap() {
int i, j, k, p;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
map[i][j] = MAX;
}
map[i][i] = 0;
}
for (k = 0; k < M; k++) {
scanf("%d%d%d", &i, &j, &p);
map[i - 1][j - 1] = p;
map[j - 1][i - 1] = p;
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif
while (scanf("%d", &N) == 1 && N > 0) {
scanf("%d", &M);
Buildmap();
dijistra(1);
for (int i = 0; i < N; i++) {
mypoints[i].index = i;
mypoints[i].pathlen = D[i];
mypoints[i].routes = 0;
}
sort(mypoints, mypoints + N);
int i = 0;
while (mypoints[i].index != 0) {
i++;
}
mypoints[i].routes = 1;
for (; i < N - 1; i++) {
for (int j = i + 1; j < N; j++) {
if (mypoints[j].pathlen < mypoints[i].pathlen) {
if (map[mypoints[i].index][mypoints[j].index] < MAX) {
mypoints[j].routes += mypoints[i].routes;
}
}
}
}
printf("%d\n", mypoints[N - 1].routes);
}
return 0;
}