码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank "AND xor OR"

时间:2015-11-23 16:27:44      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

Actually I think problem statement is somewhat misleading. No need to mention range [L, R] at all.

The intention is a variation to "Largest Rectangle" which is a classic stack problem on LeetCode.

But you need to run Largest Rectangle twice: increased and decreased.

技术分享
#include <cmath>
#include <stack>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int n; cin >> n;
    vector<int> in(n);
    for(int i = 0; i < n; i ++)
        cin >> in[i];
    
    int ret = 0;
    {
        in.push_back(0); 
        stack<int> stk;
        for (int i = 0; i < in.size(); i++)
        {
            if (stk.empty() || in[i] > stk.top())
            {
                stk.push(in[i]);
            }
            else
            {
                int lastV = stk.top(); stk.pop();
                if (!stk.empty())
                {
                    ret = std::max(ret, (lastV ^ stk.top()));            
                    //cout << lastV << "-" << stk.top() << "=" << (lastV ^ stk.top()) << endl;
                }
                i--;
            }
        }
        in.pop_back();
    }
    {
        
        stack<int> stk;
        in.insert(in.begin(), 0);
        for (int i = in.size() - 1; i >= 0; i --)
        {
            if (stk.empty() || in[i] > stk.top())
            {
                stk.push(in[i]);
            }
            else
            {
                int lastV = stk.top(); stk.pop();
                if (!stk.empty())
                {
                    ret = std::max(ret, (lastV ^ stk.top()));            
                    //cout << lastV << "-" << stk.top() << "=" << (lastV ^ stk.top()) << endl;
                }
                i++;
            }
        }
    }
    
    cout << ret << endl;
    return 0;
}
View Code

HackerRank "AND xor OR"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4988677.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!