其他分享
首页 > 其他分享> > 1155

1155

作者:互联网

纪念一下我写出来的第一个dfs

#include <bits/stdc++.h>
using namespace std;//完全二叉树用数组存储
int m,k,heap[1001];
bool maxheap(){
	for(int i=1;i<=m/2;i++){
		if(2*i<=m){
			if(heap[2*i]>heap[i])return false;
		}if(2*i+1<=m){
			if(heap[2*i+1]>heap[i])return false;
		}
	}
	return true;
}
bool minheap(){
	for(int i=1;i<=m/2;i++){
		if(2*i<=m){
			if(heap[2*i]<heap[i])return false;
		}if(2*i+1<=m){
			if(heap[2*i+1]<heap[i])return false;
		}
	}return true;
}int cnt=0;vector<int>vec;
void dfs(int root){
	if(root>m)return ;
	vec.push_back(heap[root]);
	if(2*root>m&&2*root+1>m){
		for(int i=0;i<vec.size();i++)
			printf("%s%d",i==0?"":" ",vec[i]);
			printf("\n");
	}
	dfs(2*root+1);
	dfs(2*root);
	vec.pop_back();
}
int main()
{
	int root;cin>>m;
	cnt=0;
		for(int i=1;i<=m;i++)
			scanf("%d",&heap[i]);
			dfs(1);
			if(maxheap())printf("Max Heap\n");
			else if(minheap())printf("Min Heap\n");
			else printf("Not Heap\n");
		
	
	return 0;
}

标签:false,1155,dfs,int,bool,return,root
来源: https://blog.csdn.net/ilikecarrots/article/details/87901519