This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int MAXN = 2000;
const int MAXK = 1e5;
const int dy[]={-1, 1, 0, 0};
const int dx[]={0, 0, -1, 1};
int N, K, A[MAXN+10][MAXN+10];
int conv(int y, int x) { return (y-1)*N+(x-1); }
int par[MAXN*MAXN+10], Rank[MAXN*MAXN+10], cnt=0, ans;
int Find(int x) { return x==par[x]?x:par[x]=Find(par[x]); }
void Union(int x, int y)
{
x=Find(x); y=Find(y);
if(Rank[x]<Rank[y]) swap(x, y);
if(Rank[x]==Rank[y]) Rank[x]++;
par[y]=x;
}
struct Queue { int y, x; };
queue<Queue> Q;
int main()
{
int i, j, k;
scanf("%d%d", &N, &K);
for(i=0; i<N*N; i++) par[i]=i, Rank[i]=1;
for(i=1; i<=K; i++)
{
int y, x;
scanf("%d%d", &y, &x);
A[y][x]=1;
Q.push({y, x}); cnt++;
}
for(i=1; i<=N; i++) for(j=1; j<=N; j++)
{
if(!A[i][j]) continue;
for(k=0; k<4; k++)
{
int ny=i+dy[k], nx=j+dx[k];
if(!(1<=ny && ny<=N && 1<=nx && nx<=N)) continue;
if(!A[ny][nx]) continue;
if(Find(conv(ny, nx))!=Find(conv(i, j)))
{
cnt--;
Union(conv(ny, nx), conv(i, j));
}
}
}
//for(i=1; i<=N; i++) { for(j=1; j<=N; j++) printf("%d ", A[i][j]); printf("\n"); }
//printf("\n");
if(cnt==1) return !printf("0");
while(!Q.empty())
{
int sz=Q.size(); ans++;
while(sz--)
{
Queue T=Q.front(); Q.pop();
for(i=0; i<4; i++)
{
int ny=T.y+dy[i], nx=T.x+dx[i];
if(!(1<=ny && ny<=N && 1<=nx && nx<=N)) continue;
if(Find(conv(ny, nx))==Find(conv(T.y, T.x))) continue;
if(A[ny][nx]==0)
{
Union(conv(ny, nx), conv(T.y, T.x));
A[ny][nx]=1;
Q.push({ny, nx});
}
else
{
cnt--;
Union(conv(ny, nx), conv(T.y, T.x));
}
}
}
sz=Q.size();
while(sz--)
{
Queue T=Q.front(); Q.pop(); Q.push(T);
for(i=0; i<4; i++)
{
int ny=T.y+dy[i], nx=T.x+dx[i];
if(!(1<=ny && ny<=N && 1<=nx && nx<=N)) continue;
if(Find(conv(ny, nx))==Find(conv(T.y, T.x))) continue;
if(A[ny][nx]!=0)
{
cnt--;
Union(conv(ny, nx), conv(T.y, T.x));
}
}
}
//for(i=1; i<=N; i++) { for(j=1; j<=N; j++) printf("%d ", A[i][j]); printf("\n"); }
//printf("-> %d\n", cnt);
if(cnt==1) return !printf("%d", ans);
}
}
Compilation message (stderr)
civilization.cpp: In function 'int main()':
civilization.cpp:36:10: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d%d", &N, &K);
~~~~~^~~~~~~~~~~~~~~~
civilization.cpp:41:14: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d%d", &y, &x);
~~~~~^~~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |