D题解 | #小美的树上染色#

小美的树上染色

https://ac.nowcoder.com/acm/contest/63585/D

D题 可以当成二分图最大匹配问题来做 这里用的是匈牙利算法 (但是没有dp快

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n,match[N],w[N];
vector<int> v[N];
bool vis[N];
bool check(int x)
{
    int temp = sqrt(x);
    if(temp*temp == x) return true;
    return false;
}
bool dfs(int u)
{
    vis[u] = true;
    for(auto t : v[u])
    {
        if(vis[t]) continue;
        vis[t] = true;
        if(match[t] == -1 || dfs(match[t]))
        {
            match[t] = u;
            match[u] = t;
            return true;
        }
    }
    return false;
}
int main()
{
    cin >> n;
    memset(match,-1,sizeof match);
    for(int i = 1; i <= n; i++)scanf("%d",&w[i]);
    for(int i = 1; i < n; i++)
    {
        int a,b;
        scanf("%d %d",&a,&b);
        if(!check(w[a]*w[b])) continue;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    
    int res = 0;
    for(int i = 1; i <= n; i++)
    {
        if(match[i] != -1) continue;
        memset(vis,0,sizeof vis);
        if(dfs(i)) res++;
    }
    cout << res*2 << endl;
    return 0;
}
全部评论
确实是一个思路,但是如果所有点的值都是2,且构建出类似 菊花图 的树形结构,按照O(V*E)=O(n^2)=10^10, 感觉扛不住
点赞 回复 分享
发布于 2023-08-21 21:41 上海

相关推荐

评论
3
收藏
分享

创作者周榜

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