hdu 1142 dijkstra+记忆化搜索
#include <iostream>
using namespace std;
const int MAXN = 1010;
const int INF = INT_MAX;
int map[MAXN][MAXN];
int dist[MAXN], n, m, dp[MAXN];
bool hash[MAXN];
void dijkstra(int Start)
{
memset(hash, 0, sizeof(hash));
int i, j;
for (i = 1; i <= n; ++i)
{
dist[i] = INF;
}
dist[Start] = 0;
for (i = 0; i < n; ++i)
{
int MIN = INF, p = -1;
for (j = 1; j <= n; ++j)
{
if (!hash[j] && dist[j] < MIN)
{
MIN = dist[j];
p = j;
}
}
if (p == -1) break;
hash[p] = true;
for (j = 1; j <= n; ++j)
{
if (p != j && map[p][j])
{
int q = dist[j];
if (MIN + map[p][j] < q)
{
dist[j] = MIN + map[p][j];
}
}
}
}
}
int search(int pos)
{
if (dp[pos] != -1)
{
return dp[pos];
}
else if (pos == 2)
{
return 1;
}
else
{
int sum = 0, i;
for (i = 1; i <= n; ++i)
{
if (map[i][pos] && dist[i] < dist[pos])
{
sum += search(i);
}
}
dp[pos] = sum;
return sum;
}
}
int main()
{
while (scanf("%d", &n) != EOF && n)
{
scanf("%d", &m);
memset(dp, -1, sizeof(dp));
int i, j;
for (i = 1; i <= n; ++i)
{
for (j = 1; j <= n; ++j)
{
map[i][j] = 0;
}
}
for (i = 0; i < m; ++i)
{
int a, b, d;
scanf("%d %d %d", &a, &b, &d);
if (!map[a][b] || map[a][b] > d)
{
map[a][b] = d;
map[b][a] = d;
}
}
dijkstra(2);
search(1);
printf("%d\n", dp[1]);
}
return 0;
}
using namespace std;
const int MAXN = 1010;
const int INF = INT_MAX;
int map[MAXN][MAXN];
int dist[MAXN], n, m, dp[MAXN];
bool hash[MAXN];
void dijkstra(int Start)
{
memset(hash, 0, sizeof(hash));
int i, j;
for (i = 1; i <= n; ++i)
{
dist[i] = INF;
}
dist[Start] = 0;
for (i = 0; i < n; ++i)
{
int MIN = INF, p = -1;
for (j = 1; j <= n; ++j)
{
if (!hash[j] && dist[j] < MIN)
{
MIN = dist[j];
p = j;
}
}
if (p == -1) break;
hash[p] = true;
for (j = 1; j <= n; ++j)
{
if (p != j && map[p][j])
{
int q = dist[j];
if (MIN + map[p][j] < q)
{
dist[j] = MIN + map[p][j];
}
}
}
}
}
int search(int pos)
{
if (dp[pos] != -1)
{
return dp[pos];
}
else if (pos == 2)
{
return 1;
}
else
{
int sum = 0, i;
for (i = 1; i <= n; ++i)
{
if (map[i][pos] && dist[i] < dist[pos])
{
sum += search(i);
}
}
dp[pos] = sum;
return sum;
}
}
int main()
{
while (scanf("%d", &n) != EOF && n)
{
scanf("%d", &m);
memset(dp, -1, sizeof(dp));
int i, j;
for (i = 1; i <= n; ++i)
{
for (j = 1; j <= n; ++j)
{
map[i][j] = 0;
}
}
for (i = 0; i < m; ++i)
{
int a, b, d;
scanf("%d %d %d", &a, &b, &d);
if (!map[a][b] || map[a][b] > d)
{
map[a][b] = d;
map[b][a] = d;
}
}
dijkstra(2);
search(1);
printf("%d\n", dp[1]);
}
return 0;
}