饿
(hungry.pas/c/cpp)
【背景描述】
给出?个面值分别为?? 的纸币,每种纸币有无限张。另有?次询问,每次询问一个价格?,问用若干张纸币是否可以恰好得到?。
【输入格式】
第一行两个整数?,?。
接下来一行?个整数,第?个整数表示?? 。
接下来?行,每行一个整数?表示询问。
【输出格式】
对于每个询问输出一行一个整数表示答案,可行输出1,无解输出−1。
【样例输入】
2 2
2 3
5
1
【样例输出】
1
-1
【数据规模】
对于 30% 的数据,? ≤ 100000
对于另外 10% 的数据, ? = 2。
对于另外 30% 的数据, ? ≤ 5。
对于 100% 的数据,1 ≤ ? ≤ 50,1 ≤ ?i, ? ≤ 100000,1 ≤ ? ≤ 1018
题意:给定n个数,q个询问,每个询问问这个数能不能被上面n个数凑出来
考虑对于模a[1]的每一个值,计算出用a[2]~a[n]表示出的最小的数。
即dist[i]表示最小的模a[1]=i的数,且dist[i]可以用a[2]~a[n]表示出来,注意不限制每个数用多少次。
很显然,对于询问x,若i = x % a[1],dist[i]存在且小于等于x的话x就可以被表示出来(就是dist[i]不断加a[1]),而若是存在但是大于x的话一定表示不出来,因为根据定义dist[i]是最小的的能被a[2]~a[n]表示出来的模a[1]=i的数。
计算dist[i]就是跑一遍最短路
#include<bits/stdc++.h> using namespace std;typedef long long LL; const int N=1e5+15; int n,Q; int a[N]; LL dis[N]; bool inq[N]; queue <int> q; void Spfa() {memset(dis, -1, sizeof dis) ; dis[0] = 0, q.push(0), inq[0] = 1; while (q.size()) { int cur = q.front() ; q.pop() ; inq[cur] = 0 ; for (int i = 2; i <= n; i ++) {int to = (cur + a[i]) % a[1], w = a[i] ; if (dis[to] < 0 || dis[to] > dis[cur] + w) {dis[to] = dis[cur] + w ; if (!inq[to]) inq[to] = 1, q.push(to) ; }}} } int main() {freopen("hungry.in","r",stdin);freopen("hungry.out","w",stdout);scanf("%d%d", &n, &Q) ; for (int i = 1; i <= n; i ++) scanf("%d", &a[i]) ; sort(a + 1, a + n + 1) ; Spfa() ; while (Q --) { LL x ; scanf("%I64d", &x) ; if (dis[x % a[1]] != -1 && dis[x % a[1]] <= x) puts("1") ;else puts("-1") ; } }
想要数据的话Q我,3260540979