您的位置:首页 > Web前端

ACM ZOJ Problem Set - 1403 Safecracker

2014-07-28 01:25 309 查看

//虽然题目比较简单,但是这是我第一次使用dfs算法做这种题

//题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1403

#include<iostream>

#include<cmath>

#include<string>

using namespace std;

int b[5];

char c[5];

bool d[26];

string s;

int n;

int main()

{

 int i, j;

 bool f(int);

 while (cin >> n >> s&&n != 0 && s != "END")

 {

  for (i = 1; i < s.length(); i++)

  {

   for (j = 0; j < s.length()-i; j++)

   {

    if (s[j] < s[j + 1])

    {

     char a = s[j];

     s[j] = s[j + 1];

     s[j + 1] = a;

    }

   }

  }

  for (i = 0; i < 26; i++)

  {

   d[i] = 0;

  }

  if (f(5))

  {

   for (i = 0; i < 5; i++)

   {

    c[i] = char('A' + b[i] - 1);

    cout << c[i];

   }

   cout << endl;

  }

  else cout << "no solution" << endl;

 }

 return 0;

}

bool f(int m)

{

 int i, j, k;

 if (m == 0)

 {

  j = -1;

  k = 0;

  for (i = 0; i < 5; i++)

  {

   j = j *(-1);

   k += j*(int)pow((double)b[i], (double)(i + 1));

  }

  if (k == n)return 1;

  else return 0;

 }

 else

 {

  for (i = 0; i < s.length(); i++)

  {

   if (d[i] == 0)

   {

    b[5 - m] = (int)(s[i] - 'A' + 1);

    d[i] = 1;

    if (f(m - 1)) return 1;

    else d[i] = 0;

   }

  }

  return 0;

 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: