알고리즘 의 미소스 코드 발표 (3)

본 고 는 (전자 공업 출판사 2016 년 출판) 제4 장 코드 (P91 ~ P117) 를 집록 했다.전체 텍스트 디 렉 터 리, '45 개 알고리즘' 디 렉 터 리, '22 개 고전 문제 디 렉 터 리', 그리고 벌레 잡기 활동 에 대한 상세 한 정 보 는 다음 과 같은 링크 를 보십시오.http://blog.csdn.net/baimafujinji/article/details/50484348
부록 중의 고전 필기시험, 면접 문제 참고 답안 은 다음 과 같 습 니 다.
http://blog.csdn.net/baimafujinji/article/details/50484683
算法之美_源代码发布(3)_第1张图片
내용 소개: 비밀 알고리즘 세 계 를 탐색 하고 데이터 구조의 길 을 모색 한다.전형 적 인 문 제 를 모 아 프로 그래 밍 기법 의 취 미 를 즐 깁 니 다.구직 핫 이 슈 를 지적 하여 개업 계 의 유명 기업 의 문 을 두드리다.이 책 은 알고리즘 과 데이터 구조 라 는 화 제 를 중심 으로 현대 컴퓨터 기술 에서 자주 사용 하 는 40 여 개의 전형 적 인 알고리즘 과 역 추적 법, 분 치 법, 탐욕 법 과 동적 계획 등 알고리즘 디자인 사상 을 점차적으로 소개 했다.이 과정 에서 이 책 은 링크 (단 방향 링크, 단 방향 순환 링크 와 양 방향 순환 링크 포함), 스 택, 대기 열 (일반 대기 열 과 우선 순위 대기 열 포함), 트 리 (이 진 트 리, 하프 만 트 리, 더미, 레 드 블랙 트 리, AVL 트 리 와 사전 트 리 포함), 그림, 집합 (교차 하지 않 음 포함) 과 사전 등 상용 데이터 구 조 를 체계적으로 설명 했다.이 동시에 22 개의 전형 적 인 문제 (조세 프 링 문제, 한 노 타 문제, 8 황후 문제 와 기사 여행 문제 등 포함) 에 대한 설명 을 통 해 데이터 구조 뒤에 숨겨 진 알고리즘 원 리 를 점차적으로 밝 히 고 독자 들 이 지식 비축 을 다 지 는 데 도움 을 주 며 사고 기술 을 활성화 시 키 고 최종 적 으로 프로 그래 밍 능력 의 향상 을 방해 하 는 복잡 한 울 타 리 를 돌파 하려 고 한다.완전한 C + + 소스 코드 를 추가 하고 STL 의 각종 용 기 를 삽입 하여 소개 합 니 다.
인터넷 서점:
중국 - pub 중국 상호작용 출판 망:http://product.china-pub.com/4911922
당당 망:http://product.dangdang.com/23851244.html
아마 존:http://www.amazon.cn/%E7%AE%97%E6%B3%95%E4%B9%8B%E7%BE%8E-%E9%9A%90%E5%8C%BF%E5%9C%A8%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E8%83%8C%E5%90%8E%E7%9A%84%E5%8E%9F%E7%90%86-%E5%B7%A6%E9%A3%9E/dp/B01AGNUIE8/ref=sr_1_8?ie=UTF8&qid=1453527399&sr=8-8&keywords=%E5%B7%A6%E9%A3%9E
만약 당신 이 이 책의 독자 라면 반드시 알고리즘 학습 군 (495573865) 을 추가 하 세 요. 그 안에 더 많은 자원 이 있 습 니 다. 그리고 당신 이 책 을 읽 으 면서 만난 의문 도 제 첫 번 째 시간의 해답 을 얻 을 수 있 습 니 다.본 블 로그 에 더 많은 관심 을 가지 고 있 습 니 다. 저 는 이 책의 모든 소스 코드 를 본 블 로그 에 계속 발표 할 것 입 니 다.
P94: 링크 노드 클래스
// #ifndef _LISTNODE_H_
// #define _LISTNODE_H_

