Luogu3320 SDOI2015 寻宝游戏 链并

传送门


可以发现从哪里开始的最优答案都是一样的。我们只需要用一种比较好维护的方法维护答案就好了。

我们考虑用$dfs$序加上$set$维护链并。先预处理$dfs$序,将当前有宝藏的点丢入$set$中,按照$dfs$序排序,那么答案就是相邻两个点之间的路径的和加上第一个点到最后一个点的路径的和。动态维护这个答案九星了。

#include<bits/stdc++.h>
#define int long long
//This code is written by Itst
using namespace std;

inline int read(){
    ;
    ;
    char c = getchar();
    while(c != EOF && !isdigit(c)){
        if(c == '-')
            f = ;
        c = getchar();
    }
    while(c != EOF && isdigit(c)){
        a = (a << ) + (a << ) + (c ^ ');
        c = getchar();
    }
    return f ? -a : a;
}

;
struct Edge{
    int end , upEd , w;
}Ed[MAXN << ];
] , dep[MAXN] , ans , N , M , ts , cntEd;
struct cmp{
    bool operator ()(int a , int b){
        return dfn[a] < dfn[b];
    }
};
set < int , cmp > s;
set < int , cmp > :: iterator it , it1 , it2;

inline void addEd(int a , int b , int c){
    Ed[++cntEd].end = b;
    Ed[cntEd].upEd = head[a];
    Ed[cntEd].w = c;
    head[a] = cntEd;
}

void dfs(int now , int fa){
    jump[now][] = fa;
    dep[now] = dep[fa] + ;
    dfn[now] = ++ts;
     ; jump[now][i - ] ; ++i)
        jump[now][i] = jump[jump[now][i - ]][i - ];
    for(int i = head[now] ; i ; i = Ed[i].upEd)
        if(Ed[i].end != fa){
            len[Ed[i].end] = len[now] + Ed[i].w;
            dfs(Ed[i].end , now);
        }
}

inline int jumpToLCA(int x , int y){
    if(dep[x] < dep[y])
        swap(x , y);
     ; i >=  ; --i)
         << i) >= dep[y])
            x = jump[x][i];
    if(x == y)
        return x;
     ; i >=  ; --i)
        if(jump[x][i] != jump[y][i]){
            x = jump[x][i];
            y = jump[y][i];
        }
    ];
}

inline int calcLen(int x , int y){
    );
}

inline void insert(int x){
    it = s.lower_bound(x);
    if(it == s.end() || *it != x){
        if(!s.empty()){
            int p , q;
            if(it == s.end())
                q = *s.begin();
            else
                q = *it;
            if(it == s.begin())
                p = *--s.end();
            else
                p = *--it;
            ans = ans - calcLen(p , q) + calcLen(p , x) + calcLen(x , q);
        }
        s.insert(x);
    }
    else{
        int p , q;
        it1 = it;
        ++it1;
        if(it1 == s.end())
            q = *s.begin();
        else
            q = *it1;
        it1 = it;
        if(it1 == s.begin())
            p = *--s.end();
        else
            p = *--it1;
        ans = ans + calcLen(p , q) - calcLen(p , x) - calcLen(x , q);
        s.erase(it);
    }
}

signed main(){
#ifndef ONLINE_JUDGE
    freopen("3320.in" , "r" , stdin);
    //freopen("3320.out" , "w" , stdout);
#endif
    N = read();
    M = read();
     ; i < N ; ++i){
        int a = read() , b = read() , c = read();
        addEd(a , b , c);
        addEd(b , a , c);
    }
    dfs( , );
     ; i <= M ; ++i){
        insert(read());
        printf("%lld\n" , ans);
    }
    ;
}
上一篇:C#DataSet/DataAdapter


下一篇:poj 3259 Wormholes spfa算法