luogu P2052 [NOI2011]道路修建 基础dfs子树节点个数好题

题目描述

在 W 星球上有 nnn 个国家。为了各自国家的经济发展,他们决定在各个国家之间建设双向道路使得国家之间连通。但是每个国家的国王都很吝啬,他们只愿意修建恰好 n−1n - 1n−1 条双向道路。

每条道路的修建都要付出一定的费用,这个费用等于道路长度乘以道路两端 的国家个数之差的绝对值。例如,在下图中,虚线所示道路两端分别有 222 个、444 个国家,如果该道路长度为 111,则费用为 1×∣2−4∣=21×|2 - 4|=21×∣2−4∣=2。图中圆圈里的数字表示国家的编号。

由于国家的数量十分庞大,道路的建造方案有很多种,同时每种方案的修建费用难以用人工计算,国王们决定找人设计一个软件,对于给定的建造方案,计算出所需要的费用。请你帮助国王们设计一个这样的软件。
输入格式

输入的第一行包含一个整数 nnn,表示 W 星球上的国家的数量,国家从 111 到 nnn 编号。

接下来 n–1n–1n–1 行描述道路建设情况,其中第 iii 行包含三个整数 ai,bia_i,b_iai​,bi​ 和 cic_ici​,表示第 iii 条双向道路修建在 aia_iai​ 与 bib_ibi​ 两个国家之间,长度为 cic_ici​。
输出格式

| 在这里插入图片描述

输出一个整数,表示修建所有道路所需要的总费用。
输入输出样例
输入 #1

6
1 2 1
1 3 1
1 4 2
6 3 1
5 2 1

输出 #1

20

说明/提示

对于 100%100%100% 的数据,1≤ai,bi≤n1\leq a_i, b_i\leq n1≤ai​,bi​≤n,0≤ci≤1060\leq c_i\leq10^60≤ci​≤106,2≤n≤1062\leq n\leq 10^62≤n≤106。
测试点编号 n=n=n=
111 222
222 101010
333 100100100
444 200200200
555 500500500
666 600600600
777 800800800
888 100010001000
999 10410^4104
101010 2×1042\times 10^42×104
111111 5×1045\times 10^45×104
121212 6×1046\times 10^46×104
131313 8×1048\times 10^48×104
141414 10510^5105
151515 6×1056\times 10^56×105
161616 7×1057\times 10^57×105
171717 8×1058\times 10^58×105
181818 9×1059\times 10^59×105
19,2019,2019,20 10610^6106


题意:给定一棵树,一条边的边权w
如果删除这条边,则花费 W e d = w ∗ a b s ( 联 通 块 A 个 数 − 联 通 块 B 个 数 ) W_{ed}=w*abs(联通块A个数 - 联通块B个数) Wed=wabs(AB)
问删除所有边的花费和 ( W e d W_{ed} Wed和) 是多少?

  1. 任选一个根开始dfs
  2. dfs将返回以u为根的树的节点个数chls
  3. c h l s = 1 + ∑ i = 1 子 树 个 数 d f s ( i ) chls=1+\sum_{i=1}^{子树个数}dfs(i) chls=1+i=1dfs(i)
    再dfs得过程中算答案即可ans += (w*1l* abs(edchls-(n-edchls)));
  4. Java代码RE920号测试点
#define debug
#ifdef debug
#include <time.h>
#include "win_majiao.h"
#endif

#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>

#define MAXN ((int)1e6+7)
#define ll long long
#define int long long
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)

using namespace std;
typedef vector<vector<int> > VVI;

#define show(x...) \
	do { \
		cout << "\033[31;1m " << #x << " -> "; \
		err(x); \
	} while (0)

void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }

namespace FastIO{

	char print_f[105];
	void read() {}
	void print() { putchar('\n'); }

	template <typename T, typename... T2>
	   inline void read(T &x, T2 &... oth) {
		   x = 0;
		   char ch = getchar();
		   ll f = 1;
		   while (!isdigit(ch)) {
			   if (ch == '-') f *= -1; 
			   ch = getchar();
		   }
		   while (isdigit(ch)) {
			   x = x * 10 + ch - 48;
			   ch = getchar();
		   }
		   x *= f;
		   read(oth...);
	   }
	template <typename T, typename... T2>
	   inline void print(T x, T2... oth) {
		   ll p3=-1;
		   if(x<0) putchar('-'), x=-x;
		   do{
				print_f[++p3] = x%10 + 48;
		   } while(x/=10);
		   while(p3>=0) putchar(print_f[p3--]);
		   putchar(' ');
		   print(oth...);
	   }
} // namespace FastIO
using FastIO::print;
using FastIO::read;

int n, m, Q, K;

struct Edge {
	int v, w;
} ;

ll ans = 0;
vector<Edge> G[MAXN];

#define calc(x) ((w*1L) * (abs((x)-(n-x))))

int dfs(int u, int fa) { //dfs返回u点的子节点个数
	int chls = 0 /*表示所有子树相加的个数*/,
	    edchls = 0 /*表示当前边连接的子树的节点个数*/;
	for(auto& ed : G[u]) {
		int v = ed.v, w = ed.w;
		if(v == fa) continue ;
		edchls = dfs(v, u);
		chls += edchls;
		ans += calc(edchls);
	}
	return chls+1; //+1 因为要把u也算上
}

