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>
#define f first
#define s second
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pi;
ll n,k,p[4000004],transp[2004][2004],cnt,coj,anw,vis[4000004];
bool ck[4000004];
ll dx[]={1,-1,0,0},dy[]={0,0,1,-1};
vector<pi> ar;
queue<pi> q,wq;
ll par(int a)
{
if(p[a]==a)
return a;
return p[a]=par(p[a]);
}
bool merge(ll a,ll b) //a's par to b
{
a=par(a),b=par(b);
if(a!=b)
{
p[a]=b;
return 1;
}
return 0;
}
int main()
{
//ios::sync_with_stdio(false);
//cin.tie(NULL);
cin>>n>>k;
for(int i=0;i<k;i++)
{
ll a,b;cin>>a>>b;
ar.push_back({a,b});
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
transp[i][j]=++cnt;
for(int i=1;i<=n*n+1;i++)
p[i]=i;
for(int i=0;i<k;i++)
{
wq.push(ar[i]);
ck[transp[ar[i].f][ar[i].s]]=1;
}
while(1)
{
bool flag=1;
anw++;
while(!wq.empty())
{
pi a=wq.front();
q.push(a);
wq.pop();
}
while(!q.empty())
{
ll nwx=q.front().f,nwy=q.front().s;
q.pop();
for(int i=0;i<4;i++)
{
ll ntx=nwx+dx[i],nty=nwy+dy[i];
if(ntx<1||ntx>n||nty<1||nty>n)
continue;
if(ck[p[transp[ntx][nty]]])
{
if(merge(transp[ntx][nty],transp[nwx][nwy]))
{
if(vis[transp[ntx][nty]]==anw)
flag=0;
coj++;
}
}
else
{
vis[transp[ntx][nty]]=anw;
if(merge(transp[ntx][nty],transp[nwx][nwy]))
wq.push({ntx,nty});
}
}
}
if(coj==k-1)
{
if(flag)
cout<<anw-1;
else
cout<<anw;
break;
}
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |