计蒜客 合并数字

  题目链接:合并数字

  由于每次需要删除最左边的两个相差为一的较大数,可以用栈来模拟。

AC代码

#include <stdio.h>
#include <math.h>
#include <stack>
#include <algorithm>
using namespace std;
stack<int> s;

int main() {
    int n, ans;
    while(scanf("%d", &n) == 1) {
        ans = 0;
        while(!s.empty()) s.pop();
        int val;
        int a, b;
        for(int i = 0; i < n; i++) {
            scanf("%d", &val);
            s.push(val);
            bool flag = true;
            while(s.size() >= 2 && flag) {
                a = s.top(); s.pop();
                b = s.top(); s.pop();
                if(abs(a-b) == 1) {
                    ans++;
                    a = min(a, b);
                    s.push(a);
                } else {
                    flag = false;
                    //注意入栈顺序 
                    s.push(b);
                    s.push(a);
                }
            }
        }
        printf("%d
", ans);
    }
    return 0;
}

如有不当之处欢迎指出!

原文地址:https://www.cnblogs.com/flyawayl/p/8658498.html