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 5\,000$; $1 \leq m \leq 20\,000$) — 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:
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]))


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


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


import sys
input = sys.stdin.readline
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())
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)


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


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


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