A - Rooms and Passages Gym - 102215A

There are (n+1)(n+1) rooms in the dungeon, consequently connected by nn passages. The rooms are numbered from 00 to nn, and the passages — from 11 to nn. The ii-th passage connects rooms (i−1)(i−1) and ii.

Every passage is equipped with a security device of one of two types. Security device of the first type checks if a person who walks through the passage has the pass of the certain color, and forbids movement if such pass is invalid. Security device of the second type never forbids movement, but the pass of the certain color becomes invalid after the person walks through.

In the beginning you are located in the room ss and have all the passes. For every ss from 00 to (n−1)(n−1) find how many rooms you can walk through in the direction of the room nn.

Input
The first line contains an integer nn (1≤n≤5000001≤n≤500000) — the number of passages.

The second line contains nn integers aiai (1≤|ai|≤n1≤|ai|≤n). The number |ai||ai| is a color of the pass which the ii-th passage works with. If ai>0ai>0, the ii-th passage is the first type passage, and if ai<0ai<0 — the second type.

Output
Output nn integers: answers for every ss from 00 to (n−1)(n−1).

Examples
Input
6
1 -1 -1 1 -1 1
Output
3 2 1 2 1 1
Input
7
2 -1 -2 -3 1 3 2
Output
4 3 3 2 3 2 1

反向遍历

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 5e5+10;
int a[maxn];
int pos[maxn];         //第一种类型的通道时,记录每种颜色出现的最早位置
int room[maxn];  


int main()
{
    int n;
    while(cin>>n)
    {
        int i;
        int las = maxn + 1;
        for(i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
        }
        memset(pos,0,sizeof(pos));
        memset(room,0,sizeof(room));
        for(i=n; i>0; i--)
        {
            if(a[i]>0)
            {
                room[i] = room[i+1] + 1; 
                pos[a[i]] = i;          //记录a[i]出现的最靠前的位置
            }
            else
            {
                if(!pos[-a[i]])
                {
                    room[i] = room[i+1] + 1;     //如果在i后边没有这种颜色,可通过就是下一个情况加1。
                }
                else
                {
                    las = min(las,pos[-a[i]]);       // 寻找能到达的最靠前的位置
                    room[i] = las-i;
                }
            }
        }
        for(i=1; i<=n; i++)
        {
            if(i==1)
                printf("%d",room[i]);
            else
                printf(" %d",room[i]);
        }
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44694282/article/details/93778912