[CF286C] Main Sequence

Problem Description

Lucky number is defined columns:

Empty columns are lucky series

If S is the lucky number columns, then {r, S, -r} column is lucky number (r> 0)

If T and S are the lucky number columns, {S, T} is the lucky number of columns

To the absolute value of each a predetermined number of lucky number of columns, and wherein some of the required number is negative, the other may be positive or negative.

Q. Is there a legitimate program, and if so, any given program. N ≤ 10 ^ 6

Fortunately, the number of columns example: {1, 2, -2, -1, 1, -1, 1, -1}

Input: 1111 third number is negative output claim: 11-1-1

Sample input

2
1 1
0

Sample Output

YES
1 -1

Resolve

It can be relatively easy to see this is in the form of a sequence of parentheses. If viewed as a positive number left parenthesis, right parenthesis seen as a negative number, then the number given some of the negative Minchin said, given some of the closing parenthesis, we need to determine whether to meet the requirements of left parenthesis. In order to define a right parenthesis, we sweep from right to left again, if the current top of the stack is not equal to the current element or elements are designated as negative, and will be labeled as negative elements in the stack; otherwise pop the top element. Finally, if the stack is not empty, indicating no solution; otherwise the output answer.

Code

#include <iostream>
#include <cstdio>
#define int long long
#define N 1000002
using namespace std;
int n,m,i,a[N],q[N],s[N],top;
bool f[N];
int read()
{
    char c=getchar();
    int w=0;
    while(c<'0'||c>'9') c=getchar();
    while(c<='9'&&c>='0'){
        w=w*10+c-'0';
        c=getchar();
    }
    return w;
}
signed main()
{
    n=read();
    for(i=1;i<=n;i++) a[i]=read();
    m=read();
    for(i=1;i<=m;i++){
        q[i]=read();
        f[q[i]]=1;
    }
    for(i=n;i>=1;i--){
        if(s[top]!=a[i]||f[i]) s[++top]=a[i],f[i]=1;
        else top--;
    }
    if(top){
        puts("NO");
        return 0;
    }
    puts("YES");
    for(i=1;i<=n;i++){
        if(f[i]) printf("%lld ",-a[i]);
        else printf("%lld ",a[i]);
    }
    puts("");
    return 0;
}

Reflection

If the sequence of the original sequence regarded as brackets, which is a given number is a negative number is equivalent to some handpicked position closing parenthesis. So write from right to left will be a lot less than from left to right. Or pay attention to wonder if it is to simplify the wording of the code after a good, or else it may bring a lot of trouble.

Guess you like

Origin www.cnblogs.com/LSlzf/p/11745968.html