【CodeForces 803B】Distances to Zero(模擬)


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 thati = 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 
題目大意:n個元素,求每個數到離它最近的0的距離
思路:模擬瞎暴力,記錄相鄰兩個0的位置,依次做比較
#include <bits/stdc++.h>
#define manx 200005
#define INF 0x3f3f3f3f
using namespace std;

int main()
{
    int a[manx],ans[manx],n;
    while(~scanf("%d",&n)){
        memset(a,0,sizeof(a));
        memset(ans,0,sizeof(ans));
        int k[2],t=0;  //k記錄相鄰兩個0的位置
        k[0]=k[1]=INF;
        for (int i=0; i<n; i++)
            scanf("%d",&a[i]);
        for (int i=0; i<n+1; i++){
            if (!a[i]){
                ans[i]=0;
                if (i!=n) k[t%2]=i;
                int f;
                if (k[(t+1)%2]==INF) f=0;
                else f=k[(t+1)%2];
                for (int j=f; j<i; j++)
                    ans[j]=min(abs(k[0]-j),abs(k[1]-j));
                t++;
            }
        }
        for (int i=0; i<n; i++)
            printf("%d ",ans[i]);
        printf("\n");
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章