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;
}
上一篇:Coding Contest HDU - 5988


下一篇:Codeforces Round #713 (Div. 3) F. Education 超详细思考过程