天天看點

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​。

輸出格式

|

luogu P2052 [NOI2011]道路修建 基礎dfs子樹節點個數好題

輸出一個整數,表示修建所有道路所需要的總費用。

輸入輸出樣例

輸入 #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​=w∗abs(聯通塊A個數−聯通塊B個數),

問删除所有邊的花費和 ( 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=1子樹個數​dfs(i)

    再dfs得過程中算答案即可

    ans += (w*1l* abs(edchls-(n-edchls)));

  4. Java代碼RE

    9

    20

    号測試點
#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;
        }
    }
}