zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    AJAX
    JQUERY基础
    PHP 数据库抽象层pdo
    会话控制:session与cookie
    php 如何造一个简短原始的数据库类用来增加工作效率
    php 数据访问(以mysql数据库为例)
    面向对象设计原则
    php 设计模式 例子
    PHP中静态与抽象的概念
    键盘的按钮键名
  • 原文地址:https://www.cnblogs.com/captain1/p/9756989.html
Copyright © 2011-2022 走看看