POJ 1248 Safecracker 模拟+排序

传送门:http://poj.org/problem?id=1248

题意:给定字符串,从字符串中选择字符转换成整形满足密码公式,要求输出结果按照最大字典序输出。

因为没有重复的字符,所以最多有26个字符,5重循环直接暴力不会超时。

注意的是排序的时候吧字符串从大到小排序扫描循环的时候vwxyz,且不能有重复,前面都是从0开始,保证字典序肯定最大,所以只能从最后一个慢慢+1,让字典序递减,看是否满足密码公式。

eg:

Z Y X W V,判断。。。

Z Y X W U,判断。。。

Z Y X W T,判断。。。(假设给定的字符串是26个字母)

#include <iostream>
#include <set>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
int len,ans;
char s[30],tmp[50];
bool cmp(char a,char b){
     return a>b;
     }
int deal(int v,int w,int x,int y,int z ){
        if(v - w*w + x*x*x - y*y*y*y + z*z*z*z*z==ans)
            return 1;
        else
            return 0;//return -1 和 1是一样的除0之外都是返回都是ture,0为false,正常函数退出
}

void solve(){
    for(int v = 0; v<len; v++){
        for(int w = 0; w<len; w++){
                if(v==w)
                continue;
            for(int x = 0; x<len; x++){
                if(x==v||x==w)
                continue;
              for(int y=0; y<len; y++){
                  if(y==v||y==x||y==w)
                  continue;
                for(int z=0; z<len; z++){
                        if(z==v||z==w||z==x||z==y)
                        continue;
        if(deal(s[v]-'A'+1,s[w]-'A'+1,s[x]-'A'+1,s[y]-'A'+1,s[z]-'A'+1)){
           printf("%c%c%c%c%c\n",s[v],s[w],s[x],s[y],s[z]);
          return ;
                }
     }
            }
        }
    }
    }
    printf("no solution\n");
}

int main()
{
    //freopen("in.txt","r",stdin);
    while(scanf("%d%s",&ans,s),ans){
        len = strlen(s);
        sort(s,s+len,cmp);
        solve();
    }
    return 0;
    }




posted @ 2016-08-31 17:06  Lawliet__zmz  阅读(193)  评论(0编辑  收藏  举报