hdu 3804 Query on a tree

STL中multiset容器的应用,一开始还以为是树链剖分+线段树|RMQ,看来别想太复杂就好

#include <stdio.h>
#include <vector>
#include <string.h>
#include <algorithm>
#include <set>
using namespace std;
typedef long long ll;
const int MAXN = 100010;
#ifndef __GNUC__
#pragma comment(linker, "/STACK:1024000000,1024000000")
#endif // __GNUC__
int n, q;
struct _edge
{
    int to, next, val;
} edge[MAXN << 1];
int head[MAXN], cn_edge;
multiset<int> mset;

void add ( int u, int v, int z )
{
    edge[cn_edge].to = v; edge[cn_edge].next = head[u];
    edge[cn_edge].val = z;
    head[u] = cn_edge++;
}
struct ques
{
    int q, pos;
    ques ( int a, int b ) {q = a, pos = b;}
};
int qcnt;
int ans[MAXN];
vector<ques> msign[MAXN];
void init()
{
    memset ( head, -1, sizeof head );
    cn_edge = 0;
    mset.clear();
    qcnt = 0;
    for ( int i = 1; i <= n; ++i ) { msign[i].clear(); }
}
multiset<int>::iterator it;
void solve ( ques exa )
{
    it = mset.begin();
    if ( *it > exa.q )
    {
        ans[exa.pos] = -1; return;
    }
    it = mset.find ( exa.q );
    if ( it != mset.end() )
    {
        ans[exa.pos] = *it;
    }
    else
    {
        mset.insert ( exa.q );
        it = mset.find ( exa.q );
        it--;
        ans[exa.pos] = *it++;
        mset.erase ( it );
    }
}
void dfs ( int u, int pre, int val )
{
    if ( u != 1 )
    {
        mset.insert ( val );
        for ( int i = 0; i < msign[u].size(); ++i )
        {
            solve ( msign[u][i] );
        }
    }
    for ( int i = head[u]; ~i; i = edge[i].next )
    {
        int v = edge[i].to;
        int val = edge[i].val;
        if ( v == pre ) { continue; }
        dfs ( v, u, val );
    }
    if ( u != 1 )
    {
        it = mset.find ( val );
        mset.erase ( it );
    }
}
int main()
{
#ifdef  __GNUC__
    freopen ( "in.txt", "r", stdin );
#endif // __GNUC__
    int cs;
    scanf ( "%d", &cs );
    while ( cs-- )
    {
        scanf ( "%d", &n );
        init();
        for ( int i = 1; i < n; ++i )
        {
            int u, v, z;
            scanf ( "%d%d%d", &u, &v, &z );
            add ( u, v, z );
            add ( v, u, z );
        }
        scanf ( "%d", &q );
        for ( int _ = 0; _ < q; ++_ )
        {
            int a, b;
            scanf ( "%d%d", &a, &b );
            msign[a].push_back ( ques ( b, qcnt++ ) );
        }
        for ( int i = 0; i < msign[1].size(); ++i )
        {
            ques tp = msign[1][i];
            ans[tp.pos] = -1;
        }
        dfs ( 1, 0, 0 );
        for ( int i = 0; i < qcnt; ++i )
        {
            printf ( "%d\n", ans[i] );
        }
    }
    return 0;
}


你可能感兴趣的:(hdu 3804 Query on a tree)