跳到正文

题解

题解:P8187 [USACO22FEB] Robot Instructions S

Chenyuze24约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月12日
篇幅
约 4 分钟
题目
P8187

版本

  1. v1当前

来水一篇蓝题题解。

Part1 题意分析

题目中说的很明白了,就是从 (0,0)(0,0) 开始走,要你走到 (xg,yg)(x_g,y_g),有 nn 条指令,让你求从里面选 kk 个指令有几种方案能到 (xg,yg)(x_g,y_g)。

Part2 做法分析

如果直接爆搜,那复杂度就是 O(240)O(2^{40}),显然会超了,那么就考虑折半搜索。那么我们就可以用它来考虑选和不选,我们可以用一个哈希表来存。那么我们要存什么呢,显然就是到那个点,选了的个数和对应的方式数。

C++
unordered_map<long long, unordered_map<long long, unordered_map<int, int>>> mp;

我们用一个结构体来存输入的指令。用 a.xa.x 和 a.ya.y 表示指令的 xx 和 yy。然后用 ansans 去存最后的答案。在 dfs 时,需要用的变量有当前数组遍历到哪里了,最后要遍历到什么位置,现在在坐标平面上的位置,现在选了几个了,现在是第几遍 dfs。

C++
void dfs(int i, int e, long long x, long long y, int cnt, int j) //i为当前数组遍历到哪里了,e为最后要遍历到什么位置,x,y为现在在坐标平面上的位置,cnt为现在选了几个了,j为现在是第几遍 dfs。

那么基本的搞好之后,开始 dfs。如果是第一次 dfs,当 i>ei>e 时,那么就 mp[x][y][cnt]++ ,就是把到 (x,y)(x,y) 这个点选了 cntcnt 个指令的方案数加 11。如果是第二次 dfs,当 i>ei>e 时,那么就去找有么有在 mpmp 中的 (x,y)(x,y) 使得可以与现在走到的点匹配而走到 (xg,yg)(x_g,y_g)。那么就 ans[cnt + iter.first] += iter.second,其中 iteriter 代表的是匹配的点的下标,iter.firstiter.first 代表选了的指令数量,而 iter.seconditer.second 代表对应的方案数量。那么最后就是十分简单的选与不选的搜索了。

C++
dfs(i + 1, e, x, y, cnt, j);//不选。
dfs(i + 1, e, x + a[i].x, y + a[i].y, cnt + 1, j);//选。

然后这道题就做完了。

Part3 代码

具体的看代码吧。

C++
#include<bits/stdc++.h>//万能头。
#define int long long//保险些。
using namespace std;
int n;
struct NODE{//结构体存输入的指令。
	int x;
	int y;

}a[45];
int idx=0;
long long xg, yg;
long long ans[45];
unordered_map<long long, unordered_map<long long, unordered_map<int, int>>> mp;//哈希表。
void dfs(int i, int e, long long x, long long y, int cnt, int j) {//i为当前数组遍历到哪里了,e为最后要遍历到什么位置,x,y为现在在坐标平面上的位置,cnt为现在选了几个了,j为现在是第几遍 dfs。
	if (i > e) //这个注意。
	{
		if (j == 0)
			mp[x][y][cnt]++;
		else
		{
			if (mp.count(xg - x) && mp[xg - x].count(yg - y))
				for (auto & iter : mp[xg - x][yg - y])
					ans[cnt + iter.first] += iter.second;
		}
		return;
	}
	dfs(i + 1, e, x, y, cnt, j);//不选。
	dfs(i + 1, e, x + a[i].x, y + a[i].y, cnt + 1, j);//选。
}

signed main()
{
	cin >> n;
	cin >> xg >> yg;
	for (int i = 1; i <= n; i++)
		cin >> a[i].x >> a[i].y;
	dfs(1, n / 2, 0, 0, 0, 0);//两个dfs。
	dfs(n / 2 + 1, n, 0, 0, 0, 1);//注意起始和终止位置。
	for (int i = 1; i <= n; i++)
		cout << ans[i] << '\n';//输出。
	return 0;
}
原文