Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

A typical game theory problem - Recursion + Memorized Search
http://justprogrammng.blogspot.com/2012/06/interviewstreet-challenges-permutation.html#.VlEMrvmrTIU

#include<iostream>
#include<set>
using namespace std;

//    Bit Ops Utils
int set(int a, int i)
{
    return  a | 1 << i;
}
int unset(int a, int i)
{
    return a & (~(1 << i));
}
int get(int a, int i)
{
    return ((a&(1 << i)) >> i);
}

//
int array[32770]; // for results record
int a[32770];

//
int play(int a[], int n, int r)
{
    if (array[r] != -1) return array[r];

    // Check increase
    int last = 0, i;
    for (i = 0; i < n; i++)
    {
        if (get(r, i))
        {
            if (a[i]>last)    last = a[i];
            else    break;
        }
    }
    if (i == n)
    {
        array[r] = 0;
        return 0;
    }

    //    Recursively check each possibility
    int rec[2] = { 0, 0 };
    for (int i = 0; i<n; i++)
    {
        if (get(r, i))
        {
            int ret = play(a, n, unset(r, i));
            rec[ret] = 1;
        }
    }
    array[r] = rec[0];

    return array[r];

}

int main()
{
    int T;
    cin >> T;

    while (T--)
    {
        for (int i = 0; i < 32768; i++)
            array[i] = -1;
        
        int n; cin >> n;    
        for (int i = 0; i < n; i++)
            cin >> a[i];

        int res = play(a, n, (1 << n) - 1);
        if (!res)    cout << "Bob\n";
        else        cout << "Alice\n";
    }
}
View Code

 

posted on 2015-11-22 10:34  Tonix  阅读(277)  评论(0编辑  收藏  举报