UVa 10917 - Walk Through the Forest (路径计数)

2021/7/18 6:07:35

本文主要是介绍UVa 10917 - Walk Through the Forest (路径计数),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目链接:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=0&problem=1858&mosmsg=Submission+received+with+ID+26582881

转化题意后就是如果一个点 \(B\) 到终点的最短路小于 \(A\) 到终点的最短路,则 \(A->B\) 可以通过。

从终点求一遍最短路,新图是 \(DAG\),记忆化搜索统计路径即可

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;

const int maxn = 1010;
const int INF = 0x3f3f3f3f;

int n, m; 
int h[maxn], cnt = 0;
struct E{
	int to, cost, next;
}e[maxn * maxn * 2];
void add(int u, int v, int w){
	e[++cnt].to = v;
	e[cnt].cost = w;
	e[cnt].next = h[u];
	h[u] = cnt;
}

int d[maxn];
void dij(int S){
	memset(d, 0x3f, sizeof(d));
	priority_queue<pii, vector<pii>, greater<pii> > q;
	d[S] = 0;
	q.push(pii(0, S));
	
	while(!q.empty()){
		pii p = q.top(); q.pop();
		int u = p.second;
		
		if(p.first != d[u]) continue;
		
		for(int i = h[u] ; i != -1 ; i = e[i].next){
			int v = e[i].to;
			if(d[v] > d[u] + e[i].cost){
				d[v] = d[u] + e[i].cost;
				q.push(pii(d[v], v));
			}
		}
	}
}

int dp[maxn];
int DP(int u){
	if(dp[u] > 0) return dp[u];
	
	for(int i = h[u] ; i != -1 ; i = e[i].next){
		int v = e[i].to;
		if(d[u] > d[v]) dp[u] += DP(v);
	}
	return dp[u];
}

ll read(){ ll s = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); } return s * f; }

int main(){
	while(scanf("%d", &n) == 1 && n){
		memset(h, -1, sizeof(h)); cnt = 0;
		scanf("%d", &m);
		int u, v, w;
		for(int i = 1 ; i <= m ; ++i){
			scanf("%d%d%d", &u, &v, &w);
			add(u, v, w), add(v, u, w);
		}
		
		dij(2);
		
		memset(dp, 0, sizeof(dp));
		dp[2] = 1;
		DP(1);
		printf("%d\n", dp[1]);
	}
	return 0;
}


这篇关于UVa 10917 - Walk Through the Forest (路径计数)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程