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 
#include 
#include 
#include 
#include 
#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;
}

你可能感兴趣的:(贪心)