您的位置:首页 > 其它

poj1694 排序+DFS

2014-03-12 00:25 190 查看
/**
* poj1694
* 深搜+排序
* 以深搜的方式计算每一点所需的点数,计算的方法是
* 如果该点为叶子,返回1
* 否则,将其子点以子点的子点个数排序
* 从子点最多的子点开始模拟,根据需要的点和剩余的点,直到模拟出该点所需要的点的个数
* 最后返回root所需点的个数即可
*/

#include <iostream>
#include <stdlib.h>
using namespace std;

int tree[201][201];
int child_num[201];
int status[201];

int cmp ( const void *a , const void *b )
{
return *(int *)b - *(int *)a;
}

int dfs(const int idx){

const int num = child_num[idx];

if(num == 0) return 1;
int needed[num+1];
//计算各child的need值
for(int i=1;i<=num;++i){
needed[i] = dfs(tree[idx][i]);
}
//对所有need值排序
qsort(needed+1,num,sizeof(needed[0]),cmp);
/*
cout << idx << "th sorted: ";
for(int i=1;i<=num;++i){
cout << " " << needed[i];
}
cout << endl;
*/
//计算到达本点的needed值,返回
int need = 0,left = 0;
for(int i=1;i<=num;++i){
if(left<needed[i]){
need += needed[i] - left;
left = needed[i] - 1;
}

else{
left -= 1;
}
}

//cout << "idx: " << idx << " need " << need << endl;
return need;
}

int main(){
int m;

cin >> m;
while(m--){
int leaf_num;
cin >> leaf_num;
for(int i=1;i<=leaf_num;++i){
int leaf_idx;
cin >> leaf_idx;
cin >> child_num[leaf_idx];
for(int j=1;j<=child_num[leaf_idx];++j){
cin >> tree[leaf_idx][j];
}

}

int needed = 0,left = 0;

/*
for(int i=1;i<=leaf_num;++i){
for(int j=1;j<=child_num[i];++j){
cout << tree[i][j] << " ";
}
cout << endl;
}
*/
needed = dfs(1);
cout << needed << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: