九度 oj 题目1482:玛雅人的密码

62 篇文章 0 订阅
6 篇文章 0 订阅

http://ac.jobdu.com/problem.php?pid=1482


参考了 http://blog.csdn.net/thyftguhfyguj/article/details/8994521


#include <stdio.h>
#include <cstring>
#include <queue>

static bool visit[1600000];
typedef struct node{ 
    char s[14];
    int step; 
} Node; 

bool there2012(char s[]){ 
    int len = (int) strlen(s);  
    bool found = false;
    for (int i = 0; i < len-3; ++i) { 
        if(s[i] == '2' && s[i+1] == '0' && s[i+2] == '1' && s[i+3] == '2'){ 
            found = true; 
            break;
        }   
    } 
    return found;
} 

int hashString(char s[]){ 
    int hashcode = 0; 
    int len = (int) strlen(s); 
    for (int i = 0; i < len; ++i) { 
        hashcode*=3; 
        hashcode += s[i] - '0';
    } 
    return hashcode;
}  


int main(){ 
    //freopen("in/1482.in","r",stdin); 
    int n,n0,n1,n2;
    char s[14];
    std::queue<Node> Q;
    while(scanf("%d\n",&n)!=EOF){ 
        scanf("%s",s); 
        while(!Q.empty()) Q.pop(); 
        memset(visit,false,sizeof(visit)); 
        n0 = n1 =n2 = 0;
        for (int i = 0; i < n; ++i) { 
            if(s[i] == '0') n0++;  
            if(s[i] == '1') n1++;  
            if(s[i] == '2') n2++;  
        } 
        if(n0<1||n1<1||n2<2) { 
            printf("-1\n");
            continue;  
        }  
        Node node;
        strcpy(node.s,s),node.step = 0;  
        Q.push(node);
        bool found = false;
        int min_step = 0;
        while(!Q.empty() && !found){ 
            Node t = Q.front();
            Q.pop(); 
            if(visit[hashString(t.s)]) continue;
            visit[hashString(t.s)] = true;
            if(there2012(t.s) ){ 
                found = true; 
                min_step = t.step;
                break;
            }  
            for (int i = 0; i < n-1; ++i) { 
                std::swap(t.s[i],t.s[i+1]);  
                Node newt;
                strcpy(newt.s,t.s);
                newt.step = t.step+1;
                Q.push(newt); 
                std::swap(t.s[i],t.s[i+1]);  
            } 
        }  
        if(found) printf("%d\n",min_step); 
        else printf("-1\n"); 
    }   
    return 0;
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值