Stay Hungry,Stay Foolish!

D - Robot Arms 2 -- ATCODER

D - Robot Arms 2

题目 : https://atcoder.jp/contests/abc274/tasks/abc274_d

参考: https://zhuanlan.zhihu.com/p/576281206

 

分析

dfs或者bfs最大复杂度 2^1000, 超时必然的。

采用内存换时间的方法, dp 动态规划, 打表计算每一步执行后,可能到达的坐标。

 

由于目标位置为二维空间上的一点, 分为两个分量, X方向和y方向;

那么 第一步,第三步,第五步,... 奇数步骤都是在x方向是进行移动;

第二步,第四步,第六步,... 偶数步骤都是在y方向上进行移动。

 

需要建立两张表,进行追踪每个步骤后移动到的目标位置;最终判断表中在目标位置是否可达。

 

code

https://atcoder.jp/contests/abc274/submissions/35927313

const int N = 1005;
const int SPACE = 20010;
int n, x, y;
int xsteps[N];
int ysteps[N];
 
int xindex = 0;
int yindex = 0;
 
map<int, map<int, bool>> fx;
map<int, map<int, bool>> fy;
 
 
int main()
{
    cin >> n >> x >> y;
 
    for(int i=0; i<n; i++){
        if (i % 2 == 0){
            cin >> xsteps[++xindex];
        } else {
            cin >> ysteps[++yindex];
        }
    }
 
    // after step one in x direction
    // get offset xsteps[1];
    fx[1][xsteps[1]] = true;
 
    // initial status in y direction
    // get offset 0;
    fy[0][0] = true;
    
    // skip step one in x direction
    for(int i=2; i<=xindex; i++){
        int xi = xsteps[i];
        
        // based on i-1 status, move xi
        // calculate i status
        map<int, bool> fx_prev = fx[i-1];
        map<int, bool>::iterator it;
        for(it=fx_prev.begin(); it!=fx_prev.end(); it++){
            int j = it->first;
 
            int left = j - xi;
            int right = j + xi;
 
            fx[i][left] = true;
            fx[i][right] = true;
        }
    }
 
    for(int i=1; i<=yindex; i++){
        int yi = ysteps[i];
//        cout << "i=" << i << " yi=" << yi << endl;
 
        // based on i-1 status, move yi
        // calculate i status
        map<int, bool> fy_prev = fy[i-1];
        map<int, bool>::iterator it;
        for(it=fy_prev.begin(); it!=fy_prev.end(); it++){
            int j = it->first;
 
            int up = j + yi;
            int down = j - yi;
 
            fy[i][down] = true;
            fy[i][up] = true;
        }
    }
 
//    cout << "fx[xindex][x] = " << fx[xindex][x] << endl;
//    cout << "fy[yindex][y] = " << fy[yindex][y] << endl;
 
//    for(int i=0; i<10000; i++){
//        if (fy[xindex][i] == false){
//            continue;
//        }
//
//        cout << "!!fy[xindex][" << i << "] = " << fy[xindex][i] << endl;
//    }
 
    if (fx[xindex][x] && fy[yindex][y]){
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
 
    return 0;
}
 

 

posted @ 2022-10-24 09:48  lightsong  阅读(46)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel