15.子根拥有的权值种类

class Solution {
    int p[200005],ne[200005],h[200005],f[200005],s[100005][26],m=0;
    string t;
    vector<int> ans;
public:
    void dfs(int x){
        s[x][t[x]-'a']=1;
        cout<<x<<" ";
        for(int i=h[x];i;i=ne[i])if(p[i]!=f[x]){
            f[p[i]]=x;
            dfs(p[i]);
            for(int j=0;j<26;j++)s[x][j]+=s[p[i]][j];
        }
        ans[x]=s[x][t[x]-'a'];
    }
    vector<int> countSubTrees(int n, vector<vector<int>>& edges, string labels) {
        ans.resize(n);
        for(auto e:edges){
            p[++m]=e[1];
            ne[m]=h[e[0]];
            h[e[0]]=m;
            p[++m]=e[0];
            ne[m]=h[e[1]];
            h[e[1]]=m;
        }
        t=labels;
        dfs(0);
        return ans;
    }
};

s[100005][26]真是神仙操作,记录了每个结点对应自己+子树的字母种类

posted @ 2020-07-20 21:47  阿破  阅读(76)  评论(0编辑  收藏  举报