template <class T> class ListNode {
          
	T data;
	ListNode<T>*  link;

public:

	ListNode() : link(NULL){}
	ListNode (T value) : link(NULL) , data(value) {}
	~ListNode(){};
	void SetLink(ListNode<T>* next);
	void SetData(T value);
	ListNode<T>*  GetLink ();
	T& GetData ();
};

template <class T>
void ListNode<T>::SetLink(ListNode<T>* next){ 
	link = next;
}

template <class T>
void ListNode<T>::SetData(T value){
	data = value;
}

template <class T>
ListNode<T>* ListNode<T>::GetLink(){
	return link;
}

template <class T>
T&  ListNode<T>::GetData(){//        
	return data;
}

//#endif

P96: 링크 클래스
 #ifndef _LIST_H_
 #define _LIST_H_

#include "ListNode.h"

template <class T> class List{

ListNode<T>* head;
ListNode<T>* tail;

public:

	List ();
	virtual ~List ();

	bool AddTail (T value);
	bool RemoveTail ();
	bool InsertAt (int index , T value);
	bool RemoveAt (int index);

	T& GetAt (int index);
	bool IsEmpty ();
	int GetCount ();
	void RemoveAll ();

	ListNode<T>* GetHead();
	ListNode<T>* GetTail();
	ListNode<T>* GetNodeAt(int index);
	ListNode<T>* GetCur();
	ListNode<T>* TowardCur();
};

template<class T>  
List<T>::List()  
{  
    head=new ListNode<T>();  
    tail=head;  
    tail->SetLink (NULL);  
} 

template<class T>  
List<T>::~List()  
{  
    RemoveAll();  
    delete head;  
} 

template <class T> 
bool List<T> :: AddTail (T value){ 
	ListNode<T>* add = new ListNode<T> (value);
	tail->SetLink (add);    	//         ,     
	tail = tail->GetLink();		//            
	tail->SetLink (NULL); 
	if (tail != NULL)
		return true;
	else  
		return false;
}

