リスの新しいホームLCA +ツリーの違い

題名

中国の質問の意味を分析する必要はありません。

分析

まず、2つのポイント間で、最良のソリューションを取得するために最短のパスを使用する必要があります。したがって、2つのポイントがx、y、LCA(x、y)= uであると仮定すると、LCAを簡単に考えることができます。したがって、パスxを使用するだけで済みます。 -> u-> yのすべてのポイントにキャンディーを追加できます。暴力的なアプローチは間違いなくtになるため、非常に賢いアプローチを検討します。ツリー上の
2つの子ノードの違い+ 1、LCA-1、そして最後にLCAがここにあるためです。パス上では、2つのポイントの子ノードが1追加されるため、LCAは2倍に増加し、LCAとその親ノードは1である必要があります。

結局、始点を除いて、すべての点が始点と終点になりますが、キャンディーを1つだけ配置する必要があり、最後のポイントはキャンディーを配置する必要がないと言っているので、各ポイントが必要です-1

コード

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 3e5 + 10;
int h[N],e[N * 2],ne[N * 2],idx;
int d[N];
int a[N];
int num[N];
int ans[N];
int f[N][31];
int n,m;

void add(int a,int b){
    
    
    ne[idx] = h[a],e[idx] = b,h[a] = idx++;
}

void bfs(int root){
    
    
    memset(d,0x3f,sizeof d);
    d[0] = 0,d[root] = 1;
    queue<int> Q;
    Q.push(root);
    while(Q.size()){
    
    
        int t = Q.front();
        Q.pop();
        for(int i = h[t];~i;i = ne[i]){
    
    
            int j = e[i];
            if(d[j] > d[t] + 1){
    
    
                d[j] = d[t] + 1;
                Q.push(j);
                f[j][0] = t;
                for(int k = 1;k <= 30;k++)
                    f[j][k] = f[f[j][k - 1]][k - 1];
            }
        }
    }
}

int LCA(int a,int b){
    
    
    if(d[a] < d[b]) swap(a,b);
    for(int i = 30;i >= 0;i--)
        if(d[f[a][i]] >= d[b])
            a = f[a][i];
    if(a == b) return a;
    for(int i = 30;i >= 0;i--)
        if(f[a][i] != f[b][i])
            a = f[a][i],b = f[b][i];
    return f[a][0];
}

void dfs(int u,int fa){
    
    
    for(int i = h[u];~i;i = ne[i]){
    
    
        int j = e[i];
		if(j == fa)continue;
		dfs(j, u);
		num[u] += num[j];
    }
}


int main(){
    
    
    memset(h,-1,sizeof h);
    scanf("%d",&n);
    m = n - 1;
    for(int i = 1;i <= n;i++) scanf("%d",&a[i]);
    while(m--){
    
    
        int a,b;
        scanf("%d%d",&a,&b);
        add(a,b),add(b,a);
    }
    bfs(1);
    for(int i = 1;i < n;i++){
    
    
        int x = a[i],y = a[i + 1];
        int u = LCA(x,y);
        num[f[u][0]]--;
        num[u]--;
        num[x]++;
        num[y]++;
    }
    dfs(1,0);
    for(int i = 2;i <= n;i++) num[a[i]]--;
    for(int i = 1;i <= n;i++) printf("%d\n",num[i]);
    return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/




おすすめ

転載: blog.csdn.net/tlyzxc/article/details/110820270