#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int n, index, balance;
vector<int> neighbour[20001];
bool vis[20001];
int subtree[20001];
void postTraverse(int i)
{
vis[i] = true;
subtree[i] = 1;
const vector<int>& v = neighbour[i];
int tmp = 0, j = 0, s = v.size(), k;
for(; j < s; ++j){
k = v[j];
if(!vis[k]){
postTraverse(k);
subtree[i] += subtree[k];
tmp = max(tmp, subtree[k]);
}
}
tmp = max(tmp, n - subtree[i]);
if(tmp < balance || tmp == balance && i < index){
balance = tmp;
index = i;
}
}
int main()
{
int test, i, x, y;
for(scanf("%d", &test); test--; ){
scanf("%d", &n);
//initialize
for(i = 1; i <= n; ++i){
neighbour[i].clear();
vis[i] = false;
}
balance = 20002;
//input edges
for(i = 1; i < n; ++i){
scanf("%d%d", &x, &y);
neighbour[x].push_back(y);
neighbour[y].push_back(x);
}
//find a leave to be an root
for(i = 1; i <= n; ++i){
if(neighbour[i].size() == 1) break;
}
//post traverse and find each subtree's nodes count, then solve the problem
postTraverse(i);
printf("%d %d\n", index, balance);
}
return 0;
}
实际上,我们并不需要找出一个leave,而且上面的vis可以用带parent的DFS省去,subtree[]可以用postTraverse返回值省去,这样我们还可以省去20001*(sizeof(int) + sizeof(bool)) ~100K的空间:
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int n, index, balance;
vector<int> neighbour[20001];
int postTraverse(int i, int pre)
{
const vector<int>& v = neighbour[i];
int tmp = 0, j = 0, s = v.size(), k, tree = 1, subtree;
for(; j < s; ++j){
k = v[j];
if(k != pre){
subtree = postTraverse(k, i);
tree += subtree;
tmp = max(tmp, subtree);
}
}
tmp = max(tmp, n - tree);
if(tmp < balance || tmp == balance && i < index){
balance = tmp;
index = i;
}
return tree;
}
int main()
{
int test, i, x, y;
for(scanf("%d", &test); test--; ){
scanf("%d", &n);
//initialize
for(i = 1; i <= n; ++i) neighbour[i].clear();
balance = 20002;
//input edges
for(i = 1; i < n; ++i){
scanf("%d%d", &x, &y);
neighbour[x].push_back(y);
neighbour[y].push_back(x);
}
//post traverse and find each subtree's nodes count, then solve the problem
postTraverse(1, 0);
printf("%d %d\n", index, balance);
}
return 0;
}
明明省去了找leave的过程,没想到运行时间却变长了,真是……