码迷,mamicode.com
首页 > 其他好文 > 详细

E 旗鼓相当的对手

时间:2020-04-15 21:44:00      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:lib   ==   ons   limits   print   tin   i++   limit   ++   

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<climits>
#include<stack>
#include<vector>
#include<queue>
#include<set>
#include<bitset>
#include<map>
//#include<regex>
#include<cstdio>
#include <iomanip>
#pragma GCC optimize(2)
#define up(i,a,b)  for(int i=a;i<b;i++)
#define dw(i,a,b)  for(int i=a;i>b;i--)
#define upd(i,a,b) for(int i=a;i<=b;i++)
#define dwd(i,a,b) for(int i=a;i>=b;i--)
//#define local
typedef long long ll;
typedef unsigned long long ull;
const double esp = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int inf = 1e9;
using namespace std;
ll read()
{
	char ch = getchar(); ll x = 0, f = 1;
	while (ch<‘0‘ || ch>‘9‘) { if (ch == ‘-‘)f = -1; ch = getchar(); }
	while (ch >= ‘0‘ && ch <= ‘9‘) { x = x * 10 + ch - ‘0‘; ch = getchar(); }
	return x * f;
}
typedef pair<int, int> pir;
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lrt root<<1
#define rrt root<<1|1
const int N = 1e5 + 10;
vector<ll>cnt[N], num[N];
int n, k;
struct eg {
	int next, to;
}edge[N<<1];
int head[N << 1];
ll ai[N];
int eg_cnt = 0;
int dist[N], d[N], son[N];
int root[N];
ll ans[N];
void addedge(int u, int v)
{
	edge[eg_cnt].to = v;
	edge[eg_cnt].next = head[u];
	head[u] = eg_cnt++;
}
void dfs1(int u, int fa,int dep)
{
	for (int i = head[u]; ~i; i = edge[i].next)
	{
		int v = edge[i].to;
		if (v == fa)continue;
		dfs1(v, u, dep + 1);
		if (d[son[u]] < d[v])
			son[u] = v;
	}
	d[u] = d[son[u]] + 1;
}
int d_cnt = 0;
void dfs2(int u, int fa, int top)
{
	if (u == top)
	{
		root[u] = d_cnt++;
		cnt[root[u]].resize(d[u]);
		num[root[u]].resize(d[u]);
	}
	if (son[u])
	{
		root[son[u]] = root[u];
		dist[son[u]] = dist[u] + 1;
		dfs2(son[u], u, top);
	}
	num[root[u]][dist[u]]++;
	cnt[root[u]][dist[u]] += ai[u];
	for (int i = head[u]; ~i; i = edge[i].next)
	{
		int v = edge[i].to;
		if (v == fa || v == son[u])continue;
		dfs2(v, u, v);
		up(j, 0, d[v])
		{
			int dd = k - j - 1 + dist[u];
			if (dd < d[top] && k - j - 1 > 0)
			{
				ans[u] += cnt[root[u]][dd] * num[root[v]][j];
				ans[u] += num[root[u]][dd] * cnt[root[v]][j];
			}
		}
		up(j, 0, d[v])	
		{
			cnt[root[u]][j + 1 + dist[u]] += cnt[root[v]][j];
			num[root[u]][j + 1 + dist[u]] += num[root[v]][j];
		}
	}
}
int main()
{
	n = read(), k = read();
	memset(head, -1, sizeof(head));
	upd(i, 1, n)ai[i] = read();
	int x, y;
	up(i, 1, n)
	{
		x = read(), y = read();
		addedge(x, y);
		addedge(y, x);
	}
	dfs1(1, 0, 1);
	dfs2(1, 0, 1);
	upd(i, 1, n)printf("%lld ", ans[i]);
	return 0;
}

E 旗鼓相当的对手

标签:lib   ==   ons   limits   print   tin   i++   limit   ++   

原文地址:https://www.cnblogs.com/LORDXX/p/12708194.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!