NOIP2017:逛公园

Sol

发现\(NOIP2017\)还没\(AK\)???

赶紧改

考场上明明打出了\(DP\),没时间了,没判环,重点是没初始化数组,爆\(0\)

\(TAT\)

先最短路,然后\(f[i][j]\)表示到\(i\)时,比最短路大\(j\)的方案

大力记搜就好了

判环就记录一下当前转移的是否在栈中就没了

明明这么简单,可我就是与\(AC\)擦肩而过

# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
const int _(1e5 + 5);
typedef long long ll;
typedef int Arr[_]; IL int Input(){
RG int x = 0, z = 1; RG char c = getchar();
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
} Arr first, dis, vis, f[55], in[55];
int n, m, k, p, cnt, ans, flg;
struct Edge{
int to, next, w;
} edge[_ << 1];
queue <int> Q; IL void Add(RG int u, RG int v, RG int w){
edge[cnt] = (Edge){v, first[u], w}; first[u] = cnt++;
} IL void SPFA(){
dis[1] = 0, Q.push(1), vis[1] = 1;
while(!Q.empty()){
RG int u = Q.front(); Q.pop();
for(RG int e = first[u]; e != -1; e = edge[e].next){
RG int v = edge[e].to, w = edge[e].w;
if(dis[u] + w < dis[v]){
dis[v] = dis[u] + w;
if(!vis[v]) Q.push(v), vis[v] = 1;
}
}
vis[u] = 0;
}
} IL int Dfs(RG int u, RG int d){
if(flg) return 0;
if(in[d][u]) return !(flg = 1);
if(~f[d][u]) return f[d][u];
in[d][u] = 1, f[d][u] = (u == n && d <= k);
for(RG int e = first[u]; e != -1; e = edge[e].next){
RG int v = edge[e].to, fd = dis[u] + edge[e].w + d - dis[v];
if(fd < 0 || fd > k) continue;
(f[d][u] += Dfs(v, fd)) %= p;
}
return f[d][u] + (in[d][u] = 0);
} int main(RG int argc, RG char* argv[]){
RG int T = Input();
while(T--){
n = Input(), m = Input(), k = Input(), p = Input();
Fill(first, -1), Fill(dis, 127), Fill(f, -1), Fill(in, 0);
flg = ans = cnt = 0;
for(RG int i = 1; i <= m; i++){
RG int u = Input(), v = Input(), w = Input();
Add(u, v, w);
}
SPFA(), ans = Dfs(1, 0);
printf("%d\n", flg ? -1 : ans);
}
return 0;
}
上一篇:洛谷 P3953 [ NOIP 2017 ] 逛公园 —— 最短路DP


下一篇:「NOIP2017」逛公园