题解CF37E Trial for Chief

Topic: CF37E Trial for Chief

This problem is very clever. Here you can put a piece of continuous dyeing area easily mislead those who do problems. In fact the practice of this question is converted to the shortest path.
why? Think carefully, to this point, and it painted the same point and it must be up and down adjacent points points connected.
Each time a new coloring will contribute to +1, so when a new coloring again? This point is clearly different and it is necessary to point adjacent to the new color when painted once.
So we can not even point for each side and its vertical and horizontal point, when the two sides of the same color right is 0, 1 otherwise. Then we ran to the side of dij beginning of each point, record it all black dots maximum path length, the answer is the minimum value + the length.
Why is it black? Because the initial white.
Why +1 it? Because your default starting point of dis is 0, but it is actually the first time coloring. Special case is full white, so Maxn initial value of -1.
 1 #include<stdio.h>
 2 #include<queue>
 3 #define it register int
 4 #define il inline
 5 using namespace std;
 6 const int N=1000005;
 7 const int dx[]={0,0,1,-1};
 8 const int dy[]={1,-1,0,0};
 9 char s[55][55];
10 int n,m,ans,d[N],h[N],nxt[N],adj[N],w[N],t,cnt,bh[55][55];
11 struct ky{
12     int u,dis;
13     bool operator<(const ky &p)const{
14         return dis>p.dis;
15     }
16 };
17 priority_queue<ky> q;
18 il void add(it u,it v,it x){
19     nxt[++t]=h[u],h[u]=t,adj[t]=v,w[t]=x;
20 }
21 il int Min(it p,it q){
22     return p<q?p:q;
23 }
24 il int Max(it p,it q){
25     return p>q?p:q;
26 }
27 il void dij(it st){
28     for(it i=1;i<=cnt;++i) d[i]=1e9;
29     d[st]=0,q.push((ky){st,0});
30     register ky top;
31     while(!q.empty()){
32         top=q.top();q.pop();
33         if(top.dis^d[top.u]) continue;
34         for(it i=h[top.u],j;i;i=nxt[i])
35             if(d[j=adj[i]]>top.dis+w[i]) d[j]=top.dis+w[i],q.push((ky){j,d[j]});
36     }
37     it maxn=-1;
38     for(it i=1;i<=n;++i)
39         for(it j=1;j<=m;++j)
40             if(s[i][j]=='B') maxn=Max(maxn,d[bh[i][j]]); 
41     ans=Min(ans,maxn+1);
42 }
43 int main(){
44     scanf("%d%d",&n,&m);
45     for(it i=1;i<=n;++i) scanf("%s",s[i]+1);
46     for(it i=1;i<=n;++i)
47         for(it j=1;j<=m;++j)
48             bh[i][j]=++cnt;
49     for(it i=1,tx,ty;i<=n;++i)
50         for(it j=1;j<=m;++j)
51             for(it k=0;k<4;++k){
52                 tx=i+dx[k],ty=j+dy[k];
53                 if(tx<1||tx>n||ty<1||ty>m) continue;
54                 add(bh[i][j],bh[tx][ty],s[i][j]!=s[tx][ty]);
55             }
56     ans=0x7fffffff;
57     for(it i=1;i<=cnt;++i) dij(i);
58     printf("%d",ans);
59     return 0;
60 }
View Code

 

Guess you like

Origin www.cnblogs.com/Kylin-xy/p/11798494.html