用dijkstra求出最短路径 每个点i回家的最短路径d[i], 题意 为存在一条从B出发回家的路径 比所有从A出发回家的路径都要短
即d[B]<d[A] 则 A->B 可行。 这样可以建立一个新的图 求出起点到终点 的路径条数。用DP可以做。
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#define maxn 10001
#define INF 1<<30
using namespace std;
struct Edge
{
int from,to,dist;
};
struct heapnode
{
int d,u;
bool operator < (const heapnode &rhs) const
{
return d>rhs.d;
}
};
int n,m;
int map[maxn][maxn];
vector<Edge> edges;
vector<int> G[maxn];
bool done[maxn];
int p[maxn];
int d[maxn];
void init(int n)
{
//this->n=n;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
map[i][j] = INF;
if(i==j) map[i][j] = 0;
}
}
for(int i = 0; i <= n; i++)
G[i].clear();
edges.clear();
}
void Addedge(int from,int to,int dist)
{
edges.push_back((Edge)
{
from,to,dist
});
int m = edges.size();
G[from].push_back(m-1);
map[from][to] = map[to][from] = dist;
}
void dijkstra(int s)
{
priority_queue<heapnode> Q;
for(int i = 0; i <= n; i++)
d[i] = INF;
d[s] = 0;
memset(done,0,sizeof(done));
Q.push((heapnode)
{
0,s
});
while(!Q.empty())
{
heapnode x = Q.top();
Q.pop();
int u = x.u;
if(done[u]) continue;
done[u]=true;
for(int i = 0; i < G[u].size(); i++)
{
Edge& e = edges[G[u][i]];
if(d[e.to]>d[u]+e.dist)
{
d[e.to] = d[u]+e.dist;
p[e.to] = G[u][i];
Q.push((heapnode)
{
d[e.to],e.to
});
}
}
}
}
int dp[maxn];
int dfs(int s)
{
if(dp[s]) return dp[s];
if(s==2) return dp[s]=1;
int sum = 0;
for(int i = 1; i <= n; i++)
{
if(map[s][i] < INF && d[s] > d[i])
{
if(dp[i]) dp[s] = dp[s] + dp[i];
else dp[s] += dfs(i);
}
}
return dp[s];
}
int main()
{
int t1,s,t,count=0;
int f,to,di;
while(scanf("%d",&n)==1)
{
if(!n) break;
scanf("%d",&m);
memset(d,-1,sizeof(d));
memset(p,-1,sizeof(p));
memset(dp,0,sizeof(dp));
init(n);
for(int i = 0; i < m; i++)
{
scanf("%d %d %d",&f,&to,&di);
Addedge(f,to,di);
Addedge(to,f,di);
}
dijkstra(2);
printf("%d\n",dfs(1));
}
return 0;
}