template <class T > 
bool List< T >::InsertAt ( int index,T value ) {
	//         
	if(index > this->GetCount ()-1 || index<0 ) {  
		cout<<"A wrong position!
"; return false; } ListNode<T>* current = head; // while(index) { current = current->GetLink (); // , cur --index; } ListNode<T>* add = new ListNode<T> (value); add->SetLink (current->GetLink ()); // current->SetLink (add); if (current->GetLink () != NULL) return true; else return false; } template <class T> bool List<T>::RemoveTail() {// // RemoveAt(int index) return RemoveAt(this->GetCount()-1); } template <class T> bool List<T>::RemoveAt(int index){ // if(index > this->GetCount ()-1 || index<0){ cout<<"A wrong position!
"; return false; } // 。 ,cur //preCur ListNode<T>* cur,* curPre; cur = head; // index curPre = cur->GetLink(); // preCur cur while(index){ cur = cur->GetLink(); // , cur preCur curPre = curPre->GetLink(); --index; } // , cur if(tail == curPre) tail = cur; cur->SetLink (curPre->GetLink()); // delete curPre; if(curPre != NULL) return true; else return false; } template <class T> T& List<T>::GetAt(int index) { // value if (index > this->GetCount()-1 || index<0) { cout<<"A wrong position!
"; } ListNode<T>* cur; cur = head->GetLink(); while(index){ // ,cur cur = cur->GetLink(); --index; } return cur->GetData (); // value } template <class T> bool List< T >::IsEmpty ( ) { // return head ->GetLink()==NULL ; } template <class T> int List< T >::GetCount() { // ( ) int count = 0; // count // ( ) ListNode<T>* current = head->GetLink ( ); while(current != NULL) { ++count; current = current->GetLink ( ); // cur } return count; } template <class T> void List< T >::RemoveAll() { // ListNode<T>* cur; // , while(head->GetLink() != NULL) { cur = head->GetLink(); head->SetLink (cur->GetLink()); delete cur; } tail = head; // } template <class T> ListNode<T>* List<T>::GetHead(){// return head; } template <class T> ListNode<T>* List<T>::GetTail(){// return tail; } // index template <class T > ListNode< T >* List< T >::GetNodeAt(int index){ // if(index > this->GetCount()-1 || index<0){ cout<<"A wrong position!
"; } //handle , index 。 ListNode< T >* handle = head->GetLink(); while(index){ // index handle = handle->GetLink(); --index; } return handle; } template <class T> ListNode<T>* List<T>::GetCur(){ return cur; } template <class T> ListNode<T>* List<T>::TowardCur(){ cur = cur->GetLink(); return cur } #endif

링크 클래스 테스트 프로그램
#include "stdafx.h"
#include "List.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	List<int> list;
	for(int i = 0; i <9; i++)
		list.AddTail(i);

	cout<<list.GetCount()<<endl;

	cout<<list.GetAt(3)<<endl;

	list.RemoveAt(3);

	cout<<list.GetCount()<<endl;
	cout<<list.GetAt(3)<<endl;

	list.RemoveAll();
	cout<<list.GetCount()<<endl;

	system("PAUSE");
	return 0;
}

P101: 질서 있 는 링크 의 합병
#include "stdafx.h"
#include "List.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	//      listFirst, listSecond
	List<int> listFirst;
	List<int> listSecond;

	//     listFirst
	listFirst.AddTail(1);
	listFirst.AddTail(6);
	listFirst.AddTail(8);
	listFirst.AddTail(9);
	listFirst.AddTail(13);

	//     listSecond
	listSecond.AddTail(0);
	listSecond.AddTail(3);
	listSecond.AddTail(4);
	listSecond.AddTail(6);
	listSecond.AddTail(11);
	listSecond.AddTail(17);

	while (listSecond.GetCount() != 0){ // listSecond        
		int indexFirst = 0;
		//   listSecond            listFirst  
		// while          
		while (listSecond.GetAt(0)>listFirst.GetAt(indexFirst)){
			++indexFirst;
			//  listFirst      ,      
			if (indexFirst == listFirst.GetCount()){
				break;
			}
		}
		if (indexFirst == listFirst.GetCount()){//     listFirst    
			listFirst.AddTail(listSecond.GetAt(0));
			listSecond.RemoveAt(0);
		}
		else{//     listFirst    
			listFirst.InsertAt(indexFirst, listSecond.GetAt(0));
			listSecond.RemoveAt(0);
		}
	}

	ListNode<int> * curNode = listFirst.GetHead();
	while (curNode != listFirst.GetTail())
	{
		curNode = curNode->GetLink();
		cout << curNode->GetData() << endl;
	}
	

	system("PAUSE");

	return 0;
}

P104: 단 방향 순환 링크 클래스
//#ifndef _CIRLIST_H_
//#define _CIRLIST_H_

#include "ListNode.h"

template <class T > class CirList{

	ListNode<T>* head;
	ListNode<T>* tail;
	ListNode<T>* cur;

public :
	CirList();
	~CirList();

	bool AddTail(T value);
	void RemoveThis();
	void RemoveAll();
	void SetBegin();
	int GetCount();
	ListNode<T>* GetCur();

	bool IsEmpty();
	T GetNext();
};

template <class T >  
CirList<T>::CirList(){//       
	head = tail = new ListNode<T>; //    ,    head   tail 
	cur = head; 
	head->SetLink(head);
}

template <class T>  
CirList<T>::~CirList(){
	RemoveAll();
	delete head;
}

template <class T> 
bool CirList< T >::AddTail(T value){ //         
    //    ,     value 
	ListNode<T>* add = new ListNode<T>(value);

	tail->SetLink(add);			//        
	tail = tail->GetLink();		//  tail      
	tail->SetLink(head);		//         

	if(tail != NULL)
		return true;
	else
		return false;
}

template <class T> 
void CirList<T>::RemoveThis(){// cur        
	if(cur == head){
    	//    cur head  ,          ,    cur     
		//  。
	    cur = cur->GetLink();
	}
 
	//   preCur  cur     , node_del        
	ListNode<T>* node_del = cur;
	ListNode<T>* preCur = cur;
    //  cur     ,  preCur    
	for(int i=0;i<this->GetCount();i++){
	    preCur = preCur->GetLink();
	}

    // cur         cur    ,   cur     
	preCur->SetLink(cur->GetLink());
	delete node_del;
    //   cur        。
	cur = preCur->GetLink();
	preCur = NULL;
}

