Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

138 lines
1.7 KiB

  1. #include <nt.h>
  2. #include <ntrtl.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. //
  6. // 'tstsum.c'
  7. // Largest sum of a subarray
  8. //
  9. // 05/14/92 DarekM created
  10. //
  11. int
  12. main(int argc, char *argv[])
  13. {
  14. Randomize();
  15. n1(); Results(1);
  16. n2(); Results(2);
  17. n3(); Results(3);
  18. printf("\n\n");
  19. return 1;
  20. }
  21. #define NUM_NUMS 20
  22. int x[NUM_NUMS];
  23. int sLargest; /* largest sum */
  24. int iLargest; /* index of subarray */
  25. int cLargest; /* size of subarray */
  26. Randomize()
  27. {
  28. int i;
  29. int s;
  30. s = getpid();
  31. printf("\n");
  32. for (i=0; i < NUM_NUMS; i++)
  33. {
  34. s = (s * 89 + 13) % 47; /* generate random numbers around -25 to 25 */
  35. x[i] = s - 25;
  36. printf("Num[%02d] = %+d\n", i, x[i]);
  37. }
  38. printf("\n");
  39. }
  40. FindLargest(s, i, c)
  41. int s, i, c;
  42. {
  43. /* takes the gives sum, index, and count of a subarray and
  44. * if it is a largest sum so far keep track of it.
  45. */
  46. if ((s > sLargest) || ((s == sLargest) && (c < cLargest)))
  47. {
  48. sLargest = s;
  49. iLargest = i;
  50. cLargest = c;
  51. }
  52. }
  53. Results(o)
  54. int o;
  55. {
  56. printf("O(%d): Largest subarray is Num[%d..%d] with a sum of %d\n",
  57. o, iLargest, iLargest+cLargest-1, sLargest);
  58. }
  59. n1()
  60. {
  61. int i, c, s;
  62. sLargest = -999;
  63. s = c = 0;
  64. for (i = 0; i < NUM_NUMS; i++)
  65. {
  66. if (s + x[i] < 0)
  67. {
  68. s = c = 0;
  69. continue;
  70. }
  71. s += x[i];
  72. c++;
  73. FindLargest(s, i-c+1, c);
  74. }
  75. }
  76. n2()
  77. {
  78. int i, c, s;
  79. sLargest = -999;
  80. for (i = 0; i < NUM_NUMS; i++)
  81. {
  82. s = 0;
  83. for (c = 1; c <= (NUM_NUMS-i); c++)
  84. {
  85. s += x[i+c-1];
  86. FindLargest(s, i, c);
  87. }
  88. }
  89. }
  90. n3()
  91. {
  92. int i, c, s, j;
  93. sLargest = -999;
  94. for (i = 0; i < NUM_NUMS; i++)
  95. {
  96. for (c = 1; c <= (NUM_NUMS-i); c++)
  97. {
  98. s = 0;
  99. for (j = i; j < (i+c); j++)
  100. s += x[j];
  101. FindLargest(s, i, c);
  102. }
  103. }
  104. }