算式轉(zhuǎn)移(hard)

題目描述:
給出一個僅包含加減乘除四種運算符的算式(不含括號),如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;
} 
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容