• NOIP2014 联合权值


    传送门

    这题还是比较考验思维的……也是我太菜了orz。

    一开始看到相隔距离为2想到爆搜……?不过估计会T。因为这个图是一棵树,我们发现能贡献联合权值的只有两种,一是祖父和孙子,二是兄弟。祖父和孙子可以直接在dfs的时候计算,这个直接把祖父传进去即可。然后对于每个节点,我们记录其儿子节点的最大值和次大值,用之更新最大值,然后我们直接暴力组合儿子会超时……但是利用数学推导,就知道我们只要计算权值和然后减去所有点权值的平方即可。

    看一下代码。

    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    #include<iostream>
    #include<cmath>
    #include<set>
    #include<queue>
    #define rep(i,a,n) for(int i = a;i <= n;i++)
    #define per(i,n,a) for(int i = n;i >= a;i--)
    #define enter putchar('
    ')
    
    using namespace std;
    typedef long long ll;
    const int M = 200005;
    const int INF = 1000000009;
    const ll mod = 10007;
    
    ll read()
    {
        ll ans = 0,op = 1;
        char ch = getchar();
        while(ch < '0' || ch > '9')
        {
        if(ch == '-') op = -1;
        ch = getchar();
        }
        while(ch >= '0' && ch <= '9')
        {
        ans *= 10;
        ans += ch - '0';
        ch = getchar();
        }
        return ans * op;
    }
    
    struct edge
    {
        ll next,to;
    }e[M<<1];
    
    ll n,x,y,w[M],maxn,tot,ecnt,head[M],mson[M],sson[M],sum[M],size[M];
    
    void add(ll x,ll y)
    {
        e[++ecnt].to = y;
        e[ecnt].next = head[x];
        head[x] = ecnt;
    }
    
    void dfs(int x,int f,int g)
    {
        int cur = 0;
        maxn = max(maxn,w[x] * w[g]),tot += (w[x] * w[g]) << 1,tot %= mod;
        for(int i = head[x];i;i = e[i].next)
        {
        if(e[i].to == f) continue;
        dfs(e[i].to,x,f);
        sum[x] += w[e[i].to],cur++;
        if(w[e[i].to] > mson[x]) mson[x] = w[e[i].to];
        else if(w[e[i].to] > sson[x]) sson[x] = w[e[i].to];
        }
        maxn = max(maxn,mson[x] * sson[x]);
        if(cur <= 1) return;
        tot += sum[x] * sum[x];
        for(int i = head[x];i;i = e[i].next)
        {
        if(e[i].to == f) continue;
        tot -= w[e[i].to] * w[e[i].to];
        }
        tot %= mod;
    
    }
    
    int main()
    {
        n = read();
        rep(i,1,n-1) x = read(),y = read(),add(x,y),add(y,x);
        rep(i,1,n) w[i] = read();
        dfs(1,0,0);
        printf("%lld %lld
    ",maxn,tot % mod);
        return 0;
    }
  • 相关阅读:
    使用PHP获取用户客户端真实IP的解决方案
    PHP中使用mkdir创建多级目录的方法
    javascript中将字符串转换为json格式的三种方法
    Codeigniter处理用户登录验证后URL跳转
    PHP正则表达式匹配URL中的域名
    开源项目列表
    PG JDBC COPY感谢原作者
    if中return的用法
    读数据库查询的 ResultSet时java.sql.SQLException: 流已被关闭
    一篇讲JAVA JDBC的好文章
  • 原文地址:https://www.cnblogs.com/captain1/p/9756989.html
Copyright © 2020-2023  润新知