hdu1226 超級密碼 bfs

來源:互聯網
上載者:User

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1226

思路:

因為n <= 5000 ,所以方案個數也只有5000個,可以用bfs來做。。一開始挺糾結怎麼做,但是上網一看別的大牛的代碼,一下子就恍然大悟豁然開朗,如同撥開雲霧見青天~~~^o^~~~~

代碼:

#include <iostream>#include <cstdio>#include <string>#include <queue>using namespace std;const int maxn = 20;const int maxm = 5100;const int inf = (0x7f7f7f7f);int n, c, t, m;bool jud[maxn];bool vis[maxm];int flag;struct node{string ans;int mod;};string res;queue<node> q;void init(){while (!q.empty()) q.pop();memset(jud, false, sizeof(jud));memset(vis, false, sizeof(vis));flag = -1;res = "";}void bfs(){int i;node now, next;for (i=1; i<16; i++){if (jud[i]){vis[i%n] = true;now.ans = "";if (i < 10)now.ans = i + '0';elsenow.ans = i + 'A' - 10;now.mod = i % n;q.push(now);}}while (!q.empty()){now = q.front();q.pop();if (flag == 1 && (now.ans.size() > res.size()))continue;if (now.mod == 0){if (flag == -1){flag = 1;res = now.ans;}else{if (res.size() > now.ans.size() || (res.size() == now.ans.size() && res > now.ans))res = now.ans;}}for (i=0; i<16; i++){if (jud[i]){next = now;if (i < 10)next.ans +=  i+'0';elsenext.ans += i+'A'-10;next.mod = (now.mod * c + i) % n;if ((next.ans.size() <= 500 && vis[next.mod]==false) || next.mod==0){vis[next.mod] = true;q.push(next);}}}}}int main(){scanf("%d", &t);while (t--){scanf("%d %d %d", &n, &c, &m);init();char ch[4];for (int i=0; i<m; i++){scanf("%s", ch);if (ch[0] >= '0' && ch[0] <= '9') jud[ch[0]-'0'] = true;else jud[ch[0]-'A'+10] = true;}if (n == 0){if (jud[0])puts("0");elseputs("give me the bomb please");continue;}bfs();if (flag == -1)puts("give me the bomb please");elsecout<<res<<endl;}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.