uva 10400 Game Show Math(記憶化搜尋)

來源:互聯網
上載者:User

題目串連:10400 - Game Show Math


題目大意:給出n個數值,可以任意的在數值之間添加+,- ,*  ,/,運算,要求找到一個算式可以使得算式的值等於目標值。

注意:1、算式的運算子沒有優先順序,都是從左至右結合。

2、數值之間的位置不能更換,也就是說數值的順序是確定的,只能修改運算子。

3、運算的過程中不能出現運算值的絕對值大於32000的。


解題思路:最開始想到的是遞迴,沒有想到好的剪枝, 就直接遞迴下去了,結果就逾時了,後來看了別人的題解後知道要用記憶化搜尋。就是記錄住當前前n個數字通過任意的運算所的到的sum, 如果這個sum被判定為不能達成目標, 那麼另外一種不同的運算方式使得前n個的sum等於前面判定過的,那麼剪掉這條枝,因為它已經不可能到達了。

#include <stdio.h>#include <string.h>#include <stdlib.h>const int N = 105;const int M = 32000;const char sign[] = "+-*/";int n, num[N], order, vis[N][2 * M + 10];char str[N];int count(int sum, char c, int number) {    if (c == '+')return sum + number;    else if (c == '-')return sum - number;    else if (c == '*')return sum * number;    else if (c == '/')return sum / number;     return 0;}int find(int sum, int deep) {    if (deep == n) {if (sum == order) {    str[deep - 1] = '=';    return true;}else    return false;    }    int cur;    for (int i = 0; i < 4; i++) {if (i == 3 && (num[deep] == 0))  continue;cur = count(sum, sign[i], num[deep]);if (cur < -32000 || cur > 32000)continue;if (vis[deep][cur + M])continue;if (find(cur, deep + 1)) {    str[deep - 1] = sign[i];    return true;}vis[deep][cur + M] = 1;    }    return false;}int main () {    int cas, flag;    scanf("%d", &cas);    while (cas--) {memset(str, 0, sizeof(str));memset(vis, 0, sizeof(vis));scanf("%d", &n);for (int i = 0; i < n; i++)    scanf("%d", &num[i]);scanf("%d", &order);if (find(num[0], 1)) {    for (int i = 0; i < n; i++)printf("%d%c", num[i], str[i]);    printf("%d\n", order);}else    printf("NO EXPRESSION\n");    }    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.