P4185 [USACO18JAN] MooTube G

>>>find lian 的模板熟练

>>>找祖宗时要彻底

》》》每次q  *n   超时 -》 单调性 -》

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<bits/stdc++.h>
#define ll long long
#define ddd printf("-----------------debug\n");
using namespace std;
const int maxn=1e5+10;

int n,q;
int siz[maxn],ans[maxn],fa[maxn<<2];

struct edge{
    int u,v,w;
}e[maxn<<2];

struct qry{
    int id,k,v;
}qr[maxn<<2];

int find(int x){
    return fa[x]==x? x: fa[x]=find(fa[x]);
}
void lian(int x,int y){
    int f1=find(x),f2=find(y);
    if(f1==f2) return;
    fa[f2]=f1;
    siz[f1]+=siz[f2];
} 

bool cmp1(edge a,edge b){
    return a.w>b.w;
}
bool cmp2(qry a,qry b){
    return a.k>b.k;
}

int main()
{
    ios::sync_with_stdio(false); cin.tie(0);
    cin>>n>>q;
    for(int i=1;i<=n;i++) fa[i]=i,siz[i]=1;
    
    for(int i=1;i<=n-1;i++){
        cin>>e[i].u>>e[i].v>>e[i].w;
    }
    for(int i=1;i<=q;i++){
        cin>>qr[i].k>>qr[i].v; qr[i].id=i;
    }
    sort(e+1,e+n,cmp1); sort(qr+1,qr+1+q,cmp2);
    
    int pos=1;
    for(int i=1;i<=q;i++)
    {
        while(pos<=n-1&&e[pos].w>=qr[i].k){
            lian(e[pos].u,e[pos].v);
            pos++;
        }
    //    ddd
        ans[qr[i].id]=siz[find(qr[i].v)]-1;
    }
    
    for(int i=1;i<=q;i++) cout<<ans[i]<<'\n';
    
    return 0;
}
View Code
 

 

 
posted @ 2023-07-27 23:02  JMXZ  阅读(8)  评论(0)    收藏  举报