A Walk Through the Forest HDU - 1142 (Dijkstra+DFS)
程序员文章站
2024-02-24 19:46:34
...
读错题了...要的是满足:如果从a到b,a到终点的距离>b到终点的距离,这个就算有效的
问的是以上有效的有几个,而不是多少从起点到终点的路径...
TLE了还以为是自己没抄板子dijkstra写错了...
#include <iostream>
#include <cstdio>
#include <cstring>
#include<algorithm>
#include<sstream>
#include<queue>
#define ull unsigned long long
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 1003;
int n,m;
struct EDGE
{
int to,dis;
EDGE()
{
to = dis = 0;
}
EDGE(int a,int b)
{
to = a;
dis = b;
}
};
vector<EDGE> vec[1003];
int dis[1003];
bool vis[1003][1003];
int path[1003];
void init()
{
for(int i=0; i<=n; i++)
{
vec[i].clear();
dis[i] = INF;
}
memset(vis,false,sizeof(vis));
}
void dijkstra(int start,int endd)
{
priority_queue<pair<int,int> > que;
que.push(make_pair(0,endd));
dis[endd] = 0;
EDGE a;
while(!que.empty())
{
pair<int,int> P = que.top();
que.pop();
int pos = P.second;
int len = vec[pos].size();
for(int i=0; i<len; i++)
{
a = vec[pos][i];
if(dis[a.to] > dis[pos] + a.dis)
{
dis[a.to] = dis[pos] + a.dis;
que.push(make_pair(dis[a.to],a.to));
}
}
}
}
int DFS(int src)
{
if(path[src] != -1)
return path[src];
if(src == 2)
return 1;
path[src] = 0;
for(int i=1;i<=n;i++)
{
if(dis[i] < dis[src] && vis[i][src])
{
path[src] += DFS(i);
}
}
return path[src];
}
int main()
{
// freopen("in.txt","r",stdin);
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
while(cin>>n>>m && m+n)
{
init();
int a,b,c;
for(int i=0; i<m; i++)
{
cin>>a>>b>>c;
vec[a].push_back(EDGE(b,c));
vec[b].push_back(EDGE(a,c));
vis[a][b] = vis[b][a] = true;
}
dijkstra(1,2);
memset(path,-1,sizeof(path));
// for(int i=1;i<=n;i++)
// {
// cout<<i<<" "<<dis[i]<<endl;
// }
cout<<DFS(1)<<'\n';
}
return 0;
}