题解:P8187 [USACO22FEB] Robot Instructions S
Chenyuze24 · · 题解
来水一篇蓝题题解。
Part1 题意分析
题目中说的很明白了,就是从
Part2 做法分析
如果直接爆搜,那复杂度就是
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。
那么基本的搞好之后,开始 dfs。如果是第一次 dfs,当 mp[x][y][cnt]++,就是把到 ans[cnt + iter.first] += iter.second,其中
dfs(i + 1, e, x, y, cnt, j);//不选。
dfs(i + 1, e, x + a[i].x, y + a[i].y, cnt + 1, j);//选。
然后这道题就做完了。
Part3 代码
具体的看代码吧。
#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;
}