Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 2273 | Accepted: 831 |
Description
Input
Output
Sample Input
5 6 1 3 2 1 4 2 3 4 3 1 5 12 4 2 34 5 2 24 7 8 1 3 1 1 4 1 3 7 1 7 4 1 7 5 1 6 7 1 5 2 1 6 2 1 0
Sample Output
2 4略过了这一段话,很自然的就按照求有多少最短路径了。
He considers taking a path from A to B to be progress if there exists a route from B to his home that is shorter than any possible route from A. Calculate how many different routes through the forest Jimmy might take.
当我们选择B的时候,一定是B到终点的距离小于A到终点的距离。
#include<iostream> #include<cstdio> #include<cstring> #include<map> #include<cmath> #include<vector> #include<algorithm> #include<set> #include<string> #include<queue> #include <stack> using namespace std; #pragma warning(disable : 4996) const int MAXN = 1005; const int INF = 999999; int n; int maps[MAXN][MAXN]; bool visited[MAXN]; int dist[MAXN]; int dp[MAXN]; void Dijkstra(int s) { int i, j; int minValue, minNode; memset(visited, false, sizeof(visited)); dist[s] = 0; visited[s] = true; for (i = 1; i <= n; i++) { dist[i] = maps[s][i]; } for (i = 1; i <= n; i++) { minValue = INF; minNode = 0; for (j = 1; j <= n; j++) { if(!visited[j] && minValue > dist[j]) { minNode = j; minValue = dist[j]; } } if(minNode == 0) { break; } visited[minNode] = true; for (j = 1; j <= n; j++) { if(!visited[j] && maps[minNode][j] != INF && dist[j] > dist[minNode] + maps[minNode][j]) { dist[j] = dist[minNode] + maps[minNode][j]; } } } } int dfs(int v) { if (dp[v] != -1) { return dp[v]; } if(v == 2) { return 1; } dp[v] = 0; for (int i = 1; i <= n; i++) { if(maps[v][i] != INF && dist[i] < dist[v]) { dp[v] += dfs(i); } } return dp[v]; } int main() { freopen("in.txt", "r", stdin); int m, a, b, d; while (scanf("%d", &n) != EOF) { if(n == 0) { break; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if(i == j) { maps[i][j] = 0; } else { maps[i][j] = INF; } } } scanf("%d", &m); while (m--) { scanf("%d %d %d", &a, &b, &d); if(maps[a][b] > d) { maps[a][b] = d; maps[b][a] = d; } } Dijkstra(2); for (int i = 1; i <= n; i++) { cout << dist[i] << " "; } cout << endl; memset(dp, -1, sizeof(dp)); cout << dfs(1) << endl; } return 0; }