思路:參考自
先用兩個數組來存儲數字(opNum)和這個數字以前的操做符(opChar)。其中ops第一個元素固定是'+',由於第一個數沒有符號。例如樣例就會獲得以下的兩個數組: ios
索引 | 0 | 1 | 2 | 3 | 4 | 5 |
nums | 3 | 2 | 1 | -4 | -5 | 1 |
ops | + | + | + | + | * | + |
#include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; int Partition(vector<int> &nums, int l, int r){ int pivot = nums[l]; while(l<r){ while(l<r && pivot<=nums[r]) --r; nums[l] = nums[r]; while(l<r && pivot>=nums[l]) ++l; nums[r] = nums[l]; } nums[l] = pivot; return l; } void QuickSort(vector<int> &nums, int l, int r){ if(l<r){ int mid = Partition(nums, l, r); QuickSort(nums, l, mid-1); QuickSort(nums, mid+1, r); } } int main() { int n; cin>>n; vector<int> opNum(n, 0); vector<char> opChar(n, '+'); for(int i=0;i<n-1;i++){ cin>>opNum[i]; cin>>opChar[i+1]; } cin>>opNum[n-1]; int l=0, r=0; while(r<n){ while( r<n && opChar[l]==opChar[r]){ r++; } r--; //cout<<l<<" "<<r<<endl; if(opChar[l]=='*' ){ if(l-1>=0 && (opChar[l-1]=='+' || opChar[l-1]=='-')) QuickSort(opNum, l-1, r); else QuickSort(opNum, l, r); }else if(opChar[l]=='+' || opChar[l]=='-'){ if(r+1<n-1 && (opChar[r+1]=='*' || opChar[r+1]=='|')) QuickSort(opNum, l, r-1); else QuickSort(opNum, l, r); }else if(opChar[l]=='/'){ QuickSort(opNum, l, r); } r++; l = r; } for(int i=0;i<n-1;i++){ cout<<opNum[i]<<" "; cout<<opChar[i+1]<<" "; } cout<<opNum[n-1]<<endl; return 0; //3 + 2 + 1 + -4 * -5 + 1 ---> 1 + 2 + 3 + -5 * -4 + 1 }