signed main() {
#ifdef debug
	// freopen("test.txt", "r", stdin);
	freopen("P2052_9.in", "r", stdin);
	clock_t stime = clock();
#endif
	read(n);
	int u, v, w;
	for(int i=1; i<n; i++) {
		read(u, v, w);
		G[u].push_back({v, w}),
		G[v].push_back({u, w});
	}
	dfs(1, 1);
	// show(ans);
	printf("%lld\n", ans);





#ifdef debug
	clock_t etime = clock();
	printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif 
	return 0;
}



java代码



import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

public class Main {
    public static final boolean debug = true;
    public static String INPATH = "C:\\Users\\majiao\\Desktop\\P2052_9.in",
            OUTPATH = "C:\\Users\\majiao\\Desktop\\out.txt";
    public static StreamTokenizer tok;
    public static BufferedReader cin;
    public static PrintWriter cout;

    public static long start_time = 0, out_time = 0, ans = 0;
    public static int n, m, K, Q, MAXN = (int)1e6+7, INF = 0x3f3f3f3f;

    static List<Edge> G[] = new ArrayList[MAXN];

    static class Edge {
        int v, w;
        public Edge(int v, int w) {
            this.v = v;
            this.w = w;
        }
    }

    public static int abs(int a) {
        return (a < 0) ? -a : a;
    }

    public static int dfs(int u, int fa) {
        int chls = 0, edchls = 0;
        for (Edge ed : G[u]) {
            int v = ed.v, w = ed.w;
            if(v == fa) continue ;
            edchls = dfs(v, u);
            chls += edchls;
            ans += (w*1l* abs(edchls-(n-edchls)));
        }
        return chls + 1;
    }
    public static void main(String[] args) throws IOException {
        main_init();
        if(debug) { start_time = System.currentTimeMillis(); }
        if(false) { System.setOut(new PrintStream(OUTPATH)); }

        n = read_int();
        int u, v, w;
        for(int i=1; i<=n+1; i++) G[i] = new ArrayList<>();
        for(int i=1; i<n; i++) {
            u = read_int(); v = read_int(); w = read_int();
            G[u].add(new Edge(v, w));
            G[v].add(new Edge(u, w));
        }
        dfs(1, 1);
        cout.printf("%d\n", ans);








        if(debug) {
            out_time = System.currentTimeMillis();
            cout.printf("run time : %d ms\n", out_time-start_time);
        }
        cout.flush();
    }

    public static void show(List<Object> list, Object... obj) {
        cout.printf("%s : ", obj.length>0 ? obj[0] : "");
        for(Object x : list) {
            cout.printf("[%s] ", x);
        }
        cout.printf("\n");
    }

    public static void show(Map<Object, Object> mp, Object... obj) {
        cout.printf("%s : ", obj.length>0 ? obj[0] : "");
        Set<Map.Entry<Object, Object>> entries = mp.entrySet();
        for (Map.Entry<Object, Object> en : entries) {
            cout.printf("[%s,%s] ", en.getKey(), en.getValue());
        }
        cout.printf("\n");
    }

    public static<T> void forarr(T arr[], int ...args) {
        int lef = 0, rig = arr.length - 1;
        if(args.length > 0) { lef = args[0]; rig = args[1]; }
        cout.printf(" : ");
        for( ; lef<=rig; lef++) {
            cout.printf("[%s] ", args[lef]);
        }
        cout.printf("\n");
    }

    public static void main_init() {
        try {
            if (debug) {
                cin = new BufferedReader(new InputStreamReader(
                        new FileInputStream(INPATH)));
            } else {
                cin = new BufferedReader(new InputStreamReader(System.in));
            }
            cout = new PrintWriter(new OutputStreamWriter(System.out));
//            cout = new PrintWriter(OUTPATH);
            tok = new StreamTokenizer(cin);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String next_str() {
        try {
            tok.nextToken();
            if (tok.ttype == StreamTokenizer.TT_EOF)
                return null;
            else if (tok.ttype == StreamTokenizer.TT_NUMBER) {
                return String.valueOf((int)tok.nval);
            } else if (tok.ttype == StreamTokenizer.TT_WORD) {
                return tok.sval;
            } else return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static int read_int() {
        String tmp_next_str = next_str();
        return null==tmp_next_str ? -1 : Integer.parseInt(tmp_next_str);
    }
    public static long read_long() { return Long.parseLong(next_str()); }
    public static double read_double() { return Double.parseDouble(next_str()); }
    public static BigInteger read_big() { return new BigInteger(next_str()); }
    public static BigDecimal read_dec() { return new BigDecimal(next_str()); }


    class Pair implements Comparable<Pair>{
        int fst, sec;
        public Pair() { }
        public Pair(int fst, int sec) {
            this.fst = fst;
            this.sec = sec;
        }
        @Override
        public int compareTo(Pair o) {
            return fst - o.fst == 0 ? sec - o.sec : fst - o.fst;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值