跳到正文

题解

题解:CF2118D1 Red Light, Green Light (Easy version)

_little_duck_约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
CF2118D1

版本

  1. v1当前

CodeForces 2118D1 题解

题意

给定你 nn 个红绿灯,每个红绿灯有一个位置和延迟。有公共周期 kk,对于红绿灯 i∈ni \in n,l×k+dil \times k + d_i 为红灯,否则为绿灯,问能否走出红绿灯路段

思路

  • 用记忆化搜索
  • 如果在同一个位置、同样时间、同样方向重复出现,则说明无法离开
  • 不枚举每个点,只枚举红绿灯位置

易错点

  • 必须要满足位置、时间、方向同时重复时,才算非法

代码

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long

const int N = 1010;

int T, n, k, q, f[N][N][5], fl, y;

int p[N], d[N];

void dfs(int x, int t, int pos){
  if(fl != 0){
    return ;
  }
  if(x > n || x < 1){
    fl = -1;
    return ;
  }
  (t += abs(p[x] - y) % k) %= k;
  if(t == d[x]){
    pos = -pos;
  }
  if(f[x][t][pos + 1]){
    fl = 1;
    return ;
  }
  f[x][t][pos + 1] = 1;
  y = p[x];
  dfs(x + pos, t, pos);
}

void solve(){
  cin >> n >> k;
  for(int i = 1; i <= n; i++){
    cin >> p[i];
  }
  for(int i = 1; i <= n; i++){
    cin >> d[i];
  }
  cin >> q;
  while(q--){
    cin >> y;
    int pp = lower_bound(p + 1, p + 1 + n, y) - p;
    memset(f, 0, sizeof(f));
    fl = 0;
    dfs(pp, 0, 1);
    if(fl == 1){
      cout << "NO\n";
    }
    else{
      cout << "YES\n";
    }
  }
}

signed main(){
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> T;
  while(T--){
    solve();
  }
  return 0;
}
原文