Codeforces 524C.The Art of Dealing with ATM(暴力)

我先采用了智障解法(n * n枚举...刚开始把n看成1000了还以为能过)

理所当然的t了,不过我怀疑优化一下能过?(感觉数据不太行的亚子

然后就是O(n * k * k)的解法,看到好多人快乐二分,其实完全用不到,建一个10000000的数组就ok了(我刚开始还以为会MLE

不过有几个地方要注意一下

1.要判断是不是在范围内,不然会出现查询的时候越界,快乐re的情况

2.要判断是不是>0,同理,而且负数取模会有你意想不到的结果

#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 5010;
int a[N];
bool map[10000010];
int main() {
    int n, K;
    scanf("%d %d", &n, &K);
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]), map[a[i]] = true;
    int q;
    scanf("%d", &q);
    while (q--) {
        int s;
        scanf("%d", &s);
        int ans = K + 10;
        for (int i = 0; i < n; i++)
            for (int j = 0; j <= K; j++)
                for (int k = 1; k <= (K - j); k++) {
                    if ((s - j * a[i]) % k != 0 || s <= j * a[i])
                        continue;
                    if ((s - j * a[i]) / k > a[n - 1])
                        continue;
                    if (map[(s - j * a[i]) / k])
                        ans = min(ans, j + k);
                }
        if (ans <= K)
            printf("%d
", ans);
        else
            puts("-1");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/cminus/p/11946636.html