DFS深度优先搜索案例:马戏团叠罗汉

2012创新工场校园招聘的一道编程算法题:马戏团里有个叠罗汉的表演,为了便于美观,下面的人身高和体重都要大于上面的人。现在知道n个演员的身高和体重,请问最多能叠多少层?

设计思路:

首先生成一个有向图map,用连接矩阵的方式来表示。map[i][j]==1表示第i个人上面可以放第j个人。然后开始对每个人进行dfs深度搜索,这个图中不可能有环。所以对于每个人来说就是一棵树,搜索树的高度。再找出最高的高度即是答案。

 

/*
* DieLuoHan.cpp
* 马戏团里有个叠罗汉的表演,为了便于美观,下面的人身高和体重都要大于上面的人。
* 现在知道n个演员的身高和体重,请问最多能叠多少层?
* @author arhaiyun
* Date: 2013/09/24
**/

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <time.h>

using namespace std;

double* weight;
double* height;

int** map;
int n;

int maxDepth;
vector<int> bestPath;

int dfs(int index, vector<int> &path)
{
	int flag = 0; // 是否有人可以站在index上
	int depth = 0;
	
	for(int i = 0; i < n; i++)	
	{
		if(map[index][i] == 1)
		{
			flag = 1;
			vector<int> tPath;
			int tDepth = dfs(i, tPath);
			
			if(tDepth > depth)
			{
				path = tPath;
				depth = tDepth;
			}
		}
	}
	
	if(flag == 0)
	{
		path.clear();
		path.push_back(index);
		return 1;
	}
	
	path.push_back(index);
	return depth + 1;
}

void GenerateData(void)
{
	ofstream out("in.txt");
	n = 30;
	out<<n<<endl;
	
	srand(time(0));
	
	for(int i = 0; i < n; i++)
	{
		out<<rand()%50 + 50<<" ";
		out<<rand()%50 + 150<<endl;
	}
}

void GenerateMap()
{
	map = new int*[n];
	
	for(int i = 0; i < n; i++)
	{
		map[i] = new int[n];
		memset(map[i], 0, sizeof(map[i]));
	}
	
	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < n; j++)
		{
			//map[i][j] = 1表示j可以放站在i上
			if(weight[i] > weight[j] && height[i] > height[j])
			{
				map[i][j] = 1;
			}
		}
	}
}

void PrintData(void)
{
	cout<<"weight\theight"<<endl;
	for(int i = 0; i < n; i++)
	{
		cout<<weight[i]<<"\t"<<height[i]<<endl;
	}
}


int main(void)
{
	GenerateData();
	//fstream input("in.txt", ios::in);
	freopen("in.txt", "r", stdin);
	
	cin>>n;
	weight = new double[n];
	height = new double[n];
	
	for(int i = 0; i < n; i++)	
	{
		cin>>weight[i]>>height[i];
	}

	PrintData();
	GenerateMap();
	
	int depth = 0;
	
	for(int i = 0; i < n; i++)
	{
		vector<int> tPath;
		
		int tDepth = dfs(i, tPath);
		if(tDepth > depth)
		{
			bestPath = tPath;
			depth = tDepth;
		}
	}
	
	cout<<"Max layers:"<<depth<<endl;
	
	for(int i = 0; i < (int)bestPath.size(); i++)
	{
		cout<<height[bestPath[i]]<<" "<<weight[bestPath[i]]<<endl;
	}

	for(int i = 0; i < n; i++)
	{
		delete[] map[i];
	}
	delete[] map;

	delete[] weight;
	delete[] height;

	system("pause");
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值