Distances to Zero(lower_bound和upper_bound应用)

B. Distances to Zero
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given the array of integer numbers a0, a1, ..., an - 1. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array.

Input

The first line contains integer n (1 ≤ n ≤ 2·105) — length of the array a. The second line contains integer elements of the array separated by single spaces ( - 109 ≤ ai ≤ 109).

Output

Print the sequence d0, d1, ..., dn - 1, where di is the difference of indices between i and nearest j such that aj = 0. It is possible that i = j.

Examples
Input
9
2 1 0 3 0 0 3 2 4
Output
2 1 0 1 0 0 1 2 3 
Input
5
0 1 2 3 4
Output
0 1 2 3 4 
Input
7
5 6 0 1 -2 3 4
Output
2 1 0 1 2 3 4 
题意:题意比较好理解,就是找每个非零数,离这个数组中的零的最短距离,数组中可能有多个零,找最近的算出距离,最后并大印
出来
思路:一开始看到时间限制2000ms,就想直接暴力,遇到非零数左右遍历,但是超时了,但是听他们说暴力做也过了,哎不管了,自己
能想到的暴力都是最简单最单纯的暴力,人家的暴力可能还动了些手脚,后来学长讲了更搞笑(高效)的方法,储存下零的位置,再储存
下非零数的位置,以非零数位置为查找值用lower_bound和upper_bound找到,这个非零位置左右两边零的位置,相减比较位置
下面是代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define INF 0x3f3f3f3f
int n;
int a[200100];
int dis[200100];
vector<int>zero,number;
int main(){
    int i;
    zero.push_back(-INF);//先把一个最小的数放在数组首位置
    scanf("%d",&n);
    for(i = 0; i < n; i++){
        scanf("%d",&a[i]);
        if(a[i]==0){
            dis[i] = 0;//如果是零距离是零,直接存
            zero.push_back(i);//把零的位置依次存到数组中
        }
        else number.push_back(i);//把非零的数的位置存到另一个数组中
    }
    zero.push_back(INF);//把一个最大数放在数组的末尾位置
    vector<int>::iterator it;
    for(i = 0,it = number.begin(); it != number.end(); it++,i++){//用迭代器遍历非零的数组
        int pos1,pos2;
        pos1 = *(lower_bound(zero.begin(),zero.end(),number[i])-1);//lower_bound找到第一个大于等于的坐标,然后减1,得到这个数左边零的位置
        pos2 = *upper_bound(zero.begin(),zero.end(),number[i]);//upper_bound找到第一个大于的坐标,找到的是右边零的位置
        int dis1,dis2;                                         //注意两个函数返回的是一个迭代器,所以取星得到的值才是零在原来数组的位置
        dis1 = number[i]-pos1;
        dis2 = pos2-number[i];//分别求这两个数和左右两个零的位置
        dis[number[i]] = min(dis1,dis2);//取最小
    }
    for(i = 0; i < n; i++){//输出
        if(i==0)printf("%d",dis[i]);
        else printf(" %d",dis[i]);
    }
    puts("");
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值