题解 | 在树上游玩

在树上游玩

https://www.nowcoder.com/practice/8c0d60834a924ce98e7425fed9c62ab8

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define int long long
unordered_map<int,int> mp1,mp2;   // mp1记录节点i的父节点j,mp2记录节点i的邻居白点数

int find(int x) {
    return mp1[x]==x?x:mp1[x]=find(mp1[x]);
}

// 快速乘
int mul(int a,int b) {
    a = a%(1000000007LL);
    b = b%(1000000007LL);
    int ans = 0;
    while (b) {
        if (b&1) {
            ans +=a;
            ans %= 1000000007LL;
        }
        b>>=1;
        a<<=1;
    }
    return ans;
}

signed main() {
    int n,k;
    cin >> n >> k;
    vector<int> a(k+1);
    for (int i=1;i<=k;++i) {
        cin >> a[i];
        mp1[a[i]] = a[i];
    }
    int u,v;
    for (int i=1;i<=n-1;++i) {
        cin >> u >> v;
        if (mp1.count(u) && mp1.count(v)) {
            if (find(u) != find(v)) {
                mp2[find(v)]+=mp2[find(u)];
                mp2.erase(find(u));
                mp1[find(u)] = v;
            }
        } else if (mp1.count(u)) {
            mp2[find(u)]++;
        } else if (mp1.count(v)) {
            mp2[find(v)]++;
        }
    }
    int ans = 1;
    for (auto&it:mp2) {
        // ans = mul(ans,it.second);
        ans = ans*(it.second%(1000000007LL))%(1000000007LL);
    }
    cout << mp2.size() << " " << ans << endl;
}

全部评论

相关推荐

Lorn的意义:你这标个前端是想找全栈吗?而且项目确实没什么含金量,技术栈太少了,边沉淀边找吧 现在学院本想就业好一点四年至少得高三模式两年加油吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务