60分求助!
查看原帖
60分求助!
259774
liyonghao楼主2022/9/25 16:09
#include<bits/stdc++.h>
using namespace std;
struct rot{
	int num,left,right,to_root,len,v;
}root[1001];
int find(int a,int l,int x,int vis){
	if (root[a].to_root == x){
		root[vis].v = 1;
		return l+1;
	}
	if (root[a].left == x or root[a].right == x){
		root[vis].v = 1;
		return l+1;
	}
	if (root[a].to_root != -1){
		return find(root[a].to_root,l+1,x,vis);
	}else return l;
}
int main(){
    int n;
    cin>>n;
    for (int i = 1;i <= n;i++){
    	cin>>root[i].num >>root[i].left >>root[i].right;
    	if (root[i].left != 0) root[root[i].left].to_root = i;
    	if (root[i].right != 0) root[root[i].right].to_root = i;
	}
	root[1].to_root = -1;
	int sum = 0, mins = 1000000000;
	for (int j = 1;j <= n;j++){
		for (int i = 1;i <= n;i++){
			root[i].v = 0;
		}
		for (int i = 1;i <= n;i++){
			root[i].len = 0;
			root[i].len = find(i,0,j,i);
	    }
	    for (int i = 1;i <= n;i++){
	    	int ln = 0;
	    	if (root[i].v == 0) ln = root[j].len + root[i].len;
	    	else if (i == j) ln = 0;
	    	else ln = root[i].len;
			sum += ln * root[i].num; 
		}
		mins = min(mins,sum);
		sum = 0;
	}
	cout<<mins;
	return 0;
}

2022/9/25 16:09
加载中...