#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
#define inf 1e9
using namespace std;
inline int read(){
	int re=0,flag=1;char ch=getchar();
	while(ch>'9'||ch<'0'){
		if(ch=='-') flag=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') re=(re<<1)+(re<<3)+ch-'0',ch=getchar();
	return re*flag;
}
int first[101010],cnt=0,n,m,S,K;
int dis[101010],d[101010][110],vis[101010];
struct edge{
	int to,next;
}a[300010];
inline void add(int u,int v){
	a[++cnt]=(edge){v,first[u]};first[u]=cnt;
	a[++cnt]=(edge){u,first[v]};first[v]=cnt;
}
int q[200010],head,tail,maxq=200000;
void spfa(int s,int num){
	int i,u,v;head=0,tail=1;
	for(i=1;i<=n+K;i++) dis[i]=inf,vis[i]=0;
	dis[s]=-1;vis[s]=1;q[0]=s;
	while(head!=tail){
		u=q[head];head=(head+1)%maxq;
		for(i=first[u];~i;i=a[i].next){
			v=a[i].to;
			if(dis[v]>dis[u]+1){
				dis[v]=dis[u]+1;
				if(!vis[v]){
					vis[v]=1;
					q[tail]=v;tail=(tail+1)%maxq;
				}
			}
		}
	}
	for(i=1;i<=n;i++) d[i][num]=dis[i];
}
int main(){
	memset(first,-1,sizeof(first));
	n=read();m=read();K=read();S=read();int i,t1,t2,j;
	for(i=1;i<=n;i++){
		t1=read();
		add(n+t1,i);
	}
	for(i=1;i<=m;i++){
		t1=read();t2=read();
		add(t1,t2);
	}
	for(i=1;i<=K;i++){
		spfa(n+i,i);
	}
	for(i=1;i<=n;i++){
		sort(d[i]+1,d[i]+K+1);
		t1=0;
		for(j=1;j<=S;j++) t1+=d[i][j];
		printf("%d ",t1);
	}
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
#define inf 1e9
#define next ddf
using namespace std;
inline int read(){
	int re=0,flag=1;char ch=getchar();
	while(ch>'9'||ch<'0'){
		if(ch=='-') flag=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') re=(re<<1)+(re<<3)+ch-'0',ch=getchar();
	return re*flag;
}
int first[201010],cnt=0,n,m,S,K;
int dis[201010],d[201010][110],vis[201010];
int to[600010],next[600010];
inline void add(int u,int v){
	++cnt;to[cnt]=v;next[cnt]=first[u];first[u]=cnt;
	++cnt;to[cnt]=u;next[cnt]=first[v];first[v]=cnt;
}
int q[200010],head,tail,maxq=200000;
void spfa(int s,int num){
	int i,u,v;head=0,tail=1;
	for(i=1;i<=n+K;i++) dis[i]=inf,vis[i]=0;
	dis[s]=-1;vis[s]=1;q[0]=s;
	while(head!=tail){
		u=q[head];
		head=(head+1)%maxq;
		for(i=first[u];~i;i=next[i]){
			v=to[i];
			if(dis[v]>dis[u]+1){
				dis[v]=dis[u]+1;
				if(!vis[v]){
					vis[v]=1;
					if(dis[v]>dis[q[head]]){
						q[tail]=v;
						tail=(tail+1)%maxq;
					}
					else{
						head=(head-1+maxq)%maxq;
						q[head]=v;
					}
				}
			}
		}
	}
	for(i=1;i<=n;i++) d[i][num]=dis[i];
}
int main(){
	memset(first,-1,sizeof(first));
	n=read();m=read();K=read();S=read();int i,t1,t2,j;
	for(i=1;i<=n;i++){
		t1=read();
		add(n+t1,i);
	}
	for(i=1;i<=m;i++){
		t1=read();t2=read();
		add(t1,t2);
	}
	for(i=1;i<=K;i++){
		spfa(n+i,i);
	}
	for(i=1;i<=n;i++){
		sort(d[i]+1,d[i]+K+1);
		t1=0;
		for(j=1;j<=S;j++) t1+=d[i][j];
		printf("%d ",t1);
	}
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
#define inf 1e9
#define next ddf
using namespace std;
inline int read(){
	int re=0,flag=1;char ch=getchar();
	while(ch>'9'||ch<'0'){
		if(ch=='-') flag=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') re=(re<<1)+(re<<3)+ch-'0',ch=getchar();
	return re*flag;
}
int first[201010],cnt=0,n,m,S,K;
int dis[201010],d[201010][110],vis[201010];
int to[600010],next[600010];
inline void add(int u,int v){
	++cnt;to[cnt]=v;next[cnt]=first[u];first[u]=cnt;
}
int q[500010],head,tail,maxq=500000;
void spfa(int s,int num){
	int i,u,v;head=0,tail=1;
	for(i=1;i<=n+K;i++) dis[i]=inf,vis[i]=0;
	dis[s]=0;vis[s]=1;q[0]=s;
	while(head!=tail){
		u=q[head];
		head=(head+1)%maxq;
		for(i=first[u];~i;i=next[i]){
			v=to[i];
			if(dis[v]>dis[u]+1){
				dis[v]=dis[u]+1;
				if(!vis[v]){
					vis[v]=1;
					if(dis[v]>dis[q[head]]){
						q[tail]=v;
						tail=(tail+1)%maxq;
					}
					else{
						head=(head-1+maxq)%maxq;
						q[head]=v;
					}
				}
			}
		}
	}
	for(i=1;i<=n;i++) d[i][num]=dis[i];
}
int main(){
	memset(first,-1,sizeof(first));
	n=read();m=read();K=read();S=read();int i,t1,t2,j;
	for(i=1;i<=n;i++){
		t1=read();
		add(n+t1,i);
	}
	for(i=1;i<=m;i++){
		t1=read();t2=read();
		add(t1,t2);add(t2,t1);
	}
	for(i=1;i<=K;i++){
		spfa(n+i,i);
	}
	for(i=1;i<=n;i++){
		sort(d[i]+1,d[i]+K+1);
		t1=0;
		for(j=1;j<=S;j++) t1+=d[i][j];
		printf("%d ",t1-S);
	}
}


#include<bits/stdc++.h>
#define ll long long
#define N 100005
#define INF 100005
using namespace std;
int n,m,k,s,a[N],r[N<<3];
int head[N],Next[N<<1],vet[N<<1],num;
int f[105][N],F[N],ans[105];
void add(int x,int y){
	Next[++num]=head[x];
	head[x]=num;
	vet[num]=y;
}
int main(){
	scanf("%d%d%d%d",&n,&m,&k,&s);
	for (int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	for (int i=1;i<=m;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		add(x,y);
		add(y,x);
	}
	for (int I=1;I<=k;I++){
		int tou=0,wei=0;
		for (int j=1;j<=n;j++) f[I][j]=INF;
		for (int j=1;j<=n;j++)
		if (a[j]==I){
			r[++wei]=j;
			F[j]=1;
			f[I][j]=0;
		}
		while (tou<wei){
			tou++;
			for (int i=head[r[tou]];i;i=Next[i]){
				if (f[I][vet[i]]>f[I][r[tou]]+1){
					f[I][vet[i]]=f[I][r[tou]]+1;
					if (!F[vet[i]]){
						F[vet[i]]=1;
						r[++wei]=vet[i];
					}
				}
			}
			F[r[tou]]=0;
		}
	}
	for (int i=1;i<=n;i++){
		for (int j=1;j<=k;j++){
			ans[j]=f[j][i];
		}
		sort(ans+1,ans+k+1);
		ll res=0;
		for (int j=1;j<=s;j++) res+=ans[j];
		printf("%d%c",res,(i==n)?'\n':' ');
	}
}


#include<bits/stdc++.h>
#define ll long long
#define N 100005
#define INF 100005
using namespace std;
int n,m,k,s,a[N],r[N<<3];
int head[N],Next[N<<1],vet[N<<1],num;
int f[105][N],F[N],ans[105];
void add(int x,int y){
	Next[++num]=head[x];
	head[x]=num;
	vet[num]=y;
}
int main(){
	scanf("%d%d%d%d",&n,&m,&k,&s);
	for (int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	for (int i=1;i<=m;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		add(x,y);
		add(y,x);
	}
	for (int I=1;I<=k;I++){
		int tou=0,wei=0;
		for (int j=1;j<=n;j++) f[I][j]=INF;
		for (int j=1;j<=n;j++)
		if (a[j]==I){
			r[++wei]=j;
			F[j]=1;
			f[I][j]=0;
		}
		while (tou<wei){
			tou++;
			for (int i=head[r[tou]];i;i=Next[i]){
				if (f[I][vet[i]]>f[I][r[tou]]+1){
					f[I][vet[i]]=f[I][r[tou]]+1;
					if (!F[vet[i]]){
						F[vet[i]]=1;
						r[++wei]=vet[i];
					}
				}
			}
			F[r[tou]]=0;
		}
	}
	for (int i=1;i<=n;i++){
		for (int j=1;j<=k;j++){
			ans[j]=f[j][i];
		}
		sort(ans+1,ans+k+1);
		ll res=0;
		for (int j=1;j<=s;j++) res+=ans[j];
		printf("%I64d",res);
		if (i==n) printf("\n"); else printf(" ");
	}
}


#include <cstdio>
#include <vector>
#include <algorithm>
#define REP(i, n) for (int i = 1; i <= n; ++i)
#define FOR(i, n) for (__typeof(n.begin())i = n.begin(); i != n.end(); ++i)
using namespace std;

const int MAXN = 100010;
const int MAXK = 110;
int n, m, k, s, l, r;
int a[MAXN];
vector<int> v[MAXN];
int dp[MAXN][MAXK];
bool vis[MAXN][MAXK];
int line[MAXN * MAXK][3];

int main() {
	// freopen("1.in", "r", stdin);
	scanf("%d%d%d%d", &n, &m, &k, &s);
	REP(i, n) scanf("%d", &a[i]);
	REP(i, m) {
		int x, y;
		scanf("%d%d", &x, &y);
		v[x].push_back(y);
		v[y].push_back(x);
	}
	REP(i, n) {
		vis[i][a[i]] = true;
		++r;
		line[r][0] = i;
		line[r][1] = a[i];
		line[r][2] = 0;
		dp[i][a[i]] = 0;
	}
	for (l = 1; l <= r; ++l)
		FOR(p, v[line[l][0]])
			if (!vis[*p][line[l][1]]) {
				vis[*p][line[l][1]] = true;
				++r;
				line[r][0] = *p;
				line[r][1] = line[l][1];
				line[r][2] = line[l][2] + 1;
				dp[*p][line[r][1]] = line[r][2];
			}
	REP(i, n) {
		sort(dp[i] + 1, dp[i] + k + 1);
		int tmp = 0;
		REP(j, s) tmp += dp[i][j];
		printf(i == n ? "%d\n" : "%d ", tmp);
	}
	return 0;
}


#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m,k,s,hw[100005],zdl[100005][105],stp[100005],cnt;
vector<int> edge[100005];
void bfs(int hwm)
{
	memset(stp,-1,sizeof(stp));
	queue<int> que;
	for(int i=1;i<=n;i++)
	{
		if(hw[i]==hwm)
		{
			que.push(i);
			stp[i]=0;
			zdl[i][hwm]=0;
		}
	}
	while(!que.empty())
	{
		int u=que.front();
		que.pop();
		for(int i=0;i<edge[u].size();i++)
		{
			int v=edge[u][i];
			if(stp[v]!=-1)continue;
			que.push(v);
			stp[v]=stp[u]+1;
			if(stp[v]<zdl[v][hwm]||zdl[v][hwm]==-1)zdl[v][hwm]=stp[v];
		}
	}
}
int main()
{
	for(int i=0;i<100005;i++)
	  for(int j=0;j<105;j++)
		zdl[i][j]=2e9;
	scanf("%d%d%d%d",&n,&m,&k,&s);
	for(int i=1;i<=n;i++)scanf("%d",&hw[i]);
	for(int i=0,a,b;i<m;i++)
	{
		scanf("%d%d",&a,&b);
		edge[a].push_back(b);
		edge[b].push_back(a);
	}
	for(int i=1;i<=k;i++)bfs(i);
	for(int i=1;i<=n;i++)
	{
		cnt=0;
//		for(int j=1;j<=k;j++)printf("%d ",zdl[i][j]);printf("\n");
		nth_element(zdl[i]+1,zdl[i]+s+1,zdl[i]+k+1);
		for(int j=1;j<=s;j++)cnt+=zdl[i][j];
		printf("%d ",cnt);
	}
}


#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m,k,s,hw[100005],zdl[100005][105],cnt;
vector<int> edge[100005];
void bfs(int curr)
{
	int stp[100005];
	memset(stp,-1,sizeof(stp));
	queue<int> que;
	que.push(curr);
	stp[curr]=0;
	zdl[curr][hw[curr]]=0;
	while(!que.empty())
	{
		int u=que.front();
		que.pop();
		for(int i=0;i<edge[u].size();i++)
		{
			int v=edge[u][i];
			if(stp[v]!=-1)continue;
			que.push(v);
			stp[v]=stp[u]+1;
			if(stp[v]<zdl[v][hw[curr]]||zdl[v][hw[curr]]==-1)zdl[v][hw[curr]]=stp[v];
		}
	}
}
int main()
{
	for(int i=0;i<100005;i++)
	  for(int j=0;j<105;j++)
		zdl[i][j]=2e9;
	scanf("%d%d%d%d",&n,&m,&k,&s);
	for(int i=1;i<=n;i++)scanf("%d",&hw[i]);
	for(int i=0,a,b;i<m;i++)
	{
		scanf("%d%d",&a,&b);
		edge[a].push_back(b);
		edge[b].push_back(a);
	}
	for(int i=1;i<=n;i++)bfs(i);
	for(int i=1;i<=n;i++)
	{
		cnt=0;
//		for(int j=1;j<=k;j++)printf("%d ",zdl[i][j]);printf("\n");
		nth_element(zdl[i]+1,zdl[i]+s+1,zdl[i]+k+1);
		for(int j=1;j<=s;j++)cnt+=zdl[i][j];
		printf("%d ",cnt);
	}
}


#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m,k,s,hw[100005],zdl[100005][105],cnt;
vector<int> edge[100005];
void bfs(int curr)
{
	int stp[100005];
	memset(stp,-1,sizeof(stp));
	queue<int> que;
	que.push(curr);
	stp[curr]=0;
	zdl[curr][hw[curr]]=0;
	while(!que.empty())
	{
		int u=que.front();
		que.pop();
		for(int i=0;i<edge[u].size();i++)
		{
			int v=edge[u][i];
			if(stp[v]!=-1)continue;
			que.push(v);
			stp[v]=stp[u]+1;
			if(stp[v]<zdl[v][hw[curr]]||zdl[v][hw[curr]]==-1)zdl[v][hw[curr]]=stp[v];
		}
	}
}
bool cmp(int a,int b)
{
	return b==-1||a<b;
}
int main()
{
	memset(zdl,-1,sizeof(zdl));
	scanf("%d%d%d%d",&n,&m,&k,&s);
	for(int i=1;i<=n;i++)scanf("%d",&hw[i]);
	for(int i=0,a,b;i<m;i++)
	{
		scanf("%d%d",&a,&b);
		edge[a].push_back(b);
		edge[b].push_back(a);
	}
	for(int i=1;i<=n;i++)bfs(i);
	for(int i=1;i<=n;i++)
	{
		cnt=0;
//		for(int j=1;j<=k;j++)printf("%d ",zdl[i][j]);printf("\n");
		sort(zdl[i]+1,zdl[i]+k+1,cmp);
		for(int j=1;j<=s;j++)cnt+=zdl[i][j];
		printf("%d ",cnt);
	}
}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <cmath>
#include <algorithm>

using namespace std;

const int MAXN = 100005, MAXK = 105, INF = 99999999;

int dis[MAXN][MAXK], good[MAXN];
int N, M, K, S;

struct Edge{
	int t;
	Edge *next;
};
Edge pool[MAXN * 2];
Edge vertex[MAXN];
int pool_top = 0;

void addedge(int a, int b){
	Edge *e = &pool[pool_top ++];
	e->t = b;
	e->next = vertex[a].next;
	vertex[a].next = e;
}

int queue[MAXN * 2], head, tail;

void calc(int category){
	head = 1;	tail = 0;

	for(int i = 1; i <= N; i ++)
		if(good[i] == category){
			queue[++ tail] = i;
			dis[i][category] = 0;
		}

	int tmp;
	while(head <= tail){
		tmp = queue[head ++];

		for(Edge *e = vertex[tmp].next; e != NULL; e = e->next){
			if(dis[e->t][category] > dis[tmp][category] + 1){
				dis[e->t][category] = dis[tmp][category] + 1;
				queue[++ tail] = e->t;
			}
		}
	}
}

int list[MAXK];

int find(int v){
	int rec = 0;
	for(int i = 1; i <= K; i ++)	list[i] = dis[v][i];

	sort(list + 1, list + K + 1);

	for(int i = 1; i <= S; i ++)	rec += list[i];

	return rec;
}

int main(){
	int a, b;

	scanf("%d%d%d%d", &N, &M, &K, &S);
	for(int i = 1; i <= N; i ++){
		scanf("%d", &good[i]);
		vertex[i].next = NULL;
		for(int j = 1; j <= K; j ++)	dis[i][j] = INF;
	}

	for(int i = 1; i <= M; i ++){
		scanf("%d%d", &a, &b);
		addedge(a, b);
		addedge(b, a);
	}

	for(int i = 1; i <= K; i ++)
		calc(i);

	for(int i = 1; i < N; i ++)
		printf("%d ", find(i));
	printf("%d\n", find(N));

	return 0;
}


#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
struct Data{ int nsp,u,ds; }data;
struct edge{ int v,nxt; }e[200005];
int n,m,k,s,head[100005],tot,dis[100005][105],anss[105],ans;
bool vis[100005][105];
void add(int u,int v){ e[++tot].v=v; e[tot].nxt=head[u]; head[u]=tot; }
queue<Data>q;
void bfs(){
	while(!q.empty()){
		int u=q.front().u,nsp=q.front().nsp,ds=q.front().ds; q.pop();
		for(int i=head[u];i;i=e[i].nxt)
			if(!vis[e[i].v][nsp]){
				vis[e[i].v][nsp]=1;
				dis[e[i].v][nsp]=ds+1;
				data.u=e[i].v;
				data.nsp=nsp;
				data.ds=ds+1;
				q.push(data);
			}
	}
}
int main(){
	scanf("%d %d %d %d",&n,&m,&k,&s);
	memset(dis,0x3f,sizeof(dis));
	for(int sp,i=1;i<=n;++i){
		scanf("%d",&sp);
		vis[i][sp]=1;
		dis[i][sp]=0;
		data.nsp=sp;
		data.u=i;
		data.ds=0;
		q.push(data);
	}
	for(int u,v,i=1;i<=m;++i){
		scanf("%d %d",&u,&v);
		add(u,v); add(v,u);
	}
	bfs();
	for(int i=1;i<=n;++i){
		ans=0;
		for(int j=1;j<=k;++j) anss[j]=dis[i][j];
		nth_element(anss+1,anss+1+s,anss+1+k);
		for(int j=1;j<=s;++j) ans+=anss[j];
		printf("%d ",ans);
	}
	return 0;
}


#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<cmath>
#include<map>
#include<cstdlib>
#include<vector>
#include<set>
#include<deque>
#include<chrono>
#include<random>
#include<bitset>
#include<assert.h>
#include<cstdio>
#include<string.h>
using namespace std;
ofstream fo("test.out");
ifstream fi("test.inp");
#define ll long long
#define For(i,n) for (ll(i) = 0; (i)<(n); (i)++)
#define For1(i,n) for (ll(i) = 1; (i) <= (n); (i)++)
#define Forlr(i,l,r) for (ll(i) = (l); (i) <= (r); (i)++)
#define Forrl(i,r,l) for (ll(i) = (r); (i) >= (l); (i)--)
#define pb push_back
#define pp pop_back
#define mp make_pair
const ll MOD = 1e9 + 7;
const ll base = 269;
const ll oo = LLONG_MAX;
const int ooi = 1<<30;
const int N = 1e5 + 5;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

ll P(ll x, ll y) // x^y
{
	ll ret = 1;
	while (y > 0)
	{
		if (y & 1) ret *= x;
		y /= 2;
		x = x * x;
	}
	return ret;
}
ll GCD(ll a, ll b)
{
	return (b ? GCD(b, a%b) : a);
}

/*
MIKUNO - 15/02/1999
*/
ll n, m, q, k, pos, rs, check, t, T;
ll maxx = -1e9, minn = 1e9;
ll x, y, s;
ll l, r;
vector<int>g[N], goods[105];
int w[N];

int Free[N];
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	cin >> n >> m >> k >> s;
	For1(i, n)
		cin >> w[i], goods[w[i]].pb(i);
	For(i, m)
	{
		cin >> x >> y;
		g[x].pb(y);
		g[y].pb(x);
	}
	vector<vector<int>>ans(k + 1, vector<int>(n + 1, -1));
	For1(i, k)
	{
		deque<int>q;
		For(j, goods[i].size())
		{

			int v = goods[i][j];
			ans[i][v] = 0;
			Free[v]++;
			q.push_back(v);

		}
		while (!q.empty())
			{
				int to = q.front();
				q.pop_front();
				for (int u : g[to])
					if (ans[i][u] == -1)
					{
						ans[i][u] = ans[i][to] + 1;
						q.pb(u);
					}
			}
	}
	For1(i, n)
	{
		vector<int>d(k);
		For(j, k)
			d[j] = ans[j + 1][i];
		sort(d.begin(), d.end());
		ll sum = 0;
		For(j, s)
			sum += d[j];
		cout << sum << " ";
	}
}


#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<cmath>
#include<map>
#include<cstdlib>
#include<vector>
#include<set>
#include<deque>
#include<chrono>
#include<random>
#include<bitset>
#include<assert.h>
#include<cstdio>
#include<string.h>
using namespace std;
ofstream fo("test.out");
ifstream fi("test.inp");
#define ll long long
#define For(i,n) for (ll(i) = 0; (i)<(n); (i)++)
#define For1(i,n) for (ll(i) = 1; (i) <= (n); (i)++)
#define Forlr(i,l,r) for (ll(i) = (l); (i) <= (r); (i)++)
#define Forrl(i,r,l) for (ll(i) = (r); (i) >= (l); (i)--)
#define pb push_back
#define pp pop_back
#define mp make_pair
const ll MOD = 1e9 + 7;
const ll base = 269;
const ll oo = LLONG_MAX;
const int ooi = 1<<30;
const int N = 1e5 + 5;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

ll P(ll x, ll y) // x^y
{
	ll ret = 1;
	while (y > 0)
	{
		if (y & 1) ret *= x;
		y /= 2;
		x = x * x;
	}
	return ret;
}
ll GCD(ll a, ll b)
{
	return (b ? GCD(b, a%b) : a);
}

/*
MIKUNO - 15/02/1999
*/
ll n, m, q, k, pos, rs, check, t, T;
ll maxx = -1e9, minn = 1e9;
ll x, y, s;
ll l, r;
vector<int>g[N], goods[105];
int w[N];
int ans[105][N];
int Free[N];
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	For(i, 100)
		For(j, N)
		ans[i][j] = ooi;
	cin >> n >> m >> k >> s;
	For1(i, n)
		cin >> w[i], goods[w[i]].pb(i);
	For(i, n)
	{
		cin >> x >> y;
		g[x].pb(y);
		g[y].pb(x);
	}
	For1(i, k)
	{

		For(j, goods[i].size())
		{
			For(k, N)
				Free[k] = 0;
			int v = goods[i][j];
			ans[i][v] = 0;
			Free[v]++;
			deque<int>q;
			q.push_back(v);
			while (!q.empty())
			{
				int to = q.front();
				q.pop_front();
				for (int u : g[to])
					if (!Free[u] && w[u] != i)
					{
						q.pb(u);
						ans[i][u] = min(ans[i][u], ans[i][to] + 1);
						Free[u]++;
					}
			}
		}
	}
	For1(i, n)
	{
		vector<int>d(k);
		For(j, k)
			d[j] = ans[j + 1][i];
		sort(d.begin(), d.end());
		ll sum = 0;
		For(j, s)
			sum += d[j];
		cout << sum << " ";
	}
}


#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<cmath>
#include<map>
#include<cstdlib>
#include<vector>
#include<set>
#include<deque>
#include<chrono>
#include<random>
#include<bitset>
#include<assert.h>
#include<cstdio>
#include<string.h>
using namespace std;
ofstream fo("test.out");
ifstream fi("test.inp");
#define ll long long
#define For(i,n) for (ll(i) = 0; (i)<(n); (i)++)
#define For1(i,n) for (ll(i) = 1; (i) <= (n); (i)++)
#define Forlr(i,l,r) for (ll(i) = (l); (i) <= (r); (i)++)
#define Forrl(i,r,l) for (ll(i) = (r); (i) >= (l); (i)--)
#define pb push_back
#define pp pop_back
#define mp make_pair
const ll MOD = 1e9 + 7;
const ll base = 269;
const ll oo = LLONG_MAX;
const int ooi = 1<<30;
const int N = 1e5 + 5;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

ll P(ll x, ll y) // x^y
{
	ll ret = 1;
	while (y > 0)
	{
		if (y & 1) ret *= x;
		y /= 2;
		x = x * x;
	}
	return ret;
}
ll GCD(ll a, ll b)
{
	return (b ? GCD(b, a%b) : a);
}

/*
MIKUNO - 15/02/1999
*/
ll n, m, q, k, pos, rs, check, t, T;
ll maxx = -1e9, minn = 1e9;
ll x, y, s;
ll l, r;
vector<int>g[N], goods[105];
int w[N];

int Free[N];
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	For(i, 100)
		For(j, N)
		ans[i][j] = ooi;
	cin >> n >> m >> k >> s;
	For1(i, n)
		cin >> w[i], goods[w[i]].pb(i);
	For(i, m)
	{
		cin >> x >> y;
		g[x].pb(y);
		g[y].pb(x);
	}
	vector<vector<int>>ans(k + 1, vector<int>(n + 1, -1));
	For1(i, k)
	{

		For(j, goods[i].size())
		{
			For(k, N)
				Free[k] = 0;
			int v = goods[i][j];
			ans[i][v] = 0;
			Free[v]++;
			deque<int>q;
			q.push_back(v);
			while (!q.empty())
			{
				int to = q.front();
				q.pop_front();
				for (int u : g[to])
					if (ans[i][u] == -1)
					{
						ans[i][u] = ans[i][to] + 1;
						q.pb(u);
					}
			}
		}
	}
	For1(i, n)
	{
		vector<int>d(k);
		For(j, k)
			d[j] = ans[j + 1][i];
		sort(d.begin(), d.end());
		ll sum = 0;
		For(j, s)
			sum += d[j];
		cout << sum << " ";
	}
}


#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<cmath>
#include<map>
#include<cstdlib>
#include<vector>
#include<set>
#include<deque>
#include<chrono>
#include<random>
#include<bitset>
#include<assert.h>
#include<cstdio>
#include<string.h>
using namespace std;
ofstream fo("test.out");
ifstream fi("test.inp");
#define ll long long
#define For(i,n) for (ll(i) = 0; (i)<(n); (i)++)
#define For1(i,n) for (ll(i) = 1; (i) <= (n); (i)++)
#define Forlr(i,l,r) for (ll(i) = (l); (i) <= (r); (i)++)
#define Forrl(i,r,l) for (ll(i) = (r); (i) >= (l); (i)--)
#define pb push_back
#define pp pop_back
#define mp make_pair
const ll MOD = 1e9 + 7;
const ll base = 269;
const ll oo = LLONG_MAX;
const int ooi = 1<<30;
const int N = 1e5 + 5;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

ll P(ll x, ll y) // x^y
{
	ll ret = 1;
	while (y > 0)
	{
		if (y & 1) ret *= x;
		y /= 2;
		x = x * x;
	}
	return ret;
}
ll GCD(ll a, ll b)
{
	return (b ? GCD(b, a%b) : a);
}

/*
MIKUNO - 15/02/1999
*/
ll n, m, q, k, pos, rs, check, t, T;
ll maxx = -1e9, minn = 1e9;
ll x, y, s;
ll l, r;
vector<int>g[N], goods[105];
int w[N];
int ans[105][N];
int Free[N];
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	For(i, 100)
		For(j, N)
		ans[i][j] = ooi;
	cin >> n >> m >> k >> s;
	For1(i, n)
		cin >> w[i], goods[w[i]].pb(i);
	For(i, n)
	{
		cin >> x >> y;
		g[x].pb(y);
		g[y].pb(x);
	}
	For1(i, k)
	{

		For(j, goods[i].size())
		{
			For(k, N)
				Free[k] = 0;
			int v = goods[i][j];
			ans[i][v] = 0;
			Free[v]++;
			deque<int>q;
			q.push_back(v);
			while (!q.empty())
			{
				int to = q.front();
				q.pop_front();
				for (int e : g[to])
					if (!Free[e] && w[e] != i)
					{
						q.pb(e);
						ans[i][e] = min(ans[i][e], ans[i][to] + 1);
						Free[e]++;
					}
			}
		}
	}
	For1(i, n)
	{
		vector<int>d(k);
		For(j, k)
			d[j] = ans[j + 1][i];
		sort(d.begin(), d.end());
		int sum = 0;
		For(i, s)
			sum += d[i];
		cout << sum << " ";
	}
}


#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<cmath>
#include<map>
#include<cstdlib>
#include<vector>
#include<set>
#include<deque>
#include<chrono>
#include<random>
#include<bitset>
#include<assert.h>
#include<cstdio>
#include<string.h>
using namespace std;
ofstream fo("test.out");
ifstream fi("test.inp");
#define ll long long
#define For(i,n) for (ll(i) = 0; (i)<(n); (i)++)
#define For1(i,n) for (ll(i) = 1; (i) <= (n); (i)++)
#define Forlr(i,l,r) for (ll(i) = (l); (i) <= (r); (i)++)
#define Forrl(i,r,l) for (ll(i) = (r); (i) >= (l); (i)--)
#define pb push_back
#define pp pop_back
#define mp make_pair
const ll MOD = 1e9 + 7;
const ll base = 269;
const ll oo = LLONG_MAX;
const int ooi = 1<<30;
const int N = 1e5 + 5;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

ll P(ll x, ll y) // x^y
{
	ll ret = 1;
	while (y > 0)
	{
		if (y & 1) ret *= x;
		y /= 2;
		x = x * x;
	}
	return ret;
}
ll GCD(ll a, ll b)
{
	return (b ? GCD(b, a%b) : a);
}

/*
MIKUNO - 15/02/1999
*/
ll n, m, q, k, pos, rs, check, t, T;
ll maxx = -1e9, minn = 1e9;
ll x, y, s;
ll l, r;
vector<int>g[N], goods[105];
int w[N];
int ans[105][N];
int Free[N];
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	For(i, 100)
		For(j, N)
		ans[i][j] = ooi;
	cin >> n >> m >> k >> s;
	For1(i, n)
		cin >> w[i], goods[w[i]].pb(i);
	For(i, m)
	{
		cin >> x >> y;
		g[x].pb(y);
		g[y].pb(x);
	}
	For1(i, k)
	{

		For(j, goods[i].size())
		{
			For(k, N)
				Free[k] = 0;
			int v = goods[i][j];
			ans[i][v] = 0;
			Free[v]++;
			deque<int>q;
			q.push_back(v);
			while (!q.empty())
			{
				int to = q.front();
				q.pop_front();
				for (int u : g[to])
					if (!Free[u] && w[u] != i)
					{
						q.pb(u);
						ans[i][u] = min(ans[i][u], ans[i][to] + 1);
						Free[u]++;
					}
			}
		}
	}
	For1(i, n)
	{
		vector<int>d(k);
		For(j, k)
			d[j] = ans[j + 1][i];
		sort(d.begin(), d.end());
		ll sum = 0;
		For(j, s)
			sum += d[j];
		cout << sum << " ";
	}
}


#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<cmath>
#include<map>
#include<cstdlib>
#include<vector>
#include<set>
#include<deque>
#include<chrono>
#include<random>
#include<bitset>
#include<assert.h>
#include<cstdio>
#include<string.h>
using namespace std;
ofstream fo("test.out");
ifstream fi("test.inp");
#define ll long long
#define For(i,n) for (ll(i) = 0; (i)<(n); (i)++)
#define For1(i,n) for (ll(i) = 1; (i) <= (n); (i)++)
#define Forlr(i,l,r) for (ll(i) = (l); (i) <= (r); (i)++)
#define Forrl(i,r,l) for (ll(i) = (r); (i) >= (l); (i)--)
#define pb push_back
#define pp pop_back
#define mp make_pair
const ll MOD = 1e9 + 7;
const ll base = 269;
const ll oo = LLONG_MAX;
const int ooi = 1<<30;
const int N = 1e5 + 5;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

ll P(ll x, ll y) // x^y
{
	ll ret = 1;
	while (y > 0)
	{
		if (y & 1) ret *= x;
		y /= 2;
		x = x * x;
	}
	return ret;
}
ll GCD(ll a, ll b)
{
	return (b ? GCD(b, a%b) : a);
}

/*
MIKUNO - 15/02/1999
*/
ll n, m, q, k, pos, rs, check, t, T;
ll maxx = -1e9, minn = 1e9;
ll x, y, s;
ll l, r;
vector<int>g[N], goods[105];
int w[N];
int ans[105][N];
int Free[N];
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	For(i, 100)
		For(j, N)
		ans[i][j] = ooi;
	cin >> n >> m >> k >> s;
	For1(i, n)
		cin >> w[i], goods[w[i]].pb(i);
	For(i, n)
	{
		cin >> x >> y;
		g[x].pb(y);
		g[y].pb(x);
	}
	For1(i, k)
	{

		For(j, goods[i].size())
		{
			int v = goods[i][j];
			ans[i][v] = 0;
			Free[v]++;
			deque<int>q;
			q.push_back(v);
			while (!q.empty())
			{
				int to = q.front();
				q.pop_front();
				for (int u : g[to])
					if (ans[i][u] == ooi)
						ans[i][u] = ans[i][to] + 1, q.pb(u);
			}
		}
	}
	For1(i, n)
	{
		vector<int>d(k);
		For(j, k)
			d[j] = ans[j + 1][i];
		sort(d.begin(), d.end());
		ll sum = 0;
		For(j, s)
			sum += d[j];
		cout << sum << " ";
	}
}


T = input()

for _ in xrange(T):
    n = input()
    q = []
    for i in xrange(n):
        l, r = map(int, raw_input().split())
        q.append([l, i, r])

    q.sort(key=lambda x: x[0])
    #print q
    res = [0 for i in xrange(n)]
    secondsPassed = 0
    for i in xrange(n):
        if q[i][0] > secondsPassed:
            secondsPassed = q[i][0]

        if secondsPassed >= q[i][2]:
            continue
        else:
            res[q[i][1]] = secondsPassed
            secondsPassed += 1

    print ' '.join(map(str, res))


for _ in range(input()):
    t=1
    for _ in range(input()):
        l,r=map(int,raw_input().split())
        t=max(t,l)
        if t<r:
            print t,
            t+=1
        else:
            print 0,
    print


for _ in range(input()):
    t=1
    for _ in range(input()):
        l,r=map(int,raw_input().split())
        t=max(t,l)
        if t>r:
            print 0,
        else:
            print t,
            t+=1
    print


import sys

def main():
  first_line = raw_input().split(" ")
  t = int(first_line[0])
  for i in range(t):
    second_line = raw_input().split(" ")
    n = int(second_line[0])
    queue_list = [False for k in range(5001)]
    string = ""
    for j in range(n):
      third_line = raw_input().split(" ")
      l = int(third_line[0])
      r = int(third_line[1])
      while (queue_list[l] and l <= r):
        l = l+1
      if (l <= r):
        queue_list[l] = True
        string = string + " " + str(l)
      else:
        string = string + " " + str(0)
    print(string)

main()


t = input()
for _ in xrange(t):
    n = input()
    tl = 0
    for _ in xrange(n):
        l, r = map(int ,raw_input().split(" "))
        if r > tl:
            print max(tl, l),
            tl = max(tl + 1, l + 1)
        else:
            print 0,
            tl = max(tl, r + 1)
    print


1 0 2
t = input()
for _ in xrange(t):
    n = input()
    now = 0
    for _ in xrange(n):
        l, r = map(int ,raw_input().split(" "))
        if r >= now:
            print max(now, l),
            now = max(now + 1, l + 1)
        else:
            print 0,
            now = max(now, r + 1)
    print


t = input()
for _ in xrange(t):
    n = input()
    tl = 0
    for _ in xrange(n):
        l, r = map(int ,raw_input().split(" "))
        if r > tl:
            print max(tl, l),
            tl = max(tl + 1, l + 1)
        else:
            print 0,
            tl = r + 1
    print


t = input()
for _ in xrange(t):
    n = input()
    now = 0
    for _ in xrange(n):
        l, r = map(int ,raw_input().split(" "))
        if r >= now:
            print max(now, l),
            now = max(now + 1, l + 1)
        else:
            print 0,
            now = max(now, r + 1)
    print


for _ in range(input()):
    n = input()
    times = []
    curtime = 1
    l = []
    for i in range(n):
        l.append(map(int, raw_input().split()))
    for i in range(n):
        if l[i][1] < curtime:
            times.append(0)
        else:
            curtime = max(l[i][0], curtime)
            times.append(curtime)
            curtime += 1
    for i in times:
        print i,
    print


def solution():
    t = int(raw_input().strip())
    res = []
    for it in range(t):
        n = int(raw_input().strip())
        times = [list(map(int, raw_input().strip().split())) for _ in range(n)]
        t_cur = 0
        step = []
        for item in times:
            if item[0] > t_cur:
                t_cur = item[0]
            if item[1] < t_cur:
                step.append(0)
                continue
            step.append(t_cur)
            t_cur += 1
        res.append(step)
    return res

if __name__ == '__main__':
    r = solution()
    for i in range(len(r)):
        for x in r[i]:
            print x,
        print


w=int(raw_input())
for k in range(w):
    n=int(raw_input())
    lt=[0 for p in range(n)]
    t=1
    for j in range(n):
        a,b=map(int,raw_input().strip().split())
        if t<b:
            lt[j]=max(t,a)
            t=max(t+1,a+1)
        else:
            lt[j]=0
            pass
    for g in lt:
        print g,
    print


w=int(raw_input())
for k in range(w):
    n=int(raw_input())
    lt=[0 for p in range(n)]
    t=1
    for j in range(n):
        a,b=map(int,raw_input().strip().split())
        if t<b and a<b:
            lt[j]=max(t,a)
            t=max(t+1,a+1)
        else:
            lt[j]=0
            pass
    for g in lt:
        print g,
    print


w=int(raw_input())
for k in range(w):
    n=int(raw_input())
    lt=[0 for p in range(n)]
    t=1
    for j in range(n):
        a,b=map(int,raw_input().strip().split())
        if t<=b:
            lt[j]=max(t,a)
            t=max(t+1,a+1)
        else:
            lt[j]=0
            pass
    for g in lt:
        print g,
    print


import Queue

t = int(raw_input())

def get_if_not_empty(q):
  """get element from queue if not empty, otherwise return None"""
  if q.empty():
    return None
  return q.get()

for _ in range(t):
  n = int(raw_input())
  students = []
  for _ in range(n):
    students.append(map(int, raw_input().split()))

  current_time = students[0][0]
  waiting_students = Queue.Queue()
  student_index = 0
  time_got_tea = [0] * len(students)
  current_time = students[0][0]

  while current_time < 5001 and student_index < len(students):
    if waiting_students.empty():
      current_time = students[student_index][0]
    while (student_index < len(students) and
           students[student_index][0] == current_time):
      waiting_students.put(student_index)
      student_index += 1

    student_idx = get_if_not_empty(waiting_students)
    while student_idx is not None and students[student_idx][1] < current_time:
      student_idx = get_if_not_empty(waiting_students)
    if student_idx is not None:
      time_got_tea[student_idx] = current_time
    current_time += 1

  print " ".join(map(str, time_got_tea))


import Queue

t = int(raw_input())

def get_if_not_empty(q):
  """get element from queue if not empty, otherwise return None"""
  if q.empty():
    return None
  return q.get()

for _ in range(t):
  n = int(raw_input())
  students = []
  for _ in range(n):
    students.append(map(int, raw_input().split()))

  current_time = students[0][0]
  waiting_students = Queue.Queue()
  student_index = 0
  time_got_tea = [0] * len(students)
  for current_time in range(5000 + 1):
    while (student_index < len(students) and
           students[student_index][0] == current_time):
      waiting_students.put(student_index)
      student_index += 1

    student_idx = get_if_not_empty(waiting_students)
    while student_idx is not None and students[student_idx][1] < current_time:
      student_idx = get_if_not_empty(waiting_students)
    if student_idx is not None:
      time_got_tea[student_idx] = current_time

  print " ".join(map(str, time_got_tea))


import Queue

t = int(raw_input())

def get_if_not_empty(q):
  """get element from queue if not empty, otherwise return None"""
  if q.empty():
    return None
  return q.get()

for _ in range(t):
  n = int(raw_input())
  students = []
  for _ in range(n):
    students.append(map(int, raw_input().split()))

  current_time = students[0][0]
  waiting_students = Queue.Queue()
  student_index = 0
  time_got_tea = [0] * len(students)
  current_time = students[0][0]

  while current_time < 5001:
    if waiting_students.empty():
      current_time = students[student_index][0] if student_index < len(students) else 5001
    while (student_index < len(students) and
           students[student_index][0] == current_time):
      waiting_students.put(student_index)
      student_index += 1

    student_idx = get_if_not_empty(waiting_students)
    while student_idx is not None and students[student_idx][1] < current_time:
      student_idx = get_if_not_empty(waiting_students)
    if student_idx is not None:
      time_got_tea[student_idx] = current_time
    current_time += 1

  print " ".join(map(str, time_got_tea))


for t in xrange(int(raw_input())):
	n = int(raw_input())
	l = []
	r = []
	for i in xrange(n):
		x,y = map(int,raw_input().split(' '))
		l.append(x)
		r.append(y)
	curTime = 0
	for i in xrange(n):
		if(curTime<=l[i]):
			curTime = l[i]+1
			print l[i],
		elif curTime<=r[i]:
			print curTime,
			curTime+=1
		else:
			print 0,
	print ''


t = int(raw_input())
while t > 0:
    n = int(raw_input())
    T = [False] * 5001
    while n > 0:
        l, r = map(int, raw_input().split())
        f = False
        for i in range(l, r + 1, 1):
            if not T[i]:
                f = T[i] = True
                print str(i) + " ",
                break
        if not f:
            print "0 ",
        n -= 1
    print
    t -= 1


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)
    p=max(r)
    q=[]
    left=0
    done={}
    #print l
    for i in range(n):
        if r[i]<l[i]:
            done[i+1]=0
    for time in range(1,p+1):
        #print q
        while(left<n and l[left]<=time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<=time and oth!=q[0]:
                q.remove(oth)
                done[oth+1]=0
        if len(q)>0:
            now=q[0]
            if r[now] >= time:
                done[now + 1] = time
            else:
                done[now + 1] = 0
            q=q[1:]
    #print done
    for i in q:
        done[i + 1] = 0
    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)
    p=max(r)
    q=[]
    left=0
    done={}
    #print l
    for i in range(n):
        if r[i]<l[i]:
            done[i+1]=0
    for time in range(1,p+1):
        #print q
        while(left<n and l[left]<=time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<=time and oth!=q[0]:
                q.remove(oth)
                done[oth+1]=0
        if len(q)>0:
            now=q[0]
            if r[now] >= time:
                done[now + 1] = time
            else:
                done[now + 1] = 0
            q=q[1:]
    #print done
    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)
    p=max(r)
    q=[]
    left=0
    done={}
    #print l
    for i in range(n):
        if r[i]<l[i]:
            done[i+1]=0
    for time in range(1,p+1):
        #print q
        while(left<n and l[left]<=time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<=time and oth!=q[0]:
                q.remove(oth)
                done[oth+1]=0
        if len(q)>0:
            now=q[0]
            done[now+1]=time
            q=q[1:]
    #print done
    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)
    p=max(r)
    p=max(p,max(l))
    q=[]
    left=0
    done={}
    #print l
    for time in range(1,p+1):
        #print q
        while(left<n and l[left]==time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<=time and oth!=q[0]:
                q.remove(oth)
                done[oth+1]=0
        if len(q)>0:
            now=q[0]
            if r[now] >= time:
                done[now + 1] = time
            else:
                done[now + 1] = 0
            q=q[1:]

    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)

    p=max(r)
    p=max(p,max(l))
    q=[]
    left=0
    done={}
    #print l
    for i in range(1, n + 1):
        done[i] = 0
    for time in range(1,p+1):
        #print q
        while(left<n and l[left]<=time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<time:
                done[oth+1]=0
                q.remove(oth)
            elif r[oth]==time:
                if q[0]!=oth:
                    done[oth + 1] = 0
                    q.remove(oth)

        if len(q)>0:
            now=q[0]
            if r[now]>=time:
                done[now+1]=time
            else:
                done[now]=0

            q=q[1:]
    for i in q:
        done[i + 1] = 0

    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)

    p=max(r)
    p=max(p,max(l))
    q=[]
    left=0
    done={}
    #print l
    for time in range(1,p+1):
        #print q
        while(left<n and l[left]==time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<time:
                done[oth+1]=0
                q.remove(oth)
            elif r[oth]==time:
                if q[0]!=oth:
                    done[oth + 1] = 0
                    q.remove(oth)

        if len(q)>0:
            now=q[0]
            if r[now]>=time:
                done[now+1]=time
            else:
                done[now]=0

            q=q[1:]

    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)
    p=max(r)
    p=max(p,max(l))
    q=[]
    left=0
    done={}
    #print l
    for time in range(1,p+1):
        #print q
        while(left<n and l[left]==time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<=time and oth!=q[0]:
                q.remove(oth)
                done[oth+1]=0
        if len(q)>0:
            now=q[0]
            if r[now] >= time:
                done[now + 1] = time
            else:
                done[now + 1] = 0
            q=q[1:]
    for i in q:
        done[i + 1] = 0
    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)
    p=max(r)
    q=[]
    left=0
    done={}
    #print l
    for time in range(1,p+1):
        while(left<n and l[left]<=time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<=time and oth!=q[0]:
                q.remove(oth)
                done[oth+1]=0
        if len(q)>0:
            now=q[0]
            done[now+1]=time
            q=q[1:]
    for i in q:
        done[i+1]=0
    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)

    s=0
    for i in range(n):
        a=l[i]
        b=r[i]
        if s<a:
            s=a
        if s>b:
            print 0,
        else:
            print s,
            s+=1
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)
    p=max(r)
    q=[]
    left=0
    done={}
    #print l
    for time in range(1,p+1):
        while(left<n and l[left]<=time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<=time and oth!=q[0]:
                q.remove(oth)
                done[oth+1]=0
        if len(q)>0:
            now=q[0]
            done[now+1]=time
            q=q[1:]
    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)
    p=max(r)
    q=[]
    left=0
    done={}
    #print l
    for time in range(1,p+1):
        while(left<n and l[left]<=time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<=time:
                q.remove(oth)
                done[oth+1]=0
        if len(q)>0:
            now=q[0]
            done[now+1]=time
            q=q[1:]
    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)
    p=max(r)
    q=[]
    left=0
    done={}
    #print l
    for i in range(n):
        if r[i]<l[i]:
            done[i+1]=0
    for time in range(1,p+1):
        #print q
        while(left<n and l[left]<=time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<time :
                q.remove(oth)
                done[oth+1]=0
        if len(q)>0:
            now=q[0]
            if r[now] >= time:
                done[now + 1] = time
            else:
                done[now + 1] = 0
            q=q[1:]
    #print done
    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)
    p=max(r)
    p=max(p,max(l))
    q=[]
    left=0
    done={}
    #print l
    for i in range(1,n+1):
        done[i]=0
    for time in range(1,p+1):
        #print q
        while(left<n and l[left]==time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<=time and oth!=q[0]:
                q.remove(oth)
                done[oth+1]=0
        if len(q)>0:
            now=q[0]
            if r[now] >= time:
                done[now + 1] = time
            else:
                done[now + 1] = 0
            q=q[1:]
    for i in q:
        done[i + 1] = 0
    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)

    p=max(r)
    p=max(p,max(l))
    q=[]
    left=0
    done={}
    #print l
    for time in range(1,p+1):
        #print q
        while(left<n and l[left]<=time):
            q.append(left)
            left+=1
        for oth in q:
            if r[oth]<time:
                done[oth+1]=0
                q.remove(oth)
            elif r[oth]==time:
                if q[0]!=oth:
                    done[oth + 1] = 0
                    q.remove(oth)

        if len(q)>0:
            now=q[0]
            if r[now]>=time:
                done[now+1]=time
            else:
                done[now]=0

            q=q[1:]
    for i in q:
        done[i + 1] = 0

    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)
    p=max(r)
    q=[]
    left=0
    done={}
    #print l
    for i in range(n):
        done[i+1]=0
    for time in range(1,p+1):

        while(left<n and l[left]<=time):
            q.append(left)
            left+=1

        if len(q)>0:
            now=q[0]
            if r[now]>=time:
                done[now+1]=time
            else:
                done[now+1]=0
            q=q[1:]
        for oth in q:
            if r[oth]<time :
                q.remove(oth)
                done[oth+1]=0
    #print done
    for i in range(1,n+1):
        print done[i],
    print ''


