Link problem:https://codeforces.me/contest/2090/problem/C
My code:
include <bits/stdc++.h>
define pii pair<int, int>
using namespace std;
struct cell { int x, y, d; int p=0; };
pii pos(cell a) { int p=a.p; if(p==0) return {a.x, a.y}; if(p==1) return {a.x, a.y+1}; if(p==2) return {a.x+1, a.y}; return {a.x+1, a.y+1}; }
struct cmp { bool operator()(cell a, cell b) const { pii x=pos(a); pii y=pos(b);
if(a.d!=b.d)
return a.d<b.d;
return x.first<y.first;
}};
int dist(cell a) { int p=a.p, x=a.x, y=a.y; if(p==0) return x+y; if(p==1) return x+y+1; if(p==2) return x+y+1; return x+y+4; }
set <cell, cmp> s, sgol;
int t[50003];
signed main() { ios_base::sync_with_stdio(false); cin.tie(0);
int q;
cin>>q;
while(q--)
{
s.clear();
sgol.clear();
int n, space=0, table=0;
cin>>n;
for(int i=1; i<=n; i++)
{
cin>>t[i];
if(t[i]==1)
{
if(space) space--;
else
{
table++;
space+=3;
}
}
else
{
table++;
space+=3;
}
}
int x=1, y=1;
for(int i=1; i<=table; i++)
{
cell a={x, y, x+y, 0};
sgol.insert(a);
if(y==1)
{
y=x+3;
x=1;
}
else
{
y-=3;
x+=3;
}
}
space=0;
for(int i=1; i<=n; i++)
{
if(t[i]==1)
{
bool st=true;
cell tab;
cell a={1, 1, LONG_MAX, 1};
cell b={1, 1, LONG_MAX, 1};
if(!s.empty()) a=*s.begin();
if(!sgol.empty()) b=*sgol.begin();
if(a.d<b.d) tab=a, st=true;
else if(a.d==b.d)
{
if(a.x<b.x) tab=a, st=true;
else tab=b, st=false;
}
else tab=b, st=false;
if(st) s.erase(s.begin());
else sgol.erase(sgol.begin());
pii ans=pos(tab);
cout<<ans.first<<' '<<ans.second<<'\n';
if(tab.p<3)
{
tab.p++;
tab.d=dist(tab);
s.insert(tab);
}
}
else
{
cell tab=*sgol.begin();
sgol.erase(sgol.begin());
pii ans=pos(tab);
cout<<ans.first<<' '<<ans.second<<'\n';
tab.p++;
tab.d=dist(tab);
s.insert(tab);
}
}
}
return 0;}








