題目描述:
給出一個僅包含加減乘除四種運算符的算式(不含括號),如1+2*3/4,在保持運算符順序不變的情況下,現(xiàn)在你可以進行若干次如下操作:如果交換相鄰的兩個數(shù),表達式值不變,那么你就可以交換這兩個數(shù)。
現(xiàn)在你可以進行任意次操作,使得算式的數(shù)字序列字典序最小,然后輸出結(jié)果,數(shù)字之間的字典序定義為若a<b則a的字典序小于b。
輸入
第一行包含一個整數(shù)n,表示算式的長度,即包含n個數(shù)字和n-1個運算符。(1≤n≤100000)。
第二行包含一個含有n個非0整數(shù)和n-1個運算符的算式,整數(shù)與運算符用空格隔開,運算符包括“+,-,*,/”,整數(shù)的絕對值不超過1000。
輸出
按要求輸出字典序最小的表達式,數(shù)字與符號之間用空格隔開。
樣例輸入
6
3 + 2 + 1 + -4 * -5 + 1
樣例輸出
1 + 2 + 3 + -5 * -4 + 1
int Partition(vector<int>& nums, int left, int right) {
int pivot = nums[left], l = left + 1, r = right;
while (l <= r) {
if (nums[l] > pivot && nums[r] < pivot)
swap(nums[l], nums[r]);
if (nums[l] <= pivot) l++;
if (nums[r] >= pivot) r--;
}
swap(nums[left], nums[r]);
return r;
}
void QuickSort(vector<int> &nums, int lo, int hi) {
if (hi <= lo) return;
int seg = Partition(nums, lo, hi);
QuickSort(nums, lo, seg - 1);
QuickSort(nums, seg + 1, hi);
}
int main(){
int n; 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;
--r;
if(ops[l] == '+' || ops[l] == '-'){
if(r<n-1 && (ops[r+1]=='*' || ops[r+1]=='/'))
QuickSort(nums, l, r-1);
else
QuickSort(nums, l, r);
}
else if(ops[l] == '*'){
if(l>0 && (ops[l-1]=='+' || ops[l-1]=='-'))
QuickSort(nums, l-1, r);
else
QuickSort(nums, l, r);
}
else if(ops[l] == '/'){
QuickSort(nums, l, r);
}
++r; l=r;
}
string ans = to_string(nums[0]);
for(int i=1; i<n; ++i){
ans.push_back(' ');
ans.push_back(ops[i]);
ans.push_back(' ');
ans += to_string(nums[i]);
}
cout<<ans<<endl;
return 0;
}