数据结构与算法分析C版答案.docx

上传人:b****5 文档编号:6100962 上传时间:2023-01-03 格式:DOCX 页数:43 大小:30KB
下载 相关 举报
数据结构与算法分析C版答案.docx_第1页
第1页 / 共43页
数据结构与算法分析C版答案.docx_第2页
第2页 / 共43页
数据结构与算法分析C版答案.docx_第3页
第3页 / 共43页
数据结构与算法分析C版答案.docx_第4页
第4页 / 共43页
数据结构与算法分析C版答案.docx_第5页
第5页 / 共43页
点击查看更多>>
下载资源
资源描述

数据结构与算法分析C版答案.docx

《数据结构与算法分析C版答案.docx》由会员分享,可在线阅读,更多相关《数据结构与算法分析C版答案.docx(43页珍藏版)》请在冰豆网上搜索。

数据结构与算法分析C版答案.docx

数据结构与算法分析C版答案

ModifiedbyJEEPonDecember26th,2020.

 

数据结构与算法分析C版答案

DataStructuresandAlgorithm习题答案

Prefaceii

1DataStructuresandAlgorithms1

2MathematicalPreliminaries5

3AlgorithmAnalysis17

4Lists,Stacks,andQueues23

5BinaryTrees32

6GeneralTrees40

7InternalSorting46

8FileProcessingandExternalSorting54

9Searching58

10Indexing64

11Graphs69

12ListsandArraysRevisited76

13AdvancedTreeStructures82

i

iiContents

14AnalysisTechniques88

15LimitstoComputation94

Preface

ContainedhereinarethesolutionstoallexercisesfromthetextbookAPractical

IntroductiontoDataStructuresandAlgorithmAnalysis,2ndedition.

FormostoftheproblemsrequiringanalgorithmIhavegivenactualcode.In

afewcasesIhavepresentedpseudocode.Pleasebeawarethatthecodepresented

inthismanualhasnotactuallybeencompiledandtested.WhileIbelievethealgorithms

tobeessentiallycorrect,theremaybeerrorsinsyntaxaswellassemantics.

Mostimportantly,thesesolutionsprovideaguidetotheinstructorastotheintended

answer,ratherthanusableprograms.

1

DataStructuresandAlgorithms

Instructor’snote:

Unliketheotherchapters,manyofthequestionsinthischapter

arenotreallysuitableforgradedwork.Thequestionsaremainlyintendedtoget

studentsthinkingaboutdatastructuresissues.

Thisquestiondoesnothaveaspecificrightanswer,providedthestudent

keepstothespiritofthequestion.Studentsmayhavetroublewiththeconcept

of“operations.”

Thisexerciseasksthestudenttoexpandontheirconceptofanintegerrepresentation.

AgoodanswerisdescribedbyProject,whereasingly-linked

listissuggested.Themoststraightforwardimplementationstoreseachdigit

initsownlistnode,withdigitsstoredinreverseorder.Additionandmultiplication

areimplementedbywhatamountstograde-schoolarithmetic.For

addition,simplymarchdowninparallelthroughthetwolistsrepresenting

theoperands,ateachdigitappendingtoanewlisttheappropriatepartial

sumandbringingforwardacarrybitasnecessary.Formultiplication,combine

theadditionfunctionwithanewfunctionthatmultipliesasingledigit

byaninteger.Exponentiationcanbedoneeitherbyrepeatedmultiplication

(notreallypractical)orbythetraditionalΘ(logn)-timealgorithmbasedon

thebinaryrepresentationoftheexponent.Discoveringthisfasteralgorithm

willbebeyondthereachofmoststudents,soshouldnotberequired.

AsampleADTforcharacterstringsmightlookasfollows(withthenormal

interpretationofthefunctionnamesassumed).

Chap.1DataStructuresandAlgorithms

Some

InC++,thisis1

fors1

intstrcmp(Strings1,Strings2)

One’scomplimentstoresthebinaryrepresentationofpositivenumbers,and

storesthebinaryrepresentationofanegativenumberwiththebitsinverted.

Two’scomplimentisthesame,exceptthatanegativenumberhasitsbits

invertedandthenoneisadded(forreasonsofefficiencyinhardwareimplementation).

ThisrepresentationisthephysicalimplementationofanADT

definedbythenormalarithmeticoperations,declarations,andothersupport

givenbytheprogramminglanguageforintegers.

AnADTfortwo-dimensionalarraysmightlookasfollows.

Matrixadd(MatrixM1,MatrixM2);

Matrixmultiply(MatrixM1,MatrixM2);

Matrixtranspose(MatrixM1);

voidsetvalue(MatrixM1,introw,intcol,intval);

intgetvalue(MatrixM1,introw,intcol);

Listgetrow(MatrixM1,introw);

OneimplementationforthesparsematrixisdescribedinSectionAnotherimplementation

isahashtablewhosesearchkeyisaconcatenationofthematrixcoordinates.

Everyproblemcertainlydoesnothaveanalgorithm.AsdiscussedinChapter15,

thereareanumberofreasonswhythismightbethecase.Someproblemsdon’t

haveasufficientlycleardefinition.Someproblems,suchasthehaltingproblem,

arenon-computable.Forsomeproblems,suchasonetypicallystudiedbyartificial

intelligenceresearchers,wesimplydon’tknowasolution.

Wemustassumethatby“algorithm”wemeansomethingcomposedofstepsare

ofanaturethattheycanbeperformedbyacomputer.Ifso,thananyalgorithm

canbeexpressedinC++.Inparticular,ifanalgorithmcanbeexpressedinany

othercomputerprogramminglanguage,thenitcanbeexpressedinC++,sinceall

(sufficientlygeneral)computerprogramminglanguagescomputethesamesetof

functions.

Theprimitiveoperationsare

(1)addingnewwordstothedictionaryand

(2)searching

thedictionaryforagivenword.Typically,dictionaryaccessinvolvessomesort

ofpre-processingofthewordtoarriveatthe“root”oftheword.

Atwentypagedocument(singlespaced)islikelytocontainabout20,000words.A

usermaybewillingtowaitafewsecondsbetweenindividual“hits”ofmis-spelled

words,orperhapsuptoaminuteforthewholedocumenttobeprocessed.This

meansthatacheckforanindividualwordcantakeabout10-20ms.Userswill

typicallyinsertindividualwordsintothedictionaryinteractively,sothisprocesscan

takeacoupleofseconds.Thus,searchmustbemuchmoreefficientthaninsertion.

Theusershouldbeabletofindacitybasedonavarietyofattributes(name,location,

perhapscharacteristicssuchaspopulationsize).Theusershouldalsobeabletoinsert

anddeletecities.Thesearethefundamentaloperationsofanydatabasesystem:

search,insertionanddeletion.

Areasonabledatabasehasatimeconstraintthatwillsatisfythepatienceofatypical

user.Foraninsert,delete,orexactmatchquery,afewsecondsissatisfactory.Ifthe

databaseismeanttosupportrangequeriesandmassdeletions,theentireoperation

maybeallowedtotakelonger,perhapsontheorderofaminute.However,thetime

spenttoprocessindividualcitieswithintherangemustbeappropriatelyreduced.In

practice,thedatarepresentationwillneedtobesuchthatitaccommodatesefficient

processingtomeetthesetimeconstraints.Inparticular,itmaybenecessarytosupport

operationsthatprocessrangequeriesefficientlybyprocessingallcitiesinthe

rangeasabatch,ratherthanasaseriesofoperationsonindividualcities.

Studentsatthislevelarelikelyalreadyfamiliarwithbinarysearch.Thus,they

shouldtypicallyrespondwithsequentialsearchandbinarysearch.Binarysearch

shouldbedescribedasbettersinceittypicallyneedstomakefewercomparisons

(andthusislikelytobemuchfaster).

TheanswertothisquestionisdiscussedinChapter8.Typicalmeasuresofcost

willbenumberofcomparisonsandnumberofswaps.Testsshouldincluderunning

timingsonsorted,reversesorted,andrandomlistsofvarioussizes.

Chap.1DataStructuresandAlgorithms

Thefirstpartiseasywiththehint,butthesecondpartisratherdifficulttodowithout

astack.

a)boolcheckstring(stringS){

intcount=0;

for(inti=0;i

if(S[i]==’(’)count++;

if(S[i]==’)’){

if(count==0)returnFALSE;

count--;

}

}

if(count==0)returnTRUE;

elsereturnFALSE;

}

b)intcheckstring(StringStr){

StackS;

intcount=0;

for(inti=0;i

if(S[i]==’(’)

(i);

if(S[i]==’)’){

if())returni;

();

}

}

if())return-1;

elsereturn();

}

AnswerstothisquestionarediscussedinSection.

Thisissomewhatdifferentfromwritingsortingalgorithmsforacomputer,since

person’s“workingspace”istypicallylimited,asistheirabilitytophysicallymanipulate

thepiecesofpaper.Nonetheless,manyofthecommonsortingalgorithmshave

theiranalogstosolutionsforthisproblem.Mosttypicalanswerswillbeinsertion

sort,variationsonmergesort,andvariationsonbinsort.

AnswerstothisquestionarediscussedinChapter8.

2

MathematicalPreliminaries

(a)Notreflexiveifthesethasanymembers.Onecouldargueitissymmetric,

antisymmetric,andtransitive,sincenoelementviolateanyof

therules.

(b)

Notreflexive(foranyfemale).Notsymmetric(considerabrotherand

sister).Notantisymmetric(considertwobrothers).Transitive(forany

3brothers).

(c)

Notreflexive.Notsymmetric,andisantisymmetric.Nottransitive

(onlygoesonelevel).

(d)

Notreflexive(fornearlyallnumbers).Symmetricsincea

+b

=b

+a,

sonotantisymmetric.Transitive,butvacuouslyso(therecanbeno

distincta,b,andc

whereaRb

andbRc).

(e)

Reflexive.Symmetric,sonotantisymmetric.Transitive(butsortof

vacuous).

(f)

Reflexive–checkallthecases.Sinceitisonlytruewhenx

=y,it

istechnicallysymmetricandantisymmetric,butrathervacuous.Likewise,

itistechnicallytransitive,butvacuous.

Ingeneral,provethatsomethingisanequivalencerelationbyprovingthatit

isreflexive,symmetric,andtransitive.

(a)

Thisisanequivalencethateffectivelysplitstheintegersintooddand

evensets.Itisreflexive(x

+x

isevenforanyintegerx),symmetric

(sincex

+y

=y

+x)andtransitive(sinceyouarealwaysaddingtwo

oddorevennumbersforanysatisfactorya,b,andc).

(b)

Thisisnotanequivalence.Tobeginwith,itisnotreflexiveforany

integer.

(c)

Thisisanequivalencethatdividesthenon-zerorationalnumbersinto

positiveandnegative.Itisreflexivesincex

˙

x>

0.Itissymmetricsince

xy˙

=yx˙.Itistransitivesinceanytwomembersofthegivenclass

satisfytherelationship.

5

Chap.2MathematicalPreliminaries

(d)

Thisisnotanequivalancerelationsinc

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 求职职场 > 简历

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1