• 滴滴笔试——算式转移


    题目:给出一个仅包含加减乘除四种运算符的算式(不含括号),如1+2*3/4,在保持运算符顺序不变的情况下,现在你可以进行若干次如下操作:如果交换相邻的两个数,表达式值不变,那么你就可以交换这两个数。

    #include <vector>
    #include <iostream>
    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);//为什么要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;
    }
    
    • 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
  • 相关阅读:
    PHP上网网址电影视频导航网站设计
    《CTFshow-Web入门》10. Web 91~110
    ul滚动卡顿解决办法分享
    26-Docker-常用命令详解-docker rmi
    Mac下XDebug安装
    Docker容器端口暴露方式
    尚硅谷Flink(三)时间、窗口
    软件开发项目 质量管理的6大关键事项
    一篇博客搞定移动端布局
    2022年外卖行业分析
  • 原文地址:https://blog.csdn.net/qq_45257495/article/details/132737634