一名苦逼的OIer,想成为ACMer

Iowa_Battleship

洛谷3953 逛公园

原题链接

记忆化搜索。
先在反图上跑一边最短路,求出\(dis[x]\),表示点\(x\)到点\(n\)的最短距离,当然也同时也排除了不能到达\(n\)的点。
\(f[x][k]\)表示从\(x\)点走到\(n\)点允许比\(dis[x]\)多走\(k\)距离的方案数,\(a_i\)表示\(x\)能到达的点,且边权为\(v_i\),共\(s_x\)个,则有转移方程:

\(\qquad\qquad f[x][k] = \sum\limits_{i = 1}^{i \leqslant s_x} f[a_i][k - (dis[a_i] + v_i - dis[x])]\)

最后的答案就是\(f[1][K]\)
至于判断零环则可以另开一个数组\(sta[x][k]\)(可以理解为栈),当搜到\((x,k)\)的状态时,若\(sta[x][k]\)\(1\),即该状态还在栈里,就返回\(-1\)

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int N = 1e5 + 10;
const int M = 2e5 + 10;
const int K = 55;
struct dd{
	int x, D;
	bool operator < (const dd &b) const
	{
		return D > b.D;
	}
};
int fi[N], di[M], ne[M], da[M], f_fi[N], f_ne[M], f_di[M], f_da[M], dis[N], f[N][K], l, fl, p, n;
bool v[N], sta[N][K];
priority_queue<dd>q;
inline int re()
{
	int x = 0;
	char c = getchar();
	bool p = 0;
	for (; c < '0' || c > '9'; c = getchar())
		p |= c == '-';
	for (; c >= '0' && c <= '9'; c = getchar())
		x = x * 10 + c - '0';
	return p ? -x : x;
}
inline void add(int x, int y, int z)
{
	di[++l] = y;
	da[l] = z;
	ne[l] = fi[x];
	fi[x] = l;
	f_di[++fl] = x;
	f_da[fl] = z;
	f_ne[fl] = f_fi[y];
	f_fi[y] = fl;
}
void dij()
{
	int i, x, y;
	q.push((dd){n, 0});
	dis[n] = 0;
	while (!q.empty())
	{
		x = q.top().x;
		q.pop();
		if (v[x])
			continue;
		v[x] = 1;
		for (i = f_fi[x]; i; i = f_ne[i])
			if (dis[y = f_di[i]] > dis[x] + f_da[i])
			{
				dis[y] = dis[x] + f_da[i];
				q.push((dd){y, dis[y]});
			}
	}
}
int dfs(int x, int k)
{
	int i, y, va;
	if (sta[x][k])
		return -1;
	if (f[x][k])
		return f[x][k];
	sta[x][k] = 1;
	f[x][k] = x ^ n ? 0 : 1;
	for (i = fi[x]; i; i = ne[i])
		if ((va = dis[y = di[i]] - dis[x] + da[i]) <= k)
		{
			if ((va = dfs(y, k - va)) < 0)
				return f[x][k] = -1;
			f[x][k] = (f[x][k] + va) % p;
		}
	sta[x][k] = 0;
	return f[x][k];
}
int main()
{
	int i, m, x, y, z, t, k;
	t = re();
	while (t--)
	{
		n = re();
		m = re();
		k = re();
		p = re();
		memset(fi, 0, sizeof(fi));
		memset(f_fi, 0, sizeof(f_fi));
		memset(f, 0, sizeof(f));
		memset(sta, 0, sizeof(sta));
		memset(dis, 60, sizeof(dis));
		memset(v, 0, sizeof(v));
		l = fl = 0;
		for (i = 1; i <= m; i++)
		{
			x = re();
			y = re();
			z = re();
			add(x, y, z);
		}
		dij();
		printf("%d\n", dfs(1, k));
	}
	return 0;
}

posted on 2018-10-18 11:20  Iowa_Battleship  阅读(78)  评论(0编辑  收藏  举报

导航