基础算法递推法Recursive algorithm.docx
《基础算法递推法Recursive algorithm.docx》由会员分享,可在线阅读,更多相关《基础算法递推法Recursive algorithm.docx(9页珍藏版)》请在冰豆网上搜索。
![基础算法递推法Recursive algorithm.docx](https://file1.bdocx.com/fileroot1/2022-11/27/005dae72-00b9-46fe-9757-d81bd34082b2/005dae72-00b9-46fe-9757-d81bd34082b21.gif)
基础算法递推法Recursivealgorithm
基础算法-递推法(Recursivealgorithm)
Thereisaclassofquestions,thechangesbetweeneverytwoadjacentitemshaveacertainregularity,wecanputthisruleintosimplerecursiveformulaasfollows:
Fn=g(Fn-1)
Thisisthenumberinthesequence,establishtherelationshipbetweentheantecedentandconsequent,thenfromtheinitialcondition(orend)tostart,stepbystepaccordingtotherecursiverelationofrecursion,untilthefinalresultsobtained(orinitialvalue).Manyprogramsaresolvedinthisway.Ifatest,ifwecanfindarelationshipbeforeandafteraclearanditsinitialcondition(endresult),liketosolvetheproblem,letthecomputercalculationisastepbystep,letthecomputerdothehigh-speedrepetitiveoperation,canreallyplaythe"bestuse"effect.
Recursive,backwardpushandpushtwoforms.Generalanalysisidea:
IfsolvingconditionF1
Thenbegin{inverted}
Theproblem(orrecursiverelation)todeterminethefinalresultofFa;
ForinvertedformulaFi-1=g'(Fi);
I=n{{start}fromthefinalresultFn
WhilecurrentresultsFinoninitialvaluesF1doareinvertedbyFi-1=g(F1);
OutputpushbackresultsF1andpushbackwardprocess;
End{then}
Else,begin{,push,}
Theproblem(orforwardrelationship)todeterminetheinitialvalueofF1(boundaryconditions);
FindtheforwardrelationformulaF1=g(Fi-1);
I=1;{proceedfromtheboundaryconditionF1{}}
TheresultsofFiwhiledoFnnonfinalresultsbyFi=g(Fi-1)CISpushback;
TheoutputoftheFnresultsandthepushingprocess;
End;{else}
I.backwardpushingmethod
Thepushdownmethod,isnotintheinitialvalueofthecase,bysomerecursiverelationsandinformedthesolutionoftheproblemorgoal,andthenpushdownover,inferitsinitialconditions.Becausetheoperationsofsuchproblemsaremappedonebyone,therecurrenceformulacanbeanalyzed.Then,fromthissolutionorgoal,takethepushbacksection,stepbystepintotheinitialstatementoftheproblem.
Herearesomeexamples.
[1]oilstoragepoint
Aheavytruckwantstocross1000kilometersofdesert,andthetruckuses1liters/kmoffuel,andthetotalcapacityofthetruckis500liters.Obviously,atrucknevergetsthroughthedesertatonetime.Asaresult,driversmusttrytosetupseveralstoragepointsalongthewaysothattruckscancrossthedesertsmoothly.Howcandriversbuildtheseoilstoragepoints?
Howmuchoilshouldbestoredateachpointtomakethetruckpassthroughthedesertattheexpenseofleastoil?
Algorithmanalysis:
Oilstoragepointnumbercalculationprogramandprinttheestablishment,theoilstoragefromtheedgeofthedesertofthedistanceandthestorageofoil.
No.Distance(K.M.)oil(litre)
1,X,X,X,X
2,X,X,X,X
3,X,X,X,X
........
Setdis[i]asthedistancebetweentheIoilstoragepointandtheendpoint(i=0);
Oil[i]isthestoragequantityoftheIoilstoragepoints;
Wecansolvethisproblembythebackpushingmethod.Fromtheendtothebeginningofthepushdown,onebyonetofindthelocationofeachoilstoragepointandtheamountofoilstorage.
Butwhenthereturnpointareshown:
ThestrategyofpushingbackfromtheoilstoragepointItotheoilstoragepointi+1isthatthetruckmovesbackandforthbetweenpointIandpointi+1.Eachtimethetruckreturnstoi+1,itrunsoutof500litersofgasoline,andeachtimeitleavesthei+1,ithastohold500litersofgasoline.ThedistancebetweenthetwopointsmustsatisfytheIpointi*500gasolinefuelstorageatleasttherequirements(0<=i<=n-1).Specifically,thefirstoilstoragepointi=1shouldbe500kmfromtheterminali=0andstore500litresofgasolineattheendofthetanksothatthetruckcanreachtheterminali=0ati=1.Thatistosay
Dis[1]=500oil[1]=500;
Inordertoi=1storageof500litersofgasoline,cartoi=1truckatleastfromi=2opentwofulloil.Sothei=2storesatleast2*500litersofgasoline,oroil[2]=500*2=1000.Inaddition,combinedwithareturnfromi=1toi=2atano-load,thetotalround-trip3times.Thethreeroundtripusesonly500litresoffuelatthemostprovinciallevel.Thatis,d12=500/3km
Dis[2]=dis[1]+d12=dis[1]+500/3
Inordertostore1000litersofgasolineati=2,thetruckwilldriveatleastthreefullloadvehiclesfromi=3toi=2.
Withi=3,atleast3*500litersofgasoline,oroil[3]=500*3=1500.Plusi=2toi=3atthetworeturnemptycar,total5times.Thefuelmileageshouldalsobe500liters,ord23=500/5,
Dis[3]=dis[2]+d23=dis[2]+500/5;
Andsoon,inordertostorek*500litersofgasolineatthei=k,thetruckwilldriveatleastkfullloadvehiclesfromi=k+1toi=k,i.e.
Oil[k+1]=[k+1]*500=oil[k]+500,plusthek-1returnspacefromi=ktoi=k+1,total2k-1times.This2k-1timesthetotalfuelconsumption,accordingtotheprovincialminimumrequirementof500liters,thatis
DK,k+1=500/(2k-1)
Dis[k+1]=dis[k]+dk,k+1
=dis[k]+500/(2k-1);
Finally,thedistancefromi=ntothestartingpointis1000-dis[n],oil[n]=500*n.Inordertoobtainn*500litersofpetroltruckati=n,atleastfromthestartingpointn+1fullcartoi=n,andreturnedfromthei=npointofNtimesthetotalreturnempty,2n+1times,2n+1timesthetotalfuelconsumptionshouldbejustfor(1000-dis[n])*(2n+1),isthestartingpointforoilreservoir(oil[n]+1000-dis[n])*(2n+1).
Here'stheprogramcode:
Programoil_lib;
Var
K:
integer;{oilpointpositionserialnumber}
D,{thedistancefromthecumulativefinishtothecurrentpointofoilstorage
D1:
real;{i=ntostartpointdistance}
Oil,dis:
array[1..10],of,real;
I:
integer;{auxiliaryvariable}
Begin
Writeln('NO.','distance(K.M):
30,'oil(1.):
80);
K:
=1;
D:
=500;{startati=1,pushbackwardtothestartpoint}
Dis[1]:
=500;
Oil[1]:
=500;
Repeat
K:
=k+1;
D:
=d+500/(2*k-1);
Dis[k]:
=d;
Oil[k]:
=oil[k-1]+500;
Untild>=1000;
Dis[k]:
=1000;{startingpointtoenddistancevalue}
D1:
=1000-dis[k-1]={i=ntostartpoint}
Oil[k]:
=d1*(2*k+1)+oil[k-1];{startpointoilstorage}
Fori:
=0tokdo{startfromthestartpoint,printthestartingpointtothedistancefromthecurrentoilstoragepointandtheamountofoilstorage}
Writeln(I,1000-dis[k-i]:
30,oil[k-i]:
80);
End.{main}
ConvertstotheClanguageprogramasfollows:
#include
Void,main()
{
Intk;/**/oilstoragelocationnumber
FloatD,D1/*d:
;thecumulativeendpointtothecurrentoilstoragepointdistance,d1:
i=ndistancetothestartingpoint.
Float,oil[10],dis[10];
Inti;
Printf("NO.distance(K.M.)\toil(L.)\n");
K=1;
D=500;/**/startingpointbegantopushdownfromi=1
Dis[1]=500;
Oil[1]=500;
Do{
K=k+1;
D=d+500/(2*k-1);
Dis[k]=d;
Oil[k]=oil[k-1]+500;
}while((d>=1000));
Dis[k]=1000;/*thestartpointtotheendpointofthedistance.
D1=1000-dis[k-1];/*fori=ntothestartingpointofthedistance.
Oil[k]=d1*(2*k+1)+oil[k-1];/*forstartingpointofoilreservoir.
For(i=0;iPrintf("%d\t%f\t%f\t\n","I","1000-dis[k-i]","oil[k-i]");
}
Practicalalgorithm(basicalgorithm-recursivemethod-02)
Dateofissue:
April10,2003provenance:
analysisandprogrammingofpracticalalgorithms.Author:
Clanguagehomecollation,1317readershavereadthisarticle
Forwardpushingmethod
Thereverseprocessofthepushdownmethodispushedalong,startingfromtheboundaryconditions,therecursiverelationslaunchedbythelattervalue,valueaccordingtotherecursiveformulaofrelaunch,followedbyconsequentvalue......recursive,untiltheproblemfromtheinitialstatementtomoveforwardtothesolutionofthisproblem.
Realnumbersequence:
arealnumberserieswithNitemsknown
Ai=(ai-1-ai+1)/2+d,(1
ThekeyboardinputsareN,D,A1,an,m,andoutputam
Noerrorisrequiredforinputdata.
Algorithmanalysis:
Analysisoftheproblem,theformula:
Ai=(Ai-1-Ai+1)/2+d(1
Makeathoroughstudyanddiscussitslawofdigitaltransformation.Otherwise,therewillbenowaytostart.
MakeX=A2s2[i]=(PI,Qi),
Ri)representsAi=PiX+QiD+RiA1
Wecanaccordingto
Ai=Ai-2-2Ai-1+2D
=PiX+QiD+RiA1
Formularelease
PiX+QiD+RiA1=(Pi-2-2Pi-1),X+(Qi-2-2Qi-1+2),D+(Ri-2-2Ri-1),A1
ComparingthecoefficientsofX,DandA1attheendsofanequalsign
Pi=Pi-2-2Pi-1
Qi=Qi-2-2Qi-1+2
Ri=Ri-2-2Ri-1
Withtwoboundaryconditions
P1=0Q1=0R1=1(A1=A1)
P2=1Q2=0R2=0(A2=A2)
AccordingtotherecursionformulaofPi,QiandRi,itcanbecalculated
S2[1]=(0,0,1);
S2[3]=(-2,2,1);
S2[4]=(5,-2,-2);
S2[5]=(-12,8,5);
...
S2[i]=(Pi,Qi,Ri);
...
S2[N]=(PN,QN,RN);
Withthesefundamentals,AMisnothardtoget.Therearetwoways:
1,becauseAN,A1andPN,QN,RNknown,soyoucanfirstaccordingtoformula:
A2=AN-QND-RNA1/PN
FindA2.ThenA2issubstitutedintotheformula
A3=A1-2A2+2D
FindA3.ThenA3issubstitutedintotheformula
A4=A2-2A3+2D
FindA4.ThenA4issubstitutedintotheformula
And...
FindAi-1.ThenAi-1issubstitutedintotheformula
Ai=Ai-2-2Ai-1+2D
FindAi.Andsoon,untilthedeliveryuntilAM.
ThedefectisduetotheA2algorithmistheresultofthedivision,andthedivisorPNincrements,sotheerrorcanhardlybeavoided,recursiveprocesswillcontinuetoexpandaftertheerror,evenwhenMismorethan40AMwascalculatedfromthecorrectvaluebias.Obviously,thismethodissimplebutunreliable.
2,wemakeA2=A2,A3=X,representedbyS3[i]=(Pi,Qi,Ri),andAi=PiX+QiD+RiA2(i>=2)canbecalculated:
S3[2]=(0,0,1)=S2[1];
S3[3]=(1,0,0)=S2[2];
S3[4]=(-2,2,1)=S2[3];
S3[5]=(5,-2-2)=S2[4];
And...
S3[i]=(....)=S2[i-1];
................