tql,我当时想着分类讨论,想着想着思路就乱了,还要思路清晰、有条不紊地用代码实现出来,脑子已经一团乱麻了。基于楼主大佬的思路,我改写了个更简洁点的版本。
#include <iostream>
#include <vector>
using namespace std;
int n;
void QuickSort(vector<int>& nums, int left, int right){
if(left >= right) return;
int pivot = nums[left], l = left, r = right;
while(l < r){
while(l < r && nums[r] > pivot) --r;
while(l < r && nums[l] <= pivot) ++l;
swap(nums[l], nums[r]);
}
swap(nums[left], nums[r]);
QuickSort(nums, left, r-1);
QuickSort(nums, r+1, right);
}
int main(){
cin >> n;
vector<int> nums(n, 0);
vector<char> ops(n, '+');
for(int i=0; i<n-1; ++i){
cin >> nums[i];
cin >> ops[i+1];
}
cin >> nums[n-1];
int l = 0, r = 0;
while(r < n){
while(r < n && ops[r] == ops[l]) ++r;
if(ops[l] == '+' || ops[l] == '-'){
if(r < n && (ops[r] == '*' || ops[r] == '/')) QuickSort(nums, l, r-2);
else QuickSort(nums, l, r-1);
}else if(ops[l] == '*'){
if(l > 0 && (ops[l-1] == '+' || ops[l-1] == '-')) QuickSort(nums, l-1, r-1);
else QuickSort(nums, l, r-1);
}else if(ops[l] == '/'){
QuickSort(nums, l, r-1);
}
l = r;
}
cout << nums[0];
for(int i=1; i<n; ++i) cout << ' ' << ops[i] << ' ' << nums[i];
return 0;
}