日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

【HDU - 6567】Cotree(树形dp,思维)

發(fā)布時(shí)間:2023/12/10 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【HDU - 6567】Cotree(树形dp,思维) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題干:

Avin has two trees which are not connected. He asks you to add an edge between them to make them connected while minimizing the function?∑ni=1∑nj=i+1dis(i,j)∑i=1n∑j=i+1ndis(i,j), where?dis(i,j)dis(i,j)?represents the number of edges of the path from?ii?to?jj. He is happy with only the function value.

Input

The first line contains a number?n?(2<=n<=100000)n?(2<=n<=100000). In each of the following?n?2n?2?lines, there are two numbers?uu?and?vv, meaning that there is an edge between?uuand?vv. The input is guaranteed to contain exactly two trees.

Output

Just print the minimum function value.

Sample Input

3 1 2

Sample Output

4

題目大意:

給定n個(gè)點(diǎn)和n-2條邊,已知這是兩棵樹(shù)。讓你在每棵樹(shù)中任選一點(diǎn),加一條邊,使得變成一棵樹(shù),要求使得樹(shù)中任意兩點(diǎn)的距離之和最小,求出這個(gè)最小值。

解題報(bào)告:

以邊為單位統(tǒng)計(jì)貢獻(xiàn)就行了,注意最后統(tǒng)計(jì)的是任意兩點(diǎn)之間的距離和,而不是第一棵樹(shù)的任意一點(diǎn)和第二棵樹(shù)的任意一點(diǎn)之間的距離和。

AC代碼:

#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<stack> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; int n; vector<int> vv[MAX]; int f[MAX]; ll dp[MAX],size[MAX]; int getf(int v) {return f[v] == v ? v : f[v] = getf(f[v]); } void dfs1(int cur,int fa) {int up = vv[cur].size();size[cur] = 1;for(int i = 0; i<up; i++) {int v = vv[cur][i];if(v == fa) continue;dfs1(v,cur);size[cur] += size[v];dp[cur] += dp[v] + size[v];} } void dfs2(int cur,int fa,ll allsize) {int up = vv[cur].size();for(int i = 0; i<up; i++) {int v = vv[cur][i];if(v == fa) continue;dp[v] += dp[cur]-dp[v]-2*size[v]+allsize; // dp[v] += size[cur] - size[v] + dp[cur] - dp[v];大錯(cuò)特錯(cuò)啊,可以再想想dfs2(v,cur,allsize);} } int main() {cin>>n;for(int i = 1; i<=n; i++) f[i] = i;for(int u,v,i = 1; i<=n-2; i++) {scanf("%d%d",&u,&v);vv[u].pb(v),vv[v].pb(u);u=getf(u),v=getf(v);f[v] = u;}vector<int> rt;for(int i = 1; i<=n; i++) {if(f[i] == i) rt.pb(i);}dfs1(rt[0],-1);dfs2(rt[0],-1,size[rt[0]]);dfs1(rt[1],-1);dfs2(rt[1],-1,size[rt[1]]);ll mi0 = 1e18,mi1=1e18;ll tmp = 0; for(int i = 1; i<=n; i++) {if(getf(f[i]) == getf(f[rt[0]])) mi0 = min(mi0,dp[i]);else mi1 = min(mi1,dp[i]);tmp += dp[i];}printf("%lld\n",tmp/2 + size[rt[0]]*size[rt[1]]+mi0*size[rt[1]]+mi1*size[rt[0]]);return 0 ; }

?

總結(jié)

以上是生活随笔為你收集整理的【HDU - 6567】Cotree(树形dp,思维)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。