您的位置:首页 > 其它

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

2014-09-30 13:38 337 查看
转载自:http://blog.csdn.net/arhaiyun/article/details/11983913

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

设计思路:

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

[cpp] view
plaincopy

/*

* 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*
;

for(int i = 0; i < n; i++)

{

map[i] = new int
;

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
;

height = new double
;

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: