Title Link: http://acm.swust.edu.cn/problem/412/
Time limit (ms): Memory Limit (KB): 65535 description has a binary tree,
Among them, the number in the circle represents the population of the inhabitants of the node. The number on the rim indicates the node number, which is now required to set up a hospital on a node, making the sum of the distances traveled by all residents minimal, and agreeing to believe that the distance between contacts is 1. If the hospital is built in:
1, the distance and =4+12+2*20+2*40=136
3, the distance and =4*2+13+20+40=81
...... Input first line an integer n, which represents the node number of the tree. (n≤100)
The next n rows each row describes the condition of a node, consisting of three integers, separated by spaces (one or more), where: The first number is the number of inhabitants, the second number is the left link, 0 is no link, and the third number is the right link. Output An integer that represents the minimum distance and. Sample Input
513 2 34 0 012 4 520 0 040 0 0 |
Sample Output
The idea of solving problems: There are only 5 lines in the legend Floyd algorithm (link) You can go in there and do it. •--, en ~ ~ To see the sample data in the title, subscript starting from 1 (the PIT) ~ ~ ~ The code is as follows:
1#include <iostream>2#include <algorithm>3#include <cstring>4 using namespacestd;5 #defineINF 0x3f3f3f6 7 intN, ptr[101], mpt[101][101], L, R;8 voidFloyd () {9 for(intK =1; K <= N; k++){Ten for(inti =1; I <= N; i++){ One for(intj =1; J <= N; J + +) AMpt[i][j] = min (Mpt[i][j], mpt[i][k] +mpt[k][j]); - } - } the } - intMain () { - intI, J, SUM, TMP; - while(Cin >>N) { +sum =inf; -memset (MPT, INF,sizeof(MPT)); + for(i =1; I <= N; i++){ ACIN >> Ptr[i] >> L >>R; atMpt[l][i] = mpt[i][l] = Mpt[r][i] = Mpt[i][r] =1; - } - Floyd (); - for(i =1; I <= N; i++){ -TMP =0; - for(j =1; J <= N; J + +) { in if(I! =j) -TMP + = mpt[i][j] *Ptr[j]; to } +sum =min (SUM, TMP); - } thecout << sum <<Endl; * } $ return 0;Panax Notoginseng}
View Code
[Swust OJ 412]--Hospital setup (Floyd algorithm)