数据结构与算法分析 C++语言描述 第四版课后练习

第一章

  1. 编写一个程序解决选择问题,令k=N/2.得到所编程序对于N的不同值的运行时间
    (语法方面很多不熟悉,所以做了相关的笔记注释)
    *选择问题是指 设有一组N个数而要确定其中第K个最大者
    考虑用两种方法实现这个问题
    一种是将N个数读进一个数组里,再通过冒泡排序,以递减顺序将数组排序,然后返回位置k上的元素
    另一种方法是先排序再比较
#include <iostream>
#include <ctime>//为了使用日期和时间相关的函数和结构,需要在 C++ 程序中引用 <ctime> 头文件
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;



void sort(vector<int> & vec)
{ // bubble sort ascending
  bool sorted = false;
  while (!sorted)
  {
	sorted = true;
	for (auto i = 1; i < vec.size(); i++)
	{
	  if (vec[i-1]> vec[i])
	  {
        swap(vec[i],vec[i-1]);//C++中的swap函数:交换函数

                                //好处:不用担心交换变量精度的缺失,无需构造临时变量,不会增加空间复杂度

                                //swap 包含在命名空间std 里面

                                //swap(a,b);(交换两个数)

                                //swap(a[i] = b[j]);(交换两个位置上的变量)

 
		sorted = false;
	  }
	}
  }
}

void sortDec(vector<int> & vec)
{ // bubble sort descending
  bool sorted = false;
  while (!sorted)
  {
	sorted = true;
	for (auto i = 1; i < vec.size(); i++)
	{
	  if (vec[i-1]< vec[i])
	  {
        swap(vec[i],vec[i-1]);
		sorted = false;
	  }
	}
  }
}

 int  select1(vector<int>  nums)
{
  int k = (nums.size()+1)/2;
  sort(nums);
  return nums[k];
}


  int  select2(const vector<int> &nums)
{
	int k = nums.size()/2;
	vector<int> topK(nums.begin(), nums.begin() + k);//c.begin();           返回指向容器 最开始位置数据的指针
                                                    //c.end();             返回指向容器最后一个数据单元+1的指针
	 
	sortDec(topK);
	for (auto i = k; i < nums.size(); i++)
	{
		if (nums[i] > topK[k-1])
		{
			for (auto j = k-2; j >=0 ; j--)
				if (nums[i] < topK[j])
				{topK[j+1] = nums[i]; break;}
				else
					topK[j+1] = topK[j];
			if (topK[0] < nums[i])
				topK[0] = nums[i];
		}
	}
	return topK[k-1];
}

int main()
{
  vector<int> nums;
  int selected;
  time_t start, end;//有四个与时间相关的类型:clock_t、time_t、size_t 和 tm。类型 clock_t、size_t 和 time_t 能够把系统时间和日期表示为某种整数。

  srand(time(NULL));//srand函数是随机数发生器的初始化函数。
                    //原型:void srand(unsigned seed);
                    //用法:它需要提供一个种子,这个种子会对应一个随机数,
  for (auto numInts = 1000; numInts<=10000; numInts+=1000)
	  // sizes 1,000, 2,000, 3,000, ...10,000
  {
        nums.resize(numInts);//resize 设置数组大小
        
        start = time(NULL);
        for (auto i = 0; i < 10; i++) // run 10 times
        {
            for (auto j = 0; j < numInts; j++)
            nums[j] = rand()%(2*numInts);//rand函数产生一组随机数,前面需要用srand函数做初始化
            selected = select2(nums); // or selected = select2(nums);
        }
        end = time(NULL);
        cout<<numInts<<"\t"<<difftime(end,start)<<endl;
  }
  return 0;
}


  1. 字谜游戏
    输入一些由字母构成的二维数组和一个单词表组成。目标是找出字谜中的单词,这些单词可能是水平、垂直或者在对角线上以任何方式放置的。
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include "matrix.h"
#include<algorithm>

using namespace std;

const int MAXROWS = 4;
const int MAXCOLS = 4;

