[COCI2015]JABUKE

题目大意:
  一个$n imes m(n,mleq500)$的网格图中有若干个标记点,有$q(qleq10^5)$个操作,每次新加入一个标记点,并询问和新加入点最近的点的距离。

思路:
  记录对于每个点$(x,y)$,同一列上在它上面最近的点$u(x,y)$和在它下面最近的点$d(x,y)$。
  每次询问时枚举同一行的点的$u(x,j)$和$d(x,j)$,取距离最小值即可,时间复杂度$O(q(n+m))$。

 1 #include<cstdio>
 2 #include<cctype>
 3 #include<climits>
 4 #include<algorithm>
 5 inline int getint() {
 6     register char ch;
 7     while(!isdigit(ch=getchar()));
 8     register int x=ch^'0';
 9     while(isdigit(ch=getchar())) x=(((x<<2)+x)<<1)+(ch^'0');
10     return x;
11 }
12 inline bool isblock(const char &ch) {
13     return ch=='.'||ch=='x';
14 }
15 inline bool getblock() {
16     register char ch;
17     while(!isblock(ch=getchar()));
18     return ch=='x';
19 }
20 const int N=500;
21 bool map[N][N];
22 int n,m,u[N][N],d[N][N];
23 inline int sqr(const int &x) {
24     return x*x;
25 }
26 inline int dist(const int &x1,const int &y1,const int &x2,const int &y2) {
27     return sqr(x1-x2)+sqr(y1-y2);
28 }
29 inline void update(const int &j) {
30     for(register int i=0,last=-1;i<n;i++) {
31         if(map[i][j]) last=i;
32         u[i][j]=last;
33     }
34     for(register int i=n-1,last=-1;~i;i--) {
35         if(map[i][j]) last=i;
36         d[i][j]=last;
37     }
38 }
39 inline int query(const int &x,const int &y) {
40     int ans=INT_MAX;
41     for(register int j=0;j<m;j++) {
42         if(~u[x][j]) ans=std::min(ans,dist(x,y,u[x][j],j));
43         if(~d[x][j]) ans=std::min(ans,dist(x,y,d[x][j],j));
44     }
45     return ans;
46 }
47 int main() {
48     n=getint(),m=getint();
49     for(register int i=0;i<n;i++) {
50         for(register int j=0;j<m;j++) {
51             map[i][j]=getblock();
52         }
53     }
54     for(register int j=0;j<m;j++) {
55         update(j);
56     }
57     for(register int q=getint();q;q--) {
58         const int x=getint()-1,y=getint()-1;
59         printf("%d
",query(x,y));
60         map[x][y]=true;
61         update(y);
62     }
63     return 0;
64 }
原文地址:https://www.cnblogs.com/skylee03/p/8420968.html