t=input()
for p in range(t):
    n=input()
    l=[]
    r=[]
    for i in range(n):
        a,b=map(int,raw_input().split())
        l.append(a)
        r.append(b)

    s=l[0]
    for i in range(n):
        a=l[i]
        b=r[i]
        if s<=b:
            print s,
            s+=1
        else:
            print 0,
    print ''


n = int(raw_input())
for _ in xrange(n):
	q = 0
	r = []
	for __ in xrange(int(raw_input())):
		a,b = map(int,raw_input().split())
		if a>=q:
			r.append(a)
			q=a+1
		else:
			if b>=q:
				r.append(q)
				q+=1
			else:
				r.append(0)
	print ' '.join(map(str,r))


t = input()
for x in range(0, t, +1):
    n = input()
    temp_str = ''
    temp = 1
    for y in range(0, n, +1):
        l,r = map(int, raw_input('').split(' '))
        if r >= temp:
            if l >= temp:
                temp_str += str(l) + ' '
                temp = l
                continue
            else:
                temp_str += str(temp) + ' '
                temp += 1
        else:
            temp_str += '0 '
    print temp_str


t = input()
for x in range(0, t, +1):
    n = input()
    temp_str = ''
    temp = 1
    for y in range(0, n, +1):
        l,r = map(int, raw_input('').split(' '))
        if r >= temp:
            temp_str += str(temp) + ' '
            temp += 1
        else:
            temp_str += '0 '
    print temp_str


t = input()
for x in range(0, t, +1):
    n = input()
    temp_str = ''
    temp = 1
    for y in range(0, n, +1):
        l,r = map(int, raw_input('').split(' '))
        if r >= temp:
            if l >= temp:
                temp_str += str(l) + ' '
                temp = l + 1
                continue
            else:
                temp_str += str(temp) + ' '
                temp += 1
        else:
            temp_str += '0 '
    print temp_str


from sys import stdin,stdout
r,w = stdin.readline,stdout.write
t = int(r(),10)
for i in xrange(t):
	n = int(r(),10);q = [];f = 0
	[q.append(map(int,r().split())) for k in xrange(n)]
	w(str(q[0][0]))
	for j in xrange(1,n):
		if q[j][1] < k+q[0][0]-f:
			f+=1
			w(' 0')
		else: w(' '+str(k+q[0][0]-f))
	w('\n')


from sys import stdin,stdout
from heapq import heappush,heappop
r = stdin.readline; w = stdout.write
t = int(r(),10)
for i in xrange(t):
	n = int(r(),10); h =[];f=0
	[heappush(h,(i,map(int,r().split())[1])) for i in xrange(n)]
	w('1')
	for i in xrange(1,n):
		if h[i][1] <= i+1-f:
			w(' 0')
			f+=1
		else: w(' '+str(i+1-f))
	w('\n')


from sys import stdin,stdout
r,w = stdin.readline,stdout.write
t = int(r(),10)
for i in xrange(t):
	n = int(r(),10);q = [];f = 0
	[q.append(map(int,r().split())) for k in xrange(n)]
	w(str(q[0][0]))
	for j in xrange(1,n):
		if q[j][1] < j+q[0][0]-f:
			f+=1
			w(' 0')
		else: w(' '+str(j+q[0][0]-f))
	w('\n')


from sys import stdin,stdout
r,w = stdin.readline,stdout.write
t = int(r(),10)
for i in xrange(t):
	n = int(r(),10);q = [];f = 0
	[q.append(map(int,r().split())) for k in xrange(n)]
	f = q[0][0]+1
	w(str(q[0][0]))
	for j in xrange(1,n):
		if q[j][1] < f:w(' 0')
		else:
			w(' '+str(f))
			f = f+1
	w('\n')


from sys import stdin,stdout
r,w = stdin.readline,stdout.write
t = int(r(),10)
for i in xrange(t):
	n = int(r(),10);q = [];f = 0
	[q.append(map(int,r().split())) for k in xrange(n)]
	f = q[0][0]+1
	w(str(q[0][0]))
	for j in xrange(1,n):
		if q[j][1] < f:w(' 0')
		else:
			f = max(q[j][0],f)
			w(' '+str(f))
			f+=1
	w('\n')


from sys import stdin,stdout
r,w = stdin.readline,stdout.write
t = int(r(),10)
for i in xrange(t):
	n = int(r(),10);q = [];f = 0
	[q.append(map(int,r().split())) for k in xrange(n)]
	f = q[0][0]+1
	w(str(q[0][0]))
	for j in xrange(1,n):
		if q[j][1] < f:w(' 0')
		else:
			w(' '+str(f))
			f = q[j][0]+1
	w('\n')


t = input()
while t>0:
    t-=1
    n = input()
    k = []
    for i in range(n):
        k1 = map(int,raw_input().split())
        k.append([k1[0],i,k1[1],-1])

    # k.sort()
    for i in range(1005):
        done = 0
        for j in range(n):
            if k[j][3]==-1 and i+1>=k[j][0]:
                k[j][3] = i+1
                done = 1
                for i1 in range(j+1,n):
                    k[i1][2]-=1
                    if k[i1][2]<=0:
                        k[i1][3] = 0
            if done==1:
                break
        # for m in k:
        #     print m
    for i in k:
        print i[3],

    print ""


t = input()
while t>0:
    t-=1
    n = input()
    k = []
    for i in range(n):
        k1 = map(int,raw_input().split())
        k.append([k1[0],i,k1[1],-1])

    # k.sort()
    for i in range(2005):
        done = 0
        for j in range(n):
            if k[j][3]==-1 and i+1>=k[j][0]:
                k[j][3] = i+1
                done = 1
                for i1 in range(j+1,n):
                    k[i1][2]-=1
                    if k[i1][2]<=0:
                        k[i1][3] = 0
            if done==1:
                break
        # for m in k:
        #     print m
    for i in k:
        print i[3],

    print ""


t = input()
while t>0:
    t-=1
    n = input()
    k = []
    for i in range(n):
        k1 = map(int,raw_input().split())
        k.append([k1[0],i,k1[1],-1])

    k.sort()
    for i in range(1001):
        done = 0
        for j in range(n):
            if k[j][3]==-1:
                k[j][3] = i+1
                done = 1
                for i1 in range(j+1,n):
                    k[i1][2]-=1
                    if k[i1][2]==0:
                        k[i1][3] = 0
            if done==1:
                break
    for i in k:
        print i[3],

    print ""


t = input()
while t>0:
    t-=1
    n = input()
    k = []
    for i in range(n):
        k1 = map(int,raw_input().split())
        k.append([k1[0],i,k1[1],-1])

    # k.sort()
    for i in range(1005):
        done = 0
        for j in range(n):
            if k[j][3]==-1:
                k[j][3] = i+1
                done = 1
                for i1 in range(j+1,n):
                    k[i1][2]-=1
                    if k[i1][2]<=0:
                        k[i1][3] = 0
            if done==1:
                break
        # for m in k:
        #     print m
    for i in k:
        print i[3],

    print ""


t1 = input()
while t1>0:
    t1-=1
    n = input()
    k = []
    for i in range(n):
        k1 = map(int,raw_input().split())
        k.append(k1)
    ans = [-1]*n
    t = 1
    i=0
    while i<n:
        if k[i][0]<=t:
            if k[i][1]>=t:
                print t,
                t+=1
            else:
                print 0,
            i+=1
        else:
            t+=1
    print


from fractions import gcd
from math import factorial, ceil, sqrt, atan2, log, pi, e
from itertools import *
import string
import copy
import random
import bisect
from decimal import *
def id_generator(size=20, chars=string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def mp():
    return map(int,str(raw_input()).split())

t=input()
for i in range(t):
	n=input()
	z=[]
	m=0
	for j in range(n):
		l,r=mp()
		z+=[[l,r]]
		m=max(l,r)
	#z.sort()
	k=1
	p=0
	l=[0 for i in range(n)]
	while k<=m and p<n:
		#print z[p][0],z[p][1],p,k
		if z[p][0]<=k:
			if z[p][1]>=k:
				l[p]=k
				p+=1
			else:
				p+=1
				k-=1
		k+=1

	for i in l:
		print i,
	print


from fractions import gcd
from math import factorial, ceil, sqrt, atan2, log, pi, e
from itertools import *
import string
import copy
import random
import bisect
from decimal import *
def id_generator(size=20, chars=string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def mp():
    return map(int,str(raw_input()).split())

t=input()
for i in range(t):
	n=input()
	z=[]
	m=0
	for j in range(n):
		l,r=mp()
		z+=[[l,r]]
		m=max(m,r)
	#z.sort()
	k=1
	p=0
	l=[0 for i in range(n)]
	while k<=m and p<n:
		#print z[p][0],z[p][1],p,k
		if z[p][0]<=k:
			if z[p][1]>=k:
				l[p]=k
				p+=1
			else:
				p+=1
				k-=1
		k+=1

	for i in l:
		print i,
	print


from sys import stdout, exit
from operator import itemgetter, attrgetter, methodcaller

maxn = 1000 + 10

interval = []
res = [0 for i in range(maxn)]

if __name__ == '__main__':
    test_cases = int(raw_input())
    for current_test in range(test_cases):
        n = int(raw_input())
        del interval[:]
        for i in range(n):
            u, v = map(int, raw_input().split(' '))
            node = u, v, i
            interval.append(node)
        interval.sort(key = itemgetter(0, 2))
        # print interval
        time = interval[0][0]
        for i in range(n):
            if (interval[i][1] < time):
                res[interval[i][2]] = 0
                if (i < n - 1): time = max(time, interval[i + 1][0])
            else:
                res[interval[i][2]] = time
                if (i < n - 1): time = max(time + 1, interval[i + 1][0])
        for i in range(n):
            print res[i],
        print


#include<stdio.h>
#include<string.h>
int main(){
    int t;
    while(t--){
int n;
    scanf("%d",&n);
    int entryTime[n],exitTime[n];
    int max = -999,min = 9999;
    for(int i=0;i<n;i++){
        scanf("%d %d",&entryTime[i],&exitTime[i]);
        if(exitTime[i] > max){
            max = exitTime[i];
        }
        if(entryTime[i] < min){
            min = entryTime[i];
        }
    }
    int visited[n];
    memset(visited,0,sizeof(visited));
    for(int t=min;t<=max;t++){
        for(int i=0;i<n;i++){
            if(entryTime[i] <= t && exitTime[i] >= t && visited[i] == 0){
                visited[i] = t;
                break;
            }
        }
    }
    for(int i=0;i<n;i++) printf("%d ",visited[i]);
    }

    return 0;
}


#include<stdio.h>
#include<string.h>
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
int n;
    scanf("%d",&n);
    int entryTime[n],exitTime[n];
    int max = -999,min = 9999;
    for(int i=0;i<n;i++){
        scanf("%d %d",&entryTime[i],&exitTime[i]);
        if(exitTime[i] > max){
            max = exitTime[i];
        }
        if(entryTime[i] < min){
            min = entryTime[i];
        }
    }
    int visited[n];
    memset(visited,0,sizeof(visited));
    for(int t=min;t<=max;t++){
        for(int i=0;i<n;i++){
            if(entryTime[i] <= t && exitTime[i] >= t && visited[i] == 0){
                visited[i] = t;
                break;
            }
        }
    }
    for(int i=0;i<n;i++) printf("%d ",visited[i]);
    }

    return 0;
}


/* Coached by rainboy */
#include <stdio.h>

int main() {
	int t;

	scanf("%d", &t);
	while (t--) {
		int n, x, y;

		scanf("%d", &n);
		x = 0;
		while (n--) {
			int l, r;

			scanf("%d%d", &l, &r);
			y = x + 1 > l ? x + 1 : l;
			if (y > r)
				printf("0 ");
			else
				printf("%d ", x = y);
		}
		printf("\n");
	}
	return 0;
}


#include <stdio.h>

int Max(int a, int b)
{
    return a > b ? a : b;
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--) {
        int n;
        scanf("%d", &n);
        int last = 0;
        while(n--) {
            int l, r;
            scanf("%d %d", &l, &r);
            int cur = Max(last, l);
            if(cur <= r) {
                printf("%d ", cur);
                last = cur + 1;
            } else {
                printf("%d ", 0);
            }
        }
        puts("");
    }
    return 0;
}


#include <stdio.h>
int main()
{
	int t,p;
	scanf("%d",&t);
	for(p=0;p<t;p++)
	{
	int n,a,b,ti=0,i;
	scanf("%d",&n);
	scanf("%d %d",&a,&b);
	ti=a+1;
	printf("%d ",a);
	for(i=1;i<n;i++)
	{
		scanf("%d %d",&a,&b);
        if(ti<a)
        {
			ti=a+1;
			printf("%d ",a);
		}
        else if(ti>a)
        {
			if(ti<=b)
			{
				printf("%d ",ti);
				ti=ti+1;
			}
			else
				printf("0 ");
		}
        else
		{
			printf("%d ",ti);
			ti++;
		}
	}
	}
}


#include <stdio.h>
int main()
{
	int t,p;
	scanf("%d",&t);
	for(p=0;p<t;p++)
	{
	int n,a,b,ti=0,i;
	scanf("%d",&n);
	scanf("%d %d",&a,&b);
	ti=a+1;
	printf("%d ",a);
	for(i=1;i<n;i++)
	{
		scanf("%d %d",&a,&b);
        if(ti<a)
        {
			ti=a+1;
			printf("%d",a);
		}
        else if(ti>a)
        {
			if((ti-a)<b)
			{
				printf("%d ",ti);
				ti=ti+1;
			}
			else
				printf("0 ");
		}
        else
		{
			printf("%d",ti);
			ti++;
		}
	}
	}
}


#include <stdio.h>
int main()
{
	int t,p;
	scanf("%d",&t);
	for(p=0;p<t;p++)
	{
	int n,a,b,ti=0,i;
	scanf("%d",&n);
	scanf("%d %d",&a,&b);
	ti=a+1;
	printf("%d ",a);
	for(i=1;i<n;i++)
	{
		scanf("%d %d",&a,&b);
        if(ti<a)
        {
			ti=a+1;
			printf("%d ",a);
		}
        else if(ti>a)
        {
			if((ti-a)<b)
			{
				printf("%d ",ti);
				ti=ti+1;
			}
			else
				printf("0 ");
		}
        else
		{
			printf("%d ",ti);
			ti++;
		}
	}
	}
}


#include <stdio.h>
int main()
{
	int t,p;
	scanf("%d",&t);
	for(p=0;p<t;p++)
	{
	int n,a,b,ti=0,i;
	scanf("%d",&n);
	scanf("%d %d",&a,&b);
	ti=a+1;
	printf("%d ",a);
	for(i=1;i<n;i++)
	{
		scanf("%d %d",&a,&b);
        if(ti<a)
        {
			ti=a+1;
			printf("%d ",a);
		}
        else if(ti>a)
        {
			if(ti<b)
			{
				printf("%d ",ti);
				ti=ti+1;
			}
			else
				printf("0 ");
		}
        else
		{
			printf("%d ",ti);
			ti++;
		}
	}
	}
}


using System;
using System.Linq;

namespace CSharp
{
    class _920B
    {
        public static void Main()
        {
            for (int t = int.Parse(Console.ReadLine()); t > 0; t--)
            {
                int n = int.Parse(Console.ReadLine());
                var l = new int[n];
                var r = new int[n];

                for (int i = 0; i < n; i++)
                {
                    var tokens = Console.ReadLine().Split();

                    l[i] = int.Parse(tokens[0]);
                    r[i] = int.Parse(tokens[1]);
                }

                int time = 0;
                var used = new int[n];

                foreach (int i in Enumerable.Range(0, n).OrderBy(i => l[i]).ThenBy(i => i))
                {
                    if (time < r[i])
                    {
                        used[i] = time = Math.Max(time + 1, l[i]);
                    }
                }

                Console.WriteLine(string.Join(" ", used));
            }
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using CompLib.Util;

public class Program
{

    public void Solve()
    {
        var sc = new Scanner();
        int t = sc.NextInt();
        Console.SetOut(new System.IO.StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        for (int i = 0; i < t; i++)
        {
            Q(sc);
        }
        Console.Out.Flush();
    }

    void Q(Scanner sc)
    {
        int n = sc.NextInt();
        int[] l = new int[n];
        int[] r = new int[n];
        for (int i = 0; i < n; i++)
        {
            l[i] = sc.NextInt();
            r[i] = sc.NextInt();
        }

        /*
         * n人
         * iはL_iに列に並ぶ
         * 同じ時はiが大きい方が後ろ
         *
         * 先頭にいるとき 1秒かけて
         *
         * r_iまでにできないなら列から抜ける
         */

        var sorted = new int[n];
        for (int i = 0; i < n; i++)
        {
            sorted[i] = i;
        }

        Array.Sort(sorted, (x, y) => l[x] == l[y] ? x.CompareTo(y) : l[x].CompareTo(l[y]));
        var q = new Queue<(int num, int l, int r)>();
        foreach (var i in sorted)
        {
            q.Enqueue((i, l[i], r[i]));
        }

        var ans = new int[n];
        int t = 0;
        for (int i = 0; i < n; i++)
        {
            var d = q.Dequeue();
            if (t < d.l)
            {
                t = d.l;
            }
            if (t <= d.r)
            {
                ans[d.num] = t;
                t++;
            }

        }

        Console.WriteLine(string.Join(" ", ans));
    }

    public static void Main(string[] args) => new Program().Solve();
}

namespace CompLib.Util
{
    using System;
    using System.Linq;

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            if (_index >= _line.Length)
            {
                string s;
                do
                {
                    s = Console.ReadLine();
                } while (s.Length == 0);

                _line = s.Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public string ReadLine()
        {
            _index = _line.Length;
            return Console.ReadLine();
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            string s = Console.ReadLine();
            _line = s.Length == 0 ? new string[0] : s.Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using static System.Console;
using static System.Convert;
using static System.Math;
using static Template;
using Pi = Pair<int, int>;

class Solver
{
    public void Solve(Scanner sc)
    {
        var T = sc.Int;
        while (T-- > 0)
        {
            var N = sc.Int;
            var LR = sc.ArrInt2D(N);
            var now = 0;
            var res = new int[N];
            for(int i=0;i<N;i++)
            {
                int l = LR[i][0], r = LR[i][1];
                if (now < l) { res[i] = l; now = l + 1;continue; }
                if (now >= r) continue;
                res[i]=now++;
            }
            Console.WriteLine(string.Join(" ", res));
        }
    }
}

#region Template
public static class Template
{
    static void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        new Solver().Solve(new Scanner());
        Console.Out.Flush();
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) > 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) < 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T a, ref T b) { var t = b; b = a; a = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(this IList<T> A, int i, int j) { var t = A[i]; A[i] = A[j]; A[j] = t; }
    public static T[] Create<T>(int n, Func<T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(); return rt; }
    public static T[] Create<T>(int n, Func<int, T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(i); return rt; }
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> A) => A.OrderBy(v => Guid.NewGuid());
    public static int CompareTo<T>(this T[] A, T[] B, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; for (var i = 0; i < Min(A.Length, B.Length); i++) { int c = cmp(A[i], B[i]); if (c > 0) return 1; else if (c < 0) return -1; } if (A.Length == B.Length) return 0; if (A.Length > B.Length) return 1; else return -1; }
    public static int MaxElement<T>(this IList<T> A, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; T max = A[0]; int rt = 0; for (int i = 1; i < A.Count; i++) if (cmp(max, A[i]) < 0) { max = A[i]; rt = i; } return rt; }
    public static T PopBack<T>(this List<T> A) { var v = A[A.Count - 1]; A.RemoveAt(A.Count - 1); return v; }
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
}
public class Scanner
{
    public string Str => Console.ReadLine().Trim();
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray();
    public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray();
    public char[][] Grid(int n) => Create(n, () => Str.ToCharArray());
    public int[] ArrInt1D(int n) => Create(n, () => Int);
    public long[] ArrLong1D(int n) => Create(n, () => Long);
    public int[][] ArrInt2D(int n) => Create(n, () => ArrInt);
    public long[][] ArrLong2D(int n) => Create(n, () => ArrLong);
    private Queue<string> q = new Queue<string>();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); }
    public void Make<T1>(out T1 v1) => v1 = Next<T1>();
    public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); }
    public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); }
    public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); }
    public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); }
    public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); }
    public void Make<T1, T2, T3, T4, T5, T6, T7>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6, out T7 v7) { Make(out v1, out v2, out v3, out v4, out v5, out v6); v7 = Next<T7>(); }
    //public (T1, T2) Make<T1, T2>() { Make(out T1 v1, out T2 v2); return (v1, v2); }
    //public (T1, T2, T3) Make<T1, T2, T3>() { Make(out T1 v1, out T2 v2, out T3 v3); return (v1, v2, v3); }
    //public (T1, T2, T3, T4) Make<T1, T2, T3, T4>() { Make(out T1 v1, out T2 v2, out T3 v3, out T4 v4); return (v1, v2, v3, v4); }
}
public class Pair<T1, T2> : IComparable<Pair<T1, T2>>
{
    public T1 v1;
    public T2 v2;
    public Pair() { }
    public Pair(T1 v1, T2 v2)
    { this.v1 = v1; this.v2 = v2; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2> p)
    {
        var c = Comparer<T1>.Default.Compare(v1, p.v1);
        if (c == 0)
            c = Comparer<T2>.Default.Compare(v2, p.v2);
        return c;
    }
    public override string ToString() => $"{v1.ToString()} {v2.ToString()}";
    public void Deconstruct(out T1 a, out T2 b) { a = v1; b = v2; }
}

public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>>
{
    public T3 v3;
    public Pair() : base() { }
    public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2)
    { this.v3 = v3; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2, T3> p)
    {
        var c = base.CompareTo(p);
        if (c == 0)
            c = Comparer<T3>.Default.Compare(v3, p.v3);
        return c;
    }
    public override string ToString() => $"{base.ToString()} {v3.ToString()}";
    public void Deconstruct(out T1 a, out T2 b, out T3 c) { Deconstruct(out a, out b); c = v3; }
}
#endregion


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using static System.Console;
using static System.Convert;
using static System.Math;
using static Template;
using Pi = Pair<int, int>;

class Solver
{
    public void Solve(Scanner sc)
    {
        var T = sc.Int;
        while (T-- > 0)
        {
            var N = sc.Int;
            var LR = sc.ArrInt2D(N);
            var now = 0;
            var res = new int[N];
            for(int i=0;i<N;i++)
            {
                int l = LR[i][0], r = LR[i][1];
                if (now < l) { res[i] = l; now = l + 1;continue; }
                if (now > r) continue;
                res[i]=now++;
            }
            Console.WriteLine(string.Join(" ", res));
        }
    }
}

#region Template
public static class Template
{
    static void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        new Solver().Solve(new Scanner());
        Console.Out.Flush();
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) > 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) < 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T a, ref T b) { var t = b; b = a; a = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(this IList<T> A, int i, int j) { var t = A[i]; A[i] = A[j]; A[j] = t; }
    public static T[] Create<T>(int n, Func<T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(); return rt; }
    public static T[] Create<T>(int n, Func<int, T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(i); return rt; }
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> A) => A.OrderBy(v => Guid.NewGuid());
    public static int CompareTo<T>(this T[] A, T[] B, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; for (var i = 0; i < Min(A.Length, B.Length); i++) { int c = cmp(A[i], B[i]); if (c > 0) return 1; else if (c < 0) return -1; } if (A.Length == B.Length) return 0; if (A.Length > B.Length) return 1; else return -1; }
    public static int MaxElement<T>(this IList<T> A, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; T max = A[0]; int rt = 0; for (int i = 1; i < A.Count; i++) if (cmp(max, A[i]) < 0) { max = A[i]; rt = i; } return rt; }
    public static T PopBack<T>(this List<T> A) { var v = A[A.Count - 1]; A.RemoveAt(A.Count - 1); return v; }
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
}
public class Scanner
{
    public string Str => Console.ReadLine().Trim();
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray();
    public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray();
    public char[][] Grid(int n) => Create(n, () => Str.ToCharArray());
    public int[] ArrInt1D(int n) => Create(n, () => Int);
    public long[] ArrLong1D(int n) => Create(n, () => Long);
    public int[][] ArrInt2D(int n) => Create(n, () => ArrInt);
    public long[][] ArrLong2D(int n) => Create(n, () => ArrLong);
    private Queue<string> q = new Queue<string>();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); }
    public void Make<T1>(out T1 v1) => v1 = Next<T1>();
    public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); }
    public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); }
    public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); }
    public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); }
    public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); }
    public void Make<T1, T2, T3, T4, T5, T6, T7>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6, out T7 v7) { Make(out v1, out v2, out v3, out v4, out v5, out v6); v7 = Next<T7>(); }
    //public (T1, T2) Make<T1, T2>() { Make(out T1 v1, out T2 v2); return (v1, v2); }
    //public (T1, T2, T3) Make<T1, T2, T3>() { Make(out T1 v1, out T2 v2, out T3 v3); return (v1, v2, v3); }
    //public (T1, T2, T3, T4) Make<T1, T2, T3, T4>() { Make(out T1 v1, out T2 v2, out T3 v3, out T4 v4); return (v1, v2, v3, v4); }
}
public class Pair<T1, T2> : IComparable<Pair<T1, T2>>
{
    public T1 v1;
    public T2 v2;
    public Pair() { }
    public Pair(T1 v1, T2 v2)
    { this.v1 = v1; this.v2 = v2; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2> p)
    {
        var c = Comparer<T1>.Default.Compare(v1, p.v1);
        if (c == 0)
            c = Comparer<T2>.Default.Compare(v2, p.v2);
        return c;
    }
    public override string ToString() => $"{v1.ToString()} {v2.ToString()}";
    public void Deconstruct(out T1 a, out T2 b) { a = v1; b = v2; }
}

public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>>
{
    public T3 v3;
    public Pair() : base() { }
    public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2)
    { this.v3 = v3; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2, T3> p)
    {
        var c = base.CompareTo(p);
        if (c == 0)
            c = Comparer<T3>.Default.Compare(v3, p.v3);
        return c;
    }
    public override string ToString() => $"{base.ToString()} {v3.ToString()}";
    public void Deconstruct(out T1 a, out T2 b, out T3 c) { Deconstruct(out a, out b); c = v3; }
}
#endregion


using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Tea_Queue
{
    internal class Program
    {
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            int t = Next();
            for (int i = 0; i < t; i++)
            {
                Solve(args);
            }
            writer.Flush();
        }

        private static void Solve(string[] args)
        {
            int n = Next();

            var l = new int[n];
            var r = new int[n];
            for (int i = 0; i < n; i++)
            {
                l[i] = Next();
                r[i] = Next();
            }

            int t = 0;
            var q = new Queue<int>();
            for (int i = 0; i < n; i++)
            {
                q.Enqueue(i);
                if (t < l[i])
                {
                    t = l[i];
                }

                while (q.Count > 0 && r[q.Peek()] < t)
                {
                    writer.Write("0 ");
                    q.Dequeue();
                }

                if (q.Count > 0)
                {
                    writer.Write(t);
                    writer.Write(' ');
                    q.Dequeue();
                    t++;
                }
            }
            writer.WriteLine();
        }

        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class TEST{
	static void Main(){
		Sol mySol =new Sol();
		mySol.Solve();
	}
}

class Sol{
	public void Solve(){

		for(;T>0;T--){

			int N = ri();
			Pair[] P = new Pair[N];
			for(int i=0;i<N;i++){
				var d = ria();
				P[i] = new Pair(i, d[0], d[1]);
			}

			Array.Sort(P, (p, q) => p.L == q.L ? p.Idx.CompareTo(q.Idx) : p.L.CompareTo(q.L));

			int[] ans = new int[N];
			int now = 0;

			foreach(var p in P){
				var l = p.L;
				var r = p.R;
				var i = p.Idx;

				if(now <= l){
					ans[i] = l;
					now = l + 1;
					continue;
				} else if(now <= r){
					ans[i] = now;
					now = now + 1;
					continue;
				}

			}

			Console.WriteLine(String.Join(" ",ans));
		}

	}

	class Pair{
		public int Idx, L, R;
		public Pair(int idx, int l, int r){
			Idx = idx; L = l; R = r;
		}

	}

	int T;
	public Sol(){
		T = ri();
	}

	static String rs(){return Console.ReadLine();}
	static int ri(){return int.Parse(Console.ReadLine());}
	static long rl(){return long.Parse(Console.ReadLine());}
	static double rd(){return double.Parse(Console.ReadLine());}
	static String[] rsa(char sep=' '){return Console.ReadLine().Split(sep);}
	static int[] ria(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>int.Parse(e));}
	static long[] rla(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>long.Parse(e));}
	static double[] rda(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>double.Parse(e));}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces
{
   class B
   {
      static void Main(string[] args)
      {
        int t = int.Parse(Console.ReadLine());

        for(int i=0;i<t;i++){
          int n = int.Parse(Console.ReadLine());

          int[] l = new int[n];
          int[] r = new int[n];

          int sec = 0;

          for(int j=0;j<n;j++){
            string[] token = Console.ReadLine().Split();
            l[j] = int.Parse(token[0]);
            r[j] = int.Parse(token[1]);
            int sSec = l[j];

            if(sSec>=l[j]&&sSec<r[j]){
              sec++;
              if(sec<l[j])sec = l[j];
              if(sec>=r[j])
               Console.Write(0 + " ");
              else
               Console.Write(sec + " ");
            }else
              Console.Write(0 + " ");
          }
          Console.WriteLine();
        }
      }
   }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces
{
   class B
   {
      static void Main(string[] args)
      {
        int t = int.Parse(Console.ReadLine());

        for(int i=0;i<t;i++){
          int n = int.Parse(Console.ReadLine());

          int[] l = new int[n];
          int[] r = new int[n];

          int sec = 0;

          for(int j=0;j<n;j++){
            string[] token = Console.ReadLine().Split();
            l[j] = int.Parse(token[0]);
            r[j] = int.Parse(token[1]);

            if(r[j]<sec){
              Console.Write(0+" ");
            }else{
              if(l[j]>sec)
               sec = l[j];
              Console.Write(sec+" ");
              sec++;
            }
          }
          Console.WriteLine();
        }
      }
   }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces
{
   class B
   {
      static void Main(string[] args)
      {
        int t = int.Parse(Console.ReadLine());

        for(int i=0;i<t;i++){
          int n = int.Parse(Console.ReadLine());

          int[] l = new int[n];
          int[] r = new int[n];

          int sec = 0;

          for(int j=0;j<n;j++){
            string[] token = Console.ReadLine().Split();
            l[i] = int.Parse(token[0]);
            r[i] = int.Parse(token[1]);
            int sSec = l[i];

            if(sSec>=l[i]&&sSec<r[i]){
              sec++;
              if(sec<l[i])sec = l[i];
              if(sec>=r[i])
               Console.Write(0 + " ");
              else
               Console.Write(sec + " ");
            }else
              Console.Write(0 + " ");
          }
          Console.WriteLine();
        }
      }
   }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

class Program
{
    static void Main(string[] args)
    {
        var t = int.Parse(Console.ReadLine());

        List<string> res = new List<string>();

        for (int z = 0; z < t; z ++)
        {
            List<int> l = new List<int>();
            List<int> r = new List<int>();
            var a = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
            int n = a[0];

            for (int k = 0; k < n; k++)
            {
                a = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
                l.Add(a[0]);
                r.Add(a[1]);
            }

            var ans = new int[n];

            int next = 0;

            for (int time = l.Min(); time < 5000 && next < n;)
            {
                if (time >= l[next])
                {
                    while (time > r[next])
                    {
                        ans[next] = 0;
                        next++;

                        if (next >= n)
                            goto exit;
                    }

                    ans[next] = l[next] > time ? l[next] : time;
                    time = l[next] > time ? l[next] : time;
                    next++;
                    time++;
                    continue;

                }
                else
                {
                    time = l[next];
                }

            }
            exit:

            res.Add(string.Join(" ", ans));
            continue;

        }

        res.ForEach(x=>Console.WriteLine(x));
    }
}


#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>

using namespace std;

int main() {

  int t;scanf("%d",&t);

  while(t--)
  {

    priority_queue <int> b;
    vector <pair<int,int> > v;
    vector <int> ans;

    int n;scanf("%d",&n);

    for(int i=0;i<n;++i) //getting the times L & R
    {
      int l,r;scanf("%d %d",&l,&r);
      v.push_back(make_pair(l,r));

    }

    //sort(v.begin(),v.end());

    for(int i=0;i<n;i++)
    {
      if(i==0){ans.push_back(v[i].first);b.push(v[i].first);continue;}

      if(v[i].first>b.top()) { ans.push_back(v[i].first);b.push(v[i].first);}
      else
      if(v[i].first==b.top() && v[i].second > b.top()) {ans.push_back(v[i].first+1);b.push(v[i].first+1);}

      else {ans.push_back(0);}

    }

    for(int i=0;i<n;i++)
    {
      printf("%d ",ans[i]);

    }

    printf("\n");

  }

  return 0;
}


#include <bits/stdc++.h>
using namespace std;

vector <int> ans;

int main() {

  int t;cin>>t;

  while(t--)
  {

    priority_queue <int> b;
    vector <pair<int,int> > v;
    vector <int> ans;

    int n;cin>>n;

    for(int i=0;i<n;++i) //getting the times L & R
    {
      int l,r;cin>>l>>r;
      v.push_back(make_pair(l,r));

    }

    //sort(v.begin(),v.end());

    for(int i=0;i<n;i++)
    {
      if(i==0){ans.push_back(v[i].first);b.push(v[i].first);continue;}

      if(v[i].first>b.top()) { ans.push_back(v[i].first);b.push(v[i].first);}
      else
      if(v[i].first==b.top() && v[i].second > b.top()) {ans.push_back(v[i].first+1);b.push(v[i].first+1);}

      else {ans.push_back(0);}

    }

    for(int i=0;i<n;i++)
    {
      cout<<ans[i]<<" ";

    }

    cout<<endl;

  }

  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin>>t;
  while(t--)
  {
    vector <pair<int,int> > v;

    vector <int> ans;

    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
      int l,r;
      cin>>l>>r;
      if(i==0) {cout<<l<<" ";ans.push_back(l); v.push_back(make_pair(l,r));continue;}

      v.push_back(make_pair(l,r));

      if(l>ans.back()) cout<<l<<" ";
      else if(l==ans.back() && r>ans.back()){ans.push_back(l+1);cout<<l+1<<" ";}
      else cout<<0<<" ";

    }

    puts("");
  }

  return 0;
}


#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
using namespace std;
int main() {
  int t;
  scanf("%d",&t);
  while(t--)
  {
    vector <pair<int,int> > v;

    vector <int> ans;

    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
      int l,r;
      scanf("%d %d",&l,&r);
      if(i==0) {printf("%d ",l);ans.push_back(l); v.push_back(make_pair(l,r));continue;}

      v.push_back(make_pair(l,r));

      if(l>ans.back()) printf("%d ",l);
      else if(l==ans.back() && r>ans.back()){ans.push_back(l+1);printf("%d ",l+1);}
      else printf("0 ");

    }

    printf("\n");

  }

  return 0;
}


#include <bits/stdc++.h>
using namespace std;

vector <pair<int,int> > v;

vector <int> ans;

int main() {

  int t;cin>>t;

  while(t--)
  {

    priority_queue <int> b;
    v.clear();
    ans.clear();
    int n;cin>>n;

    for(int i=0;i<n;++i) //getting the times L & R
    {
      int l,r;cin>>l>>r;
      v.push_back(make_pair(l,r));

    }

    //sort(v.begin(),v.end());

    for(int i=0;i<n;i++)
    {
      if(i==0){ans.push_back(v[i].first);b.push(v[i].first);continue;}

      if(v[i].first>b.top()) { ans.push_back(v[i].first);b.push(v[i].first);}
      else
      if(v[i].first==b.top() && v[i].second > b.top()) {ans.push_back(v[i].first+1);b.push(v[i].first+1);}

      else {ans.push_back(0);}

    }

    for(int i=0;i<n;i++)
    {
      cout<<ans[i]<<" ";

    }

    cout<<endl;

  }

  return 0;
}


#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
using namespace std;
int main() {
  int t;
  scanf("%d",&t);
  while(t--)
  {
    vector <pair<int,int> > v;

    vector <int> ans;

    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
      int l,r;
      scanf("%d %d",&l,&r);
      if(i==0) {printf("%d ",l);ans.push_back(l); v.push_back(make_pair(l,r));continue;}

      v.push_back(make_pair(l,r));

      if(l>ans.back()) printf("%d ",l);
      else if(l==ans.back() && r>ans.back()){ans.push_back(l+1);printf("%d ",l+1);}
      else if(l<ans.back() && r>ans.back()){printf("%d ",ans.back()+1);ans.push_back(ans.back()+1);}
      else printf("0 ");

    }

    printf("\n");

  }

  return 0;
}


#include <bits/stdc++.h>
using namespace std;

vector <pair<int,int> > v;

stack <int> before;

vector <int> ans;

int main() {

  int t;cin>>t;

  while(t--)
  {
    v.clear();
    ans.clear();
    int n;cin>>n;

    for(int i=0;i<n;++i) //getting the times L & R
    {
      int l,r;cin>>l>>r;
      v.push_back(make_pair(l,r));

    }

    //sort(v.begin(),v.end());

    for(int i=0;i<n;i++)
    {
      if(i==0){ans.push_back(v[i].first);continue;}

      if(v[i].first>ans.back()) { ans.push_back(v[i].first);}
      else
      if(v[i].first==ans.back() && v[i].second > ans.back()) {ans.push_back(v[i].first+1);}

      else {ans.push_back(0);}

    }

    for(int i=0;i<n;i++)
    {
      cout<<ans[i]<<" ";

    }

    cout<<endl;

  }

  return 0;
}


#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
using namespace std;
int main() {
  int t;
  scanf("%d",&t);
  while(t--)
  {
    vector <pair<int,int> > v;

    vector <int> ans;

    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
      int l,r;
      scanf("%d %d",&l,&r);
      if(i==0) {printf("%d ",l);ans.push_back(l); v.push_back(make_pair(l,r));continue;}

      v.push_back(make_pair(l,r));

      if(l>ans.back()) {printf("%d ",l);ans.push_back(l);}
      else if(l==ans.back() && r>ans.back()){ans.push_back(l+1);printf("%d ",l+1);}
      else if(l<ans.back() && r>ans.back()){printf("%d ",ans.back()+1);ans.push_back(ans.back()+1);}
      else printf("0 ");

    }

    printf("\n");

  }

  return 0;
}


#include <bits/stdc++.h>
#define ll long long
using namespace std;
int main() {
	int T, n, st, en, x;
	cin >> T;
	while (T--) {
		cin >> n;
		int srv = 0;
		while (n--) {
			cin >> st >> en;
			if (srv < st) {
				cout << st << " ";
				srv = st + 1;
			}
			else {
				if (srv > en)cout << 0 << " ";
				else cout << srv++ << " ";
			}
		}
		cout << endl;
	}
	//system("pause");
	return 0;
}


#include <iostream>
#include <queue>

using namespace std;

int main(void) {
int t;
cin>>t;
queue<int> q;
vector<int> v1, v2;
for(int l=0; l<t; l++) {
int n;
int tmp1, tmp2;
int k=0;
cin>>n;

while(!q.empty()) q.pop();
v1.clear();
v2.clear();

for(int i=0; i<n; i++) {
    cin>>tmp1>>tmp2;
    v1.push_back(tmp1);
    v2.push_back(tmp2);
    }

for(int i=1; i<=5000; i++) {
    while((k<n)&&(v1[k]==i)) {q.push(v2[k]); k++;}
    while(true) {
        if (q.empty()) break;
        if (q.front()<i) {q.pop(); cout<<0<<' '; continue;}
        if (q.front()>=i) {q.pop(); cout<<i<<' '; break;}
        }
    }
cout<<endl;
}
return 0;
}


package main

import (
  "bufio"
  "fmt"
  "os"
  "sort"
  "strconv"
)

type Student struct {
  Pos int
  l   int
  r   int
}

func solve() {
  t := readInt()
  for i := 0; i < t; i++ {
    n := readInt()
    students := make([]Student, n)
    for j := 0; j < n; j++ {
      students[j].Pos = j
      students[j].l = readInt()
      students[j].r = readInt()
    }
    sort.Sort(ByTime(students))
    curtime := 1
    for j := 0; j < n; j++ {
      st := students[j]
      if curtime < st.l {
        curtime = st.l
        students[j].r = curtime + 1
      } else if curtime >= st.r {
        students[j].r = 0
      } else {
        students[j].r = curtime
        curtime++
      }
    }
    for j := 0; j < n; j++ {
      if j > 0 {
        fmt.Print(" ")
      }
      fmt.Print(students[j].r)
    }
    fmt.Println()
  }
}

type ByTime []Student

func (a ByTime) Len() int      { return len(a) }
func (a ByTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByTime) Less(i, j int) bool {
  if a[i].l == a[j].l {
    return a[i].Pos < a[j].Pos
  }
  return a[i].l < a[j].l
}


package main

import (
  "bufio"
  "fmt"
  "os"
  "sort"
  "strconv"
)

type Student struct {
  Pos int
  l   int
  r   int
}

func solve() {
  t := readInt()
  for i := 0; i < t; i++ {
    n := readInt()
    students := make([]Student, n)
    for j := 0; j < n; j++ {
      students[j].Pos = j
      students[j].l = readInt()
      students[j].r = readInt()
    }
    sort.Sort(ByTime(students))
    curtime := 1
    for j := 0; j < n; j++ {
      st := students[j]
      if curtime < st.l {
        curtime = st.l
        students[j].r = curtime + 1
      } else if curtime >= st.r {
        students[j].r = 0
      } else {
        students[j].r = curtime
        curtime++
      }
    }
    for j := 0; j < n; j++ {
      if j > 0 {
        fmt.Print(" ")
      }
      fmt.Print(students[j].r)
    }
    fmt.Println()
  }
}

type ByTime []Student

func (a ByTime) Len() int      { return len(a) }
func (a ByTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByTime) Less(i, j int) bool {
  if a[i].l == a[j].l {
    return a[i].Pos < a[j].Pos
  }
  return a[i].l < a[j].l
}

var scanner *bufio.Scanner

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  const MaxTokenLength = 1024 * 1024
  scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
  scanner.Split(bufio.ScanWords)
  solve()
}

// IO

func readString() string {
  scanner.Scan()
  return scanner.Text()
}

func readInt() int {
  val, _ := strconv.Atoi(readString())
  return val
}

func readInt64() int64 {
  v, _ := strconv.ParseInt(readString(), 10, 64)
  return v
}

func readIntArray(sz int) []int {
  a := make([]int, sz)
  for i := 0; i < sz; i++ {
    a[i] = readInt()
  }
  return a
}

func readInt64Array(n int) []int64 {
  res := make([]int64, n)
  for i := 0; i < n; i++ {
    res[i] = readInt64()
  }
  return res
}


    curtime := 1
    for j := 0; j < n; j++ {
      st := students[j]
      if curtime < st.l {
        curtime = st.l
        students[j].r = curtime + 1
      } else if curtime >= st.r {
        students[j].r = 0
      } else {
        students[j].r = curtime
        curtime++
      }
    }
    for j := 0; j < n; j++ {
      if j > 0 {
        fmt.Print(" ")
      }
      fmt.Print(students[j].r)
    }
    fmt.Println()
  }
}

type ByTime []Student

func (a ByTime) Len() int      { return len(a) }
func (a ByTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByTime) Less(i, j int) bool {
  if a[i].l == a[j].l {
    return a[i].Pos < a[j].Pos
  }
  return a[i].l < a[j].l
}

var scanner *bufio.Scanner

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  const MaxTokenLength = 1024 * 1024
  scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
  scanner.Split(bufio.ScanWords)
  solve()
}

// IO

func readString() string {
  scanner.Scan()
  return scanner.Text()
}

func readInt() int {
  val, _ := strconv.Atoi(readString())
  return val
}

func readInt64() int64 {
  v, _ := strconv.ParseInt(readString(), 10, 64)
  return v
}

func readIntArray(sz int) []int {
  a := make([]int, sz)
  for i := 0; i < sz; i++ {
    a[i] = readInt()
  }
  return a
}

func readInt64Array(n int) []int64 {
  res := make([]int64, n)
  for i := 0; i < n; i++ {
    res[i] = readInt64()
  }
  return res
}


package main

import (
  "bufio"
  "fmt"
  "os"
  "sort"
  "strconv"
)

type Student struct {
  Pos int
  l   int
  r   int
}

func solve() {
  t := readInt()
  for i := 0; i < t; i++ {
    n := readInt()
    students := make([]Student, n)
    for j := 0; j < n; j++ {
      students[j].Pos = j
      students[j].l = readInt()
      students[j].r = readInt()
    }
    sort.Sort(ByTime(students))
    curtime := 1
    for j := 0; j < n; j++ {
      st := students[j]
      if curtime < st.l {
        curtime = st.l
        students[j].r = curtime
        curtime++
      } else if curtime > st.r {
        students[j].r = 0
      } else {
        students[j].r = curtime
        curtime++
      }
    }
    for j := 0; j < n; j++ {
      if j > 0 {
        fmt.Print(" ")
      }
      fmt.Print(students[j].r)
    }
    fmt.Println()
  }
}

type ByTime []Student

func (a ByTime) Len() int      { return len(a) }
func (a ByTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByTime) Less(i, j int) bool {
  if a[i].l == a[j].l {
    return a[i].Pos < a[j].Pos
  }
  return a[i].l < a[j].l
}

var scanner *bufio.Scanner

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  const MaxTokenLength = 1024 * 1024
  scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
  scanner.Split(bufio.ScanWords)
  solve()
}

// IO

func readString() string {
  scanner.Scan()
  return scanner.Text()
}

func readInt() int {
  val, _ := strconv.Atoi(readString())
  return val
}

func readInt64() int64 {
  v, _ := strconv.ParseInt(readString(), 10, 64)
  return v
}

func readIntArray(sz int) []int {
  a := make([]int, sz)
  for i := 0; i < sz; i++ {
    a[i] = readInt()
  }
  return a
}

func readInt64Array(n int) []int64 {
  res := make([]int64, n)
  for i := 0; i < n; i++ {
    res[i] = readInt64()
  }
  return res
}


package main

import (
  "bufio"
  "fmt"
  "os"
  "sort"
  "strconv"
)

type Student struct {
  Pos int
  l   int
  r   int
}

func solve() {
  t := readInt()
  for i := 0; i < t; i++ {
    n := readInt()
    students := make([]Student, n)
    for j := 0; j < n; j++ {
      students[j].Pos = j
      students[j].l = readInt()
      students[j].r = readInt()
    }
    sort.Sort(ByTime(students))
    curtime := 1
    for j := 0; j < n; j++ {
      st := students[j]
      if curtime < st.l {
        curtime = st.l
        students[j].r = curtime
        curtime++
      } else if curtime >= st.r {
        students[j].r = 0
      } else {
        students[j].r = curtime
        curtime++
      }
    }
    for j := 0; j < n; j++ {
      if j > 0 {
        fmt.Print(" ")
      }
      fmt.Print(students[j].r)
    }
    fmt.Println()
  }
}

type ByTime []Student

func (a ByTime) Len() int      { return len(a) }
func (a ByTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByTime) Less(i, j int) bool {
  if a[i].l == a[j].l {
    return a[i].Pos < a[j].Pos
  }
  return a[i].l < a[j].l
}

var scanner *bufio.Scanner

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  const MaxTokenLength = 1024 * 1024
  scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
  scanner.Split(bufio.ScanWords)
  solve()
}

// IO

func readString() string {
  scanner.Scan()
  return scanner.Text()
}

func readInt() int {
  val, _ := strconv.Atoi(readString())
  return val
}

func readInt64() int64 {
  v, _ := strconv.ParseInt(readString(), 10, 64)
  return v
}

func readIntArray(sz int) []int {
  a := make([]int, sz)
  for i := 0; i < sz; i++ {
    a[i] = readInt()
  }
  return a
}

func readInt64Array(n int) []int64 {
  res := make([]int64, n)
  for i := 0; i < n; i++ {
    res[i] = readInt64()
  }
  return res
}