struct Orientation
{
	Orientation() : delRow(0), delCol(0) {}
Orientation operator() (int direction)
  {
    switch (direction)
   {
	case 0 : delRow = -1; delCol = -1; break;
	case 1 : delRow = -1; delCol =  0; break;
	case 2 : delRow = -1; delCol =  1; break;
	case 3 : delRow = 0; delCol =  -1; break;
	case 4 : delRow = 0; delCol =   1; break;
	case 5 : delRow = 1; delCol =  -1; break;
	case 6 : delRow = 1; delCol =   0; break;
	case 7 : delRow = 1; delCol =   1; break;
   }
	return *this;
  }
  int delRow;
  int delCol;
};

class Puzzle
{
public:

  
  Puzzle(int numRows, int numCols ) 
	{ 
		matrix<char> temp(numRows,numCols);
		puzzle= temp;
		initPuzzle();
	}
	Puzzle(int numRows , int numCols , vector<string> wordList) : dictionary(wordList)
     { 
	    matrix<char> temp(numRows,numCols);
		  puzzle= temp;
		  initPuzzle();
	 }
	void solvePuzzle();
	void findWords(int startRow, int startCol, Orientation orient);
private:
   void initPuzzle();
   matrix<char> puzzle;
   vector<string> dictionary;
};

void Puzzle::initPuzzle()
{
  puzzle[0][0] = 't';
  puzzle[0][1] = 'h';
  puzzle[0][2] = 'i';
  puzzle[0][3] = 's';
  puzzle[1][0] = 'w';
  puzzle[1][1] = 'a';
  puzzle[1][2] = 't';
  puzzle[1][3] = 's';
  puzzle[2][0] = 'o';
  puzzle[2][1] = 'a';
  puzzle[2][2] = 'h';
  puzzle[2][3] = 'g';
  puzzle[3][0] = 'f';
  puzzle[3][1] = 'g';
  puzzle[3][2] = 'd';
  puzzle[3][3] = 't';
}

void Puzzle::solvePuzzle()
{
  Orientation orient;
  for ( auto startRow = 0; startRow < puzzle.numrows(); startRow++)
	  for ( auto startCol=0; startCol < puzzle.numcols(); startCol++)
		 for (auto i = 0; i < 8 ; i++)
			 findWords(startRow,startCol,orient(i));
}


void Puzzle::findWords(int startRow, int startCol, Orientation orient)
{
  string word ="";
 int row = startRow;
 int col = startCol;
 do
	 { 
		 word = word + puzzle[row][col];
		 if (find(dictionary.begin(), dictionary.end(), word) != dictionary.end())
			 cout<<word<<" found starting at ("<<startRow<<","<<startCol<<")\n";
		 row += orient.delRow;
		 col += orient.delCol;
	 }  while (row > -1 && col > -1 && row < puzzle.numrows() && col < puzzle.numcols());
}

int main()
{
 string diction[] = {"this", "two", "fat", "fats", "at", "wad", "ad", "hat", "that", "his","is","it","ah"} ;
 vector<string> dictionary(diction,diction+ 12);
 Puzzle puzzle(MAXROWS, MAXCOLS, dictionary);

  puzzle.solvePuzzle();

  return 0;
}

#ifndef MATRIX_H
#define MATRIX_H

#include <vector>
#include <initializer_list>
using namespace std;

template <typename Object>
class matrix
{
  public:
    // add default construction function
    matrix(){}
    matrix( int rows, int cols ) : array( rows )
    {
        for( auto & thisRow : array )
            thisRow.resize( cols );
    }

    matrix( initializer_list<vector<Object>> lst ) : array( lst.size( ) )
    {
        int i = 0;
        for( auto & v : lst )
            array[ i++ ] = std::move( v );
    }

    matrix( const vector<vector<Object>> & v ) : array{ v }
      { } 
    matrix( vector<vector<Object>> && v ) : array{ std::move( v ) }
      { }
    
    const vector<Object> & operator[]( int row ) const
      { return array[ row ]; }
    vector<Object> & operator[]( int row )
      { return array[ row ]; }

    int numrows( ) const
      { return array.size( ); }
    int numcols( ) const
      { return numrows( ) ? array[ 0 ].size( ) : 0; }
  private:
    vector<vector<Object>> array;
};

#endif
  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值