A - Rooms and Passages

29 篇文章 0 订阅

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

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 s and have all the passes. For every s from 0 to (n−1) find how many rooms you can walk through in the direction of the room n.

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

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

Output
Output n integers: answers for every s from 0 to (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
题意:就是每个数可以一直往下走直到遇到前面经过的一个负数的绝对值,题求的是在每个位置上可以往下走的最大深度(语文不好,只能解释成这样了)
题解:可以从后往前扫一遍,用一下简单的Dp。要记录正数的位置,因为是往下走到最深处,所以想到用后往前推。
下面是AC代码:

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=5e5+10;
int a[N];
int b[N];
int ans[N];
int main()
{
    int n,i;
    cin>>n;
    for(i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    ans[n]=1;
    if(a[n]>0)
        b[a[n]]=n;//初始化,最后一个值是1,如果是正数,用桶记录位置。a[n]是数值,b[]标记的是数值的位置。
    for(i=n-1;i>=1;i--)
    {
        if(a[i]>0)
            ans[i]=ans[i+1]+1;//如果是正数,不过使得数值失效,后面的值加1即可。
        else
        {
            if(b[-a[i]]!=0)//此位置又标记,即值存在。
                ans[i]=min(ans[i+1]+1,b[-a[i]]-i);//负数会影响,所以看下面存不存在着失效的,所以应取两者最小值,因为上一个值距离失效的可能会距离更短,所以取上一个。
            else
                ans[i]=ans[i+1]+1;
        }
        if(a[i]>0)
           b[a[i]]=i;//不断更新,使得失效值永远是距离最近的。
    }
   for(i=1;i<=n;i++)
   {
       if(i==n)
        printf("%d\n",ans[i]);
       else
        printf("%d ",ans[i]);
   }
    return 0;
}

总结:这个题的核心思想就是倒着往前处理,然后的就是标记位置及值的大小。b[a[i]]=i这样的桶方式记录两个值很实用的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值