AtCoder Beginner Contest 248 D - Range Count Query 「二分」

D - Range Count Query

题目描述:

给一个数组A[i]q次询问,每次询问都问[l, r]中等于x的数的数量

思路:

我们可以给每种数都开一个数组,把等于他的所有的id都顺次放进去,对于每个询问,我们去对应的数组二分即可

(开始写了个莫队,结果不出意料的T掉了

#include 
using namespace std;

#define endl '\n'
#define inf 0x3f3f3f3f
#define mod7 1000000007
#define mod9 998244353
#define m_p(a,b) make_pair(a, b)
#define mem(a,b) memset((a),(b),sizeof(a))
#define io ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define debug(a) cout << "Debuging...|" << #a << ": " << a << "\n";
typedef long long ll;
typedef pair <int,int> pii;

#define MAX 300000 + 50
int n, m, k, x, l, r;
vector<int>tr[MAX];

void work(){
    cin >> n;
    for(int i = 1; i <= n; ++i){
        cin >> x;tr[x].push_back(i);
    }
    cin >> m;
    for(int i = 1; i <= m; ++i){
        cin >> l >> r >> x;
        if(tr[x].size() == 0)cout << 0 << endl;
        else{
            ll lp = lower_bound(tr[x].begin(), tr[x].end(), l) - tr[x].begin();
            ll rp = upper_bound(tr[x].begin(), tr[x].end(), r) - tr[x].begin();
            if(lp == tr[x].size()){
                cout << 0 << endl;
                continue;
            }
            cout << rp - lp<< endl;
        }
    }
}


int main(){
    io;
    work();
    return 0;
}

你可能感兴趣的:(Atcoder,二分)