Distances to Zero CodeForces - 803B (二分)

题目链接:https://vjudge.net/problem/CodeForces-803B#author=0

题意:

给你一个数组,其中至少包括一个0,求每一个元素距离最近一个0的距离是多少。

样例:

Input
9
2 1 0 3 0 0 3 2 4
Output
2 1 0 1 0 0 1 2 3 

思路:把每一个0的下标都放进一个新数组中,然后枚举每一个数组pos,用二分查找pos在新数组中刚好大于等于pos的那个index,
然后再和前后的index比较下取最小值,然后即得出答案。

作者的博客原链接:https://www.cnblogs.com/qieqiemin/
我的AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#define rep(i,x,n) for(int i=x;i<n;i++)
#define repd(i,x,n) for(int i=x;i<=n;i++)
#define pii pair<int,int>
#define pll pair<long long ,long long>
#define gbtb std::ios::sync_with_stdio(false)
#define MS0(X) memset((X), 0, sizeof((X)))
#define MSC0(X) memset((X), '\0', sizeof((X)))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define gg(x) getInt(&x)
using namespace std;
typedef long long ll;
inline void getInt(int* p);
const int maxn=1000010;
const int inf=0x3f3f3f3f;
/*** TEMPLATE CODE * * STARTS HERE ***/
int n;
int ans[maxn];
int a[maxn];
int cnt=0;
int l[maxn];
int main()
{
    gg(n);
    repd(i,1,n)
    {
        gg(a[i]);
    }
    repd(i,1,n)
    {
        if(a[i]==0)
        {
            l[cnt++]=i;
        }
    }
    repd(i,1,n)
    {
        if(a[i]!=0)
        {
            int j1=lower_bound(l,l+cnt,i)-l;
//            int j2=uppercase()
            int v=l[j1];
            if(v==0)
            {
                ans[i]=i-l[cnt-1];
            }else
            {
                int num=abs(v-i);
                if(j1>=cnt-1)
                {

                }else
                {
                    num=min(num,abs(l[j1+1]-i));

                }
                if(j1>0)
                {
                    num=min(num,abs(l[j1-1]-i));
                }
                ans[i]=num;
            }
        }
    }

    repd(i,1,n)
    {
        printf("%d ",ans[i]);
    }
    return 0;
}

inline void getInt(int* p) {
    char ch;
    do {
        ch = getchar();
    } while (ch == ' ' || ch == '\n');
    if (ch == '-') {
        *p = -(getchar() - '0');
        while ((ch = getchar()) >= '0' && ch <= '9') {
            *p = *p * 10 - ch + '0';
        }
    }
    else {
        *p = ch - '0';
        while ((ch = getchar()) >= '0' && ch <= '9') {
            *p = *p * 10 + ch - '0';
        }
    }
}
View Code
 

猜你喜欢

转载自www.cnblogs.com/qieqiemin/p/10241186.html