题解:P8187 [USACO22FEB] Robot Instructions S

· · 题解

来水一篇蓝题题解。

Part1 题意分析

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

Part2 做法分析

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

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

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

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>e 时,那么就 mp[x][y][cnt]++,就是把到 (x,y) 这个点选了 cnt 个指令的方案数加 1。如果是第二次 dfs,当 i>e 时,那么就去找有么有在 mp 中的 (x,y) 使得可以与现在走到的点匹配而走到 (x_g,y_g)。那么就 ans[cnt + iter.first] += iter.second,其中 iter 代表的是匹配的点的下标,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;
}