template <class T> 
void CirList< T >::RemoveAll(){//      
    SetBegin();//          
	int length = GetCount();//      
	for(int i=0;i<length;i++){ 
		RemoveThis();
	}
	cur = head;  // cur  head  
}

template <class T> 
void CirList< T >::SetBegin(){// cur  head  ,       
	cur = head;
}

template <class T> 
int CirList<T>::GetCount(){//      
	int num = 0;
	if (cur==NULL)
		this->SetBegin();
	ListNode<T>* here = cur;  //        
	while(cur->GetLink() != here){ //      ,      
		cur = cur->GetLink();
		++num;
	}
	//cur = cur->GetLink();// cur         
	cur = here;
	return 
		num;
}

template <class T> 
ListNode<T>* CirList< T >::GetCur(){//       cur
	return cur;
}

template <class T > 
bool CirList< T >::IsEmpty(){//        
	return 
		head->GetLink() == head;
}

//          ,  cur        
template <class T> 
T CirList< T >::GetNext(){
	if(cur == head){
        //      ,              
		cur = cur->GetLink();
	}
	T num = cur->GetData();	//    
	cur = cur->GetLink();	//    cur       
	return 	
	num; 
}

//#endif

P107: 조세 프 링 문제
#include "stdafx.h"
#include "CirList.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	CirList<int> jos; //        ,       
	
	//      1~15 ,     1~15   
	for(int i=1;i<16;i++){
		jos.AddTail(i);
	}

	jos.SetBegin();//         

	//         ,                
	//      14 
	int length = jos.GetCount();
	for(int i=1;i<length;i++)
	{
		for(int j=0;j<3;j++)
			jos.GetNext();
		jos.RemoveThis();
	}
	
	cout<<jos.GetNext()<<endl;

	system("PAUSE");
	return 0;
}

P108: 마술사 카드 발급 문제
#include "stdafx.h"
#include "CirList.h"
#include <iostream>
//#include "vld.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	CirList<int> poker;
	for(int i=0;i<13;i++){
		poker.AddTail(0);			//      ,  13    
	}
	cout<<poker.GetCount()<<endl;

	poker.SetBegin();
	poker.GetCur()->GetLink()->SetData(1);
	for(int i=2;i<14;i++){
		for(int j=0;j<i;j++){
			poker.GetNext();                //      
			if(poker.GetCur()->GetData() != 0){
				j--;			//         ,          
			}
		}
		poker.GetCur()->SetData(i);
	}

	poker.SetBegin();
	for(int i=0;i<13;i++){
		cout<<poker.GetNext()<<"*";
	}
	cout<<endl;

	system("PAUSE");
	return 0;
}

P109: 라틴 방진 문제
#include "stdafx.h"
#include "CirList.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	int num;
	cout<<"        (2<=N<=9):";
	cin>>num;
	CirList<int> latin;
	for(int i=1;i <= num; i++){
		latin.AddTail(i);				//      
	}

	latin.SetBegin();
	for(int i=1; i<=num; i++){
		for(int j=1; j<=num; j++){
			cout<<latin.GetNext()<<" ";	        //         
		}
		cout<<endl;
		latin.GetNext();				//             
	}

	system("PAUSE");
	return 0;
}

P111: 양 방향 순환 링크 노드 클래스
#ifndef _DOULISTNODE_H
#define _DOULISTNODE_H

template <class T > class DouListNode{

	T data;
	DouListNode<T>* link;
	DouListNode<T>* prior;

public :

	DouListNode() : link(NULL),prior(NULL){}
	DouListNode(T value) : link(NULL),prior(NULL),data(value){}
	~DouListNode(){};
	void SetLink(DouListNode<T>* next);
	void SetPrior(DouListNode<T>* pre);
	DouListNode<T>* GetLink();
	DouListNode<T>* GetPrior();
	T& GetData();
};


template <class T > 
void DouListNode< T >::SetLink( DouListNode<T>* next ){ //  link  
	link = next;
}

template <class T > 
void DouListNode< T >::SetPrior( DouListNode<T>* pre ){ //  prior  
	prior = pre;
}

//                
template <class T > 
DouListNode<T>* DouListNode< T >::GetLink(){
	return link;
}

