1. 程式人生 > >1155 Heap Paths

1155 Heap Paths

純找規律,算數方法做的。。。感覺考試的時候千萬不能慌,題目肯定能做,慌了就涼涼。。。

  1 #include <iostream>
  2 #include <stdlib.h>
  3 #include <string>
  4 #include<algorithm>
  5 #include<vector>
  6 #include<cmath>
  7 #include<map>
  8 #include<set>
  9 #include <unordered_map>
 10
11 using namespace std; 12 13 14 15 int main(){ 16 int n; 17 cin >> n; 18 vector<int> arr(1001); 19 for (int i = 0; i < n; i++) { 20 cin >> arr[i]; 21 } 22 23 bool max=true, min=true; 24 25 for (int i = 1; i < n; i++) {
26 if (arr[i] > arr[(i - 1) / 2]) { 27 max = 0; 28 } 29 30 if (arr[i] < arr[(i - 1) / 2]) { 31 min = 0; 32 } 33 } 34 int level,total=0; 35 for (int i = 0; total < n; i++) { 36 total+=pow(2,i); 37 level = i;
38 } 39 int last_l = n - total/2; 40 int sec_last_l = 0; 41 if (last_l % 2 == 0) { 42 sec_last_l = pow(2, level - 1) - last_l/2; 43 } 44 else { 45 sec_last_l = pow(2, level - 1) - (last_l + 1) / 2; 46 } 47 48 vector<int> last; 49 vector<int> seclast; 50 for (int i = n-last_l; i < n; i++) { 51 52 last.push_back(i); 53 } 54 55 for (int i = n - last_l-sec_last_l; i < n - last_l; i++) { 56 57 seclast.push_back(i); 58 } 59 60 reverse(last.begin(), last.end()); 61 reverse(seclast.begin(), seclast.end()); 62 63 for (int i = 0; i < seclast.size(); i++) { 64 vector<int> path; 65 int k = seclast[i]; 66 while (k != 0) { 67 path.push_back(arr[k]); 68 k = (k - 1) / 2; 69 } 70 path.push_back(arr[0]); 71 reverse(path.begin(), path.end()); 72 for (int j = 0; j < path.size(); j++) { 73 if (j != 0) { 74 cout <<' '<< path[j]; 75 } 76 else { 77 cout << path[j]; 78 } 79 } 80 cout << endl; 81 } 82 83 for (int i = 0; i < last.size(); i++) { 84 vector<int> path; 85 int k = last[i]; 86 while (k != 0) { 87 path.push_back(arr[k]); 88 k = (k - 1) / 2; 89 } 90 path.push_back(arr[0]); 91 reverse(path.begin(), path.end()); 92 for (int j = 0; j < path.size(); j++) { 93 if (j != 0) { 94 cout << ' ' << path[j]; 95 } 96 else { 97 cout << path[j]; 98 } 99 } 100 cout << endl; 101 } 102 103 if (min == 1) { 104 cout << "Min Heap" << endl; 105 } 106 if (max == 1) { 107 cout << "Max Heap" << endl; 108 } 109 if (max == 0 && min == 0) { 110 cout << "Not Heap" << endl; 111 } 112 system("pause"); 113 };