您的位置:首页 > 其它

UVA10917 Walk Through the Forest (dijkstra + dfs)

2017-10-19 21:35 405 查看
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1858

题意: jimmy每天想走不同的路回家,但他也不想太晚回家,因此他不会走回头路,换句话说,他只会沿着(A,B)这样的道路走,存在一条从B出发回家的路径,比所有从A出发回家的路径都短,求一共有多少条这样的路径。

思路:dijkstra求从家到各点的单源最短路径,然后dfs求路径即可。

#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
#define LL long long
#define inf 1LL << 60
using namespace std;

const int maxn = 1e6+ 10;
int N,M,cnt;
int head[maxn],vis[1100],dp[1100];
LL dist[maxn];
struct Edge{
int to,w,next;
}edge[maxn];
struct node{
int dis,v;
friend bool operator <(node A, node B){
return A.dis > B.dis;
}
};

void add(int u, int v, int w){
edge[cnt].to = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt ++;
}

void dijkstra(int x){
for(int i = 1; i <= N; i ++ ) dist[i] = inf,vis[i] = 0;
dist[x] = 0;
priority_queue<node > q;
node p;
p.dis = 0, p.v = x;
q.push(p);
while(!q.empty()){
p = q.top(); q.pop();
if(vis[p.v]) continue;
vis[p.v] = 1;
for(int i = head[p.v]; i != -1; i = edge[i].next){
int v = edge[i].to;
if(dist[v] > dist[p.v] + edge[i].w){
dist[v] = dist[p.v] + edge[i].w;
node no;
no.dis = dist[v], no.v = v;
q.push(no);
}
}
}
}

int dfs(int x){
if(x == 2) return 1;
if(dp[x]) return dp[x];
int ret = 0;
for(int i = head[x]; i != -1; i = edge[i].next){
int v = edge[i].to;
if(dist[x] > dist[v]) ret += dfs(v);
}
return dp[x] = ret;
}

int main(){
while(~scanf("%d",&N) && N){
scanf("%d",&M);
memset(head,-1,sizeof(head));
int u,v,w;
cnt = 0;
for(int i = 1; i <= M; i ++){
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
dijkstra(2);
memset(dp,0,sizeof(dp));
printf("%d\n",dfs(1));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: