This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.

Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described.

Bob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \leq i \leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \neq b_i$). [Image] The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example. 

The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.

Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.


-----Input-----

The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 100$; $1 \leq m \leq 200$) — the number of stations and the number of candies, respectively.

The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$; $a_i \neq b_i$) — the station that initially contains candy $i$ and the destination station of the candy, respectively.


-----Output-----

In the first and only line, print $n$ space-separated integers, the $i$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $i$.


-----Examples-----
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5

Output
10 9 10 10 9 

Input
2 3
1 2
1 2
1 2

Output
5 6 



-----Note-----

Consider the second sample.

If the train started at station $1$, the optimal strategy is as follows.  Load the first candy onto the train.  Proceed to station $2$. This step takes $1$ second.  Deliver the first candy.  Proceed to station $1$. This step takes $1$ second.  Load the second candy onto the train.  Proceed to station $2$. This step takes $1$ second.  Deliver the second candy.  Proceed to station $1$. This step takes $1$ second.  Load the third candy onto the train.  Proceed to station $2$. This step takes $1$ second.  Deliver the third candy. 

Hence, the train needs $5$ seconds to complete the tasks.

If the train were to start at station $2$, however, it would need to move to station $1$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $5+1 = 6$ seconds.

Difficulty: MEDIUM_HARD
Tags: Complete search

Greedy algorithms
Skill types: Complete search

Greedy algorithms

Starter code:

Solutions:
import sys
(n, m) = map(int, input().split())
dist = [n] * n
candy_cnt = [0] * n
for (a, b) in (map(int, l.split()) for l in sys.stdin):
	if a > b:
		b += n
	if dist[a - 1] > b - a:
		dist[a - 1] = b - a
	candy_cnt[a - 1] += 1
dist *= 2
candy_cnt *= 2
ans = [0] * n
for i in range(n):
	time = 0
	for j in range(i, i + n):
		if candy_cnt[j] == 0:
			continue
		t = (candy_cnt[j] - 1) * n + dist[j] + j - i
		if time < t:
			time = t
	ans[i] = time
print(*ans)


(N, M) = map(int, input().split())
X = [0] * N
Y = [-N] * N
Z = [0] * N
for _ in range(M):
	(a, b) = map(int, input().split())
	a -= 1
	b -= 1
	X[a] += 1
	if Y[a] < 0:
		Y[a] = (b - a) % N
	else:
		Y[a] = min((b - a) % N, Y[a])
for i in range(N):
	Z[i] = (X[i] - 1) * N + Y[i]
ANS = []
for i in range(N):
	ma = 0
	for k in range(N):
		j = (i + k) % N
		ma = max(Z[j] + k, ma)
	ANS.append(str(ma))
print(' '.join(ANS))


import sys
input = sys.stdin.readline
mii = lambda : list(map(int, input().split()))
(n, m) = mii()
a = [[] for _ in range(n)]
c = [123456 for _ in range(n)]
for _ in range(m):
	(u, v) = mii()
	u %= n
	v %= n
	if v < u:
		v += n
	a[u].append(v)
	if c[u] > v:
		c[u] = v
ans = []
for i in list(range(1, n)) + [0]:
	out = 0
	for j in range(i, n):
		if not a[j]:
			continue
		tmp = j - i + (len(a[j]) - 1) * n + (c[j] - j)
		out = max(out, tmp)
	for j in range(i):
		if not a[j]:
			continue
		tmp = j + n - i + (len(a[j]) - 1) * n + (c[j] - j)
		out = max(out, tmp)
	ans.append(out)
print(' '.join(map(str, ans)))


import copy
(n, m) = list(map(int, input().strip().split()))
items = [[] for _ in range(n)]
for _ in range(m):
	(u, v) = list(map(int, input().strip().split()))
	items[u - 1].append(v - 1)
for (i, line) in enumerate(items):
	pairs = []
	for v in line:
		pairs.append((v - i, v) if v > i else (n - i + v, v))
	pairs = sorted(pairs, reverse=True)
	items[i] = [pair[1] for pair in pairs]
ans = []
for s in range(n):
	need = m
	items_idx = [0 for _ in range(n)]
	items_cnt = [0 for _ in range(n)]
	items_tot = 0
	ans.append(-1)
	while need > 0 or items_tot > 0:
		idx = s % n
		if items_idx[idx] < len(items[idx]):
			items_cnt[items[idx][items_idx[idx]]] += 1
			items_idx[idx] += 1
			items_tot += 1
			need -= 1
		items_tot -= items_cnt[idx]
		items_cnt[idx] = 0
		s += 1
		ans[-1] += 1
	ans[-1] = max(0, ans[-1])
print(' '.join(map(str, ans)))


from collections import defaultdict

def main():
	(n, m) = map(int, input().split())
	dest_dict = defaultdict(list)
	for _ in range(m):
		(a, b) = map(int, input().split())
		(a, b) = (a - 1, b - 1)
		dest_dict[a].append(b)
	total_dests = [0] * n
	for i in range(n):
		total_candy = len(dest_dict[i])
		if total_candy:
			total_dest = (total_candy - 1) * n
			min_last_dest = n
			for e in dest_dict[i]:
				min_last_dest = min(min_last_dest, (e - i) % n)
			total_dests[i] = total_dest + min_last_dest
	ret = [0] * n
	for i in range(n):
		for j in range(n):
			if total_dests[j]:
				ret[i] = max(ret[i], total_dests[j] + (j - i) % n)
	print(*ret)
main()


import heapq
import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
rem = [0] * (n + 1)
d = {}
for i in range(m):
	(a, b) = map(int, input().split())
	if a in d:
		diff = 0
		if b < a:
			diff = n - a + (b - 1) + 1
		else:
			diff = b - a
		heapq.heappush(d[a], (-1 * diff, b))
	else:
		diff = 0
		if b < a:
			diff = n - a + (b - 1) + 1
		else:
			diff = b - a
		o = [(-1 * diff, b)]
		heapq.heapify(o)
		d[a] = o
w = []
for j in range(n):
	ans = 0
	cnt = m
	i = j
	g = {}
	for k in d:
		g[k] = d[k].copy()
	while cnt > 0:
		cycle = i % n + 1
		if rem[cycle] > 0:
			cnt -= rem[cycle]
			rem[cycle] = 0
		if cycle in g:
			if len(g[cycle]) > 0:
				e = heapq.heappop(g[cycle])[1]
				rem[e] += 1
		i += 1
		if cnt <= 0:
			break
		ans += 1
	w.append(ans)
print(*w)


def __starting_point():
	from sys import stdin
	(n, m) = list(map(int, stdin.readline().split()))
	c = {}
	for _ in range(m):
		(a, b) = list(map(int, stdin.readline().split()))
		if a - 1 not in c.keys():
			c[a - 1] = []
		x = b - a + (n if b < a else 0)
		c[a - 1].append(x)
	for (k, l) in c.items():
		c[k] = min(l) + (len(l) - 1) * n
	out_ = []
	for x in range(n):
		res = 0
		for (y, v) in c.items():
			s = y - x + (n if y < x else 0)
			res = max(res, v + s)
		out_.append(res)
	print(*out_)
__starting_point()


import sys
from collections import defaultdict as dd
mod = 10 ** 9 + 7

def ri(flag=0):
	if flag == 0:
		return [int(i) for i in sys.stdin.readline().split()]
	else:
		return int(sys.stdin.readline())
(n, m) = ri()
t = dd(list)

def dis(i, j):
	if i <= j:
		return j - i
	else:
		return n - i + j
for i in range(m):
	(u, v) = ri()
	k = dis(u, v)
	t[u].append((k, v))
for i in range(n + 1):
	t[i].sort(reverse=True)
check = [-999999 for i in range(n + 1)]
for i in t:
	temp = 0
	so = i
	de = t[i]
	for j in range(len(de)):
		temp += de[j][0]
		if j != len(de) - 1:
			temp += dis(de[j][1], so)
	check[i] = temp
for i in range(1, n + 1):
	now = i
	ans = -1
	for j in range(1, n + 1):
		if check[j] != 0:
			ans = max(ans, dis(now, j) + check[j])
	print(ans, end=' ')


(n, m) = map(int, input().split())
d = {}
for i in range(n):
	d[i] = []
for i in range(m):
	(a, b) = map(int, input().split())
	d[a - 1].append(b - 1)

def fn(x, i):
	if x >= i:
		return x - i
	else:
		return n - 1 - i + x
for i in range(n):
	d[i] = sorted(d[i], key=lambda x: fn(x, i))
md = 0
for i in d:
	md = max(md, len(d[i]))
ans = []
for i in range(n):
	cc = 0
	dc = [0 for k in range(n)]
	dp = [len(d[j]) - 1 for j in range(n)]
	j = i
	fans = -1
	while cc < m:
		fans += 1
		cc += dc[j]
		dc[j] = 0
		if dp[j] > -1:
			dc[d[j][dp[j]]] += 1
			dp[j] -= 1
		j += 1
		j %= n
	ans.append(fans)
print(' '.join([str(i) for i in ans]))


(n, m) = [int(x) for x in input().split()]

def distance(nrof_stations, a, b):
	if a > b:
		b += nrof_stations
	return b - a

def get_n(stations, start):
	max_d = 0
	for (i, c) in enumerate(stations):
		if len(c) == 0:
			continue
		max_d = max(distance(len(stations), start, i) + (len(c) - 1) * len(stations) + min([distance(len(stations), i, x) for x in c]), max_d)
	return max_d
stations = []
for i in range(n):
	stations.append([])
for _ in range(m):
	(i, j) = [int(x) - 1 for x in input().split()]
	stations[i].append(j)
for i in range(n):
	print(get_n(stations, i), end=' ')


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter, OrderedDict
import threading
from copy import deepcopy

def main():
	(n, m) = map(int, input().split())
	station = [[] for _ in range(n + 1)]
	time = [0] * (n + 1)
	ans = [0] * (n + 1)
	for i in range(m):
		(a, b) = map(int, input().split())
		station[a].append((b + n - a) % n)
	for i in range(1, n + 1):
		station[i] = sorted(station[i])
	for i in range(1, n + 1):
		if len(station[i]):
			time[i] = (len(station[i]) - 1) * n + station[i][0]
	for i in range(1, n + 1):
		for j in range(1, n + 1):
			if time[j] != 0:
				ans[i] = max(ans[i], time[j] + (j + n - i) % n)
	print(*ans[1:])
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from collections import defaultdict as dd, deque
(n, m) = list(map(int, input().split()))
S = dd(list)
for _ in range(m):
	(start, dest) = list(map(int, input().split()))
	S[start - 1].append(dest - 1)
closest = [0] * n
for i in range(n):
	if S[i]:
		closest[i] = min(((j - i) % n for j in S[i]))
R = [0] * n
for start in range(n):
	mx = 0
	for di in range(n):
		i = (start + di) % n
		cost = di + (len(S[i]) - 1) * n + closest[i]
		mx = max(mx, cost)
	R[start] = mx
print(' '.join([str(x) for x in R]))


def distance(fro, to):
	nonlocal n
	return to - fro if to - fro >= 0 else n + to - fro
(n, m) = list(map(int, input().split()))
count = [-1 for i in range(n + 1)]
dis = [n for i in range(n + 1)]
ans = []
for i in range(1, m + 1):
	(a, b) = list(map(int, input().split()))
	dis[a] = min(distance(a, b), dis[a])
	count[a] += 1
for i in range(1, n + 1):
	dis[i] = dis[i] + n * count[i]
for i in range(1, n + 1):
	ans.append(max([dis[k] + distance(i, k) if dis[k] > 0 else 0 for k in range(1, n + 1)]))
print(*ans)


import sys
try:
	sys.stdin = open('in.in', 'r')
	sys.stdout = open('out.out', 'w')
except:
	pass
(n, m) = map(int, input().split())

def Len(st, ed):
	st += 1
	ed += 1
	if st <= ed:
		return ed - st
	else:
		return ed + n - st
cnt = [0 for i in range(n)]
mxlen = [n + 233 for i in range(n)]
for i in range(m):
	(a, b) = map(int, input().split())
	a -= 1
	b -= 1
	cnt[a] += 1
	mxlen[a] = min(mxlen[a], Len(a, b))
for st in range(n):
	ans = 0
	for i in range(n):
		if not cnt[i]:
			continue
		tans = Len(st, i) + (cnt[i] - 1) * n + mxlen[i]
		ans = max(ans, tans)
	print(ans, end=' ')


def dist(a, b):
	return (b - a) % n
(n, m) = list(map(int, input().split(' ')))
sweets = {i: [] for i in range(n)}
for i in range(m):
	(s, t) = list(map(int, input().split(' ')))
	sweets[s - 1].append(t - 1)
t = {i: 0 for i in range(n)}
for i in range(n):
	sweets[i] = sorted(sweets[i], key=lambda x: -dist(i, x))
	if len(sweets[i]):
		t[i] = (len(sweets[i]) - 1) * n + dist(i, sweets[i][-1])
result = []
for s in range(n):
	max_dist = 0
	for i in range(n):
		if t[i] and t[i] + dist(s, i) > max_dist:
			max_dist = t[i] + dist(s, i)
	result.append(max_dist)
print(' '.join(map(str, result)))


import sys
import math
lines = sys.stdin.read().splitlines()
(n, m) = [int(x) for x in lines[0].split(' ')]
sweets = {}
total = 0
for i in range(0, m):
	total += 1
	(s_station, d_station) = [int(x) - 1 for x in lines[i + 1].split(' ')]
	if s_station in sweets:
		sweets[s_station].append((d_station - s_station) % n)
	else:
		sweets[s_station] = [(d_station - s_station) % n]
for key in sweets:
	sweets[key] = sorted(sweets[key])
stations_dist = {}
for i in range(0, n):
	if i not in sweets:
		stations_dist[i] = 0
	else:
		stations_dist[i] = (len(sweets[i]) - 1) * n + sweets[i][0]
for i in range(0, n):
	max_dist = 0
	for j in range(0, n):
		to_station = (j - i) % n
		dist = stations_dist[j]
		if dist == 0:
			continue
		else:
			dist += to_station
		if dist > max_dist:
			max_dist = dist
	print(max_dist)


def dista(start, n):
	return lambda end: n - (start - end) if start > end else end - start
(n, m) = list(map(int, input().split(' ')))
dicta = [[] for i in range(n + 1)]
for i in range(m):
	(s, d) = list(map(int, input().split(' ')))
	dicta[s].append(d)
for i in range(n + 1):
	dicta[i].sort(key=dista(i, n))
maxlen = max(list(map(len, dicta)))
result = (maxlen - 1) * n
minadd = 0
ansans = []
for k in range(1, n + 1):
	disk = dista(k, n)
	minadd = 0
	for i in range(1, n + 1):
		lndicta = len(dicta[i])
		tmp = 0
		if lndicta == maxlen - 1:
			if lndicta != 0:
				tmp = min([disk(i) + dista(i, n)(j) for j in dicta[i]]) - n
		elif lndicta == maxlen:
			tmp = min([disk(i) + dista(i, n)(j) for j in dicta[i]])
		if tmp > minadd:
			minadd = tmp
	ansans.append(str(minadd + result))
print(' '.join(ansans))


from collections import defaultdict as dd
import math

def nn():
	return int(input())

def li():
	return list(input())

def mi():
	return map(int, input().split())

def lm():
	return list(map(int, input().split()))
d = {}
(n, m) = mi()
for i in range(m):
	(a, b) = mi()
	if a in d:
		d[a].append((b - a) % n)
	else:
		d[a] = [(b - a) % n]
distances = {}
answers = []
for key in d:
	distance = n * (len(d[key]) - 1) + min(d[key])
	distances[key] = distance
for i in range(1, n + 1):
	md = 0
	for key in distances:
		new = distances[key] + (key - i) % n
		md = max(new, md)
	answers.append(md)
print(*answers)


import copy
(n, m) = map(int, input().split())
stations = [[] for i in range(n)]
max_len = 0
for i in range(m):
	(fr, to) = map(int, input().split())
	stations[fr - 1].append(to - 1)
	max_len = max(max_len, len(stations[fr - 1]))
max_go = 1000000
for i in range(n):
	stations[i].sort(key=lambda x: (x - i) % n)
go = max(max_len - 2, 0) * n
for i in range(n):
	l = max(0, len(stations[i]) - max_len + 2)
	if l == 0:
		stations[i] = []
	else:
		stations[i] = stations[i][0:l]
for station in range(n):
	st = copy.deepcopy(stations)
	to_go = 0
	counter = 0
	train = set()
	for i in range(station, n * 4):
		counter += 1
		i = i % n
		if i in train:
			train.remove(i)
			if not train:
				to_go = counter
		if len(st[i]) != 0:
			train.add(st[i][-1])
			st[i].pop()
	print(go + to_go - 1, end=' ')


(n, m) = map(int, input().split())
s2 = [[] for i in range(n)]
for i in range(m):
	(a, b) = map(int, input().split())
	(a, b) = (a - 1, b - 1)
	s2[a].append(b)
for i in range(n):
	s2[i].sort()
	for j in range(len(s2[i])):
		if s2[i][j] > i:
			s2[i] = s2[i][j:] + s2[i][:j]
			break
for i in range(n):
	now = [0 for i in range(n)]
	q = 0
	st = i
	step = 0
	r = 0
	s = []
	for j in s2:
		s.append(j[:])
	while q < m:
		if len(s[st]) > 0:
			now[s[st].pop()] += 1
		if now[st]:
			q += now[st]
			now[st] = 0
		st = (st + 1) % n
		step += 1
	print(step - 1, end=' ')


from sys import stdin
from collections import deque
import heapq

def realDist(n, long):
	out = []
	dists = [x[0] + x[1] for x in long]
	d2 = [(-1, -1)] + sorted([(dists[x], long[x][0]) for x in range(len(long))])
	before = 0
	after = d2[-1][0]
	ind = 0
	for x in range(n):
		if ind < len(long):
			if long[ind][0] < x:
				before = max(before, n - 1 + long[ind][1])
				ind += 1
		out.append(max(before, after))
		before -= 1
		after -= 1
	return out
(n, m) = [int(x) for x in stdin.readline().split()]
candy = {}
long = []
maxLen = 0
for c in range(m):
	(a, b) = [int(x) for x in stdin.readline().split()]
	a -= 1
	b -= 1
	b = (b - a) % n
	if a in candy:
		heapq.heappush(candy[a], b)
		if len(candy[a]) == maxLen:
			long.append(a)
		elif len(candy[a]) > maxLen:
			long = [a]
			maxLen = len(candy[a])
	else:
		candy[a] = [b]
		if maxLen == 0:
			maxLen = 1
			long = [a]
		elif maxLen == 1:
			long.append(a)
long2 = long[:]
long = [(x + candy[x][0]) % n for x in long]
long3 = [(x, candy[x][0]) for x in long2]
long4 = []
for c in candy:
	if len(candy[c]) == maxLen - 1:
		long4.append((c, candy[c][0]))
long.sort()
long2.sort()
long3.sort()
long4.sort()
longSet = set(long)
base = n * maxLen - n
ind = 0
out = [x + base for x in realDist(n, long3)]
out2 = [x + base - n for x in realDist(n, long4)]
out3 = [max(out[x], out2[x]) for x in range(n)]
print(' '.join([str(x) for x in out3]))


import sys
sys.setrecursionlimit(10 ** 5 + 1)
inf = int(10 ** 20)
max_val = inf
min_val = -inf
RW = lambda : sys.stdin.readline().strip()
RI = lambda : int(RW())
RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
RWI = lambda : [x for x in sys.stdin.readline().strip().split()]
import sys
sys.setrecursionlimit(100000)
(n, m) = [int(i) for i in input().split()]
A = [[int(i) for i in input().split()] for j in range(m)]
INF = 10 ** 9
mi = [INF] * (n + 1)
cnt = [0] * (n + 1)
for (a, b) in A:
	cnt[a] += 1
	mi[a] = min(mi[a], (b - a) % n)
ANS = []
for i in range(1, n + 1):
	ans = 0
	for j in range(1, n + 1):
		if cnt[j] == 0:
			continue
		ans = max(ans, (j - i) % n + (cnt[j] - 1) * n + mi[j])
	ANS.append(ans)
print(*ANS)


(n, m) = map(int, input().split())
stations = []
for i in range(n):
	stations.append([])
for i in range(m):
	(a, b) = map(int, input().split())
	stations[a - 1].append((b - a) % n)
maxes = []
for i in range(n):
	if len(stations[i]) > 0:
		big = min(stations[i])
	else:
		big = 0
	maxes.append(n * max(len(stations[i]) - 1, 0) + big)
out = []
new = maxes[:]
big = 0
for j in range(n):
	if new[j] + j > big and new[j] > 0:
		big = new[j] + j
curr = big
out.append(str(curr))
for i in range(n - 1):
	if maxes[i] > 0:
		curr = max(curr - 1, maxes[i] + n - 1)
	else:
		curr = curr - 1
	out.append(str(curr))
print(' '.join(out))


def solve(candies, start, n):
	time = 0
	train = {}
	while True:
		far = 0
		for i in candies:
			if i[0] == start:
				if i[1] < start:
					far = max(far, i[1] + n)
				else:
					far = max(far, i[1])
		if far != 0:
			if far > n:
				far -= n
			i = (start, far)
			if i not in train.keys():
				train[i] = 1
			else:
				train[i] += 1
		new = []
		for i in candies:
			if i[1] == start:
				if i in train.keys():
					train[i] -= 1
					if train[i] == 0:
						del train[i]
				else:
					new.append(i)
			else:
				new.append(i)
		candies = new[:]
		if not candies:
			break
		time += 1
		start += 1
		if start == n + 1:
			start = 1
	return time

def main():
	(n, m) = map(int, input().split())
	stations = {}
	for i in range(1, n + 1):
		stations[i] = []
	candies = []
	for i in range(m):
		(a, b) = map(int, input().split())
		candies.append((a, b))
	ans = []
	for i in range(n):
		ans.append(solve(candies[:], i + 1, n))
	for i in ans:
		print(i, end=' ')
main()


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mii = lambda : map(int, input().split())
(n, m) = mii()
a = [0 for _ in range(n)]
c = [123456 for _ in range(n)]
for _ in range(m):
	(u, v) = mii()
	u %= n
	v %= n
	if v < u:
		v += n
	a[u] += 1
	if c[u] > v:
		c[u] = v
ans = []
for i in list(range(1, n)) + [0]:
	out = 0
	for j in range(i, n):
		if not a[j]:
			continue
		tmp = j - i + (a[j] - 1) * n + (c[j] - j)
		out = max(out, tmp)
	for j in range(i):
		if not a[j]:
			continue
		tmp = j + n - i + (a[j] - 1) * n + (c[j] - j)
		out = max(out, tmp)
	ans.append(out)
print(' '.join(map(str, ans)))


(n, m) = map(int, input().split())
arr = []
for i in range(m):
	(x, y) = map(int, input().split())
	arr.append((x, y))
dict1 = {}
for i in range(1, n + 1):
	dict1[i] = []
for i in range(m):
	dict1[arr[i][0]].append(arr[i][1])
for i in range(1, n + 1):
	dict1[i].sort()
ansarr = []
for i in range(1, n + 1):
	temp = 0
	j = 1
	while j <= n:
		temp = max(temp, len(dict1[j]))
		j += 1
	j = 1
	maxdist = 0
	fans = 0
	tempdist = 10 ** 9
	while j <= n:
		if len(dict1[j]) == temp:
			if j >= i:
				mindist = 10 ** 9
				for l in range(len(dict1[j])):
					if dict1[j][l] < j:
						mindist = min(mindist, n - i + dict1[j][l])
					else:
						mindist = min(mindist, dict1[j][l] - i)
				if mindist != 10 ** 9:
					maxdist = max(maxdist, mindist)
			else:
				mindist = 10 ** 9
				for l in range(len(dict1[j])):
					if dict1[j][l] < j:
						mindist = min(mindist, n - i + n + dict1[j][l])
					else:
						mindist = min(mindist, n - i + dict1[j][l])
				if mindist != 10 ** 9:
					maxdist = max(maxdist, mindist)
			fans = max((temp - 1) * n + maxdist, fans)
		elif len(dict1[j]) == temp - 1 and temp != 1 and (j < i):
			tempdist = 10 ** 9
			for l in range(len(dict1[j])):
				if dict1[j][l] >= i:
					tempdist = min((temp - 1) * n + dict1[j][l] - i, tempdist)
				elif j < dict1[j][l] < i:
					tempdist = min((temp - 1) * n - (i - dict1[j][l]), tempdist)
				else:
					tempdist = min((temp - 1) * n + n - i + dict1[j][l], tempdist)
			if tempdist != 10 ** 9:
				fans = max(fans, tempdist)
		elif len(dict1[j]) == temp - 1 and temp != 1 and (j >= i):
			tempdist = 10 ** 9
			for l in range(len(dict1[j])):
				if j > dict1[j][l] >= i:
					tempdist = min((temp - 1) * n + dict1[j][l] - i, tempdist)
				elif dict1[j][l] > j:
					tempdist = min((temp - 2) * n + dict1[j][l] - i, tempdist)
				else:
					tempdist = min((temp - 2) * n + n - i + dict1[j][l], tempdist)
			if tempdist != 10 ** 9:
				fans = max(fans, tempdist)
		j += 1
	ansarr.append(fans)
print(*ansarr)


MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
(n, m) = I()
ans = [0 for i in range(n)]
l = [[] for i in range(5001)]
for i in range(m):
	(a, b) = I()
	a -= 1
	b -= 1
	l[a].append(b)
for i in range(n):
	l[i].sort(key=lambda x: (x - i) % n, reverse=True)
for i in range(n):
	res = 0
	k = len(l[i])
	if k:
		res = (k - 1) * n
		res += (l[i][-1] - i) % n
	ans[i] = res
res = [0 for i in range(n)]
for i in range(n):
	for j in range(n):
		if ans[j]:
			res[i] = max(res[i], ans[j] + (j - i) % n)
print(*res)


(n, m) = map(int, input().split())
a = [[] for i in range(5010)]
for i in range(m):
	(x, y) = map(int, input().split())
	if y < x:
		a[x].append(n - x + y)
	else:
		a[x].append(y - x)
for i in range(1, n + 1):
	a[i].sort()
mx = int(-1000000000.0)
for i in range(1, n + 1):
	if len(a[i]):
		mx = n * (len(a[i]) - 1) + a[i][0]
	else:
		mx = 0
	k = 1
	l = i + 1
	if l == n + 1:
		l = 1
	while l != i:
		if len(a[l]):
			mx = max(mx, n * (len(a[l]) - 1) + a[l][0] + k)
		k += 1
		l += 1
		if l == n + 1:
			l = 1
	print(mx, end=' ')
print()


(n, m) = map(int, input().strip().split())
arr = [[] for i in range(n + 1)]
for i in range(m):
	(u, v) = map(int, input().strip().split())
	arr[u].append(v)
x = 100000000000000
st = [x] * (n + 1)
for i in range(1, 1 + n):
	for j in range(len(arr[i])):
		if i <= arr[i][j]:
			st[i] = min(st[i], arr[i][j] - i)
		else:
			st[i] = min(st[i], n - (i - arr[i][j]))
	st[i] = st[i] + len(arr[i][1:]) * n
for i in range(1, 1 + n):
	if st[i] == x:
		st[i] = 0
ans = []
for i in range(1, 1 + n):
	an = st[i]
	t = 1
	for j in range(i + 1, 1 + n):
		if t + st[j] > an and len(arr[j]) > 0:
			an = t + st[j]
		t += 1
	for j in range(1, i):
		if t + st[j] > an and len(arr[j]) > 0:
			an = t + st[j]
		t += 1
	ans.append(an)
print(*ans)


from sys import stdin, stdout
import math
(N, M) = [int(x) for x in stdin.readline().split()]

def dist(a, b, N):
	if b >= a:
		return b - a
	else:
		return b - a + N
station = [2 * N] * (N + 1)
cargo = [0] * (N + 1)
for i in range(M):
	(a, b) = [int(x) for x in stdin.readline().split()]
	station[a] = min(station[a], dist(a, b, N))
	cargo[a] += 1
for i in range(1, N + 1):
	maxi = 0
	for j in range(1, N + 1):
		if cargo[j] > 0:
			d = station[j] + (cargo[j] - 1) * N + dist(i, j, N)
			maxi = max(maxi, d)
	print(maxi, end=' ')


from collections import defaultdict as dd
(n, m) = [int(i) for i in input().split(' ')]
a = []
b = []

def fnx(i, j):
	if i < j:
		return j - i
	else:
		return n - i + j

def fnr(r):
	if r % n == 0:
		return n
	else:
		return r % n
for i in range(m):
	(x, y) = [int(i) for i in input().split(' ')]
	a.append(x)
	b.append(y)
ANS = []
for ii in range(1, n + 1):
	s = [[] for i in range(n + 1)]
	d = dd(list)
	r = [-1 for i in range(n + 1)]
	y = [-1]
	for i in range(m):
		(x, yy) = (a[i], b[i])
		s[fnr(x - ii + 1)].append([fnx(fnr(x - ii + 1), fnr(yy - ii + 1)), fnr(x - ii + 1), fnr(yy - ii + 1)])
		d[yy].append(x)
	for i in range(1, n + 1):
		rt = s[i].copy()
		rt.sort()
		r[i] = rt
		y.append(len(s[i]))
	p = max(y)
	A = (p - 2) * n
	ans1 = []
	ans2 = []
	for i in range(1, n + 1):
		if y[i] == p:
			if p == 1:
				ans2.append(r[i][0])
				continue
			ans1.append(r[i][1])
			ans2.append(r[i][0])
		if y[i] == p - 1:
			if p - 1 == 0:
				continue
			ans1.append(r[i][0])
	tr = 0
	for i in range(len(ans1)):
		re = ans1[i][0] + ans1[i][1] - 1
		tr = max(tr, re)
	trf = 0
	for i in range(len(ans2)):
		re = ans2[i][0] + ans2[i][1] - 1
		trf = max(trf, re)
	er = max(A + tr, A + trf + n)
	ANS.append(er)
print(*ANS)


def dist(a, b):
	return (b - a) % n
(n, m) = map(int, input().split())
cnd = [0 for x in range(n + 1)]
mn = [5000 for x in range(n + 1)]
for i in range(m):
	(a, b) = map(int, input().split())
	cnd[a] += 1
	mn[a] = min(mn[a], dist(a, b))
for i in range(1, n + 1):
	ans = 0
	for j in range(1, n + 1):
		if cnd[j] > 0:
			ans = max(ans, dist(i, j) + n * (cnd[j] - 1) + mn[j])
	print(ans, end=' ')


((n, m), count, length) = (list(map(int, input().split())), {}, {})
for _ in range(m):
	(a, b) = list(map(int, input().split()))
	count[a] = count[a] + 1 if a in count.keys() else 1
	length[a] = min(length[a], (b + n - a) % n) if a in length.keys() else (b + n - a) % n
for i in range(1, n + 1):
	print(max((length[j] + j - i + n * (count[j] - (j >= i)) if count[j] != 0 else 0 for j in count.keys())), end=' ')


(n, m) = map(int, input().split())
d = dict()
for i in range(m):
	(a, b) = map(int, input().split())
	a -= 1
	b -= 1
	if a in d:
		d[a].append(b)
	else:
		d[a] = [b]
for i in d.keys():
	d[i].sort()
times = [0 for i in range(n)]
for i in d.keys():
	mi = 9999999
	for j in d[i]:
		mi = min(mi, (j - i) % n)
	times[i] = (len(d[i]) - 1) * n + mi
for i in range(n):
	ans = 0
	for j in range(n):
		if times[j] != 0:
			dist = (j - i) % n
			ans = max(ans, times[j] + dist)
	print(ans, end=' ')


import sys
import math as mt
input = sys.stdin.buffer.readline
t = 1
for ___ in range(t):
	(n, m) = map(int, input().split())
	d = {}
	for i in range(n + 1):
		d[i] = []
	for __ in range(m):
		(a, b) = map(int, input().split())
		d[a].append(b)
	for i in range(n + 1):
		d[i].sort()
	sub = [0] * (n + 1)
	for i in d:
		mini = 10000
		for j in range(len(d[i])):
			mini = min(mini, (d[i][j] - i) % n)
		sub[i] = mini
	for k in range(1, n + 1):
		loop = 0
		maxi = 0
		for i in range(1, n + 1):
			if len(d[i]) > 0:
				loop = (len(d[i]) - 1) * n + (i - k) % n + sub[i]
			maxi = max(maxi, loop)
		print(maxi, end=' ')


(n, m) = [int(i) for i in input().split()]
A = [[int(i) for i in input().split()] for j in range(m)]
INF = 10 ** 9
mi = [INF] * (n + 1)
cnt = [0] * (n + 1)
for (a, b) in A:
	cnt[a] += 1
	mi[a] = min(mi[a], (b - a) % n)
ANS = []
for i in range(1, n + 1):
	ans = 0
	for j in range(1, n + 1):
		if cnt[j] == 0:
			continue
		ans = max(ans, (j - i) % n + (cnt[j] - 1) * n + mi[j])
	ANS.append(ans)
print(*ANS)


from collections import defaultdict

def min_cost(src, dsts, n):
	if len(dsts) == 0:
		return 0
	ans = float('inf')
	for dst in dsts:
		if dst < src:
			dst += n
		ans = min(ans, dst - src)
	return ans

def overall_max_cost(src, costs, n):
	ans = 0
	for i in range(len(costs)):
		basic_cost = i - src
		if basic_cost < 0:
			basic_cost += n
		ans = max(ans, basic_cost + costs[i])
	return ans

def solve():
	(n, m) = map(int, input().split())
	candies = defaultdict(list)
	for i in range(m):
		(src, dst) = map(lambda x: int(x) - 1, input().split())
		candies[src].append(dst)
	costs = defaultdict(int)
	for i in range(n):
		cs = candies[i]
		cost = n * (len(cs) - 1) + min_cost(i, cs, n)
		costs[i] = cost
	result = []
	for i in range(n):
		result.append(str(overall_max_cost(i, costs, n)))
	print(' '.join(result))
solve()


import copy
r = input().split()
n = int(r[0])
m = int(r[1])
ar = [[] for i in range(n)]
for i in range(m):
	r = input().split()
	a = int(r[0])
	b = int(r[1])
	ar[a - 1].append(b - 1)
train = []
result = []
for i in range(n):
	count = m
	arr = copy.deepcopy(ar)
	time = copy.deepcopy(ar)
	ind = i
	res = 0
	for j in range(n):
		for k in range(len(arr[j])):
			if arr[j][k] >= j:
				time[j][k] = arr[j][k] - j
			else:
				time[j][k] = n - 1 - j + arr[j][k] + 1
	while count != 0 or len(train) != 0:
		if len(arr[ind]) != 0:
			train.append(arr[ind][time[ind].index(max(time[ind]))])
			del arr[ind][time[ind].index(max(time[ind]))]
			del time[ind][time[ind].index(max(time[ind]))]
			count -= 1
		while train.count(ind) != 0:
			train.remove(ind)
		ind += 1
		if ind == len(arr):
			ind = 0
		res += 1
	result.append(res - 1)
print(' '.join(map(str, result)))


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
(n, m1) = map(int, input().split())
tot = []
m = [n + 1] * n
cou = [0] * n
for i in range(m1):
	(a, b) = map(int, input().split())
	if b < a:
		b += n
	cou[a - 1] += 1
	m[a - 1] = min(m[a - 1], b - a)
for ik in range(n):
	ans = [0] * n
	for i in range(n):
		if cou[i] == 0:
			continue
		ans[i] = cou[i] * n + m[i] - n
	w = 0
	for i in range(n):
		if ans[i] != 0:
			w = max(w, ans[i] + (i - ik) % n)
	tot.append(w)
print(*tot)


from sys import exit, setrecursionlimit
setrecursionlimit(10 ** 6)
inn = lambda : input().strip()
mapp_m1 = lambda : map(lambda x: int(x) - 1, inn().split(' '))
mapp = lambda : map(int, inn().split(' '))
(N, M) = mapp()
station = [[] for _ in range(N)]
for _ in range(M):
	(a, b) = mapp()
	(a, b) = (a - 1, b - 1)
	station[a].append(b)
answers = []
for start in range(N):
	answer = 0
	for (there, candy) in enumerate(station):
		toThere = (N + there - start) % N
		cycle = N * max(0, len(candy) - 1)
		toEnd = 987654321
		for end in candy:
			toEnd = min(toEnd, (N + end - there) % N)
		if toEnd != 987654321:
			answer = max(answer, toThere + cycle + toEnd)
	answers.append(answer)
print(' '.join(map(str, answers)))


import sys
(n, m) = (int(t) for t in input().split(' '))
candies_total = [0 for _ in range(n)]
closest_distance = [n for _ in range(n)]
candies = sys.stdin.readlines()
for i in range(m):
	(from_, to) = (int(t) - 1 for t in candies[i].split(' '))
	candies_total[from_] += 1
	distance = (to + n - from_) % n
	if distance < closest_distance[from_]:
		closest_distance[from_] = distance
stations_best = [0 for _ in range(n)]
for i in range(n):
	stations_best[i] = (candies_total[i] - 1) * n + closest_distance[i]
answer = []
for i in range(n):
	cost = 0
	for j in range(n):
		if stations_best[j] > 0:
			cost = max(cost, stations_best[j] + (j + n - i) % n)
	answer.append(cost)
print(*answer)


(n, m) = list(map(int, input().split()))
(ms, md) = ([n - 1 for i in range(n + 1)], [-1 for i in range(n + 1)])

def distance(sfrom, sto):
	nonlocal n
	return sto - sfrom if sto >= sfrom else sto + n - sfrom
for i in range(m):
	(c, d) = list(map(int, input().split()))
	md[c] += 1
	ms[c] = min(distance(c, d), ms[c])
for i in range(1, n + 1):
	md[i] = n * md[i] + ms[i]
ans = []
for i in range(1, n + 1):
	ans.append(max([md[k] + distance(i, k) if md[k] > 0 else 0 for k in range(1, n + 1)]))
print(' '.join([str(i) for i in ans]))


from collections import defaultdict

def dist(a, b, n):
	if b >= a:
		return b - a
	else:
		return n - a + b
(n, m) = (int(x) for x in input().split())
stations = defaultdict(list)
for _ in range(m):
	(a, b) = (int(x) for x in input().split())
	stations[a].append(b)
needs = {}
for (station, candies) in stations.items():
	if not candies:
		continue
	loops = len(candies) - 1
	closest = min(candies, key=lambda x: dist(station, x, n))
	needs[station] = loops * n + dist(station, closest, n)
most = max(needs.values())
todelete = []
for (stat, need) in needs.items():
	if need <= most - n + 1:
		todelete.append(stat)
for stat in todelete:
	del needs[stat]
result = []
for start in range(1, n + 1):
	time = 0
	for (station, need) in needs.items():
		t = dist(start, station, n) + need
		time = max(time, t)
	result.append(str(time))
print(' '.join(result))


(n, m) = map(int, input().split())
candies = [[] for _ in range(n)]
for _ in range(m):
	(src, dst) = map(lambda x: int(x) - 1, input().split())
	candies[src].append(dst)

def get_ans():
	ans = 0
	laps = 0
	for i in range(n):
		if len(candies[i]) > 0:
			curr = 0
			sz = len(candies[i])
			a = min(candies[i])
			b = max(candies[i])
			sz += 1 if a < i and b < i else 0
			if sz >= laps:
				laps = sz
				curr = 0
				if a < i and b < i or (a > i and b > i):
					curr = max(0, n * (sz - 1)) + a
				else:
					a = min(filter(lambda x: x > i, candies[i]))
					curr = max(0, n * (sz - 1)) + a
				ans = max(ans, curr)
	return 0 if ans == 10 ** 9 else ans
ans = [0 for _ in range(n)]
ans[0] = get_ans()
for k in range(1, n):
	init = candies[0]
	for i in range(1, n):
		candies[i - 1] = candies[i]
	candies[n - 1] = init
	for i in range(n):
		for j in range(len(candies[i])):
			candies[i][j] = (candies[i][j] - 1) % n
	ans[k] = get_ans()
print(' '.join(map(str, ans)))


import sys
from collections import defaultdict, deque
(n, m) = map(int, sys.stdin.readline().split())
dist = defaultdict(list)
sweet = defaultdict(list)
for i in range(m):
	(u, v) = map(int, sys.stdin.readline().split())
	sweet[u].append(v)
	dist[u].append(0)
for i in sweet:
	le = len(sweet[i])
	for j in range(le):
		if sweet[i][j] >= i:
			dist[i][j] = sweet[i][j] - i
		else:
			dist[i][j] = n - (i - sweet[i][j])
	dist[i].sort()
for i in dist:
	count = 0
	le = len(dist[i])
	for k in range(le - 1, -1, -1):
		dist[i][k] += count * n
		count += 1
	dist[i].sort()
vis = defaultdict(int)
for i in dist:
	if dist[i] == []:
		vis[i] = 0
	else:
		vis[i] = dist[i][-1]
ans = [0 for _ in range(n)]
for i in range(1, n + 1):
	cur = 0
	for k in range(1, n + 1):
		new = 0
		if k >= i:
			if vis[k] != 0:
				new = vis[k] + k - i
		elif vis[k] != 0:
			new = vis[k] + n - (i - k)
		cur = max(cur, new)
	ans[i - 1] = cur
print(*ans)


import sys
input = sys.stdin.readline
import bisect
(n, m) = map(int, input().split())
AB = [list(map(int, input().split())) for i in range(m)]
C = [[] for i in range(n + 1)]
for (a, b) in AB:
	C[a].append(b)
C2 = [0] * (n + 1)
for i in range(1, n + 1):
	if C[i] == []:
		continue
	ANS = (len(C[i]) - 1) * n
	rest = []
	for c in C[i]:
		if c > i:
			rest.append(c - i)
		else:
			rest.append(n - i + c)
	C2[i] = ANS + min(rest)
DIAG = list(range(n))
ANS = []
for i in range(1, n + 1):
	K = DIAG[-i + 1:] + DIAG[:-i + 1]
	ANS.append(max([K[j] + C2[j + 1] for j in range(n) if C2[j + 1] != 0]))
print(' '.join([str(a) for a in ANS]))


def distance(b, a, n):
	return b - a if b >= a else b + n - a
(n, m) = map(int, input().split())
dic_last_candy = dict()
dict_node = dict()
s = ''
for i in range(m):
	(a, b) = map(int, input().split())
	c = dict_node.get(a, 0)
	c += 1
	dict_node[a] = c
	last_candy = dic_last_candy.get(a, 0)
	if last_candy:
		c1 = distance(last_candy, a, n)
		c2 = distance(b, a, n)
		if c2 < c1:
			last_candy = b
	else:
		last_candy = b
	dic_last_candy[a] = last_candy
for i in range(1, n + 1):
	c = dict_node.get(i, 0)
	if c:
		now_step = (c - 1) * n + distance(dic_last_candy[i], i, n)
		dict_node[i] = now_step
s = ''
for i in range(1, n + 1):
	now_step = dict_node.get(i, 0)
	min_step = now_step
	for j in range(1, n + 1):
		if dict_node.get(j, 0):
			now_step = dict_node.get(j, 0) + distance(j, i, n)
			if min_step < now_step:
				min_step = now_step
	s += ' ' + str(min_step)
print(s[1:])


from collections import defaultdict

def dist(a, b, n):
	if b >= a:
		return b - a
	else:
		return n - a + b
(n, m) = (int(x) for x in input().split())
stations = defaultdict(list)
for _ in range(m):
	(a, b) = (int(x) for x in input().split())
	stations[a].append(b)
needs = {}
for (station, candies) in stations.items():
	if not candies:
		continue
	loops = len(candies) - 1
	closest = min(candies, key=lambda x: dist(station, x, n))
	needs[station] = (loops, closest)
maxloops = max([pair[0] for pair in needs.values()])
maxstats = []
finishes = []
for (station, pair) in needs.items():
	if pair[0] == maxloops:
		maxstats.append(station)
result = []
for start in range(1, n + 1):
	time = 0
	for station in needs:
		if not needs[station]:
			continue
		(loops, closest) = needs[station]
		t = dist(start, station, n) + loops * n + dist(station, closest, n)
		time = max(time, t)
	result.append(str(time))
print(' '.join(result))


(n, m) = list(map(int, input().split()))
a = []
for i in range(m):
	a.append(list(map(int, input().split())))
locs = []
for i in range(n + 1):
	locs.append([])
for i in range(m):
	locs[a[i][0]].append(a[i][1])
ans = [0] * (n + 1)
for i in range(1, n + 1):
	mini = 2 ** n
	for j in locs[i]:
		if j > i:
			mini = min(mini, j - i)
		else:
			mini = min(mini, n - i + j)
	if mini == 2 ** n:
		ans[i] = 0
	else:
		ans[i] = max(0, n * (len(locs[i]) - 1) + mini)
for start in range(1, n + 1):
	maxi = 0
	for j in range(1, n + 1):
		if ans[j]:
			if j >= start:
				maxi = max(maxi, j - start + ans[j])
			else:
				maxi = max(maxi, n - start + j + ans[j])
	print(maxi, end=' ')


(n, m) = map(int, input().split())

def dist(a, b):
	return (n + b - a) % n

def main():
	inp1 = [0] * (n + 1)
	inp2 = [n] * (n + 1)
	for _ in range(m):
		(a, b) = map(int, input().split())
		inp1[a] += 1
		inp2[a] = min(inp2[a], dist(a, b))
	inp = tuple(((r1 - 1) * n + r2 for (r1, r2) in zip(inp1, inp2)))
	last = max((i + inp[i] for i in range(1, n + 1) if inp[i])) - 1
	res = [last]
	for inp_i in inp[1:n]:
		last -= 1
		if inp_i:
			last = max(last, inp_i + n - 1)
		res.append(last)
	print(*res)
main()


(N, M) = map(int, input().split())
candies = [[] for _ in [0] * N]
for (a, b) in (map(int, input().split()) for _ in [0] * M):
	candies[a - 1].append(b - 1)
ans = []
for start in range(N):
	_candies = [[] for _ in [0] * N]
	for i in range(N):
		_candies[i] = [n % N for n in sorted((n + N if n < i else n for n in candies[i]))]
	query = [0] * N
	count = 0
	for time in range(start, 1000000):
		i = time % N
		if query[i]:
			count += query[i]
			query[i] = 0
		if _candies[i]:
			query[_candies[i].pop()] += 1
		if count == M:
			ans.append(time - start)
			break
print(*ans)


(n, m) = list(map(int, input().split()))
a = [0] * m
b = [0] * m
t = [[-1]] * n
for i in range(m):
	(a[i], b[i]) = map(int, input().split())
	if t[a[i] - 1] == [-1]:
		if b[i] > a[i]:
			t[a[i] - 1] = [b[i] - a[i]]
		if b[i] < a[i]:
			t[a[i] - 1] = [n - a[i] + b[i]]
	else:
		if b[i] > a[i]:
			t[a[i] - 1].append(b[i] - a[i])
		if b[i] < a[i]:
			t[a[i] - 1].append(n - a[i] + b[i])
res = [0] * n
mx = 0
for i in range(n):
	t[i].sort()
	if t[i] == [-1]:
		res[i] = 0
		continue
	res[i] = t[i][0] + n * (len(t[i]) - 1)
	if res[i] > res[mx]:
		mx = i
ans = [0] * n
for i in range(n):
	mn = res[i]
	for j in range(1, n):
		if res[(i + j) % n] > 0:
			mn = max(mn, res[(i + j) % n] + j)
	ans[i] = mn
for i in range(n):
	print(ans[i], end=' ')


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def dist(a, b):
	return (b - a) % n
(n, m) = map(int, input().split())
cnd = [0 for x in range(n + 1)]
mn = [5000 for x in range(n + 1)]
for i in range(m):
	(a, b) = map(int, input().split())
	cnd[a] += 1
	mn[a] = min(mn[a], dist(a, b))
for i in range(1, n + 1):
	ans = 0
	for j in range(1, n + 1):
		if cnd[j] > 0:
			ans = max(ans, dist(i, j) + n * (cnd[j] - 1) + mn[j])
	print(ans, end=' ')


from copy import deepcopy
(n, m) = map(int, input().split())
d = {}
for i in range(1, n + 1):
	d[i] = []
for i in range(m):
	(x, y) = map(int, input().split())
	d[x].append(y)
for i in d:
	d[i].sort(reverse=True, key=lambda j: j + n - i if j < i else j - i)
for i in d:
	x = []
	for j in d[i]:
		if j != i:
			x.append(j)
	d[i] = x

def get_candies(start, d):
	t = 0
	for i in d:
		t += len(d[i])
	a = []
	ans = 0
	c = start
	while t:
		y = []
		for i in a:
			if i == c:
				t -= 1
			else:
				y.append(i)
		a = y
		if len(d[c]):
			x = d[c].pop(0)
			a.append(x)
		c = (c + 1) % n
		if c == 0:
			c = n
		ans += 1
	return ans - 1
for i in range(1, n + 1):
	print(get_candies(i, deepcopy(d)), end=' ')
print()


def dist(a, b):
	return (b - a) % n
(n, m) = list(map(int, input().split(' ')))
sweets = {i: [] for i in range(n)}
for i in range(m):
	(s, t) = list(map(int, input().split(' ')))
	sweets[s - 1].append(t - 1)
t = {i: -1000000.0 for i in range(n)}
for i in range(n):
	sweets[i] = sorted(sweets[i], key=lambda x: -dist(i, x))
	if len(sweets[i]):
		t[i] = (len(sweets[i]) - 1) * n + dist(i, sweets[i][-1])
result = []
(m_max, i_max) = (0, 0)
for (i, v) in t.items():
	if v + i > m_max + i_max:
		(m_max, i_max) = (v, i)
result.append(m_max + i_max)
for s in range(1, n):
	old_max = t[i_max] + dist(s, i_max)
	new_max = t[s - 1] + dist(s, s - 1)
	if new_max > old_max:
		result.append(new_max)
		i_max = s - 1
	else:
		result.append(old_max)
print(' '.join(map(str, result)))


import typing

def _ceil_pow2(n: int) -> int:
	x = 0
	while 1 << x < n:
		x += 1
	return x

def _bsf(n: int) -> int:
	x = 0
	while n % 2 == 0:
		x += 1
		n //= 2
	return x

class SegTree:

	def __init__(self, op: typing.Callable[[typing.Any, typing.Any], typing.Any], e: typing.Any, v: typing.Union[int, typing.List[typing.Any]]) -> None:
		self._op = op
		self._e = e
		if isinstance(v, int):
			v = [e] * v
		self._n = len(v)
		self._log = _ceil_pow2(self._n)
		self._size = 1 << self._log
		self._d = [e] * (2 * self._size)
		for i in range(self._n):
			self._d[self._size + i] = v[i]
		for i in range(self._size - 1, 0, -1):
			self._update(i)

	def set(self, p: int, x: typing.Any) -> None:
		assert 0 <= p < self._n
		p += self._size
		self._d[p] = x
		for i in range(1, self._log + 1):
			self._update(p >> i)

	def get(self, p: int) -> typing.Any:
		assert 0 <= p < self._n
		return self._d[p + self._size]

	def prod(self, left: int, right: int) -> typing.Any:
		assert 0 <= left <= right <= self._n
		sml = self._e
		smr = self._e
		left += self._size
		right += self._size
		while left < right:
			if left & 1:
				sml = self._op(sml, self._d[left])
				left += 1
			if right & 1:
				right -= 1
				smr = self._op(self._d[right], smr)
			left >>= 1
			right >>= 1
		return self._op(sml, smr)

	def all_prod(self) -> typing.Any:
		return self._d[1]

	def max_right(self, left: int, f: typing.Callable[[typing.Any], bool]) -> int:
		assert 0 <= left <= self._n
		assert f(self._e)
		if left == self._n:
			return self._n
		left += self._size
		sm = self._e
		first = True
		while first or left & -left != left:
			first = False
			while left % 2 == 0:
				left >>= 1
			if not f(self._op(sm, self._d[left])):
				while left < self._size:
					left *= 2
					if f(self._op(sm, self._d[left])):
						sm = self._op(sm, self._d[left])
						left += 1
				return left - self._size
			sm = self._op(sm, self._d[left])
			left += 1
		return self._n

	def min_left(self, right: int, f: typing.Callable[[typing.Any], bool]) -> int:
		assert 0 <= right <= self._n
		assert f(self._e)
		if right == 0:
			return 0
		right += self._size
		sm = self._e
		first = True
		while first or right & -right != right:
			first = False
			right -= 1
			while right > 1 and right % 2:
				right >>= 1
			if not f(self._op(self._d[right], sm)):
				while right < self._size:
					right = 2 * right + 1
					if f(self._op(self._d[right], sm)):
						sm = self._op(self._d[right], sm)
						right -= 1
				return right + 1 - self._size
			sm = self._op(self._d[right], sm)
		return 0

	def _update(self, k: int) -> None:
		self._d[k] = self._op(self._d[2 * k], self._d[2 * k + 1])
