ACM搜索:oj1015:Safecracker

題目傳送門:http://acm.hdu.edu.cn/showproblem.php?pid=1015

題目大意:讀取一個數字和一串字符串.每個大寫字母代表一個值.判斷是否存在五個大寫字母使表達式成立:v - w^2 + x^3 - y^4 + z^5 = target .如果存在.則輸出字典序最大的五個大寫字母.否則打印no solution.

最簡單的dfs即可.
AC代碼:

#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <vector>
#include <math.h>
#include <functional>
#include <algorithm>
using namespace std;
#define Size 12
typedef long long ll;

string str;
ll n;
int visit[Size];
char world[Size];
string res;
int UpCharConvertInt(char a)
{
    return int(a) - 64;
}
void UpCharConvertString()
{
    for (int i = 0; i < 5; ++i)
    {
        res += world[i];
    }
}
ll get()
{
    ll a = UpCharConvertInt(world[0]);
    ll b = UpCharConvertInt(world[1]);
    ll c = UpCharConvertInt(world[2]);
    ll d = UpCharConvertInt(world[3]);
    ll e = UpCharConvertInt(world[4]);
    return a - pow(b,2) + pow(c,3) - pow(d,4) + pow(e,5);
}
bool flag = false;
//cnt表示已經確定的個數.
void dfs(int cnt)
{
    //如果已經確定了5個數.則進行判斷.
    if (cnt == 5)
    {
        if (get() == n)
        {
            UpCharConvertString();
            flag = true;
        }
        return;
    }
    //枚舉各種情況.
    for (int i = 0; i < str.size(); ++i)
    {
        if (visit[i] == 0)
        {
            visit[i] = 1;
            world[cnt] = str[i];
            dfs(cnt + 1);
            //由於只需要打印最大的.所以一旦標識符被修改.則立馬退出搜索.就好像一層層的退出搜索.
            if (flag)
                return;
            visit[i] = 0;
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    while (1)
    {
        cin >> n >> str;

        if (n == 0 && str == "END")
            break;
        memset(visit,0,sizeof(visit));
        res.clear();
        flag = false;
        //先降序排列.
        sort(str.begin(), str.end(),greater<char>());
        dfs(0);
        if (res.empty())
            cout << "no solution" << endl;
        else
            cout << res << endl;
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章