1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include <cstdio> #include <vector> #include <algorithm> using namespace std; const int maxn=110; int n; vector<int> init,part,temp; void printArr(vector<int> v){ for(int i=0;i<v.size();i++){ if (i!=0) printf(" "); printf("%d",v[i]); } }
bool insertSort(){ bool flag=false; for(int i=1;i<n;i++){ sort(init.begin(),init.begin()+i+1); if(init==part){ flag= true; } if (flag){ sort(init.begin(),init.begin()+i+2); break; } } return flag; }
void downAdjust(int l,int r){ int i=l,j=2*i; while(j<=r){ if(j+1<=r&&init[j]<init[j+1]){ j=j+1; } if (init[j]>init[i]){ swap(init[i],init[j]); i=j; j=2*i; }else{ break; } } }
void heapSort(){ bool flag=false; for(int i=n/2;i>=1;i--){ downAdjust(i,n); } for(int i=n;i>1;i--){ swap(init[i],init[1]); downAdjust(1,i-1); if (init==part){ flag=true; } if (flag){ swap(init[i-1],init[1]); downAdjust(1,i-2); return; } }
}
int main(){ scanf("%d",&n); int x; for(int i=0;i<n;i++) { scanf("%d",&x); init.push_back(x); } for(int i=0;i<n;i++) { scanf("%d",&x); part.push_back(x); } temp=init; if(insertSort()){ printf("Insertion Sort\n"); printArr(init); }else{ printf("Heap Sort\n"); init=temp; init.insert(init.begin(),-1); part.insert(part.begin(),-1); heapSort(); init.erase(init.begin()); printArr(init); }
return 0; }
|