rock_heap.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdbool.h>
  4. #include <stdlib.h>
  5. int find_part ( int* arr, int size )
  6. {
  7. int sum = 0, i, j;
  8. for ( i = 0; i < size; i++ ) {
  9. sum += arr[i];
  10. }
  11. bool btabl[sum / 2 + 1][size + 1];
  12. for ( i = 0; i < size + 1; i ++ ) {
  13. btabl[0][i] = true;
  14. }
  15. for ( i = 1; i < sum / 2 + 1; i++ ) {
  16. btabl[i][0] = false;
  17. }
  18. for ( i = 1; i < sum / 2 + 1; i++ ) {
  19. for ( j = 1; j < size + 1; j++ ) {
  20. if ( i - arr[j - 1] >= 0 ) {
  21. btabl[i][j] = ( btabl[i][j - 1] || btabl[i - arr[j - 1]][j - 1] );
  22. } else {
  23. btabl[i][j] = btabl[i][j - 1];
  24. }
  25. }
  26. }
  27. bool part_exists = btabl[sum / 2][size];
  28. bool is_sum_even = sum % 2 == 0;
  29. int result;
  30. if ( part_exists ) {
  31. if ( is_sum_even ) {
  32. result = 0;
  33. } else {
  34. result = 1;
  35. }
  36. } else {
  37. i = sum / 2;
  38. while ( !btabl[i][size] ) {
  39. i--;
  40. }
  41. result = ( sum / 2 - i ) * 2;
  42. if ( !is_sum_even ) {
  43. result += 1;
  44. }
  45. }
  46. return result;
  47. }
  48. int main()
  49. {
  50. int size;
  51. scanf ( "%d", &size );
  52. int rocks[size];
  53. if ( size == 1 ) {
  54. int n;
  55. scanf ( "%d", &n );
  56. printf ( "%d\n", n );
  57. return 0;
  58. } else if ( size == 2 ) {
  59. int n1, n2;
  60. scanf ( "%d%d", &n1, &n2 );
  61. printf ( "%d\n", ( n1 > n2 ? n1 - n2 : n2 - n1 ) );
  62. return 0;
  63. } else {
  64. char weights[10000 * size];
  65. scanf ( "\n%[^\n]s", weights );
  66. char* token = strtok ( weights, " " );
  67. int i = 0;
  68. while ( token ) {
  69. rocks[i++] = atoi ( token );
  70. token = strtok ( NULL, " " );
  71. }
  72. int part = find_part ( rocks, size );
  73. switch ( part ) {
  74. case 0:
  75. printf ( "0\n" );
  76. break;
  77. case 1:
  78. printf ( "1\n" );
  79. break;
  80. default:
  81. printf ( "%d\n", part );
  82. }
  83. return 0;
  84. }
  85. }