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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【牛客 - 157B】凤凰(树上并查集,dfs)

發布時間:2023/12/10 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【牛客 - 157B】凤凰(树上并查集,dfs) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題干:

鏈接:https://ac.nowcoder.com/acm/contest/157/B
來源:牛客網

題目描述

????傳說,鳳凰是百鳥之王。有一天,鳳凰要召開百鳥大會,百鳥國是一個由n個節點組成的樹,每個節點有一只鳥,開會的節點定在1號節點。每只鳥可以花費1s通過一條邊,由于每根樹枝(邊)的載重有限,只允許一只鳥同時通過。作為會議的策劃師,HtBest想知道百鳥國的所有鳥在1點集合最少需要多少秒。

輸入描述:

第一行有一個正整數n,表示百鳥國節點個數。 接下來n-1行,第i行兩個正整數ai,bi用空格隔開,表示樹上節點ai,bi之間有一條邊。

輸出描述:

第一行一個整數,表示集合最少需要的時間。

示例1

輸入

復制

3 1 2 2 3

輸出

復制

2

示例2

輸入

復制

3 1 2 1 3

輸出

復制

1

示例3

輸入

復制

4 1 2 2 3 2 4

輸出

復制

3

備注:

對于100%的測試數據: 1 ≤ n ≤ 1000000 數據量較大,注意使用更快的輸入輸出方式。

解題報告:

? ?這題用dfs會超時我也不知道為什么。O(n)的復雜度。。。

AC代碼:

#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair using namespace std; const int MAX = 2e6 + 5; int n,m; vector<int> vv[MAX]; int dfs(int cur,int rt) {int res = 1;for(auto& v : vv[cur]) {if(v == rt) continue;res += dfs(v,cur);}return res; } inline int read() {char ch = getchar(); int x = 0, f = 1;while(ch < '0' || ch > '9') {if(ch == '-') f = -1;ch = getchar();} while('0' <= ch && ch <= '9') {x = x * 10 + ch - '0';ch = getchar();} return x * f; } int f[MAX],num[MAX]; int getf(int v) {return f[v] == v ? v : f[v] = getf(f[v]); } bool merge(int u,int v) {int t1 = getf(u);int t2 = getf(v);if(t1 == t2) {return 1;}else {f[t2] = t1;num[t1] += num[t2];return 0 ;} } int main() {cin>>n;for(int i = 1; i<=n; i++) f[i] = i,num[i]=1;for(int a,b,i = 1; i<=n-1; i++) {a=read();b=read();if(a!=1 && b!=1) merge(a,b);}int ans = 0 ;for(int i = 1; i<=n; i++) {ans = max(ans,num[getf(i)]);}cout << ans;return 0; }

TLE代碼:

#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair using namespace std; const int MAX = 2e6 + 5; int n,m; vector<int> vv[MAX]; int dfs(int cur,int rt) {int res = 1;for(auto v : vv[cur]) {if(v == rt) continue;res += dfs(v,cur);}return res; } int main() {cin>>n;for(int a,b,i = 1; i<=n-1; i++) {scanf("%d%d",&a,&b);vv[a].pb(b);vv[b].pb(a);}int ans = 0 ;for(auto v : vv[1]) {ans = max(ans,dfs(v,1));}cout << ans;return 0; }

?

總結

以上是生活随笔為你收集整理的【牛客 - 157B】凤凰(树上并查集,dfs)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。