(n, m) = map(int, input().split())
candies = []
INF = 10 ** 10
for i in range(n):
	candies.append([])
for _ in range(m):
	(a, b) = map(int, input().split())
	candies[a - 1].append(b - 1)
for i in range(n):
	candies[i].sort()
bestcandy = [0] * n
for i in range(n):
	if candies[i]:
		best_len = 10 ** 9
		for candy in candies[i]:
			if best_len > (candy - i) % n:
				best_len = (candy - i) % n
				bestcandy[i] = best_len
a = []
for i in range(n):
	if candies[i]:
		a.append((len(candies[i]) - 1) * n + bestcandy[i] + i)
	else:
		a.append(0)
ans = []
ans.append(max(a))
segtree = SegTree(max, -1, a)
for i in range(1, n):
	k = segtree.get(i - 1)
	if k != 0:
		segtree.set(i - 1, k + n)
	r = segtree.all_prod()
	ans.append(r - i)
print(' '.join(map(str, ans)))


(n, m) = map(int, input().split())
minima = [float('inf') for i in range(n + 1)]
counted = [-1 for i in range(n + 1)]
stored = [0 for i in range(n + 1)]
for i in range(m):
	(curr, des) = map(int, input().split())
	curr -= 1
	des -= 1
	minima[curr] = min(minima[curr], (des - curr) % n)
	counted[curr] += 1
	stored[curr] = counted[curr] * n + minima[curr]
maxi = 0
ans = []
for i in range(n):
	add = 0
	maxi = 0
	while (i + add) % n != i or add == 0:
		if stored[(i + add) % n] > 0:
			maxi = max(maxi, add + stored[(i + add) % n])
		add += 1
	ans.append(maxi)
print(*ans)


from collections import defaultdict
(n, m) = map(int, input().split())
d = defaultdict(list)
e1 = []
e2 = []

def dis(i, j):
	if j >= i:
		return j - i
	else:
		return n + j - i
for k in range(m):
	(i, j) = map(int, input().split())
	d[i].append(dis(i, j))
num = [0 for i in range(n + 1)]
for i in range(1, n + 1):
	num[i] = len(d[i])
mnum = max(max(num), 2)
for i in range(1, n + 1):
	if num[i] == mnum - 1:
		d[i].sort(reverse=True)
		e1.append((i, d[i].pop()))
	if num[i] == mnum:
		d[i].sort(reverse=True)
		e2.append((i, d[i].pop()))
ans = []
for s in range(1, n + 1):
	tmp = []
	for (i, j) in e1:
		tmp.append(dis(s, i) + j)
	for (i, j) in e2:
		tmp.append(dis(s, i) + j + n)
	ttmp = max(tmp)
	ans.append((mnum - 2) * n + ttmp)
print(' '.join(map(str, ans)))


(n, m) = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(m)]
s = [[] for _ in range(n)]
for q in a:
	s[q[0] - 1].append(q[1] - 1)
d = []
for q in range(len(s)):
	if len(s[q]) == 0:
		d.append(0)
	else:
		p = min(s[q], key=lambda x: (x - q) % n)
		d.append((len(s[q]) - 1) * n + (p - q) % n)
ans = []
for q in range(len(d)):
	max1 = -1
	for q1 in range(len(d)):
		max1 = max(max1, d[q1] + (q1 - q) % n if d[q1] != 0 else 0)
	ans.append(max1)
print(*ans)


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter, OrderedDict
import threading
from copy import deepcopy

def main():
	(n, m) = map(int, input().split())
	station = [[] for _ in range(n + 1)]
	ans = [0] * (n + 1)
	for i in range(m):
		(a, b) = map(int, input().split())
		station[a].append(b)
	for i in range(1, n + 1):
		station[i].sort()
	for _ in range(1, n + 1):
		sta = deepcopy(station)
		destination = [0] * (n + 1)
		z = 0
		flag = False
		while 1:
			for i in range(1, n + 1):
				if i != _ and (not flag):
					continue
				if i == _ and (not flag):
					flag = True
				z += destination[i]
				destination[i] = 0
				if z == m:
					break
				if len(sta[i]):
					p = [-1, -1]
					for nx in sta[i]:
						if i > nx and nx + n - i > p[0]:
							p = [nx + n - i, nx]
						elif nx > i and nx - i > p[0]:
							p = [nx - i, nx]
					sta[i].remove(p[1])
					destination[p[1]] += 1
				ans[_] += 1
			if z == m:
				break
	print(*ans[1:])
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


(N, m) = [int(value) for value in input().split()]
candies = []
for _ in range(N):
	candies.append([])
for _ in range(m):
	(start, end) = [int(value) for value in input().split()]
	candies[start - 1].append(end - 1)
min_distantions = []
for start_pos in range(N):
	min_distantion = 0
	for shift in range(N):
		current_pos = (start_pos + shift) % N
		count_candies = len(candies[current_pos])
		if count_candies > 0:
			closest_candy = N - 1
			for candy_destination in candies[current_pos]:
				closest_candy = min(closest_candy, (N + candy_destination - current_pos) % N)
			min_distantion = max(min_distantion, closest_candy + shift + N * (count_candies - 1))
	min_distantions.append(min_distantion)
print(' '.join([str(distantion) for distantion in min_distantions]))


from collections import defaultdict
(n, m) = [int(i) for i in input().split(' ')]
lookup = defaultdict(list)
for i in range(1, m + 1):
	(a, b) = [int(j) for j in input().split(' ')]
	lookup[a].append(b)

def dist(n, a, b):
	return (b + n - a) % n

def helper(s, lookup):
	res = 0
	for i in range(1, n + 1):
		if not lookup[i]:
			continue
		minn = min([dist(n, i, j) for j in lookup[i]])
		res = max(res, dist(n, s, i) + (len(lookup[i]) - 1) * n + minn)
	return res
res = []
for i in range(1, n + 1):
	res.append(str(helper(i, lookup)))
print(' '.join(res))


(n, m) = (int(t) for t in input().split(' '))
candies = [set() for _ in range(n)]
candies_total = [0 for _ in range(n)]
for _ in range(m):
	(from_, to) = (int(t) - 1 for t in input().split(' '))
	candies[from_].add(to)
	candies_total[from_] += 1
stations_best = [0 for _ in range(n)]
for i in range(n):
	closest_distance = None
	for candy in candies[i]:
		distance = (candy + n - i) % n
		if closest_distance is None or distance < closest_distance:
			closest_distance = distance
	if closest_distance is not None:
		stations_best[i] = (candies_total[i] - 1) * n + closest_distance
print(*(max((stations_best[j] + (j + n - i) % n for j in range(n) if stations_best[j] > 0)) for i in range(n)))


def prog():
	(n, m) = map(int, input().split())
	d = {i: [] for i in range(1, n + 1)}
	from sys import stdin
	for i in range(m):
		(a, b) = map(int, stdin.readline().split())
		d[a].append(b)
	res = []
	for i in range(1, n + 1):
		lst = []
		for (j, x) in enumerate(d):
			(mn, k) = (100000, -1)
			for (k, y) in enumerate(d[x]):
				if x < y:
					a = y - x
				else:
					a = n - x + y
				if a < mn:
					mn = a
			if k > -1:
				if i <= x:
					b = x - i
				else:
					b = n - i + x
				lst.append(k * n + mn + b)
		res.append(max(lst))
	print(*res)
prog()