제출 #53641

#제출 시각아이디문제언어결과실행 시간메모리
53641DiuvenRegions (IOI09_regions)C++11
70 / 100
8087 ms33568 KiB
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<int, bool> pib;
const int MX=200010, inf=2e9;

void out(int x){
    cout<<x<<endl;
}
vector<int> P[25010]; // dfs indexes
vector<pib> Q[25010];
vector<int> G[MX];
int n, H[MX], q, r;

int num[MX], sub[MX], now;

void dfs(int v){
    num[v]=++now; int &r=sub[num[v]]; r=num[v];
    for(int x:G[v]){
        dfs(x);
        r=max(r, sub[num[x]]);
    }
}

void init(){
    dfs(1);
    for(int i=1; i<=n; i++){
        int x=num[i], y=sub[x];
        P[H[i]].push_back(x);
        Q[H[i]].push_back({x,0});
        Q[H[i]].push_back({y,1});
    }
    for(int i=1; i<=r; i++){
        sort(P[i].begin(), P[i].end());
        sort(Q[i].begin(), Q[i].end());
    }
}

map<pii, int> D;

struct ord {
    int x, type; // 1(st), 2(pt), 3(ed)
    bool operator < (const ord &o) const {
        if(x==o.x) return type<o.type;
        return x<o.x;
    }
};

int solve(int x, int y){
    if(D.find({x,y})!=D.end()) return D[{x,y}];
    int &ans=D[pii(x,y)]; ans=0;

    vector<ord> A;
    int p1=0, p2=0, sz1=Q[x].size(), sz2=P[y].size();
    while(p1<sz1 && p2<sz2){
        ord a={Q[x][p1].first, Q[x][p1].second?3:1};
        ord b={P[y][p2], 2};
        if(a<b) A.push_back(a), p1++;
        else A.push_back(b), p2++;
    }
    while(p1<sz1){
        ord a={Q[x][p1].first, Q[x][p1].second?3:1};
        A.push_back(a); p1++;
    }
    while(p2<sz2){
        ord b={P[y][p2], 2};
        A.push_back(b); p2++;
    }
    int cnt=0;
    for(ord &o:A){
        if(o.type==1){
            cnt++;
        }
        else if(o.type==2){
            ans+=cnt;
        }
        else{
            cnt--;
        }
    }
    return ans;
}

int main(){
    ios::sync_with_stdio(0); cin.tie(0);
    cin>>n>>r>>q;
    for(int i=1; i<=n; i++){
        int a,b;
        if(i==1){
            cin>>a; H[i]=a;
        }
        else{
            cin>>a>>b;
            G[a].push_back(i); H[i]=b;
        }
    }
    init();
    for(; q--; ){
        int r1, r2; cin>>r1>>r2;
        out(solve(r1,r2));
    }
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...