Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5569c21

Browse files
Minmax for Tree #193
1 parent 1f9fb6d commit 5569c21

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

‎Trees/MinMax tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// A simple C++ program to find
2+
// maximum score that
3+
// maximizing player can get.
4+
#include<bits/stdc++.h>
5+
using namespace std;
6+
7+
// Returns the optimal value a maximizer can obtain.
8+
// depth is current depth in game tree.
9+
// nodeIndex is index of current node in scores[].
10+
// isMax is true if current move is
11+
// of maximizer, else false
12+
// scores[] stores leaves of Game tree.
13+
// h is maximum height of Game tree
14+
int minimax(int depth, int nodeIndex, bool isMax,
15+
int scores[], int h)
16+
{
17+
// Terminating condition. i.e
18+
// leaf node is reached
19+
if (depth == h)
20+
return scores[nodeIndex];
21+
22+
// If current move is maximizer,
23+
// find the maximum attainable
24+
// value
25+
if (isMax)
26+
return max(minimax(depth+1, nodeIndex*2, false, scores, h),
27+
minimax(depth+1, nodeIndex*2 + 1, false, scores, h));
28+
29+
// Else (If current move is Minimizer), find the minimum
30+
// attainable value
31+
else
32+
return min(minimax(depth+1, nodeIndex*2, true, scores, h),
33+
minimax(depth+1, nodeIndex*2 + 1, true, scores, h));
34+
}
35+
36+
// A utility function to find Log n in base 2
37+
int log2(int n)
38+
{
39+
return (n==1)? 0 : 1 + log2(n/2);
40+
}
41+
42+
// Driver code
43+
int main()
44+
{
45+
// The number of elements in scores must be
46+
// a power of 2.
47+
int scores[] = {3, 5, 2, 9, 12, 5, 23, 23};
48+
int n = sizeof(scores)/sizeof(scores[0]);
49+
int h = log2(n);
50+
int res = minimax(0, 0, true, scores, h);
51+
cout << "The optimal value is : " << res << endl;
52+
return 0;
53+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /