题目例如以下:
1 second
256 megabytes
standard input
standard output
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope
links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi.
The child spend vf1 + vf2 + ... + vfk energy
for removing part i where f1, f2, ..., fk are
the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000).
The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105).
Then followed m lines, each line contains two integers xi and yi,
representing a rope from part xi to
part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).
Consider all the parts are numbered from 1 to n.
Output the minimum total energy the child should spend to remove all n parts of the toy.
4 3
10 20 30 40
1 4
1 2
2 3
40
4 4
100 100 100 100
1 2
2 3
2 4
3 4
400
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
160
One of the optimal sequence of actions in the first sample is:
- First, remove part 3, cost of the action is 20.
- Then, remove part 2, cost of the action is 10.
- Next, remove part 4, cost of the action is 10.
- At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
题意:题目大意能够转化为,有很多点和很多线,当中每一个点都有一个value(后面说明),每条线连接连接两个点,这样就形成了一张图(可能包括多个子图)。
如今要求去掉全部边。求去掉全部边的cost之和的最小值。
思路分析:刚一看到这个题的时候,会非常自然的想这些边应该会依照一定顺序去掉(比如。贪心),我们仅仅要找到这个顺序。然后把全部cost加起来就是结果。
可是非常快发现,这个顺序不是那么easy找到。再细致一看题目。要求的是最小值。并没有要求得到顺序。那么。是不是存在一种方法直接找到最小值而不用求去掉边的顺序呢?答案是肯定的。
细致分析一下不难发现。当求得最小值的时候,必定是全部的边都已经去掉了。
也就是说,不管以什么样的顺序去掉这些边,得到终于的结果时全部边都已经去掉了,而我们就是仅仅要结果。去每一条边的时候,都会有一个代价值cost,必定选所连接的两个点中value最小的那个(如果一条边连接的两个点为A和B,去掉边的时候,选value(A)和value(B)中较小的作为代价值),把全部的边都去掉。全部cost加起来就是最后的答案。
有了上面的思路,代码就非常简洁了。例如以下:
#include <iostream>
#include <algorithm>
using namespace std; int main()
{
int n, m, v[1024], res = 0, x, y ;
cin >> n >> m ;
for(int i = 1; i <= n; i++)
cin >> v[i] ;
while(m--)
{
cin >> x >> y ;
res += min(v[x], v[y]) ;
}
cout << res << endl ;
return 0 ;
}
这个题目告诉我们。看似复杂的问题,背后往往都有一个简单的规律。