SHARE
    TWEET
    AlexAvram

    Untitled

    Apr 8th, 2025
    368
    0
    Never
    Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
    C++ 2.28 KB | None | 0 0
    1. //birocratie2 #4611
    2. #include <iostream>
    3. #include <fstream>
    4. #include <cmath>
    5. using namespace std;
    6. string fisier="birocratie";
    7. ifstream fin(fisier+".in");
    8. ofstream fout(fisier+".out");
    9. #define MINIM -1e9
    10. #define Nmax 1001
    11. int n, mat[Nmax][Nmax];
    12. int dp[Nmax][Nmax];
    13. /*
    14. programare dinamica pe diagonale;
    15. //
    16. parcurgem pe rand toate diagonalele paralele cu cea secundara,
    17. de sus in jos iar apoi de jos in sus; parcurgea in ambele directii
    18. este pentru a verifica ca toate costurile sunt calculate optim,
    19. fara sa conteze ordinea in care procesam elemente;
    20. in cazul fiecarui element, vedem daca putem ajunge la el
    21. prin una dintre celelalte 2 variante posibile de deplasare
    22. (in jos sau la dreapta);
    23. daca exista, alegem calea de castig maxim si o adunam elementului
    24. curent;
    25. */
    26. void citire()
    27. {
    28. fin>>n;
    29. for (int i=1; i<=n; ++i)
    30. for (int j=1; j<=n; ++j)
    31. fin>>mat[i][j];
    32. }
    33. bool sunt_in_matrice(int i, int j)
    34. {
    35. return i>=1 && i<=n && j>=1 && j<=n;
    36. }
    37. void rezolvare()
    38. {
    39. dp[1][1]=mat[1][1];
    40. for(int diag=2; diag<=2*n-1; ++diag)
    41. {
    42. int suma=MINIM;
    43. for(int i=1; i<=n; ++i)
    44. {
    45. int j=diag-i+1;
    46. if(sunt_in_matrice(i,j))
    47. {
    48. if(sunt_in_matrice(i-1,j))
    49. {
    50. suma=max(suma,dp[i-1][j]);
    51. }
    52. if(sunt_in_matrice(i,j-1))
    53. {
    54. suma=max(suma,dp[i][j-1]);
    55. }
    56. dp[i][j]=suma+mat[i][j];
    57. suma+=mat[i][j];
    58. }
    59. }
    60. suma=MINIM;
    61. for(int i=n; i>=1; --i)
    62. {
    63. int j=diag-i+1;
    64. if(sunt_in_matrice(i,j))
    65. {
    66. if(sunt_in_matrice(i-1,j))
    67. {
    68. suma=max(suma,dp[i-1][j]);
    69. }
    70. if(sunt_in_matrice(i,j-1))
    71. {
    72. suma=max(suma,dp[i][j-1]);
    73. }
    74. dp[i][j]=max(dp[i][j],suma+mat[i][j]);
    75. //vedem daca obtinem o imbunatatire fata
    76. //de prima parcurgere
    77. suma+=mat[i][j];
    78. }
    79. }
    80. }
    81. fout<<dp[n][n];
    82. }
    83. int main()
    84. {
    85. citire();
    86. rezolvare();
    87. return 0;
    88. }
    Advertisement
    Add Comment
    Please, Sign In to add comment
    Public Pastes
    We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
    Not a member of Pastebin yet?
    Sign Up, it unlocks many cool features!

    AltStyle によって変換されたページ (->オリジナル) /