Codeforces 467e Alex and complicated task (efficient)

Source: Internet
Author: User

Link: codeforces 467e Alex and complicated task

Given a sequence of N lengths, select as many 4 tuples as possible (not overlapping ).

Solution: The left end of every four tuples must be as small as possible. Therefore, a monotonous stack is used for maintenance. If the newly added number x appears in the stack, mark the number between two numbers as X. If the tag of a number is not empty, it means that the corresponding four tuples are found. Because the sequence is traversed from the left, it must be the best.

#include <cstdio>#include <cstring>#include <map>#include <stack>#include <vector>#include <algorithm>using namespace std;const int maxn = 5 * 1e5 + 5;int N, B[maxn];void solve () {    vector<int> ans;    map<int, int> pre, sum;    int mv = 0;    while (mv < N) {        pre.clear();        sum.clear();        stack<int> sta;        for (int& i = mv; i < N; i++) {            if (pre[B[i]]) {                for (int j = 0; j < 2; j++) {                    ans.push_back(pre[B[i]]);                    ans.push_back(B[i]);                }                break;            }            while (!sta.empty() && (sum[B[i]] > 1 || (sum[B[i]] == 1 && sta.top() != B[i]))) {                pre[sta.top()] = B[i];                sum[sta.top()]--;                sta.pop();            }            sta.push(B[i]);            sum[B[i]]++;        }        mv++;    }    printf("%lu\n", ans.size());    for (int i = 0; i < ans.size(); i++)        printf("%d%c", ans[i], i == ans.size() - 1 ? ‘\n‘ : ‘ ‘);}int main () {    scanf("%d", &N);    for (int i = 0; i < N; i++)        scanf("%d", &B[i]);    solve();    return 0;}

Codeforces 467e Alex and complicated task (efficient)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.