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;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值