poj1655 Balancing Act 求树的重心
直接dfs就可以了,记忆化都不需要。。复杂度o(N)
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<vector> #define REP(i,a,b) for(int i=a;i<=b;i++) #define MS0(a) memset(a,0,sizeof(a)) using namespace std; typedef long long ll; const int maxn=1000100; const int INF=1e9+10; int n; vector<int> G[maxn]; int u,v; int point,balance; int dfs(int u,int f) { int cnt=1,balance1=0; for(int i=0;i<G[u].size();i++){ int v=G[u][i]; if(v==f) continue; int tmp=dfs(v,u); cnt+=tmp; balance1=max(balance1,tmp); } balance1=max(balance1,n-cnt); if(balance1<balance){ balance=balance1; point=u; } return cnt; } int main() { freopen("in.txt","r",stdin); int T;cin>>T; while(T--){ scanf("%d",&n); REP(i,1,n) G[i].clear(); REP(i,1,n-1){ scanf("%d%d",&u,&v); G[u].push_back(v); G[v].push_back(u); } point=1,balance=INF; dfs(1,0); printf("%d %d\n",point,balance); } return 0; }
没有AC不了的题,只有不努力的ACMER!