//                
template <class T > 
DouListNode<T>* DouListNode< T >::GetPrior(){
	return prior;
}

template <class T > 
T& DouListNode< T >::GetData(){//          
	return data;
}

#endif

P114: 양 방향 순환 링크 클래스
#ifndef _DOULIST_H
#define _DOULIST_H

#include "DouListNode.h"

template <class T> class DouList{
	DouListNode<T>* head;
	DouListNode<T>* tail;
	DouListNode<T>* cur;

public :
	DouList();
 	~DouList();

	bool AddTail(T value);
	bool AddHead(T value);
	void RemoveThis(bool direction);
	void RemoveAll();
	void SetBegin();
	int GetCount();
	void TowardCur();
	void BackCur();
	DouListNode<T>* GetCur();
	DouListNode<T>* GetHead();
	DouListNode<T>* GetTail();
	void InsertAfter(T value);

	bool IsEmpty();
	T GetNext();
	T GetPrior();
};


template <class T>  
DouList<T>::DouList(){//       

	//      ,    head    tail    
	head = tail = new DouListNode<T>; 
	cur = head; 
	head->SetLink(head); //      。
	head->SetPrior(tail);
}

template <class T>  
DouList<T>::~DouList(){
	RemoveAll();
	delete head;
}

template <class T> 
bool DouList<T>::AddTail(T value){ //          

	//     ,        value   
	DouListNode<T>* add = new DouListNode<T>(value);
    tail->SetLink(add);  //               
	add->SetPrior(tail);  
	tail = tail->GetLink(); 
	tail->SetLink(head);  //           

	//              ,        
	head->SetPrior(add);
    //            ,     。
	if(tail != NULL){
		return true;
	}
	else 
		return false;
}

//                          
template <class T> 
bool DouList<T>::AddHead(T value){

    //     ,    value 
	DouListNode<T>* add = new DouListNode<T>(value);
	add->SetPrior(head);          
	add->SetLink(head->GetLink()); 

	//             add
        //  add           
	head->GetLink()->SetPrior(add);
	head->SetLink(add);      

 	//            ,        tail 
	if(tail == head){
		tail = head->GetLink();
	}
	if(add != NULL){
		return true;
	}
	else 
	    return false;
}

//   cur        ,   cur       direction   
template <class T>
void DouList<T>::RemoveThis(bool direction){
    //    cur      ,           ,    cur
    //      
	if(cur == head){
		//  direction==0,  link     cur
		if(direction == 0)
	    	cur = cur->GetLink();
		//  direction==1,  prior      cur
		if(direction == 1)
			cur = cur->GetPrior();
	}
	
 	//    preCur   nextCur。
	//preCur   cur      
	//nextCur    cur      
	DouListNode<T>* preCur = NULL;
	DouListNode<T>* nextCur = NULL;
	preCur = cur->GetPrior();        
	nextCur = cur->GetLink(); 
	DouListNode<T>* node_del = cur;
	preCur->SetLink(cur->GetLink());  // cur              
	nextCur->SetPrior(cur->GetPrior()); // cur             
 
    //  direction     cur      
    // direction ==0,  link     cur 
	if(direction == 0)
		cur = nextCur;
	// direction ==1,  prior     cur
	if(direction == 1)
		cur = preCur;
	delete node_del;
}

template <class T > 
void DouList<T>::RemoveAll(){//      (      )

	SetBegin();            //      
	int length = GetCount();  //        
	for(int i=0;i<length;i++){ //    
		RemoveThis(0);
	}
	cur = head;
}

template <class T > 
void DouList<T>::SetBegin(){// cur     
	cur = head;
}

//           (      )
template <class T > 
int DouList<T>::GetCount(){
	int num = 0;   //         
	DouListNode<T>* here = cur; // here           
	while(cur->GetLink() != here){ //    
		cur = cur->GetLink();
		++num;
	}

	cur = cur->GetLink();    //     , cur      
	//      
	return num;
}

template <class T> 
void DouList<T>::TowardCur(){// cur link    
	cur = cur->GetLink();
}

template <class T > 
void DouList<T>::BackCur(){// cur prior    
	cur = cur->GetPrior();
}

