【cf1169E】E. And Reachability(dp)

传送门

题意:
给出(a_{1,2,...,n}),定义两个位置(i,j)可达为:(a_i& a_j>0)
现在给出(q)个询问,每个询问给出(x,y),问是否存在一个序列(p),满足:

  • (x=p_1<p_2<cdots<p_k=y)
  • (p_i,p_{i+1},i<k)两两可达。

思路:
类似于序列自动机的思路,我们预处理出(next_{i,j})表示从(i)出发,二进制包含(1)最近的一个(j)且满足(j>i)
然后从后往前(dp)即可,定义(dp_{i,j})表示从(i)出发,经过一些数与二进制位包含(j)的数连通,那个数的最近位置。
转移的时候枚举所有的二进制位进行转移即可。
时间复杂度(O(nlog^2n))
细节见代码:

/*
 * Author:  heyuhhh
 * Created Time:  2020/3/19 18:08:08
 */
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#include <iomanip>
#include <assert.h>
#include <bitset>
#define MP make_pair
#define fi first
#define se second
#define pb push_back
#define sz(x) (int)(x).size()
#define all(x) (x).begin(), (x).end()
#define INF 0x3f3f3f3f
#define Local
#ifdef Local
  #define dbg(args...) do { cout << #args << " -> "; err(args); } while (0)
  void err() { std::cout << '
'; }
  template<typename T, typename...Args>
  void err(T a, Args...args) { std::cout << a << ' '; err(args...); }
  template <template<typename...> class T, typename t, typename... A> 
  void err(const T <t> &arg, const A&... args) {
  for (auto &v : arg) std::cout << v << ' '; err(args...); }
#else
  #define dbg(...)
#endif
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
//head
const int N = 3e5 + 5, M = 20;

int n, q;
int a[N];
vector <int> v[M];

int dp[N][M], nxt[N][M];

void run() {
    cin >> n >> q;
    for(int i = 1; i <= n; i++) {
        cin >> a[i];
        for(int j = 0; j < M; j++) if(a[i] >> j & 1) {
            v[j].push_back(i);
        }
    }
    for(int i = 1; i <= n; i++) {
        for(int j = 0; j < M; j++) if(a[i] >> j & 1) {
            int t = upper_bound(all(v[j]), i) - v[j].begin();
            if(t < sz(v[j])) nxt[i][j] = v[j][t];
        }
    }
    memset(dp, INF, sizeof(dp));
    for(int i = 1; i <= n; i++) {
        for(int j = 0; j < M; j++) if(a[i] >> j & 1) {
            dp[i][j] = i;
        }   
    }
    for(int i = n; i >= 1; i--) {
        for(int j = 0; j < M; j++) {
            for(int k = 0; k < M; k++) if(a[i] >> k & 1) {
                dp[i][j] = min(dp[i][j], dp[nxt[i][k]][j]);
            }
        }
    }
    while(q--) {
        int x, y; cin >> x >> y;
        bool ok = false;
        for(int i = 0; i < M; i++) if(a[y] >> i & 1) {
            if(dp[x][i] <= y) ok = true;
        }
        if(ok) cout << "Shi" << '
';
        else cout << "Fou" << '
';
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cout << fixed << setprecision(20);
    run();
    return 0;
}
原文地址:https://www.cnblogs.com/heyuhhh/p/12548524.html