J Defense Tower

题目描述

In ICPCCamp, there are n cities and (n - 1) (bidirectional) roads between cities.
The i-th road is between the aia_iai​-th and bib_ibi​-th cities.
It is guaranteed that cities are connected.

In the i-th city, there is a defense tower with power pip_ipi​.
The tower protects all cities with a road directly connected to city i.
However, the tower in city i does not protect city i itself.

Bobo would like to destroy all defense towers.
When he tries to destroy the tower in city i, any not-destroyed tower protecting city i will deal damage whose value equals to its power to Bobo.

Find out the minimum total damage Bobo will receive if he chooses the order to destroy the towers optimally.

输入描述:

The input contains at most 30 sets. For each set:
The first line contains an integer n (1≤n≤1051 \leq n \leq 10^51≤n≤105).
The second line contains n integers p1,p2,…,pnp_1, p_2, \dots, p_np1​,p2​,…,pn​ (1≤pi≤1041 \leq p_i \leq 10^41≤pi​≤104).
The i-th of the last (n - 1) lines contains 2 integers ai,bia_i, b_iai​,bi​ (1≤ai,bi≤n1 \leq a_i, b_i \leq n1≤ai​,bi​≤n).

输出描述:

For each set, an integer denotes the minimum total damage.

示例1
输入
复制

3
1 2 3
1 2
2 3

输出
复制

3

示例2
输入
复制

3
1 100 1
1 2
2 3

输出
复制

2

贪心,优先攻击能量最高的塔, ans加上与其相连的塔的能量。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <queue>
#define mem(a, b) memset(a, b, sizeof(a))
using namespace std;

const int maxn = 1e5 + 10;
typedef long long ll;
struct node{
	int v, nex;
	node(int _v = 0, int _nex = 0)
	{
		v = _v, nex = _nex;
	}
}edge[maxn << 1];
struct V{
	int data, id;
	friend bool operator <(V x, V y)
	{
		return x.data < y.data;
	}
	V(int _data = 0, int _id = 0)
	{
		data = _data, id = _id;
	}
};
int a[maxn], head[maxn];
int n, m, cnt;
ll ans = 0;
priority_queue<V> que;

void init()
{
	cnt = 0;
	mem(a, 0), mem(head, -1);
	mem(edge, 0);
	while(!que.empty())
		que.pop();
	ans = 0;
}

void addedge(int u, int v)
{
	edge[cnt] = {v, head[u]};
	head[u] = cnt++;
}

void solve(V cur)
{
	for(int i = head[cur.id]; i != -1; i = edge[i].nex)
	{
		int v = edge[i].v;
		ans += a[v];
	}
	a[cur.id] = 0;
}

int main()
{
	while(scanf("%d", &n) != EOF)
	{
		init();
		for(int i = 1; i <= n; i++)
		{
			scanf("%d", &a[i]);
			V cur = {a[i], i};
			que.push(cur);
		}
		int x, y;
		for(int i = 1; i <= n - 1; i++)
		{
			scanf("%d%d", &x, &y);
			addedge(x, y);
			addedge(y, x);
		}
		for(int i = 1; i <= n; i++)
		{
			V cur = que.top();
			que.pop();
			solve(cur);
		}
		printf("%lld\n", ans);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值