Advertisement
a53

nunta1

a53
Feb 6th, 2018
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. /**
  2. Programare dinamica metoda mixta:
  3. dp[i,j]=valorile distincte posibile care se obtin daca din sirul de
  4. petitori i, i+1, ..., j ramane unul singur
  5. dp[i,j]= este un vector de aparitii de lungime 20, dp[i,j,k]=1
  6. daca se poate obtine suma k (k=0..20)
  7. Solutia se afla in dp[1][n], afisandu-se indicii bitilor setati cu 1
  8.  
  9. Complexitate O(n x n x n), cu o constanta 21 x 21.
  10. */
  11. #include <bits/stdc++.h>
  12. #define nmax 52
  13. #define inFile "nunta1.in"
  14. #define outFile "nunta1.out"
  15.  
  16. using namespace std;
  17.  
  18. int a[nmax], n;
  19. bitset<22> dp[nmax][nmax];
  20.  
  21. inline int Modul(int x)
  22. {
  23. if (x < 0) return -x;
  24. return x;
  25. }
  26.  
  27. void Citire()
  28. {
  29. ifstream fin(inFile);
  30. fin >> n;
  31. for (int i = 1; i <= n; i++)
  32. fin >> a[i];
  33. fin.close();
  34. }
  35.  
  36. void Seteaza(int p, int k, int q)
  37. {
  38. int i, j;
  39. for (i = 0; i <= 20; i++)
  40. for (j = 0; j <= 20; j++)
  41. if (dp[p][k][i] == 1 && dp[k+1][q][j] == 1)
  42. dp[p][q][Modul(i-j)] = 1;
  43. }
  44.  
  45. void Rezolva()
  46. {
  47. int i, j, pas, k;
  48. /// initializare diagonala principala
  49. for (i = 1; i <= n; i++)
  50. dp[i][i][a[i]] = 1;
  51. /// initializare urmatoarea diagonala
  52. for (i = 1; i < n; i++)
  53. dp[i][i + 1][Modul(a[i]-a[i + 1])] = 1;
  54. /// procesarea restului matricei
  55. for (pas = 2; pas < n; pas++)
  56. for (i = 1; i <= n - pas; i++)
  57. {
  58. j = i + pas;
  59. for (k = i; k < j; k++)
  60. Seteaza(i, k, j);
  61. }
  62. }
  63.  
  64. void Afisare()
  65. {
  66. int i;
  67. ofstream fout(outFile);
  68. fout << dp[1][n].count() << "\n";
  69. for (i = 0; i <= 20; i++)
  70. if (dp[1][n][i] == 1) fout << i << " ";
  71. fout << "\n";
  72. fout.close();
  73. }
  74.  
  75. int main()
  76. {
  77. Citire();
  78. Rezolva();
  79. Afisare();
  80. return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement