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

Solutions:
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)))


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()


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) = [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()


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)))


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)


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))


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)))


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)


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=' ')


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
(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))


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()


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=' ')


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)))


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)))


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)))