题解:P8187 [USACO22FEB] Robot Instructions S

· · 题解

正难则反,反难则正,正反都难,meet in the middle。

考虑 N\le20 的部分分,可以直接暴力枚举所有 2^N 种情况,可以通过。

注意到全部数据范围是 N\le40,那么从起点开始枚举前一半的选取情况,终点开始枚举后一半的选取情况即可(因为向量的加法满足交换律,只要选了不管放在哪最后到达的地方一定相同,所以才可以这样做)。

有一个技巧可以避免写太麻烦的 dfs:把当前能到达的所有结果存到一个 map 里面,枚举到一个新的向量时加到所有这些结果后面即可,当然时间复杂度仍然是指数级的,因为每枚举到一个新的时就会把当前 map 里的元素翻倍。

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=45;
struct vec{
    int x,y;
    vec operator+(vec a){
        return {x+a.x,y+a.y};
    }
    vec operator-(vec a){
        return {x-a.x,y-a.y};
    }
    bool operator<(vec a)const{
        return make_pair(x,y)<make_pair(a.x,a.y);
    }
}v[N];
int ans[N];
signed main(){
    ios::sync_with_stdio(0);cin.tie(0);
    int n;cin>>n;
    int xg,yg;cin>>xg>>yg;
    for(int i=1;i<=n;i++){
        cin>>v[i].x>>v[i].y;
    }
    map<pair<vec,int>,int>mp1,mp2;
    mp1[{{0,0},0}]=1;mp2[{{xg,yg},0}]=1;
    for(int i=1;i<=n/2;i++){
        auto mp=mp1;
        for(auto t:mp){
            auto nw=t.first;
            nw.first=nw.first+v[i];
            nw.second++;
            int x=t.second;
            mp1[nw]+=x;
        }
    }
    for(int i=n/2+1;i<=n;i++){
        auto mp=mp2;
        for(auto t:mp){
            auto nw=t.first;
            nw.first=nw.first-v[i];
            nw.second++;
            int x=t.second;
            mp2[nw]+=x;
        }
    }
    for(auto t:mp1){
        auto nw=t.first;int x=t.second;
        vec pos=nw.first;int nk=nw.second;
        for(int i=nk;i<=n;i++){
            int lk=i-nk;
            if(mp2.find({pos,lk})!=mp2.end()){
                ans[i]+=x*mp2[{pos,lk}];
            }
        }
    }
    for(int i=1;i<=n;i++){
        cout<<ans[i]<<"\n";
    }
    return 0;
}