Distances to Zero CodeForces - 803B (二分)

时间:2023-03-09 16:35:37
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=;
const int inf=0x3f3f3f3f;
/*** TEMPLATE CODE * * STARTS HERE ***/
int n;
int ans[maxn];
int a[maxn];
int cnt=;
int l[maxn];
int main()
{
gg(n);
repd(i,,n)
{
gg(a[i]);
}
repd(i,,n)
{
if(a[i]==)
{
l[cnt++]=i;
}
}
repd(i,,n)
{
if(a[i]!=)
{
int j1=lower_bound(l,l+cnt,i)-l;
// int j2=uppercase()
int v=l[j1];
if(v==)
{
ans[i]=i-l[cnt-];
}else
{
int num=abs(v-i);
if(j1>=cnt-)
{ }else
{
num=min(num,abs(l[j1+]-i)); }
if(j1>)
{
num=min(num,abs(l[j1-]-i));
}
ans[i]=num;
}
}
} repd(i,,n)
{
printf("%d ",ans[i]);
}
return ;
} inline void getInt(int* p) {
char ch;
do {
ch = getchar();
} while (ch == ' ' || ch == '\n');
if (ch == '-') {
*p = -(getchar() - '');
while ((ch = getchar()) >= '' && ch <= '') {
*p = *p * - ch + '';
}
}
else {
*p = ch - '';
while ((ch = getchar()) >= '' && ch <= '') {
*p = *p * + ch - '';
}
}
}