Algorithms Data Structures 1
Algorithms Data Structures 1
Recursive Algorithms -
) / ( ) .( recursive call )
( .
, ...
.
:
.
.
:
-1 )
, = . ( Stack Overflow
: ... Fortran , Cobol ,
-2
: ) ( .
: .
:
, :
. :
. :
{ )void B(void
{ )int A(void
.
;) (A
// direct recursive call
.
}
;) (A
.
}
{ )int A(void
.
indirect recursive call
//
; ) (B
.
}
:
: Fact
:
:
n!= n (n 1) (n 2) ....... 2 1
!)n!= n (n 1
!)(n 1) (n 2
!)(n 2) (n 3
..............
)!1 (0
n ,
.
.
) ( :
-
)long fact(int n
;{ long f=1
;if ((n==1)||(n==0)) return 1
else
){ for (int i=1;i<=n;i++
;f*=i
} ;return f
}
)long fact(int n
)){ if ((n==1)||(n==0
;return 1
else
;)return n*fact(n-1
}
: Fibonacci -
); n 2 ( F0 = 0 , F1 = 1
:
:
..
..
F6
8
F7
13
F5
5
Fn = Fn-1 + Fn-2
F4
3
F3
2
F2
1
F1
1
F0
0
) 0 ( 1 ,
) 0 . ( 1
:
)n
;return 0
;return 1
;)return fib(n-1)+ fib(n-2
int fib(int
){ if (n==0
else
)if (n==1
else
}
: Towers of Hanoi -
n . . :
C A :
. . B .) , (.
n = 2 :
1:
2:
3:
4:
1
>#include <iostream.h
:
;int n
;)void hanoi(int n, char A, char B, char C
)(void main
{
;" =do { cout<<"Enter n
;cin>>n
;)} while (n<=0
;)'hanoi(n,'A','B','C
}
/***************************************************************************************/
)void hanoi(int n, char A, char B, char C
{
;if (n==1) cout<<A<<" --> "<<C<<endl
else
;){ hanoi(n-1,A,C,B
;cout<<A<<" --> "<<C<<endl
;)hanoi(n-1,B,A,C
}
}
) ( :
n=3
C
B
B
C
A
C
C
A
A
C
A
B
B
A
n=2
B
C
C
A
A
B
n=1
:
: ) (Prefix ) . (Postfix
) (Operator ) (Operands .
.
:
) ( Infix
) ( Prefix
) ( Postfix
A+B
+AB
AB+
A+B*C
+A*BC
ABC*+
)A*(B+C
*A+BC
*ABC+
A*B+C
+*ABC
AB*C+
A+B*C+D-E*F
-++A*BCD*EF
*ABC*+D+EF(A+B)*(C+D-E)*F
**+AB-+CDEF
*AB+CD+E-*F
. ,
.
:
, ) (.
. op
opnd1 . post1
opnd2 . post2
opnd1 , opnd2 , op .
-
1
:
const int strsize = 80;
struct string {
char ch[strSize];
int length;
};
. length ch string
:
"xy" " abc" concat
. c b a concat(a,b) . abcxy c
i S1 j S2 S2= substr(S1, i , j) S2 S2= substr(Welcome,4,2)
.( S2 S1 ) S1
. om
, convert
. ( ) find
#include <iostream.h>
#include <string.h>
//
#include <ctype.h>
//
const int strSize=80;
struct string {
char ch[strSize];
int length;
};
string prefix , postfix;
char pr[strSize];
int i;
string
string
string
int
-->
-->
/***************************************************************************************/
void main()
{
cout<<"Enter a mathimatical sentence in prefix_case :\n";
cin.getline(pr,strSize,'\n');
// reads text with white spaces
prefix.length=strlen(pr);
for (i=0;i<prefix.length;i++)
prefix.ch[i]=pr[i];
postfix=convert(prefix);
cout<<"Postfix = ";
for (i=0;i<postfix.length;i++)
cout<<postfix.ch[i];
}
/***************************************************************************************/
string concat(string s1,string s2)
{ string s3;
s3.length = s1.length + s2.length;
for (i=0;i<s1.length;i++)
s3.ch[i]=s1.ch[i];
int j=s1.length-1;
for (i=0;i<s2.length;i++)
{ j++;
s3.ch[j]=s2.ch[i];
}
return s3;
}
1
string substr(string s1,int i,int j)
{ string s2;
s2.length=j;
int m=0;
for (int k=i;k<i+j;k++)
{ s2.ch[m]=s1.ch[k];
m++;
}
return s2;
}
/***************************************************************************************/
string convert(string prefix)
{ string postfix;
char op;
// op = operator
string opnd1,opnd2,temp;
// opnd1= first operand , opnd2= second operand
string post1,post2,opstr; // post1= opnd1 after converting ,
// post2= opnd2 after converting , opstr= op as string
int m,n;
// m = length of opnd1 , n = length of opnd2
if (prefix.length==1)
if (isalpha(prefix.ch[0]))
postfix=prefix;
else
{ cout<<"Illegal prefix string !\n"; postfix.length=0; }
else
{
op=prefix.ch[0];
m=find(prefix,1);
n=find(prefix,1+m);
if (((op!='+')&&(op!='-')&&(op!='*')&&(op!='/'))||
(m==0)||(n==0)||(m+n+1!=prefix.length))
{ cout<<"Illegal prefix string !\n"; postfix.length=0; }
else
{
opnd1=substr(prefix,1,m);
opnd2=substr(prefix,1+m,n);
post1=convert(opnd1);
post2=convert(opnd2);
temp=concat(post1,post2);
opstr.length=1;
opstr.ch[0]=op;
postfix=concat(temp,opstr);
}
}
return postfix;
}
/***************************************************************************************/
int find(string s,int position)
{ if (position>=s.length)
return 0;
else
{ char first; int m,n;
first=s.ch[position];
if (isalpha(first)) return 1;
else
{ m=find(s,position+1);
n=find(s,position+1+m);
if ((m==0)||(n==0)) return 0;
else
return m+n+1;
}
}
}
: Merge Sort -
, t , ) Merge
.(Sort : , ,
. .
, .
.
6 , :
[ 9
7
3
0
6
] 1
] [9 7 3
[ 0
]6 1
][9 7] [3
[ 0
] 6 ] [1
][9][7] [3
] [ 0 ] [ 6 ] [1
][7 9 ] [3
[0
]6 ] [ 1
[3
]7 9
[0
]1 6
[ 0
1
3
6
7
] 9
, :
void merge(int low,int mid,int high,tableType t); //
;)void mergeSort(int low,int high,tableType t
//
recursive algorithm
>#include <iostream.h
;const int n=100
;]typedef int tableType[n
;tableType t,aux
// t= unsorted table
;int m
// dimension of table
/***************************************************************************************/
)(void main
{
;" = do { cout<<"Enter dimension of table , dim
;cin>>m
;)} while (m<=0
)for (int i=0;i<m;i++
;" =]"<<{ cout<<"t["<<i
;]cin>>t[i
}
;)mergeSort(0,m-1,t
)for(i=0;i<m;i++
;" "<<]cout<<t[i
}
/***************************************************************************************/
)void merge(int low,int mid,int high,tableType t
{ int i=low, j=mid+1; //i=index in first half of t , j=index in second half of t
;int k=low
// k=index in aux
))while ((i<=mid)&&(j<=high
{
)]if (t[i]<t[j
1
{ aux[k]=t[i];
k++;
i++;
}
else
if (t[i]>t[j])
{ aux[k]=t[j];
k++;
j++;
}
else
// repition of same number
{ aux[k]=t[i];
aux[k+1]=t[i];
k+=2;
i++;
j++;
}
//
or:
aux[k]=t[j]
}
while (i<=mid)
{ aux[k]=t[i];
k++;
i++;
}
while (j<=high)
{ aux[k]=t[j];
k++;
j++;
}
i=low;
while (i<=high)
{ t[i]=aux[i];
i++;
}
}
/***************************************************************************************/
void mergeSort(int low,int high,tableType t)
{ if (low!=high)
{ int mid=(low+high)/2;
mergeSort(low,mid,t);
mergeSort(mid+1,high,t);
merge(low,mid,high,t);
}
}
: Hilbert -
, .
) H1 ( H5
,
, H1 H2 ). H3 H1 H2
( H3
H1
H2
H3
Hi+1 Hi ,
, , . H1
H0 = .
1
Hi Hi-1 , Hi
Hi-1 . A,B,C,D ,
:
A :
B :
C :
D :
h . X0Y
) : ( Borland Turbo C++ under Dos
:
) lineto(x,y ). (x,y initgraph . setcolor Graphmode Textcolor . Textmode;)B(i-1
}
}
/***************************************/
)void B(int i
{
)if (i>0
{
;)C(i-1); y-=h; lineto(x,y
;)B(i-1); x+=h; lineto(x,y
;)B(i-1); y+=h; lineto(x,y
;)A(i-1
}
}
/***************************************/
)void C(int i
{
)if (i>0
{
;)B(i-1); x+=h; lineto(x,y
;)C(i-1); y-=h; lineto(x,y
;)C(i-1); x-=h; lineto(x,y
;)D(i-1
}
}
/***************************************/
)void D(int i
{
)if (i>0
{
;A(i-1); y+=h
;)lineto(x,y
;D(i-1); x-=h
;)lineto(x,y
;D(i-1); y-=h
;)lineto(x,y
;)C(i-1
}
}
)(--> getch
//
>#include <graphics.h
>#include <conio.h
;const int n=5,h0=512
;int h,x,y,x0,y0
;)void A(int i
;)void B(int i
;)void C(int i
;)void D(int i
/***************************************/
)(void main
{
;int gdriver = DETECT, gmode
;)"" initgraph(&gdriver, &gmode,
;int i=0
;h=h0
;x0=h/2
;y0=x0
{ do
;i++
;h/=2
;)setcolor(i
;)x0=x0+(h/2
;)y0=y0-(h/2
;)moveto(x0,y0
;x=x0
;y=y0
;)(A(i); getch
;)} while (i<n
;)(closegraph
}
/***************************************/
)void A(int i
{
)if (i>0
{
;)D(i-1); x-=h; lineto(x,y
;)A(i-1); y+=h; lineto(x,y
;)A(i-1); x+=h; lineto(x,y
: Sierpinsky -
:
, !
S3 - S1
S4 - S1
S1
S2 - S1
S2 S1 , ,
.
n A,B,C,D
. . 90o
S1 : A
C
) ( :
D
-
S:
10
1
S2 A :
S3 A :
. . . . . . . . . . . . . .
A
S0 .
A,B,C,D :
A :
B :
C :
D :
.
:
) : ( Borland Turbo C++ under Dos
>#include <graphics.h
>#include <conio.h
;const int n=4,h0=256
;int i,h,x,y,x0,y0
;)i
;)i
;)i
;)i
A(int
B(int
C(int
D(int
void
void
void
void
/***************************************************************************************/
)(void main
{
;int gdriver = DETECT, gmode
;)"" initgraph(&gdriver, &gmode,
11
1
i=0;
h=h0/4;
x0=2*h;
y0=h;
do {
i++;
x0-=h;
h/=2;
y0-=h;
x=x0;
y=y0;
moveto(x0,y0);
setcolor(i);
A(i); x+=h; y+=h;
B(i); x-=h; y+=h;
C(i); x-=h; y-=h;
D(i); x+=h; y-=h;
getch();
} while (i<n);
closegraph();
lineto(x,y);
lineto(x,y);
lineto(x,y);
lineto(x,y);
}
/***************************************************************************************/
void A(int i)
{
if (i>0)
{
A(i-1); x+=h;
y+=h; lineto(x,y);
B(i-1); x+=2*h;
lineto(x,y);
D(i-1); x+=h;
y-=h; lineto(x,y);
A(i-1);
}
}
/***************************************************************************************/
void B(int i)
{
if (i>0)
{
B(i-1); x-=h; y+=h;
lineto(x,y);
C(i-1);
y+=2*h; lineto(x,y);
A(i-1); x+=h; y+=h;
lineto(x,y);
B(i-1);
}
}
/***************************************************************************************/
void C(int i)
{
if (i>0)
{
C(i-1); x-=h;
y-=h; lineto(x,y);
D(i-1); x-=2*h;
lineto(x,y);
B(i-1); x-=h;
y+=h; lineto(x,y);
C(i-1);
}
}
/***************************************************************************************/
void D(int i)
{
if (i>0)
12
1
{
D(i-1);
A(i-1);
C(i-1);
D(i-1);
x+=h;
x-=h;
y-=h;
y-=2*h;
y-=h;
lineto(x,y);
lineto(x,y);
lineto(x,y);
:
a(n x n) x minor , Minors
.( n-1 x n-1 ) x a
: n a ( Determinant)
n 1
i =0
. j
#include <iostream.h>
const int m=5;
struct matrix{
int n;
int val[m][m];
};
matrix a;
int i,j;
13
1
d+=a.val[i][j]*det(mat);
}
return d;
}
}
/***************************************************************************************/
matrix minor(matrix a,int i,int j)
{
int ii,jj,t=-1,k; // t=line of new matrix , k=column of new matrix
matrix mat;
mat.n=a.n-1;
for (ii=0;ii<a.n;ii++)
if (ii!=i)
{
t++;
k=-1;
for (jj=0;jj<a.n;jj++)
if (jj!=j)
{
k++;
mat.val[t][k]=a.val[ii][jj];
}
}
return mat;
14
-1 :
,
) (.
goto while
:
) void p( X , Y
) void p( X , Y
.
{
{ start: .
.
.
.
=if (condition) Y
else
;X=E
;) p( E , Y
;goto start
.
.
.
.
}
}
X Y , , ) p( E , Y .
-2 :
, Stack .
:
) : (1 :
while
)Long fact(int n
{
;long f=1
)while (n!=0
{
;f*=n
;n--
}
;return f
}
) : (2 :
while
)int gcd(int x,int y
;{ int h
)while (y!=0
;{ h=x
;x=y
;y=h%y
}
;return x
}
goto label
)long fact(int n
;{ long f=1
Start:
))if ((n==1)||(n==0
;return f
else
;{ f*=n
;n--
;goto Start
}
}
goto label
)int gcd(int x,int y
;{ int h
Start:
;if (y==0) return x
else
;{ h=x; x=y
;y=h%y
;goto Start
}
}
)long fact(int n
{
if ((n==1)||(n==0)) return
;1
else
;)return n* fact(n-1
}
)int gcd(int x,int y
{
;if (y==0) return x
else
;)return gcd(y,x%y
}
15
int power(int x,int n)
{
if (n==0) return 1;
else
if (n==1) return x;
else
return x* power1(x,n-1);
}
goto label
int power(int x,int n)
{ int p=1;
Start:
if (n==0) return p;
else
{ p*=x;
n--;
goto Start;
}
}
: : (3)
while
int power(int x,int n)
{ int p=1;
while (n!=0)
{
p*=x;
n--;
}
return p;
}
While
goto label
: : (4)
16
goto label
y)
0;
m;
}}
: : (5)
while
int multi(int x,int y)
{ int m=x;
while (y!=1)
{
m+=x;
y--;
}
return m;
}
goto label
: t x ) ( : (6)
17
While
18
Backtracking Algorithms -
" " ) (Try-and-Error .
, ,
, , .
, , .
.
) , pseudocode ,
( :
)(void try
{
;
{ do
;
)( if
{
;
) ( if
{
;
) ( if
;
}
}
;) ()and ( }while
}
)(void try
{
;initialize selection of candidates
{ do
;select next candidate
)if (acceptable
{
;record it
)if (solution incomplete
{
;try next step
)if (not successful
;cancel recording
}
}
} while (not successful)and(remains of
;)candidates
}
.
.
: Knightstour -
nn , > <X0,Y0 0 X 0 n 1 :
2
0 Y0 n 1
) ( n - 1 .
: ,
. , " " .
:
19
1
. h :
;const int n=5
int
;]h[n][n
(X,Y) :
i :
q :
" : " ) (board not full i < n2 :
v , u ) ( L "" )
.
h[u,v] = 0 and 0 u n-1 and 0 v n-1
(acceptable :
> . <X,Y
:
1
a b :
;]a[8] , b[8
int
k .
> <X,Y ,
]. h[X,Y
X
5
8
7
, ]. h[0,0
>#include <iostream.h
>#include <iomanip.h
)(// --> setw
;const int n=5
// number of lines/columns
;int i,j
;'char q='n
// no , the solution is incomplete
;]int a[8],b[8
;}int h[n][n]={0
;)void try1(int i,int x,int y,char &q
/******************************************************************************************/
)(void main
;{ a[0]=2
;b[0]=1
;a[1]=1
;b[1]=2
;a[2]=-1; b[2]=2
;a[3]=-2; b[3]=1
;a[4]=-2; b[4]=-1
;a[5]=-1; b[5]=-2
;a[6]=1
;b[6]=-2
;a[7]=2
;b[7]=-1
;h[0][0]=1
// first step (i=1) is fixed
20
1
try1(2,0,0,q);
if (q=='y')
for (i=0;i<n;i++)
{
for (j=0;j<n;j++) cout<<setw(5)<<h[i][j];
}
cout<<endl;
else
cout<<"No solution !\n";
}
/******************************************************************************************/
void try1(int i,int x,int y,char &q)
{
int u,v,k=-1;
do {
k++;
u=x+a[k]; v=y+b[k];
if ((u>=0)&&(u<n)&&(v>=0)&&(v<n)&&(h[u][v]==0))
{
h[u][v]=i;
if (i<n*n)
{
try1(i+1,u,v,q);
if (q=='n')
h[u][v]=0;
}
else
q='y';
// yes , the solution is complete
}
} while ((q=='n')&&(k<7));
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: EightQueens -
. ,
:
void try(int i)
{
initialize selection of positions for i-th queen;
do {
make next selection;
if (safe)
{
setqueen;
if (i<7)
{
try (i+1);
if (not successful)
remove queen;
}
}
} while (not successful)and(there are more positions yet);
}
21
1
, . ,
i . i
,
.
,
) ( .
,
. :
] x[i i
a[j]==y j
b[j]==y j
c[j]==y j
//
//
//
//
;]x[8
;]a[8
;]b[15
;]c[15
int
char
char
char
:
,
i ) i (.
j
. 7
14
13
12
11
10
9
8
7
i j :
;x[i]=j
;a[j]=n
;b[7+i-j]=n
;c[i+j]=n
i j :
9 10 11 12 13 14
0
1
2
3
4
5
6
7
0 1 2 3 4 5 6
;a[j]=y
;b[7+i-j]=y
;c[i+j]=y
"" ) (safe :
:
))((a[j]==y)&&(b[7+i-j]==y)&&(c[i+j]==y
]x=[0,4,7,5,2,6,1,3
X
X
X
X
X
X
X
X
-
22
:
#include <iostream.h>
#include <iomanip.h>
int
char
char
char
char
int
i;
q='n';
a[8];
b[15];
c[15];
x[8];
// no , there is no solution
// lines
// direct diagonals
// indirect diagonals
// solution = lines
23
1
, .
, .
:
)void try(int i
{
)for (int k=0;k<m-1;k++
{
;select k-th candidate
)if (acceptable
{
;record it
)if (i<n
;)try(i+1
else
;print solution
}
}
}
:
)void try2(int i
{
)for (int j=0;j<8;j++
{
))'if ((a[j]=='y')&&(b[7+i-j]=='y')&&(c[i+j]=='y
{
;x[i]=j
;'a[j]='n
;'b[7+i-j]='n
;'c[i+j]='n
;)if (i<7) try2(i+1
else
;)(print
;'a[j]='y
;'b[7+i-j]='y
;'c[i+j]='y
}
}
}
) ( .
92 , 12
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
24
: Optimal Selection -
.
, , ,
. ,
.
.
) F(S ) S ( ,
:
) )if ( F(Solution)>F(Optimal
;Optimal=Solution
. Optimal
.
, .
, .
: ,
. , :
//
)void try(int i
{
)if (inclusion is acceptable
{
;include i-th object
)if (i<n
;)try(i+1
else
;check optimality
;erase i-th object
}
)if (exclusion is acceptable
)if (i<n
;)try(i+1
else
;check optimality
}
2n ) n(
. .
} A = { a1 , a2 , ... , an W , V A
, . ,
, .
, , :
) ( W
) ( V
a1
10
18
a2
11
20
a3
15
25
a4
17
17
30 .
, ) .
-
25
1
) .( 16
( . A
S13 , S9 , S5 , S3 , S2 , S1 .
, S10 , . 45
a1
a2
a3
a4
S15 S16
S9
S10
S8
S7
S6
S5
S4
S3
S2
S1
a[i].v
= av
;tw = 0
i =0
i = n-1 :
a[i].v
= av
;tw limW
s [ i ]=1
" " :
" " :
-
tw + a[i].w limW
av - a[i].v > maxV
26
1
.
s
. ,
i = n-1
100 10 , 12
.
#include <iostream.h>
#include <iomanip.h>
// --> setw()
const n=12;
struct objects {
int v,w;
// v=value , w=weight
};
int i;
objects a[n];
int limW,totV=0,maxV;
int w1,w2,w3;
int s[n]={0},opts[n]={0}; // if (s[i]==1) object i selected , if (s[i]==0) not selected
void try1(int i,int tw,int av);
/******************************************************************************************/
void main()
{ for (i=0;i<n;i++)
{ cout<<"Enter weight,value ("<<i<<") = ";
cin>>a[i].w>>a[i].v;
totV+=a[i].v;
}
cout<<"Enter w1,w2,w3 = ";
cin>>w1>>w2>>w3;
cout<<"Weight ";
for (i=0;i<n;i++)
cout<<setw(4)<<a[i].w;
cout<<endl;
cout<<"Value ";
for (i=0;i<n;i++)
cout<<setw(4)<<a[i].v;
cout<<endl;
do {
limW=w1;
maxV=0;
try1(0,0,totV);
cout<<setw(6)<<limW;
for (i=0;i<n;i++)
if (opts[i]==1) cout<<setw(4)<<"*";
else
cout<<setw(4)<<" ";
cout<<endl;
w1+=w2;
} while (w1<=w3);
}
/******************************************************************************************/
void try1(int i,int tw,int av)
{
int av1;
if (tw+a[i].w<=limW)
{
s[i]=1;
if (i<n-1) try1(i+1,tw+a[i].w,av);
27
1
else
)if (av>maxV
{
;maxV=av
)for (int j=0;j<n;j++
;]opts[j]=s[j
}
;s[i]=0
}
;av1=av-a[i].v
)if (av1>maxV
)if (i<n-1
;)try1(i+1,tw,av1
else
{
;maxV=av1
)for (int j=0;j<n;j++
;]opts[j]=s[j
}
10
20
30
40
50
60
70
80
90
100
10
15
*
*
*
*
*
*
*
11
18
*
*
*
*
*
*
*
*
12
15
13
17
14
21
15
20
*
*
*
*
*
*
*
*
*
16
19
17
21
18
23
19
24
20
24
21
25
*
*
*
*
*
*
*
*
*
*
*
*
*
*
28
:
,
.
.
Start ,
. Goal :
try1
,
) .
( .
Start
0
0
0
0
1
1
1
1
1
1
0
0
0
0
0
0
0
0
0
1
0
0
1
1
1
1
1
1
1
1
0
0
0
0
1
1
1
0
1
1
0
0
1
0
0
0
0
0
1
1
0
1
1
1
0
1
1
0
1
1
0
0
0
0
0
0
0
0
0
1
0
0
1
1
0
1
1
1
0
1
0
0
0
1
0
1
0
0
0
1
0
0
Goal 0
0
0
1
1
1
1
1
>#include <iostream.h
>#include <conio.h
number of lines/columns
//
int h[n][n]={{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,1,0,0,0,0,0},{0,0,1,0,1,0,1,1,0,0},
{0,1,1,0,1,0,0,1,0,0},{0,0,0,0,0,1,0,1,0,1},{1,1,1,0,1,1,0,1,0,1},
{1,0,1,0,1,1,0,1,0,1},{1,0,1,0,0,0,0,1,0,1},{1,0,0,0,1,1,1,1,0,1},
;}}{1,1,1,1,1,1,1,1,1,1
int optS[n][n]; // optimal solution
;]int a[4],b[4
)int i,j,Xn,Yn,minL=0; // minL = length of optimal solution (=shortest way
;char q='n',c
// no , the solution is incomplete
void try1(int i,int x,int y,char &q); // one solution
;)void try2(int i,int x,int y
// all solutions
;)void try3(int i,int x,int y
// optimal solution
;)]void print(int h[n][n
/******************************************************************************************/
)(void main
{
;a[0]=-1; b[0]=0
;a[1]=0; b[1]=1
;a[2]=1; b[2]=0
;a[3]=0; b[3]=-1
;cout<<"Enter Xo = "; cin>>i
;cout<<"Enter yo = "; cin>>j
;h[i][j]=2
;cout<<"Enter X-Goal = "; cin>>Xn
;cout<<"Enter y-Goal = "; cin>>Yn
cout<<"One Solution
;"--> Press 1\n
cout<<"All Solutions
;"--> Press 2\n
;"cout<<"Optimal Solution --> Press 3\n
;)(c=getch
)'if (c=='1
{
;)try1(3,i,j,q
)'if (q=='y
;)print(h
else
;"cout<<"No solution
29
1
}
else
if (c=='2')
try2(3,i,j);
else
{
try3(3,i,j);
print(optS);
}
getch();
}
/******************************************************************************************/
void try1(int i,int x,int y,char &q)
{
int u,v,k=-1;
do{
++k;
u=x+a[k]; v=y+b[k];
if ((u>=0)&&(u<n)&&(v>=0)&&(v<n)&&(h[u][v]==0))
{
h[u][v]=i;
if ((u==Xn)&&(v==Yn)) q='y';
else
{
try1(i+1,u,v,q);
if (q=='n') h[u][v]=0;
}
}
} while ((q=='n')&&(k<3));
}
/******************************************************************************************/
void try2(int i,int x,int y)
{
int u,v,k=-1;
do{
++k;
u=x+a[k]; v=y+b[k];
if ((u>=0)&&(u<n)&&(v>=0)&&(v<n)&&(h[u][v]==0))
{
h[u][v]=i;
if ((u==Xn)&&(v==Yn))
{
print(h);
getch();
}
else
try2(i+1,u,v);
h[u][v]=0;
}
} while (k<3);
}
/******************************************************************************************/
void try3(int i,int x,int y)
{ int u,v,k=-1;
do{
++k;
u=x+a[k]; v=y+b[k];
30
1
))if ((u>=0)&&(u<n)&&(v>=0)&&(v<n)&&(h[u][v]==0
{
;h[u][v]=i
))if ((u==Xn)&&(v==Yn
{
))if ((minL==0)||(i<minL
{
;minL=i
)for (int w=0;w<n;w++
)for (int t=0;t<n;t++
;]optS[w][t]=h[w][t
}
}
else
;)try3(i+1,u,v
;h[u][v]=0
}
;)} while (k<3
}
/******************************************************************************************/
)]void print(int h[n][n
{
)for (int i=0;i<n;i++
{
)for (int j=0;j<n;j++
"<<]cout<<h[i][j
;"
;cout<<endl
}
}
_________________________________________________________________________________________
:
: The stable marriage problem -
A , B . n :
1 : n > < a , b a A , b B
. , , stable
. marriage rule
B , A ,
. n > < a ,b a
b , , .
.
, , )
( , , .
,
> , < a , b , , ,
.
: A B
. .
31
COMPLEXITY
) (.
.
, :
)f(n) c g(n
c,N | n > N
))f(n) = O(g(n
:1-
f(n) = n
1
}
3
:2-
1
3
g(n) = 3n
;
) f(n) = n + n = O(n
) f(n) = 5n = O(n
:
)O(1) O(log n) O(n ) O(n) O(n log n) O(n ) O(c ) O(n!) ;(0k1c
n
)n(n + 1
2
n +1
q 1
= 1 + q + q 2 + q 3 + ..... + q n
q 1
= 1 + 2 + 3 + ... + n
:
:
: : - :
n(n + 1)q
2
= q + 2q + 3q + .... + nq
1 qn
=
1 q
n 1
1 + q + q + .... + q
2
)c*O(g) = O(g
)} O(g1) + O(g2) = O(Max { g1 , g2
) O(g1) * O(g2) = O( g1 * g2
)} O(g1) + O(g2) = O(Max { g1 , g2
:
.
: :
-1
-2 code ) compiler (
-3
-4
-5
-
32
1
:
(**1 ) ( :
= sort
=
graph
=
) max(m,n m+n m x n
) = (m x n
:
(**2 ) (
; if (c) a; else b ))T(c) + Max(T(a),T(b
n m n x m
,
:
=> T(n) = n
; n >= 1
T(0) = 0
)T(n) = 1 + T(n-1
:
) (
....
Dn n :
-1 A
cost ;
-2 A
-3 A
) (d
P(d ) Cost
= )AverageA(n
d Dn
p . d
: x n .
: . A
MaxA(n) = n
:
MinA(n) = 1
:
:
x q x
x . 0 i n-1 Dn,i n
. x :
Cost(Dn,-1) = n
Cost(Dn,i) = i+1
>=
>=
P(Dn,-1) = 1 q
P(Dn,i) = q / n
q n 1
)q n(n + 1
)q (n + 1
= (i + 1) + (1 q) n
= + (1 q) n
+ (1 q) n
n i =0
n
2
2
)(n + 1
= )Average A (n
x q=1 :
2
= )AverageA(n
33
1
3n + 1
4
x q=1/2:
= )Average A (n
:
(*1 ): (insert
n(n + 1) n
n n
=
+
) = O(n 2
2
2 2 2
2
= Cost(n) = 1 + 2 + 3 + ....... + n
: .
(*2 ): (Bubble Sort
n ) ( , n-1 . i i
i :
n 1
)n(n 1
Cost(n) = 2i = 2
) = n(n 1) = O(n 2
2
i =1
(*3 ): (Binary Search
.... . : :
T(1) = 1
n
) (T(n) = 1 + T
2
n
) (T(n) = 1 + 1 + T
4
n
) (T(n) = 2 + T
4
n
) (T(n) = 2 + 1 + T
8
n
) T(n) = 3 + T( 3
2
..
n
) T(n) = k + T( k
2
: n = 2 k => k = log n
n
) (T(n) = log n + T
n
)T(n) = log n + T(1
T(n) = log n + 1
)T(n) = O(log n
: . quick sort
). Cost(n) = n log(n
34
1
P : NP
NP
.
.
.
n2
)n log(n
, , ... ,
)(Quicksort
fact
n
)log(n
Hash
)O(1
:
:
:
T(0) = 0
)T(n) = 1 + T(n-1
)= 2 + T(n-2
)= 3 + T(n-3
.
= k + T(n-k) ; n - k = 0 k = n
)= n + T(0
= n+0
)T(n) = O(n
:
:
T(0) = 0
)T(n) = 1 + T(n-1
)= 2 + T(n-2
)= 3 + T(n-3
.
= k + T(n-k) ; n - k = 0 k = n
)= n + T(0
= n+0
)T(n) = O(n
:
T(0) = 0
:
)T(n) = 1 + T(n-1
)= 2 + T(n-2
.
= k + T(n-k) ; n - k = 0 k = n
= n+0
)T(n) = O(n
): (Bubblesort
) ( :
T(n) = (n-1) + (n-2) + .. + 2 + 1
)n(n 1
=
2
)T(n) = O(n2
-
35
1
): (Insertsort
) (Insertsort :
, , ) ( ,
. ,
, , . , ... .
, , , .... , n-1 . :
) ( :
)T(n) = 1 + 2 + 3 + + (n-1
)n(n 1
)= O(n2
=
2
): (Quicksort
) (Quicksort ) ( :
n :
.
. : . ...
. ) ,
( . : ) ( :
T(1) = 1
n
) (T(n) = n + n + 2 T
2
n
) (= 2 n + 2 T
2
n
) (= 4n + 4 T
4
n
= 6n + 8 T( ) .
8
n
n
)= 1 k = log(n
; ) = 2kn + 2 k T( k
2
2k
= 2 n log(n) + n
))T(n) = O(nlog(n
): (Hanoi
)= ( :
T(1) = 1
)T(n) = 1 + 2 T(n-1
)= 1 + 2 + 4 T(n-2
)= 1 + 2 + 4 + 8 T(n-3
)= 1 + 2 + 4 + 8 + 16 T(n-4
1 2k
)+ 2 k T(n-k
; n-k=1 k=n-1
=
1 2
1 2 n 1
)+ 2 n 1 T(1
=
1 2
= 2 n 1 - 1 + 2 n 1
= 2 2 n 1 - 1
= 2n - 1
NP
) T(n) = O( 2 n
36
1
): (Fibonacci
) ( :
= )T(0
= )T(1
= )T(n
=
=
=
=
0
0
)1 + T(n-1) + T(n-2
)1 + 2 + T(n-2) + 2T(n-3) + T(n-4
)1 + 2 + 4 + T(n-3) + 3T(n-4) + 3T(n-5) + T(n-6
)1 + 2 + 4 + 8 + T(n-4) + 4T(n-5) + 6T(n-6) + 4T(n-7) + T(n-8
)1 + 2 + 4 + 8 + 16 T(n-4
)(
k
1 2
=
)+ 2 k T(n-k
; n-k=0 k=n
1 2
= 2 n -1 + 2 n 0
NP
) T(n) = O( 2 n
) : (
1
log 2 n
N
n log n
N2
N3
2n
10
10 -6 s
3.32 ns
0.01 ms
0.03 ms
0.0001 ms
0.001 ms
1.02 s
100
10 -6 s
6.64 ns
0.1 ms
0.66 ms
0.01 s
1.00 s
4.02 x 10 16 y
10.000
1.000
10 -6 s
10 -6 s
13.29 ns
9.97 ns
10 ms
1 ms
132.88 ms
9.97 ms
100.00 s
1.00 s
11.57 d
1000.00 s
1 x 10 295 y
100.000
10 -6 s
16.61 ns
100 ms
1660.96 ms
2.78 h
31.71 y
1.000.000
10 -6 s
19.93 ns
1000 ms
19931.57 ms
11.57 d
31710 y
) ( ns = nano second , ms = milli second , s = second , min = minute , h = hour , d = day , y = year
) : (
1
log 2 n
N
n log n
n2
n3
2n
1s
10 6
63 x 10 3
10 3
100
19
1 min
6 x 10 7
28 x 10 5
7.7 x 10 3
360
25
1h
36 x 10 8
13 x 10 7
60 x 10 3
1500
31
1y
86 x 10 9
97 x 10 8
26 x 10 4
4400
36
, .
37
:
, .
:
Arrays -
.
Linked Lists -
. : ,
) ( , , .
-1 :
: .:
= elem
//
;const lmax=100
{ struct listType
;int length
;]elem val[lmax
;}
:
, .
. .
:
L L.length=0
i L
]L.val[i
=
x k
x k
)listType insert(listType L,elem x,int k
)){ if ((L.length<lmax)&&(k<=L.length
{
)for (int i=L.length-1;i>=k;i--
;]L.val[i+1]=L.val[i
;L.val[k]=x
;++L.length
}
;return L
}
38
-2 :
, ,
, :
:
nil .
, :
plast
e3
eN
e1
e2
:
, .
plast
eN
e3
e2
e1
: Pascal Triangle -
) = : ( 6
1
3 1
6 4 1
10 10 5 1
1
2
3
4
5
1
1
1
1
1
1
1 n
) ( . i
) i ( . i
i - 1 t[i,j] = t[i-1,j] + t[i-1,j-1] :
j i . t
-1 .
-2 i ) i - 1
( .
-3 n ) ( .
>#include <iostream.h
>#include <conio.h
{struct str
;int val
;str *prev,*next
;}
;str *pfirst=0,*plast=0
;str s
;int n
;)(void init
;)(void print
/******************************************************************************************/
)(void main
{
39
1
cout<<"Enter n = "; cin>>n;
cout<<"\n\n";
if (n==1) cout<<"1 \n";
else
if (n==2)
{
cout<<"1 \n";
cout<<"1 1 \n";
}
else
{
cout<<"1 \n";
cout<<"1 1 \n";
for (int i=3;i<=n;i++)
{ init();
print();
}
}
getch();
}
/******************************************************************************************/
void init()
{
if (plast==0)
{
s.next=0;
s.prev=0;
s.val=2;
plast=new str(s);
pfirst=plast;
}
else
{
s.next=0;
s.prev=plast;
s.val=1;
plast->next=new str(s);
plast=plast->next;
str *p=plast;
while (p!=pfirst)
{ p->val += (p->prev)->val;
p=p->prev;
}
p->val += 1;
}
}
/******************************************************************************************/
void print()
{
str *p=pfirst;
cout<<"1 ";
while (p!=0)
{
cout<<p->val<<"
p=p->next;
";
}
cout<<"1"<<endl;
40
1
}
41
) ( Thesaurus -
) , ( Thesaurus ,
. .
.
. -1 : -2 -3
-4 -5 -6 -7 -8
fast
''a
''c
quick
''b
rapid
speedy
''z
" "string.h :
)][ : strcpy(char s1[],char s2 ) (
)][ : stricmp(char s1[],char s2 , ,
|| )<0 if (s1<s2
)>0 if (s1>s2
|| ==0 (if s1==s2) :
:
)][strlwr(char s
, , :
;)char searchWord(words* pfirst,char word[],words* &pw1,words* &pw2
pfirst , , : )
( , ) (
;)char searchSyn(synonym* pfirst,char syn[],synonym* &ps1,synonym* &ps2
pfirst , , :
) ( , ) (
- ,
:
, ...>#include <iostream.h
>#include <conio.h
//
)(-> clrscr() , getch() , getche
#include <string.h> // -> strlen() , strcpy(destination,source)=copy string ,
)// -> stricmp(s1,s2) , strlwr(string
;const L=30
// L= maxlength of a word or a synonym
;const n=26
) // there are 26 alphabetic letters ( in English
struct synonym { // = muradef
char
;]syn[L
;synonym* next
;}
{ struct words
char
;]word[L
*words
;next
;synonym* down
;}
;]typedef words* dictionary[n
;dictionary d
;words *pw1,*pw2
;synonym *ps1,*ps2
char c; // = choice of user
42
1
char menu();
char searchWord(words* pfirst,char word[],words* &pw1,words* &pw2); // pw1=address
// of word , pw2=address of previous word
char searchSyn(synonym* pfirst,char syn[],synonym* &ps1,synonym* &ps2);
// ps1=address of synonym , ps2=address of previous synonym
void insertWord(words* pw1,words* &pw2,char word[]);
void insertSyn(synonym* ps1,synonym* &ps2,char syn[]);
void deleteWord(words* pw1,words* &pw2,char word[]);
void deleteSyn(synonym* ps1,synonym* &ps2,char syn[]);
void printSynonyms(synonym *ps);
// prints all synonyms of one word
void printDictionary(dictionary d); // prints the whole dictionary
/***************************************************************************************/
void main()
{
do {
char word[L],syn[L];
c=menu();
switch (c){
case '1':{
cout<<"Enter new word = ";
cin>>word; strlwr(word);
if (searchWord(d[int(word[0])-97],word,pw1,pw2)=='y')
// ASCII : 'a' - 'z' ( 97 - 122 )
cout<<"The word \""<<word<<"\" does already exist ! \n";
else
insertWord(pw1,pw2,word);
break;
}
case '2':{
cout<<"Enter basic word of synonym = ";
cin>>word; strlwr(word);
cout<<"Enter synonym of "<<word<<" = ";
cin>>syn; strlwr(syn);
if (searchWord(d[int(word[0])-97],word,pw1,pw2)=='n')
cout<<"Sorry , the word \""<<word<<"\" doesn't exist ! \n";
else
{ char v= searchSyn(pw1->down,syn,ps1,ps2);
if ((pw1->down!=0)&&(v=='y'))
cout<<"The synonym \""<<syn<<"\" does already exist!\n";
else
insertSyn(ps1,ps2,syn);
}
break;
}
case '3':{
cout<<"Enter the word you want to delete = ";
cin>>word; strlwr(word);
if (searchWord(d[int(word[0])-97],word,pw1,pw2)=='n')
cout<<"Sorry , the word \""<<word<<"\" does not exist ! \n";
else
deleteWord(pw1,pw2,word);
break;
}
case '4':{
cout<<"Enter the word you want to delete its synonym = ";
cin>>word; strlwr(word);
cout<<"Enter the synonym you want to delete = ";
cin>>syn; strlwr(syn);
if (searchWord(d[int(word[0])-97],word,pw1,pw2)=='n')
cout<<"Sorry , the word \""<<word<<"\" does not exist ! \n";
else
if (searchSyn(pw1->down,syn,ps1,ps2)=='n')
cout<<"Sorry , the synonym \""<<syn<<"\" does not exist ! \n";
43
1
else
deleteSyn(ps1,ps2,syn);
break;
}
case '5':{
cout<<"Enter the word you want to search for = ";
cin>>word; strlwr(word);
if (searchWord(d[int(word[0])-97],word,pw1,pw2)=='y')
cout<<"\""<<word<<"\" is found ! \n";
else
cout<<"\""<<word<<"\" is not found ! \n";
break;
}
case '6':{
cout<<"Enter the basic word of the synonym = ";
cin>>word; strlwr(word);
cout<<"Enter the synonym you want to search for = ";
cin>>syn; strlwr(syn);
if (searchWord(d[int(word[0])-97],word,pw1,pw2)=='n')
cout<<"Sorry , the word \""<<word<<"\" is not found ! \n";
else
if (searchSyn(pw1->down,syn,ps1,ps2)=='y')
cout<<"\""<<syn<<"\" is found ! \n";
else
cout<<"\""<<syn<<"\" is not found ! \n";
break;
}
case '7':{
cout<<"Enter the word you want to see its synonyms = ";
cin>>word; strlwr(word);
if (searchWord(d[int(word[0])-97],word,pw1,pw2)=='y')
if (pw1->down==0)
cout<<"Sorry , there are no synonyms for this word ! \n";
else
printSynonyms(pw1->down);
else
cout<<"Sorry , this word doesn't exist ! \n";
break;
}
case '8':{
printDictionary(d);
break;
}
} // end of switch
getch();
} while (c!='9');
}
/***************************************************************************************/
char menu()
{
char c;
do {
clrscr();
cout<<"1= Insert New Word \n";
cout<<"2= Insert New Synonym \n";
cout<<"3= Delete Word \n";
cout<<"4= Delete Synonym \n";
cout<<"5= Search For a Word \n";
cout<<"6= Search For a Synonym \n";
cout<<"7= Print All Synonyms Of a Word \n";
cout<<"8= Print The Whole Dictionary \n";
cout<<"9= Exit \n\n\n";
cout<<"Enter your choice : ";
44
1
c=getche();
// getche() : reads a char and print it on userscreen
cout<<"\n\n\n";
} while ((int(c)<49)||(int(c)>57)); // ASCCI : '1' - '9' ( 49 - 57 )
return c;
}
/***************************************************************************************/
char searchWord(words* pfirst,char word[],words* &pw1,words* &pw2)
// pw1=address of word pw2=address of previous word
{
pw1=pfirst;
pw2=pfirst;
while ((pw1!=0)&&(stricmp(pw1->word,word)<0))
{
pw2=pw1; pw1=pw1->next;
}
if ((pw1!=0)&&(stricmp(pw1->word,word)==0))
return 'y';
else
return 'n';
}
/***************************************************************************************/
char searchSyn(synonym* pfirst,char syn[],synonym* &ps1,synonym* &ps2)
// ps1=address of synonym , ps2=address of previous synonym
{
ps1=pfirst; ps2=pfirst;
while ((ps1!=0)&&(stricmp(ps1->syn,syn)<0))
{
ps2=ps1; ps1=ps1->next;
}
if ((ps1!=0)&&(strcmp(ps1->syn,syn)==0))
return 'y';
else
return 'n';
}
/***************************************************************************************/
void insertWord(words* pw1,words* &pw2,char word[])
{
words* p=new words();
strcpy(p->word,word);
p->next=pw1;
p->down=0;
if ((pw1==0)&&(pw2==0))
// linked list is empty
d[int(word[0])-97]=p;
else
if (pw1==pw2)
// insert at the beginning
d[int(word[0])-97]=p;
else
// insert anywhere else
pw2->next=p;
}
/***************************************************************************************/
void insertSyn(synonym* ps1,synonym* &ps2,char syn[])
{
synonym* p=new synonym();
strcpy(p->syn,syn);
p->next=ps1;
if ((ps1==0)&&(ps2==0))
// there are no synonyms for this word
pw1->down=p;
else
if (ps1==ps2) // insert at the beginning
pw1->down=p;
else
// insert anywhere else
ps2->next=p;
}
45
1
/***************************************************************************************/
void deleteWord(words* pw1,words* &pw2,char word[])
{
synonym *ps=pw1->down,*aux;
while (ps!=0)
// first: delete all synonyms of this word
{ aux=ps;
ps=ps->next;
delete aux;
}
if (pw1==pw2) // delete first word
{
d[int(word[0])-97]=pw1->next;
delete pw1;
}
else
// delete anywhere else
{
pw2->next=pw1->next;
delete pw1;
}
}
/***************************************************************************************/
void deleteSyn(synonym* ps1,synonym* &ps2,char syn[])
{
if (ps1==ps2)
// delete first synonym
pw1->down=ps1->next;
else
// delete anywhere else
ps2->next=ps1->next;
delete ps1;
}
/***************************************************************************************/
void printSynonyms(synonym *ps)
// prints all synonyms of one word
{
while (ps!=0)
{
cout<<ps->syn<<" , ";
ps=ps->next;
}
}
/***************************************************************************************/
void printDictionary(dictionary d) // prints the whole dictionary
{
words *pw;
synonym *ps;
for (int i=0;i<=25;i++)
{
pw=d[i];
while (pw!=0)
{
cout<<"\n Word[ "<<pw->word<<" ] = ";
ps=pw->down;
while (ps!=0)
{
cout<<ps->syn<<" , ";
ps=ps->next;
}
pw=pw->next;
}
}
}
46
Stack -
"
" ). (LIFO = Last in , First out
. ,
, . ,
LIFO .
.
.
:
: EmptyStack ) (
:
Push
:
Pop
:
Top
:
IsEmpty
: CleanUp
)Pop(s
A
F
)Push(s,B
B
A
F
A
F
: s :
IsEmpty(s) = false
) Pop(s )Top(s Pop(Push(s,e)) = s Top(Push(s,e)) = eIsEmpty(EmptyStack) = true
IsEmpty(Push(s,e)) = false) (
head
Top eN
eN-1
e1
:
:
47
1
void push(stack &s,int e)
{
if (s.top==lmax-1)
cout<<"Error: Stack is full \n";
else
{
++s.top;
s.val[s.top]=e;
}
}
/***************************************/
void pop(stack &s)
{
if (isEmpty(s)=='y')
cout<<"Error: Stack is empty \n";
else
--s.top;
}
/***************************************/
int top(stack s)
{
if (isEmpty(s)=='y')
cout<<"Error: Stack is empty \n";
else
return s.val[s.top];
}
/***************************************/
void cleanUp(stack &s)
{
if (isEmpty(s)=='y')
cout<<"Stack is already cleaned up";
else
emptyStack(s);
}
. :
: Stack_P.h :
#include <iostream.h>
#include "Stack_P.h"
int n;
long fact(int n);
/***************************************************************************************/
void main()
{
cout<<"Enter n= ";
do { cin>>n;
} while (n<0);
cout<<n<<"! = "<<fact(n)<<endl;
}
/***************************************************************************************/
long fact(int n)
{
stack s;
emptyStack(s);
long f=1;
while (n>0)
{ push(s,n);
--n;
}
48
1
)'while (isEmpty(s)=='n
;){ f*=top(s
;)pop(s
}
;return f
}
: ,
.
:
) (Infix ) (postfix .
" , "Stack_PC.h
char . int :
>#include <iostream.h
>#include <string.h
"#include "Stack_PC.h
;]char c[25
;)][void print(char s
/***************************************************************************************/
)(void main
{
;"cout<<"Enter a mathimatical infix sentence : \n
;cin>>c
;)print(c
}
/***************************************************************************************/
)][void print(char c
;{ stack s
;)emptyStack(s
)for (int i=0;i<strlen(c);i++
{
if ((int(c[i])>=48)&&(int(c[i]<=57))) // Ascci : 0 - 9
;]cout<<c[i
else
)'('==]if ((c[i]=='+')||(c[i]=='-')||(c[i]=='*')||(c[i]=='/')||(c[i
))')'==]||(c[i
)]switch (c[i
{
case '+':case '-':
))'('=!){ while ((isEmpty(s)=='n')&&(top(s
;){ cout<<top(s
;)pop(s
}
;)]push(s,c[i
;break
}
case '*':case '/':
)))'{ if ((isEmpty(s)=='n')&&((top(s)=='*')||(top(s)=='/
;){ cout<<top(s
;)pop(s
}
;)]push(s,c[i
;break
}
{case '(':
;)]push(s,c[i
49
1
;break
}
{case ')':
)'('=!)while (top(s
;){ cout<<top(s
;)pop(s
}
;)pop(s
'(' // pop
;break
}
} // end of switch
} // end of for
)'while (isEmpty(s)=='n
;){ cout<<top(s
;)pop(s
}
}
:
) * , - , + : , /
")" "(" .
: float char
, :
push :
: + , ) "(" ( , ) push : - , + ) - , + , / , * : ( (
: * , / ) "(" ( , ) push
/ , * : (
push :
(
: "(" , pop "(" .
)
val = float
val = char
,
,
><iostream.h
><string.h
""Stack_PF.h
""Stack_PC.h
#include
#include
#include
#include
;]char s[25
;)][float calculate(char s
float getNumber(char s[],int &i); //
/***************************************************************************************/
)(void main
{
;"cout<<"Enter a mathimatical infix sentence : \n
;cin>>s
;)cout<<s<<" = "<<calculate(s
}
/***************************************************************************************/
)][float calculate(char s
{
;float n1,n2; char op
;stack sF
;Cstack sC
;)emptyStack(sF); emptyStack(sC
)for (int i=0;i<strlen(s);i++
{
if ((int(s[i])>=48)&&(int(s[i]<=57))) // Ascci : 0 - 9
;))push(sF,getNumber(s,i
else
50
1
if ((s[i]=='+')||(s[i]=='-')||(s[i]=='*')||(s[i]=='/')||(s[i]=='(')||(s[i]==')'))
switch (s[i]){
case '*':
case '/':{if ((isEmpty(sC)=='n')&&((top(sC)=='*')||(top(sC)=='/')))
{
n1=top(sF); pop(sF);
n2=top(sF); pop(sF);
op=top(sC); pop(sC);
if (op=='*') push(sF,n1*n2);
else
push(sF,n2/n1);
// op == '/'
}
push(sC,s[i]);
break;
}
case '+':
case '-':{while ((isEmpty(sC)=='n')&&(top(sC)!='('))
{
n1=top(sF); pop(sF);
n2=top(sF); pop(sF);
op=top(sC); pop(sC);
if (op=='+') push(sF,n1+n2);
else
if (op=='-') push(sF,n2-n1);
else
if (op=='*') push(sF,n1*n2);
else
push(sF,n2/n1);
// op == '/'
}
push(sC,s[i]);
break;
}
case '(':{ push(sC,s[i]); break; }
case ')':{
while ((isEmpty(sC)=='n')&&(top(sC)!='('))
{
n1=top(sF); pop(sF);
n2=top(sF); pop(sF);
op=top(sC); pop(sC);
if (op=='+') push(sF,n1+n2);
else
if (op=='-') push(sF,n2-n1);
else
if (op=='*') push(sF,n1*n2);
else
push(sF,n2/n1);
// op == '/'
}
pop(sC);
// pop '('
break;
}
} // end of switch
} // end of for
while (isEmpty(sC)=='n')
{ n1=top(sF); pop(sF);
n2=top(sF); pop(sF);
op=top(sC); pop(sC);
if (op=='+') push(sF,n1+n2);
else
if (op=='-') push(sF,n2-n1);
else
if (op=='*') push(sF,n1*n2);
else
push(sF,n2/n1);
}
return top(sF);
//
op == '/'
51
1
/***************************************************************************************/
float getNumber(char s[],int &i)
{
float num=0;
while ((int(s[i])>=48)&&(int(s[i])<=57))
{
num=num*10+int(s[i])-int('0');
++i;
}
--i;
return num;
}
52
) ( Queue -
, tail
"
,head "
( FIFO = First
) . in , First Out
,
.
. .
...
)Dequeue(q
: EmptyQueue ) (
:
Enqueue
:
Dequeue
:
Top
:
IsEmpty
: CleanUp
)Enqueue(q,B
A
F
B
F
B
, :
: q
) Dequeue(q ) Top(q IsEmpty(q) = falseIsEmpty(EmptyQueue) = true
IsEmpty(Enqueue(q,e)) = false -
A
F
front
Top e1
e2
) (
rear
eN
:
front . tail
Queue_P.h
: Fibonacci
Fibonacci
>#include <iostream.h
"#include "Queue_P.h
;int n
;)int fib(int n
/**************************************/
)(void main
{
;" = cout<<"Enter n
;cin>>n
;)cout<<"Fib("<<n<<")= "<<fib(n
}
/**************************************/
)int fib(int n
{
;int f1,f2
;queue q
;)emptyQueue(q
;if (n<=1) return n
else
{
;)enqueue(q,0
// save in header file : Queue_P.h
>#include <iostream.h
{ struct elem
int
;val
;elem* link
;}
{ struct queue
;elem* front
;elem* tail
;}
/**************************************/
)void emptyQueue(queue &q
{
;q.front=0
;q.tail=0
}
/**************************************/
)char isEmpty(queue q
){ if (q.front==0
;'return 'y
;'else return 'n
}
53
1
/**************************************/
void enqueue(queue &q,int x)
{
elem* h=new elem();
h->val=x;
h->link=0;
if (isEmpty(q)=='y')
{
q.front=h;
q.tail=h;
}
else
{
q.tail->link=h;
q.tail=h;
}
}
/**************************************/
void dequeue(queue &q)
{
if (isEmpty(q)=='y')
cout<<"Error: Queue is empty \n";
else
{
elem* h=q.front;
if (q.front->link==0)
{
q.front=0;
q.tail=0;
}
else
q.front=q.front->link;
delete h;
}
}
/**************************************/
int top(queue q)
{
if (isEmpty(q)=='y')
cout<<"Error: Queue is empty \n";
else
return q.front->val;
}
/**************************************/
void cleanUp(queue &q)
{
if (isEmpty(q)=='y')
cout<<"Error: Queue is already
cleaned up \n";
else
while (isEmpty(q)=='n')
dequeue(q);
}
54
enqueue(q,1);
for (int i=2;i<=n+1;i++)
{
f1=top(q);
dequeue(q);
f2=top(q);
enqueue(q,f1+f2);
}
return top(q);
GCD
#include <iostream.h>
#include "Queue_P.h"
int x,y;
int GCD(int x,int y);
/**************************************/
void main()
{
cout<<"Enter x,y : ";
cin>>x>>y;
cout<<"GCD of ("<<x<<","<<y<<") =
"<<GCD(x,y);
}
/**************************************/
int GCD(int x,int y)
{
int f1,f2;
queue q;
emptyQueue(q);
enqueue(q,y);
enqueue(q,x);
while (top(q)!=0)
{
f1=top(q);
dequeue(q);
f2=top(q)%f1; dequeue(q);
enqueue(q,f2);
enqueue(q,f1);
}
dequeue(q);
return top(q);
}
1
:
, ,
. , )/( ) / ( .
:
) ( .
-1
-2 .
-3 .
{struct node
;char kind
// 0= bread , 1= pie
int
;num
;node* next
;}
{struct Queue
;node *top,*tail
;}
/***************************************************************************************/
)void sort(Queue q,Queue &qB,Queue &qP
;{ Queue h
)while (isEmpty(q)==n
{
;)h=top(q
)if (h->kind==0
// = bread
;)enqueue(qB,h
else
;)enqueue(qP,h
//
= pie
;)dequeue(q
}
}
/***************************************************************************************/
)void amount(Queue q,int &am
;{ Queue h
)while (isEmpty(q)==n
{
;)h=top(q
;am+=h->num
;)dequeue(q
}
}
:
) ...
( .
)void print(BTree b
;){ Queue q; emptyQueue(q
)if (b!=0
{
;)enqueue(q,b
)while (isEmpty(q)==n
{
;)b=Top(q); dequeue(q
;cout<<b->val
;)if (b->l!=0) enqueue(q,b->l
;)if (b->r!=0) enqueue(q,b->r
}
}
}
55
1
:
. ( isPerfect )
char isPerfect(BTree b)
{
Queue q; emptyQueue(q);
char c=n;
if (b!=0) enqueue(q,b);
while (isEmpty(q)==n)
{
b=Top(q); dequeue(q);
if (b==0) c=y;
else
if (c==y) return n;
if (b!=0)
{ enqueue(q,b->l);
enqueue(q,b->r);
}
}
return y;
}
56
-2 :
.
) ) ( P A , B C
( :
)= ( ,
label , label
) ( B goto ), (B
label . ) (B )
) (C !!! ( . ) (B ,
) (B .
)(void P
;{ int i=0
)while (condition
{
; A
;++i
}
;C
)while (i>0
{
; B
;--i
}
}
)(Void P
;{ int i=0
Start:
)if (condition
{
; A
;++i
;goto Start
L1:
; B
;--i
}
else
; C
;if (i>0) goto L1
}
)(void P
{
)if (condition
{
; A
;)(P
; B
}
else
; C
}
: labels ,
, .
: ,
,
. ,
. :
: ) ( .
>#include <iostream.h
"#include "Stack_P.h
// name of Stack = stack , val = int
#include "Stack_PC.h" // name of Stack = Cstack , val = char
/***************************************************************************************/
)void Hanoi(int n,char a,char b,char c
;{ stack sN; Cstack sA,sB,sC; char aux
;)emptyStack(sN); emptyStack(sA); emptyStack(sB); emptyStack(sC
start:
;if (n==1) cout<<a<<" --> "<<c<<endl
else
{
;)push(sN,n
;)push(sA,a
;)push(sB,b
;)push(sC,c
;--n
57
1
aux=b; b=c; c=aux;
goto start;
L:
cout<<a<<" --> "<<c<<endl;
--n;
aux=a; a=b; b=aux;
goto start;
}
if (isEmpty(sN)=='n')
{
n=top(sN); pop(sN);
a=top(sA); pop(sA);
b=top(sB); pop(sB);
c=top(sC); pop(sC);
goto L;
}
}
:
. PostOrder
void printPostOrder(BTree b)
{
Stack s1,s2,s3; emptyStack(s1); emptyStack(s2); emptyStack(s3);
start:
if (b!=0)
{
push(s1,b); push(s3,b);
b=b->L;
goto start;
L1:
push(s2,b);
b=b->R;
goto start;
L2:
cout<<b->val;
}
if ((isEmpty(s2)==n)&&(top(s2)==(top(s3))
{
b=top(s2); pop(s2); pop(s3);
goto L2;
}
if (isEmpty(s1)==n)
{
b=top(s1); pop(s1);
goto L1;
}
}
58
Tree Structures
:
) , (Non Sequential Structures
:
) (.
): (Tree)
, nodes , links
(Hierarchical cycles , , root
, ...
, ,
.
: :
:
)((2+y)*(x-5))+(z/x
/
x
z
5
+
x
: Binary Trees -
.
: 1 B :
) B = (
> B = < O,B1,B2 O B2 , B1 . . B1
B2 .
59
1
: 2
B1 , O B2 , O
.
: 3
. , .
: , , ,
ni ) (Ancestor , nj ni , nj ni . nj
ni ) (Grandchild , nj ni , nj ni . nj
: 4
:
) , (Internal Nodes .
: 5
) (Path , .
O
root /
+
)(
Internal Node
/
B2
||
+
x
||
)(
)External Node (leaf
B1
||
O
||
n1
n3
n2
n4
60
B x :
)D(B
)Vol(B
)h(x
)H(B
)L(B
6
7
8
D(B) = 2
)Vol( < O,B1,B2 > ) = 1 + Vol(B1) + Vol(B2
h(x) = 0
; x = root
h(x) = 1 + h(y) ; y = father of x
} H(B) = max{ h(x) ; x is a node of B
:
Vol(empty tree) = 0
)LC(B
)LCI(B
)LCE(B
: B , :
Root(B) = n1
Left Son (n1) = n2
Right Son (n1) = n4
} Leafs = { n8 , n10 , n5 , n9
} Internal Nodes = { n1 , n2 , n3 , n4 , n6 , n7
h(n1) = 0 , h(n2) = h(n4) = 1 , h(n3) = h(n5) = h(n7) = 2
h(n6) = h(n9) = 3 , h(n8) = h(n10) = 4
H(B) = 4
L(B) = 3
LC(B) = 22
LCI(B) = 9
LCE(B) = 13
n1
n4
n7
n2
n3
n5
n6
n9
n10
:
n8
-1 ) : (Linear .
-2 ) : (Complete 0
1
k
B - 1 : h
2k
h+1
Vol(B) = 1 + 2 + 4 + ..... + 2 = 2
61
1
-3 ): (Perfect
, ,
} { 47 , 25 , 77 , 11 , 43 , 93 , 65 , 31 , 17 , 7 , 44 , 68
47
25
77
93
: 2 :
} { 6 , 4 , 5 , 10 , 2 , 1 , 0 , 11
65
68
11
43
44
17 31
10
5
11
2
1
0
: 1 B n , H :
x . x
: B f , H
: n f :
n +1
.
f
2
: 2 B . n B :
: , n
: 3 B f , :
Log 2 n H n 1
Log 2 .f
)n ( n 1
2
. n2
n
2 nLog
) Log k LC ( B
2
k =1
PF ( B ). log 2 f
62
, .
-1 : :
{ struct node
;element val
;node *L,*R
;}
L
R
b ) ( .
:
b
d
k
m
f G
e
G
-2 :
, ,
:
: n , 2n , 2n+1 .
m . m/2
n
2n+1
2n
;const n=100
{ struct node
;element val
// int , char , float , ...
;int L,R
;}
;]typedef node BTable[n
{ struct TabBTree
;int root
;BTable tab
;}
;TabBTree b
63
: :
3
7
9
2
4
6
19
18
14
root
1
1
2
3
4
5
6
7
8
9
a
b
C
d
k
L
e
m
f
G
14
18
19
: Traversal -
.
, :
-
,
: Preorder
,
: Inorder
,
: Postorder
: :
a
} Preorder : { a , b , d , e , f , G , C , k , L , m
} Inorder : { d , f , e , G , b , a , k , C , m , L
} Postorder : { f , G , e , d , b , k , m , L , C , a
C
L
b
d
k
e
m
G
64
( 2 ( 1 :
( 5 ( 4 ( 3
( 8 ( 7 ( 6
( 10 ( 9
( 13 ( 12 ( 11
( 16 ( 15 ( 14
#include <iostream.h>
#include <conio.h>
//
#include <ctype.h>
//
#include <stdlib.h> //
#include <math.h>
//
#include "Queue_pBTree.h"
const m=100;
struct node{
int val;
node *l,*r;
};
typedef node* BTree;
BTree b=0,q=0;
int n,i,maxH;
int a[m]; // for width
char c;
// = choice of
-->
-->
-->
-->
//
user
char menu();
void insertNode(BTree &b,int n);
void print(BTree b);
// choices of print
void printInfix(BTree b);
void printPrefix(BTree b);
void printPostfix(BTree b);
void printInternal(BTree b);
void printLeaf(BTree b);
void printPath(BTree b,int n);
int internalNum(BTree b);
int leafNum(BTree b);
void treeHeight(BTree b,int h,int &maxH);
void fillLevels(BTree b,int a[],int i);
// for width
int width(BTree b);
int nodeHeight(BTree b,int x);
int LC(BTree b,BTree k);
int LCI(BTree b,BTree k);
int LCE(BTree b,BTree k);
char isLinear(BTree b);
char isComplete(BTree b);
char isPerfect(BTree b);
/***************************************************************************************/
void main()
{
do{ clrscr();
c=menu();
switch (c){
case '1':{cout<<"\n\nEnter the value to insert , val = ";
cin>>n;
insertNode(b,n);
65
case
case
case
case
case
case
case
case
case
case
case
case
case
case
break;
}
'2':{print(b);
break;
}
'3':{if ((b==0)||((b->l==0)&&(b->r==0)))
cout<<"\n\nThere are no internal nodes ! \n";
else printInternal(b);
break;
}
'4':{if (b==0) cout<<"\n\nThere are no external nodes ! \n";
else
printLeaf(b);
break;
}
'5':{cout<<"\nEnter the node you want to see its path , n = ";
cin>>n;
printPath(b,n);
break;
}
'6':{cout<<"\nThis tree contains "<<internalNum(b)<<" internal nodes\n";
break;
}
'7':{n=0;
cout<<"\nThis tree contains "<<leafNum(b)<<" leaves !\n";
break;
}
'8':{maxH=0;
treeHeight(b,0,maxH);
cout<<"\nThe height of this tree is H(B)= "<<maxH<<endl;
break;
}
'9':{cout<<"\nThe width of this tree = "<<width(b);
break;
}
'M':{cout<<"\nLC(B) = "<<LC(b,b);
break;
}
'I':{cout<<"\nLCI(B) = "<<LCI(b,b);
break;
}
'E':{cout<<"\nLCE(B) = "<<LCE(b,b);
break;
}
'L':{if (isLinear(b)=='y') cout<<"\nYes , this tree is linear !\n";
else
cout<<"\nNo , this tree isn't linear !\n";
break;
}
'C':{if (isComplete(b)=='y') cout<<"\nYes , this tree is complete !\n";
else
cout<<"\nNo , this tree isn't complete!\n";
break;
}
'P':{
if (isPerfect(b)=='y') cout<<"\nYes , tree is perfect !\n";
else
cout<<"\nNo , this tree isn't perfect !\n";
break;
}
66
1
char menu()
{ char ch;
do{
clrscr();
cout<<"0: Exit \n";
cout<<"1: Insert Node \n";
cout<<"2: Print Tree \n";
cout<<"3: Print Internal Nodes \n";
cout<<"4: Print External Nodes (Leafs)\n";
cout<<"5: Print Path Of A Node \n";
cout<<"6: Number Of Internal Nodes \n";
cout<<"7: Number Of External Nodes \n";
cout<<"8: Height Of Tree \n";
cout<<"9: Width Of Tree \n";
cout<<"M: LC Of Tree \n";
cout<<"I: LCI Of Tree \n";
cout<<"E: LCE Of Tree \n";
cout<<"L: Is The Tree Linear ? \n";
cout<<"C: Is The Tree Complete ? \n";
cout<<"P: Is The Tree Perfect ? \n\n";
cout<<"Enter your choice : ";
ch=getche(); cout<<endl;
ch=toupper(ch);
} while (((ch!='M')&&(ch!='I')&&(ch!='E')&&(ch!='L')&&(ch!='C')&&(ch!='P'))&&
((int(ch)<48)||(int(ch)>57)));
return ch;
}
/***************************************************************************************/
void insertNode(BTree &b,int n)
{
if (b==0)
{ b=new node; b->val=n; b->l=0; b->r=0; }
else
if (n<b->val) insertNode(b->l,n);
else
insertNode(b->r,n);
}
/***************************************************************************************/
void print(BTree b)
{ char p;
do{
clrscr();
cout<<"1: Print Infix-Traversal \n";
cout<<"2: Print Prefix-Traversal \n";
cout<<"3: Print Postfix-Traversal \n\n\n";
cout<<"Enter your choice : ";
p=getche(); cout<<endl;
} while ((p!='1')&&(p!='2')&&(p!='3'));
if (b==0) cout<<"\n\nThis tree is empty ... , press any key to continue ... \n";
else
if (p=='1') printInfix(b);
else
if (p=='2') printPrefix(b);
else
printPostfix(b);
}
/***************************************************************************************/
void printInfix(BTree b)
{ if (b!=0)
{
printInfix(b->l);
cout<<b->val<<" ";
printInfix(b->r);
}
}
67
1
/***************************************************************************************/
void printPrefix(BTree b)
{
if (b!=0)
{
cout<<b->val<<" ";
printPrefix(b->l);
printPrefix(b->r);
}
}
/***************************************************************************************/
void printPostfix(BTree b)
{
if (b!=0)
{
printPostfix(b->l);
printPostfix(b->r);
cout<<b->val<<" ";
}
}
/***************************************************************************************/
void printInternal(BTree b)
{
if ((b!=0)&&((b->l!=0)||(b->r!=0)))
{
cout<<b->val<<" ";
if (b->l!=0) printInternal(b->l);
if (b->r!=0) printInternal(b->r);
}
}
/***************************************************************************************/
void printLeaf(BTree b)
{ if (b!=0)
{ if ((b->l==0)&&(b->r==0))
cout<<b->val<<" ";
else
{ if (b->l!=0) printLeaf(b->l);
if (b->r!=0) printLeaf(b->r);
}
}
}
/***************************************************************************************/
void printPath(BTree b,int n)
{
BTree t=b;
cout<<"\nPath of "<<n<<" is : ";
while ((t!=0)&&(t->val!=n))
{
cout<<t->val<<" ";
if (n<t->val) t=t->l;
else
t=t->r;
}
if (t!=0) cout<<t->val<<endl;
else
cout<<"The node "<<n<<" doesnt exist ! \n";
}
/***************************************************************************************/
int internalNum(BTree b)
{
if ((b!=0)&&((b->l!=0)||(b->r!=0)))
return 1+internalNum(b->l)+internalNum(b->r);
else
return 0;
}
68
1
/***************************************************************************************/
int leafNum(BTree b)
{
if (b==0) return 0;
else
{ if ((b->l==0)&&(b->r==0)) return 1;
else return leafNum(b->l)+leafNum(b->r);
}
}
/***************************************************************************************/
void treeHeight(BTree b,int h,int &maxH)
{ if ((b==0)||((b->l==0)&&(b->r==0)))
{ if (h>maxH) maxH=h; }
else
{ treeHeight(b->l,h+1,maxH);
treeHeight(b->r,h+1,maxH);
}
}
/***************************************************************************************/
void fillLevels(BTree b,int a[],int i)
{ if (b!=0)
{ ++a[i];
if (b->l!=0) fillLevels(b->l,a,i+1);
if (b->r!=0) fillLevels(b->r,a,i+1);
}
}
/***************************************************************************************/
int width(BTree b)
{ int H=0;
treeHeight(b,0,H);
for (i=0;i<=H;i++) a[i]=0;
fillLevels(b,a,0);
int wid=a[0];
for (i=1;i<=H;i++)
if (a[i]>wid) wid=a[i];
return wid;
}
/***************************************************************************************/
int nodeHeight(BTree b,int x)
{ BTree t=b;
int h=0;
while ((t!=0)&&(t->val!=x))
{ ++h;
if (x<t->val) t=t->l;
else
t=t->r;
}
if (t!=0) return h;
else
return 0;
}
/***************************************************************************************/
int LC(BTree b,BTree k)
{ if (k!=0) return nodeHeight(b,k->val)+LC(b,k->l)+LC(b,k->r);
else
return 0;
}
/***************************************************************************************/
int LCI(BTree b,BTree k)
{ if ((k!=0)&&((k->l!=0)||(k->r!=0)))
return nodeHeight(b,k->val)+LCI(b,k->l)+LCI(b,k->r);
else return 0;
}
/***************************************************************************************/
69
1
int LCE(BTree b,BTree k)
{ if (k!=0)
if ((k->l==0)&&(k->r==0)) return nodeHeight(b,k->val);
else
return LCE(b,k->l)+LCE(b,k->r);
else
return 0;
}
/***************************************************************************************/
char isLinear(BTree b)
{ if (b==0) return 'y';
else
if ((b->l!=0)&&(b->r!=0)) return 'n';
else
if (b->l!=0) return isLinear(b->l);
else
return isLinear(b->r);
}
/***************************************************************************************/
char isComplete(BTree b)
{ int H=0;
treeHeight(b,0,H);
for (i=0;i<=H;i++) a[i]=0;
fillLevels(b,a,0);
char q='y';
for (i=0;i<=H;i++)
if (a[i]!=pow(2,i)) { q='n'; break; }
return q;
}
/***************************************************************************************/
char isPerfect(BTree b)
{
Queue q; emptyQueue(q);
char c=n;
if (b!=0) enqueue(q,b);
while (isEmpty(q)==n)
{
Top(q); dequeue(q);
if (b==0) c=y;
else
if (c==y) return n;
if (b!=0)
{ enqueue(q,b->l);
enqueue(q,b->r);
}
}
return y;
}
70
) !( .
;'return 'n
:
.
: .
;)insertNode(b2,b->val
;)deleteNode(b->l,x,b2
;)deleteNode(b->r,x,b2
void deleteNode(BTree
){ if (b!=0
{
)if (b->val!=x
)if (b->l!=0
)if (b->r!=0
}
}
b2 . b
:
B2 B1 B1 ) B2 (.:
-1 B2 . B1
-2 B2 . B1
3
7
: :
B2
B1
3
7
2
6
71
1
;)if (q=='y') q=equal(b1->r,b2->r
;return q
}
}
/***************************************************************************************/
;int n=0
;)frequency(b1,b2,n
;" if (n>0) cout<<"b2 is part of b1 "<<n<<" times
else
;" cout<<"b2 is not part of b1
:
) (Mirror Similar ,
) ( .
, .
1
2
4
3
5
3
7
2
6
72
Generalized Trees
. , :
-1 :
, )= (
. , .
) , (1 ) ( , 6
, ): (2
d
c
b
g
)(1
)(2
:
-2 :
;const n=6
// n = Degree of GTree
{struct gnode
;element val
// int , char , float , ...
;]gnode* a[n
;}
;typedef gnode* GTree
, . ,
, .
g
-
e
73
, :
, " "0 , " "1
.
a
0
d
1
g
1
b
0
c
0
e
1
f
0
:
, :
.
.
:
a
b
d
c
e
e
g
:
, g g .
)void printLeafs(Gtree g
){ if (g!=0
)if (g->a[0]==0
;cout<<g->val
else
)for (int i=0;i<n;i++
;)]printLeafs(g->a[i
}
74
const n=6;
struct node{
int val;
node *l,*r;
};
typedef node* BTree;
struct gnode{
int val;
gnode* a[n];
};
typedef gnode* GTree;
BTree b=0; GTree g=0;
/***************************************************************************************/
void c(GTree g,BTree &b)
{
if (g->a[0]!=0)
{
b->l=new node();
b->l->val=g->a[0]->val;
b->l->l=0; b->l->r=0;
}
else return ; //
BTree b1=b->l;
for (int i=1;i<n;i++)
if (g->a[i]!=0)
{
b1->r=new node();
b1=b1->r;
b1->val=g->a[i]->val;
b1->l=0; b1->r=0;
}
else
break;
b1=b->l;
for (i=0;i<n;i++)
if (g->a[i]!=0)
{
c(g->a[i],b1);
b1=b1->r;
}
else
break;
}
/***************************************************************************************/
void convert(GTree g,BTree &b)
{ if (g!=0)
{
b=new node();
b->val=g->val;
b->l=0; b->r=0;
c(g,b);
}
}
75
Graphs
, .
: Graph -
><v,w><w,v
> <v,w . vw :
,
.
: 1
>G = <V,E
: G
}V<G> = {1,2,3,4
}>E(G) = {<1,2>,<1,4>,<2,3>,<2,4>,<3,4
2
3
) ,
( :
: 2
>G2 = <V,E
: G2
}V<G2> = {1,2,3,4
}>E(G2) = {<1,2>,<2,1>,<2,3>,<3,4>,<4,2
1
4
3
2
)n(n 1
: n
2
. (complete graph
, )
76
1
1
: 3
: G
>G = <V,E
}V<G> = {1,2,3,4
}>E(G) = {<1,2>,<1,3>,<1,4>,<2,3>,<2,4>,<3,4
4
3
> < V , E
- V V and E E
- < v, w > E v V and w V
:
) Deg(v . ) Deg (v
+
). Deg (v
:
x2
Deg(x1) = 1
+
Deg (x1) = 1
Deg (x1) = 0
Deg(x4) = 2
+
Deg (x4) =1
Deg (x4) = 1
Deg(x3) = 5
+
Deg (x3) = 2
Deg (x3) = 3
): (path
x1
x3
x4
v w v , w w v
:
:
-1 ) ( :
) M (Adjacency Matrix , .
:
;const n=100
;]typedef char MGraph[n][n
77
1
:
:
n
Y
n
n
Y
n
n
n
n
Y
n
n
Y
n
Y
n
x1
x0
x3
x2
-2 :
30
110
: :
x0
x1
x3
x2
120
200
, , ... , .
350
M , . ] M[i][j
vi , vj vi . vj -1
. , .
:
;const n=100
or: float , char , ...
:
:
-1
32
-1
-1
18
-1
-1
-1
43
-1
57
-1
-1
25
-1
-1
//
x1
25
43
x0
18
32
57
x3
x2
-3 :
) , (Adjacency Lists
, . i j i
i , j .
;const n=100
{struct vertex
;element val
// element= int , float , char , ...
;vertex* next
;}
;]typedef vertex* LGraph[n
78
1
:
x1
x3
x0
x2
3
:
, :
Graph Traversal -
-1 :
: Depth First -
) ( , ,
, ... ,
. .
> G = < V , E v , :
;]char visited[n
, n , y .
: pseudocode
;]char visited[n
;for (int i=0;i<n;i++) visited[i]=n
= // v
)void DFS(int v
{
;int w
= // w
;visited[v]=y
)for (each vertex w adjacent to v
)if (visited[w]==n
;)DFS(w
-2-1
: Breadth First -
, ) .(Queue
. .
pseudocode :
79
1
= // v
)void BFS(int v
{
;]char visited[n
;int w
= // w
;Queue q
;for (int i=0;i<n;i++) visited[i]=n
;visited[v]=y
;)emptyQueue(q
{do
)for (all vertices w adjacent to v
)if (visited[w]==n
{
;)enqueue(q,w
;visited[w]=y
}
;if (isEmpty(q)==y) exit
else
{
;)v=Top(q
;)dequeue(q
}
exit
//
: v1 :
:
)= (
v1,v2,v4,v8,v5,v6,v3,v7
)= ( :
v1,v2,v3,v4,v5,v6,v7,v8
v1
v3
v6
v5
v7
v2
v4
v8
-2 :
. .
j i , i j < i
> , , j j ) ) Deg+(i i (.
, DFS OrDFS
.
)(pseudocode
)void DTraversal(Graph G
{
;]char visited[n
;for (int i=0;i<n;i++) visited[i]=n
)for (i=0;i<n;i++
)if (visited[i]==n
;)DFS(i,visited
}
80
1
)][void DFS(int v,char visited
{
;visited[v]=y
)for (int j=0;j< Deg+(v);j++
)if (visited[j]==n
;)DFS(j,visited
}
:
G
, :
1,3,2,6,5,7,
4,9,
8
:
1,3,5,6,7,
2,
4,9,
8
G . .
: , :
;const n=10
{srtuct vertex
;int val
;vertex* next
;}
;]typedef vertex* LGraph[n
;LGraph G
/***************************************************************************************/
)char isBTree(LGraph G
{
;int sum=0
//
vertex *p,*q; //
)for (int i=0;i<n;i++
{
;]p=G[i
;sum=0
)while (p!=0
;{ ++sum
;if (sum>2) return n
)for (j=0;j<n;j++
)if (j<>i
{
;]q=G[j
)while (q!=0
{
;if (q->val==p->val) return n
;q=q->next
}
}
;p=p->next
}
}
;return y
}
81