fork download
  1. #include <stdio.h>
  2. #include <algorithm>
  3. using namespace std;
  4.  
  5. int N, K, age[20], newScheme, newAge[20], maxAge[21];
  6.  
  7. int gcd (int a, int b){
  8. int c;
  9. while(a!=0){ c=a; a=b%a; b=c; }
  10. return b;
  11. }
  12.  
  13. void solve(int x, int sum){
  14. if(x == N){
  15. for(int i=0; i<N; i++) maxAge[i]=newAge[i];
  16. newScheme = sum;
  17. return ;
  18. }
  19. if(age[x] <= K){ newAge[x]=age[x]; solve(x+1, sum+age[x]); return ;}
  20. if(x==0) newAge[x] = age[x];
  21. else newAge[x] = max(newAge[x-1], age[x]);
  22. for(; newAge[x] <= maxAge[x+1] && sum+newAge[x] < newScheme; newAge[x]+=K){
  23. int i;
  24. for(i=0; i<x; i++) if(gcd(newAge[i], newAge[x]) != K) break;
  25. if(i==x) solve(x+1, sum+newAge[x]);
  26. }
  27. }
  28.  
  29. int main(){
  30.  
  31. int t, T, i;
  32.  
  33. scanf("%d", &T);
  34. for(t=1; t<=T; t++){
  35. scanf("%d %d", &N, &K);
  36. int oldScheme = 0;
  37. for(i=0; i<N; i++){
  38. maxAge[i] = 1<<30;
  39. scanf("%d", &age[i]);
  40. oldScheme += age[i];
  41. }
  42. maxAge[N]=1<<30;
  43.  
  44. sort(age, age+N);
  45.  
  46. for(i=0; i<N; i++){
  47. if(age[i] == 0) if(i || age[N-1] > K) age[i] = K;
  48. if(age[i] % K) age[i] += K-(age[i]%K);
  49. }
  50. newScheme = 1<<30;
  51. solve(0, 0);
  52. printf("Case #%d: %d\n", t, newScheme-oldScheme);
  53. }
  54.  
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0.02s 2688KB
stdin
20
19 3
43 38 44 43 4 16 1 3 43 37 46 8 45 4 48 19 0 9 4 
20 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
20 8
39 10 40 21 13 31 29 3 28 12 48 18 47 33 14 42 25 13 13 36 
19 8
17 34 41 7 30 23 25 28 17 46 48 16 41 48 48 35 41 15 32 
20 7
12 35 42 15 23 45 23 4 16 2 4 33 2 12 42 8 6 42 21 40 
19 4
0 24 42 4 11 35 50 24 11 9 8 25 0 37 34 8 28 7 2 
20 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 
18 17
9 27 48 38 12 10 4 39 17 19 22 4 1 24 22 20 19 18 
10 11
1 2 3 4 5 6 7 8 9 10 
20 4
39 5 32 21 9 29 28 32 35 5 22 0 38 21 23 7 23 39 17 13 
19 5
4 13 23 37 5 37 34 10 21 7 22 4 32 18 7 36 44 10 36 
20 1
50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 
20 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
19 5
45 5 36 22 10 41 40 36 37 21 9 5 18 26 32 46 46 47 9 
17 20
29 4 0 11 15 21 25 1 38 11 3 42 49 18 45 46 44 
19 3
3 22 50 41 34 10 33 49 43 35 17 23 10 27 30 23 6 17 7 
18 2
26 24 7 5 2 45 35 39 5 14 41 5 48 13 11 20 29 18 
19 4
3 22 50 29 18 42 36 32 3 44 32 44 19 42 7 50 12 19 36 
2 1
2 2
17 5
50 13 46 29 22 21 42 33 48 34 7 33 15 1 23 8 33 
stdout
Case #1: 697
Case #2: 0
Case #3: 4037
Case #4: 3424
Case #5: 1904
Case #6: 969
Case #7: 19
Case #8: 2486
Case #9: 55
Case #10: 1838
Case #11: 1520
Case #12: 643
Case #13: 19
Case #14: 1679
Case #15: 1758
Case #16: 1026
Case #17: 499
Case #18: 1228
Case #19: 1
Case #20: 1452