暴力题,速算24点

题目总结:

1.绝对暴力题。复杂度4*4*4*4*3*2*1*5远远达不到1000ms

2.涉及到next_permutation(p,p+n)全排列方法

解题过程的问题:

1.一直超时,最后改了很多局部变量成全局变量,906ms水过,很险。

2.之前wa了不下10次,思路有问题:排列数字和符号,按照符号的优先级进行计算,wa了,应该有括号

3.要学会证明为什么上面的想法不对。例如,(a+b)*(c+d)=24是唯一解,若只按照优先级,永远只能计算a+(b*c)+d,那永远达不到终点。

4.括号匹配情况有5中,列举一下就知道(a#b)#(c#d),((a#b)#c)#d,a#((b#c)#d),(a#(b#c))#d,a#((b#c)#d)

用了半天时间来做了,水题。

#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;

#define inf -10000

int n[10];

int get(char *a)
{
    if(a[0]=='1'&&a[1]=='0') return 10;
    if(a[0]=='A') return 1;
    if(a[0]=='J') return 11;
    if(a[0]=='Q') return 12;
    if(a[0]=='K') return 13;
    return a[0]-'0';
}

int note(int a,int b,int k)
{
    if(k==0) return a+b;
    if(k==1) return a-b;
    if(k==2) return a*b;
    if(k==3 && b!=0) {
        if(a%b==0) return a/b;
        else return inf;
    }
    if(k==3 && b==0) return inf;
}
int a,b,c,d;
int i,j,k;
int cal1()
{
    int res = a;
    int t1=note(a,b,i);
    if(t1 == inf) return -1;
    int t2=note(t1,c,j);
    if(t2==inf) return -1;
    int t3=note(t2,d,k);
    if(t3==inf) return -1;
    return t3;
}
int cal2()
{
    int t1=note(a,b,i),t2=note(c,d,k);
    if(t1==inf || t2==inf) return -1;
    int t3 = note(t1,t2,j);
    return t3==inf ? -1 : t3;
}
int cal3()
{
    int t1=note(b,c,j);
    if(t1==inf) return -1;
    int t2=note(a,t1,i);
    if(t2==inf) return -1;
    int t3=note(t2,d,k);
    return t3==inf ? -1 : t3;
}
int cal4()
{
    int t1=note(b,c,j);
    if(t1==inf) return -1;
    int t2=note(t1,d,k);
    if(t2==inf) return -1;
    int t3=note(a,t2,i);
    return t3==inf ? -1 : t3;
}
int cal5()
{
    int t1=note(c,d,k);
    if(t1==inf) return -1;
    int t2=note(b,t1,j);
    if(t2==inf) return -1;
    int t3=note(a,t2,i);
    return t3==inf?-1:t3;
}
int t1,t2,t3,t4,t5;
bool deal()
{
    for(i=0;i<4;i++)
    {
        for(j=0;j<4;j++)
        {
            for(k=0;k<4;k++)
            {
                t1=cal1();
                t2=cal2();
                t3=cal3();
                t4=cal4();
                t5=cal5();
                if(t1==24||t1==-24) return 1;
                if(t2==24||t2==-24) return 1;
                if(t3==24||t3==-24) return 1;
                if(t4==24||t4==-24) return 1;
                if(t5==24||t5==-24) return 1;
            }
        }
    }
    return 0;
}

bool cal()
{
    sort(n+1,n+5);
    do
    {
        a=n[1],b=n[2],c=n[3],d=n[4];
        if(deal()) return true;
    }
    while(next_permutation(n+1,n+5));
    return false;
}

int main()
{
    char c1[3],c2[3],c3[3],c4[3];
    while(scanf("%s %s %s %s",c1,c2,c3,c4)!= EOF)
    {
        n[1]=get(c1);n[2]=get(c2);n[3]=get(c3);n[4]=get(c4);
        if(cal()) puts("Yes");
        else puts("No");
    }
    return 0;
}

 

posted on 2013-11-21 14:26  从此以后  阅读(865)  评论(0编辑  收藏  举报