codevs 1501 二叉樹最大寬度和高度

題目傳送門

題目描述 Description

給出一個二叉樹,輸出它的最大寬度和高度。

輸入描述 Input Description

第一行一個整數n。

下面n行每行有兩個數,對於第i行的兩個數,代表編號爲i的節點所連接的兩個左右兒子的編號。如果沒有某個兒子爲空,則爲0。

輸出描述 Output Description

輸出共一行,輸出二叉樹的最大寬度和高度,用一個空格隔開。

樣例輸入 Sample Input

5

2 3

4 5

0 0

0 0

0 0

樣例輸出 Sample Output

2 3

數據範圍及提示 Data Size & Hint

n<106 當時就把我坑到了\color{red}n<10^6\color{blue}\text{ 當時就把我坑到了}

默認第一個是根節點

以輸入的次序爲編號

2-N+1行指的是這個節點的左孩子和右孩子

注意:第二題有極端數據!
1
0 0
這題你們別想投機取巧了,給我老老實實搜!

思路

恩,老老實實搜\color{red}\text{老老實實搜}是真理。

,也可以投機取巧\color{green}\text{投機取巧}QAQ

就是每當讀到一個點就更新最大寬度和高度。

最後輸出不就得了嗎??

說一下

最大寬度要一層層地記!\color{red}\text{最大寬度要一層層地記!}

最大寬度要一層層地記!\color{blue}\text{最大寬度要一層層地記!}

最大寬度要一層層地記!\color{green}\text{最大寬度要一層層地記!}

代碼

#include<bits/stdc++.h>
using namespace std;
struct node{
	int l,r;		//左右孩子
	int deep;		//節點的深度
}a[1000005];
int k[1000005];		//當前層數(deep)的寬度
int main()
{
/*	freopen("t5.in","r",stdin);
	freopen("t5.out","w",stdout);*/
	int n;
	scanf("%d",&n);
	if(n<=0){
		printf("0 0\n");
		return 0;
	}
	int max_deep=1,max_k=1;;
	a[1].deep=1;k[1]=1;
	int x,y;
	register int i;
	for(i=1;i<=n;i++){
		cin>>x>>y;
		a[i].l=x,a[i].r=y;
		/*處理左孩子*/
		if(a[i].l!=0){
			/*深度*/
			a[a[i].l].deep=a[i].deep+1;
			max_deep=max(max_deep,a[a[i].l].deep);
			/*寬度*/
			k[a[a[i].l].deep]++;
			max_k=max(max_k,k[a[a[i].l].deep]);
		}
		/*處理右孩子*/
		if(a[i].r!=0){
			/*深度*/
			a[a[i].r].deep=a[i].deep+1;
			max_deep=max(max_deep,a[a[i].r].deep);
			/*寬度*/
			k[a[a[i].r].deep]++;
			max_k=max(max_k,k[a[a[i].r].deep]);
		}
	}
	printf("%d %d\n",max_k,max_deep);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章