uva 10118,记忆化搜索

这个题debug了长达3个小时,acm我不能放弃,我又回来了的第一题!

 

一开始思路正确,写法不行,结果越改越乱

看了网上某神的代码,学习了一下

coding+debug:4小时左右,记忆化搜索+dp类型第一题

/*

 * Author:  Bingo

 * Created Time:  2015/3/2 21:23:20

 * File Name: uva10118.cpp

 */

#include <iostream>

#include <cstdio>

#include <cstdlib>

#include <cstring>

#include <cmath>

#include <algorithm>

#include <string>

#include <vector>

#include <stack>

#include <queue>

#include <set>

#include <time.h>

using namespace std;

const int maxint = -1u>>1;

int dp[45][45][45][45];

int a[4][45];

int f[5];

int n;

int ans;

int ok(int i,int j,int p,int q){

    int m[500];

    memset(m,0,sizeof(m));

    int top=0;

    for (int t=0;t<i;t++)

        m[top++]=a[0][t];

    for (int t=0;t<j;t++)

        m[top++]=a[1][t];

    for (int t=0;t<p;t++)

        m[top++]=a[2][t];

    for (int t=0;t<q;t++)

        m[top++]=a[3][t];

    sort(m,m+top);

    int cnt=0,tans=0;

    for (int t=0;t<top;){

        if (m[t]==m[t+1]){

            tans++;

            t+=2;

        }else {

            cnt++;

            t++;

        }

    }

    if (cnt<=5){

        ans=max(ans,tans);

        return 1;

    }

    return 0;

}

int dfs(int i,int j,int p,int q){

    if (i==n&&j==n&&p==n&&q==n) return 0;

    if (i<n){

        i++;

        if(ok(i,j,p,q)) {

            if (dp[i][j][p][q]){

                ans=max(ans,dp[i][j][p][q]);

                dp[i][j][p][q]=ans;

            }else {dp[i][j][p][q]=ans;dfs(i,j,p,q);}

        }

    }

    if (j<n){

        j++;

        if(ok(i,j,p,q)) {

            if (dp[i][j][p][q]){

                ans=max(ans,dp[i][j][p][q]);

                dp[i][j][p][q]=ans;

            }else {dp[i][j][p][q]=ans;dfs(i,j,p,q);}

        }

    }

    if (p<n){

        p++;

        if(ok(i,j,p,q)) {

            if (dp[i][j][p][q]){

                ans=max(ans,dp[i][j][p][q]);

                dp[i][j][p][q]=ans;

            }else {dp[i][j][p][q]=ans;dfs(i,j,p,q);}

        }

    }

    if (q<n){

        q++;

        if(ok(i,j,p,q)) {

            if (dp[i][j][p][q]){

                ans=max(ans,dp[i][j][p][q]);

                dp[i][j][p][q]=ans;

            }else {dp[i][j][p][q]=ans;dfs(i,j,p,q);}

        }

    }

}

int main () {

    while(cin>>n&&n){

        for (int i=0;i<n;i++) {

            cin >> a[0][i]>>a[1][i]>>a[2][i]>>a[3][i];

        }

        memset(dp,0,sizeof(dp));

        ans=0;

        memset(f,0,sizeof(f));

        //ok(3,3,3,3);

        dfs(0,0,0,0);

        cout << ans<<endl;

    }

    return 0;

}
View Code

 

你可能感兴趣的:(uva)