算法导论上机报告Word文档下载推荐.docx
《算法导论上机报告Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《算法导论上机报告Word文档下载推荐.docx(11页珍藏版)》请在冰豆网上搜索。
thatproducesthesameresultatlowercost.Ifacharacterisreplacedbyacharactera
andthenreplacedagainbyacharacterb,thenbothoperationscanbereplacedby“re
placeb”.Thismeansthatallinsertedandreplacedcharactersareneverchangedafter
performingtheinsertionorreplacement.Noticethatafterremovingtheseoperations
thatintroducedependencies,anysequenceofinsert,delete,andreplaceoperationscan
bereorderedsothattheyoccurfromlefttorightwithoutaffectingtheoutcomeofthe
transformation.
(c)Weshowthatcomputingeditdistanceforstringsxandycanbedonebyfindingthe
editdistanceofsubproblems.Defineacostfunction
(i,j)=d(x,y[1..i]||x[j+1..m])
(1)
Thatis
(i,j)istheminimumcostoftransformingthefirstjcharactersofxinto
thefirsticharactersofy.Thend(x,y)=
(n,m).Nowconsiderasequenceof
operationsS=(o1,o2,...,ok)thattransformsxtoywithcostC(S)=d(x,y).
LetSibethesubsequenceofScontainingthefirstioperationsofS.Letzibethe
auxilliarystringafterperformingoperationsSi,wherez0=xandzk=y.
(d)Wecancalculatetheeditdistanced(x,y)usingthedefinitiono𝐜
𝐱
𝐲
(i,j)fromEqua
tion1.Recallthatd(x,y)=
(m,n).Sinceweshowedinpart(a)thatthereexists
asequenceofoperationsthatachievesd(x,y)withoutusingthe“left”operation,we
onlyneedtoconsiderthefouroperations“right”,“replace”,“delete”,and“insert”.
Wecancalculate
(m,n)recursively.Thebasecaseiswhennotransformationop
erationshavebeenperformed,so𝐜
(0,0)=0.
(e)ConstructatableTwhereeachentryT[i,j]=
(i,j).Sinceeachvalue
of
(i,j)onlydependson𝐜
(i1,j2)wherei1<
=iandj1<
=j,wecancomputethe
entriesofTrowbyrowusingEquation2:
EDIT-DISTANCE(x[1..m],y[1..n])
1T[0,0]←0
2fori←1ton
3forj←1tom
4doT[i,j]←min𝐓
𝐢
−𝟏
𝐣
𝐢
𝐟
>
𝟎
𝐚
𝐧
𝐝
𝐣
[𝐢
]=𝐲
[𝐣
]𝐓
+𝟒
𝐢
𝐓
+𝟐
𝐢
+𝟑
5returnT[n,m]
Therunningtimeofthisalgorithmis
(mn).Thisalgorithmrequires
(mn)space.
(f)
x:
electricalengineering
y:
computerscience
EditDistance:
54
Oper|c|Total|z
initial|0|0|*electricalengineering
delete|2|2|*lectricalengineering
delete|2|4|*ectricalengineering
delete|2|6|*ctricalengineering
right|0|6|c*tricalengineering
insert|3|9|co*tricalengineering
insert|3|12|com*tricalengineering
insert|3|15|comp*tricalengineering
insert|3|18|compu*tricalengineering
right|0|18|comput*ricalengineering
insert|3|21|compute*ricalengineering
right|0|21|computer*icalengineering
delete|2|23|computer*calengineering
delete|2|25|computer*alengineering
delete|2|27|computer*lengineering
delete|2|29|computer*engineering
right|0|29|computer*engineering
delete|2|31|computer*ngineering
replace|4|35|computers*gineering
replace|4|39|computersc*ineering
right|0|39|computersci*neering
delete|2|41|computersci*eering
delete|2|43|computersci*ering
right|0|43|computerscie*ring
delete|2|45|computerscie*ing
delete|2|47|computerscie*ng
right|0|47|computerscien*g
insert|3|50|computerscienc*g
replace|4|54|computerscience*
(g)InputFiled(x,y)
Input11816
Input21824
Input31829
(h)AllthetransformationoperationscanbeimplementedinO
(1)timeusing
twostacks,LandR.Initially,LisemptyandRcontainsallthecharactersofxin
order.
OperationImplementation
leftIfnotEMPTY(L),thenPUSH(R,POP(L))
rightIfnotEMPTY(R),thenPUSH(L,POP(R))
replacebycIfnotEMPTY(R),thenPOP(R),PUSH(L,c)
deleteIfnotEMPTY(R),thenPOP(R)
insertcPUSH(L,c)
EachstackoperationrequiresO
(1)time,andeachtransformationoperationrequires
onlyO
(1)stackoperations.ThereforeeachoperationrequiresO
(1)time.
代码部分:
#include<
assert.h>
stdio.h>
stdlib.h>
string.h>
//OperationCosts
#defineMOVE_COST0
#defineREPLACE_COST4
#defineINSERT_COST3
#defineDELETE_COST2
//OperationTypes
typedefenum{initial,right,insert,delete,replace,final}opType;
char*opStrings[]={"
initial"
"
right"
insert"
delete"
replace"
final"
};
//Recoversandprintsouttheeditsnecessarytochangexintoy.
staticvoidrecoverEdits(char*x,intm,
char*y,intn,
int**d,opType**opPerformed);
//Computestheeditdistancebetweenxandy
staticvoidcomputeEditDistance(char*x,intm,
char*y,intn){
//Inthisdynamicprogram,d[i][j]storestheeditdistancebetween
//thestringx[i..m-1]andy[j..n-1].
//NOTE!
Carraysstartindexingat0.
int**d;
opType**opPerformed;
//storeoperationsforreconstructingtheanswer
opTypeopDone;
inti,j;
d=(int**)malloc((m+1)*sizeof(int*));
assert(d!
=NULL);
opPerformed=(opType**)malloc((m+1)*sizeof(opType*));
assert(opPerformed!
for(i=0;
i<
=m;
i++){
d[i]=(int*)malloc((n+1)*sizeof(int));
assert(d[i]!
opPerformed[i]=(opType*)malloc((n+1)*sizeof(opType));
assert(opPerformed[i]!
}
//Initializethebasecases.
//x[m]andy[n]arebothnullstrings.Editdistancebetweenthemis0.
d[m][n]=0;
opPerformed[m][n]=final;
m;
//Toconvertx[i..m-1]tothenullstringy[n],deleteall(m-i)
//remainingcharactersinx.
d[i][n]=DELETE_COST*(m-i);
opPerformed[i][n]=delete;
for(j=0;
j<
n;
j++){
//Toconvertx[m](thenullstring)intoy[j..n-1],insert
//themissingn-jcharacters.
d[m][j]=INSERT_COST*(n-j);
opPerformed[m][j]=insert;
//Startatd[m][n]andloopbackwards
for(i=m-1;
i>
=0;
i--){
for(j=n-1;
j>
=0;
j--){
intcostForReplaceOrMove;
intcostForInsert;
intcostForDelete;
intminValue;
//Computed[i][j]astheminimumof4terms:
//Ifx[i]==y[j],wecouldmoveright.
//Otherwise,wecanreplacex[i]withy[j]and
//incrementiandj.
costForReplaceOrMove=d[i+1][j+1]+REPLACE_COST*(x[i]!
=y[j])+MOVE_COST*(x[i]==y[j]);
//Ifweinsertacharacterintoxtomatchy[j],then
//weincrementjby1
costForInsert=d[i][j+1]+INSERT_COST;
//Ifwedeleteacharacterinx,thenwe
//incrementiby1.
costForDelete=d[i+1][j]+DELETE_COST;
//Oftheaboveoperations,findonethatgivesus
//aminimumcost.
minValue=costForReplaceOrMove;
if(x[i]!
=y[j]){
opDone=replace;
else{
opDone=right;
if(minValue>
costForInsert){
minValue=costForInsert;
opDone=insert;
costForDelete){
minValue=costForDelete;
opDone=delete;
d[i][j]=minValue;
opPerformed[i][j]=opDone;
//Finalanswer
printf("
EditDistance=%d\n"
d[0][0]);
//Recoveroperations/printoutansweronlyifthestringsaren'
ttoolong.
if((m<
75)&
&
(n<
75)){
recoverEdits(x,m,y,n,d,opPerformed);
free(d[i]);
free(opPerformed[i]);
free(d);
free(opPerformed);
}
int**d,opType**opPerformed){
inti=0;
intj=0;
intk=0;
inta;
intopDone;
intcostSoFar=0;
intstepCost=0;
char*newString;
newString=(char*)malloc(sizeof(char)*(m+n));
//Ratherthanimplementingastringobjectforxthatallowsus
//constant-timeinsertsanddeletesatthecursor,
//wearejustgoingtohavetwocopiesofthestring.
//newString[0..k]storeseverythingbeforethecursorthatwehave
//changed,andx[i..m-1]willstoreallthepartsafterthecursorthat
//arestillthesame.
strncpy(newString,x,m);
\n"
);
(i,j):
%8s|c|Total|z\n"
Oper"
---------------------------------------------------------------------\n"
(%2d,%2d):
%8s|%4d|%4d|"
i,j,"
costSoFar,stepCost);
*%s\n"
x);
while(opPerformed[i][j]!
=final){
opDone=opPerformed[i][j];
switch(opDone){
caseright:
newString[k]=x[i];
i++;
j++;
stepCost=MOVE_COST;
break;
casereplace:
newString[k]=y[j];
stepCost=REPLACE_COST;
caseinsert:
stepCost=INSERT_COST;
casedelete:
stepCost=DELETE_COST;
default:
//Weshouldneverafollowapointertoinitialorfinal.
ERROR.\n"
exit
(1);
if(opDone!
=delete){
k++;
costSoFar+=stepCost;
%8s|