标签:
题目链接:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11845 | Accepted: 4993 |
Description
Input
Output
Sample Input
1 7 2 6 1 2 1 4 4 5 3 7 3 1
Sample Output
1 2
题意:
问给的一棵树的重心是哪个节点以及把这个节点去掉后连通块节点个数的最大值;
思路:
dfs,找出所有节点的子树节点的个数;再找出去掉这个节点后最大连通块的节点数更新答案就好了;
AC代码:
//#include <bits/stdc++.h> #include <vector> #include <iostream> #include <queue> #include <cmath> #include <map> #include <cstring> #include <algorithm> #include <cstdio> using namespace std; #define Riep(n) for(int i=1;i<=n;i++) #define Riop(n) for(int i=0;i<n;i++) #define Rjep(n) for(int j=1;j<=n;j++) #define Rjop(n) for(int j=0;j<n;j++) #define mst(ss,b) memset(ss,b,sizeof(ss)); typedef long long LL; template<class T> void read(T&num) { char CH; bool F=false; for(CH=getchar();CH<‘0‘||CH>‘9‘;F= CH==‘-‘,CH=getchar()); for(num=0;CH>=‘0‘&&CH<=‘9‘;num=num*10+CH-‘0‘,CH=getchar()); F && (num=-num); } int stk[70], tp; template<class T> inline void print(T p) { if(!p) { puts("0"); return; } while(p) stk[++ tp] = p%10, p/=10; while(tp) putchar(stk[tp--] + ‘0‘); putchar(‘\n‘); } const LL mod=1e9+7; const double PI=acos(-1.0); const LL inf=1e18; const int N=2e5+10; const int maxn=1005; int n,son[N],ans,num; vector<int>ve[N]; void dfs(int x,int fa) { int len=ve[x].size(),mmax=0; son[x]=1; for(int i=0;i<len;i++) { int y=ve[x][i]; if(y==fa)continue; dfs(y,x); son[x]+=son[y]; if(son[y]>mmax) mmax=son[y]; } int d=max(mmax,n-son[x]); if(d<=num) { if(d==num) { if(x<ans)ans=x; } else ans=x; num=d; } } int main() { int t; read(t); while(t--) { read(n); for(int i=0;i<=n;i++)ve[i].clear(); int x,y; for(int i=1;i<n;i++) { read(x);read(y); ve[x].push_back(y); ve[y].push_back(x); } ans=1; num=50000000; dfs(1,-1); cout<<ans<<" "<<num<<"\n"; } return 0; }
poj-1655 Balancing Act(树的重心+树形dp)
标签:
原文地址:http://www.cnblogs.com/zhangchengc919/p/5616201.html