zoukankan      html  css  js  c++  java
  • HDU 1427 速算24点

    全排列,枚举运算符,枚举优先级。

    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    using namespace std;
    
    const int INF=0x7FFFFFFF;
    char s[5];
    int a[5],b[5],f[5],op[5],ans;
    
    int get()
    {
        if(s[0]=='A') return 1;
        if(s[0]=='J') return 11;
        if(s[0]=='Q') return 12;
        if(s[0]=='K') return 13;
    
        int sum=0;
        for(int i=0; s[i]; i++) sum=sum*10+s[i]-'0';
        return sum;
    }
    
    int w(int a,int b,int op)
    {
        if(op==1) return a+b;
        if(op==2) return a-b;
        if(op==3) return a*b;
        if(op==4)
        {
            if(b==0) return 0x7fffffff;
            if(a%b!=0) return 0x7fffffff;
            return a/b;
        }
    }
    
    bool cal1(int op0,int op1,int op2)
    {
        int x1=0,x2=0,x3=0;
        x1=w(b[0],b[1],op0);
        if(x1==INF) return 0;
        x2=w(x1,b[2],op1);
        if(x2==INF) return 0;
        x3=w(x2,b[3],op2);
        if(x3==INF) return 0;
        if(abs(x3)!=24) return 0;
        return 1;
    }
    
    bool cal2(int op0,int op1,int op2)
    {
        int x1=0,x2=0,x3=0;
        x1=w(b[0],b[1],op0);
        if(x1==INF) return 0;
        x2=w(b[2],b[3],op2);
        if(x2==INF) return 0;
        x3=w(x1,x2,op1);
        if(x3==INF) return 0;
        if(abs(x3)!=24) return 0;
        return 1;
    }
    
    void dfs(int x)
    {
        if(x==4)
        {
            for(op[0]=1;op[0]<=4;op[0]++)
            {
                for(op[1]=1;op[1]<=4;op[1]++)
                {
                    for(op[2]=1;op[2]<=4;op[2]++)
                    {
                        if(cal1(op[0],op[1],op[2])==1) ans=1;
                        if(ans==1) break;
                        if(cal2(op[0],op[1],op[2])==1) ans=1;
                        if(ans==1) break;
                    }
                    if(ans==1) break;
                }
                if(ans==1) break;
            }
            return;
        }
        for(int i=0;i<4;i++)
        {
            if(f[i]==1) continue;
            f[i]=1,b[x]=a[i];
            dfs(x+1); if(ans==1) return;
            f[i]=0;
        }
    }
    
    int main()
    {
        while(~scanf("%s",s))
        {
            a[0]=get();
            scanf("%s",s); a[1]=get();
            scanf("%s",s); a[2]=get();
            scanf("%s",s); a[3]=get();
    
            memset(f,ans=0,sizeof f);
            dfs(0);
    
            if(ans==1) printf("Yes
    ");
            else printf("No
    ");
        }
        return 0;
    }
  • 相关阅读:
    怎么导出SQL所有用户表的字段信息
    全面掌握C#中的拖放操作
    C#中使用Hook(钩子)
    如何在winform程序中显示网页
    设置socket.Receive()的等待时延
    局域网QQ(C#版)
    C#实现系统热键的功能
    使用C#在应用程序间发送消息
    某某人整理的c#.net函数列表
    C#串口通信编程类(修改版)
  • 原文地址:https://www.cnblogs.com/zufezzt/p/5657208.html
Copyright © 2011-2022 走看看