template <class T > 
DouListNode<T>* DouList<T>::GetCur(){//    cur 
	return 
		cur;
}

template <class T > DouListNode<T>* DouList<T>::GetHead(){
	return 
		head;
}

template <class T > DouListNode<T>* DouList<T>::GetTail(){
	return 
		tail;
}

//        。
template <class T > 
bool DouList<T>::IsEmpty(){
	//                
	return 
		head->GetLink() == head;
}

// cur                value     
//            ,     AddTail( T value )
template <class T > 
void DouList<T>::InsertAfter(T value){

	DouListNode<T>* add = new DouListNode<T>(value);
	DouListNode<T>* nextCur = cur->GetLink();  //  cur      
	cur->SetLink(add);    // cur             
	add->SetLink(nextCur); 
    nextCur->SetPrior(add); // cur             
	add->SetPrior(cur);   

	if(cur==tail){
		tail = cur->GetLink();
	}
}

//  cur         ,  cur  link     
template <class T > 
T DouList<T>::GetNext(){
    //  cur     ,     cur
	if(cur == head){
		cur = cur->GetLink();
	}
	T num = cur->GetData();  //          
	cur = cur->GetLink();//       cur(link   )
	return 	
		num;
}

//  cur         ,  cur  prior     
template <class T > 
T DouList<T>::GetPrior(){
	//  cur     ,     cur
	if(cur == head){
		cur = cur->GetPrior();
	}
	T num = cur->GetData(); //          
	cur = cur->GetPrior();   //       cur (prior   )
	return 
		num;
}

#endif

P115: 버 지 니 아 암호 화 문제
#include "stdafx.h"
#include "DouListNode.h"
#include "DouList.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	DouList<char> planText;
	DouList<char> cryptograph;
	DouList<int> key;
	DouList<char> trans;
	planText.SetBegin();
	planText.AddTail('y');
	planText.AddTail('o');
	planText.AddTail('u');
	planText.AddTail('a');
	planText.AddTail('r');
	planText.AddTail('e');
	planText.AddTail('i');
	planText.AddTail('n');
	planText.AddTail('d');
	planText.AddTail('a');
	planText.AddTail('n');
	planText.AddTail('g');      
	planText.AddTail('e');
	planText.AddTail('r');

	planText.SetBegin();
	cout<<"  :"<<'\t';
        for(int z=0;z<planText.GetCount();z++){
		cout<<planText.GetNext()<<" ";
	}
	cout<<endl<<endl;

       key.SetBegin(); //      
       for(int i=0;i<6;i++){
	   key.AddTail(1+rand()%9);
       }

	cout<<"  :"<<'\t';
	for(int i=0;i<key.GetCount();i++){
		cout<<key.GetNext()<<" ";
	}
	cout<<endl<<endl;

	planText.SetBegin();
	key.SetBegin();
	cryptograph.SetBegin();
	for(int i=0;i<planText.GetCount();i++){

		char c = planText.GetNext();
		int num = key.GetNext();
		if('a'<=c&&c<='z'-num)
			c=c+num;
		else if('z'-num<c&&c<='z')
			c = c+num-1-'z'+'a';
		cryptograph.AddTail(c);
	}

	cryptograph.SetBegin();
	cout<<"  :"<<'\t';
        for(int j=0; j<cryptograph.GetCount(); j++){
		cout<<cryptograph.GetNext()<< " ";
	}
	cout<<endl<<endl;

	trans.SetBegin();
	planText.SetBegin();
	key.SetBegin();
	for(int k=0; k<planText.GetCount(); k++){


		char c = cryptograph.GetNext();
		int num = key.GetNext();
		if('a'<=c-num && c-num<='z')
			c=c-num;
		else if('a'>c-num && c>='a')
			c = 'z'-('a'-c+num)+1;

		cryptograph.AddTail(c);
		trans.AddHead(c);
	}

	trans.SetBegin();
	cout<<"  :"<<'\t';
        for(int k=0;k<trans.GetCount();k++){
		cout<<trans.GetPrior()<<" ";
	}
	cout<<endl<<endl;

	system("PAUSE");
	return 0;
}

좋은 웹페이지 즐겨찾기