Distances to Zero (思维+模拟)

vj链接:

https://vjudge.net/contest/235444#problem/B

题意:

求每个数到离它最近的0的距离,0到本身距离是0。

测试样例:

  输入:

  9

2 1 0 3 0 0 3 2 4
输出:
2 1 0 1 0 0 1 2 3
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm> 
 5 using namespace std;
 6 const int N=2e5+10;
 7 int n;
 8 int a[N],b[N],c[N];
 9 int main()
10 {
11     while(scanf("%d", &n) == 1)
12     {
13         int x = 0;
14         for(int i=0;i<n;i++)
15         {
16             scanf("%d", &a[i]);
17             if(!a[i]) b[x++] = i;  //找出所有0的下标并存入数组b 
18         }
19         
20         int k = 0;
21         for(int i=0;i<b[x-1];i++)
22         {
23             for(int j=b[i]; j<=b[i+1];j++)
24             {
25                 a[j]=max(0,min(j-b[i],b[i+1]-j));//两个0之间的数包含两个0,min来判断该数到离它最近的它左边的0近还是右边的零近 ,max用来使0到它本身的距离等于0 
26             }
27         }
28         for(int i=0;i<b[0];i++)
29         {
30             a[i]=b[0]-i;
31         }
32         for(int i=b[x-1];i<n;i++)
33         {
34             a[i]=i-b[x-1];
35         }
36         for(int i=0;i<n;i++)
37         {
38             printf("%d%c", a[i],i<n-1?' ':'
');
39         }
40     }
41 return 0;
42 }
 
原文地址:https://www.cnblogs.com/1013star/p/9280589.html