最短路+dfs,dfs的时候要记忆化,并记得判断能否从该点来。
#include < iostream >
#include < cstdio >
#include < cstdlib >
#include < cstring >
using namespace std;
#define INF 0x03F3F3F3F
const int N = 1000 ;
int path[N], vis[N];
int n, m;
int cost[N][N], lowcost[N], dp[N];
void input()
{
scanf( " %d " , & m);
memset(cost, - 1 , sizeof (cost));
for ( int i = 0 ; i < m; i ++ )
{
int a, b, c;
scanf( " %d%d%d " , & a, & b, & c);
a -- ;
b -- ;
cost[a][b] = c;
cost[b][a] = c;
}
}
void Dijkstra( int beg)
{
int i, j, min;
memset(vis, 0 , sizeof (vis));
vis[beg] = 1 ;
for (i = 0 ; i < n; i ++ )
{
lowcost[i] = INF; path[i] = beg;
}
lowcost[beg] = 0 ;
path[beg] = - 1 ; // 树根的标记
int pre = beg;
for (i = 1 ; i < n; i ++ )
{
min = INF;
for (j = 0 ; j < n; j ++ )
// 下面的加法可能导致溢出,INF不能取太大
if (vis[j] == 0 && cost[pre][j] != - 1 && lowcost[pre] + cost[pre][j] < lowcost[j])
{
lowcost[j] = lowcost[pre] + cost[pre][j];
path[j] = pre;
}
for (j = 0 ; j < n; j ++ )
if (vis[j] == 0 && lowcost[j] < min)
{
min = lowcost[j]; pre = j;
}
vis[pre] = 1 ;
// cout << lowcost[pre] << endl;
}
}
int dfs( int a)
{
if (dp[a] != - 1 )
return dp[a];
int ans = 0 ;
for ( int i = 0 ; i < n; i ++ )
if (cost[i][a] != - 1 && lowcost[i] > lowcost[a])
ans += dfs(i);
dp[a] = ans;
return dp[a];
}
int main()
{
// freopen("D:\\t.txt", "r", stdin);
while (scanf( " %d " , & n) != EOF && n != 0 )
{
input();
Dijkstra( 1 );
memset(dp, - 1 , sizeof (dp));
dp[ 0 ] = 1 ;
printf( " %d\n " , dfs( 1 ));
}
return 0 ;
}