The minimal weight is at least $$$1$$$ since $$$1$$$ divides any integer (so $$$1$$$ divides $$$p_1$$$).
Since $$$k+1$$$ does not divide $$$k$$$, a permutation with weight equal to $$$1$$$ is: $$$[n,1,2,\cdots,n-1]$$$.
See the party as a graph.
Divide the vertices into two categories according to their degrees' parity.
Let's consider the case where $$$m$$$ is odd only, since if $$$m$$$ is even the answer is $$$0$$$.
Assume that you delete $$$x$$$ vertices with even degrees and $$$y$$$ vertices with odd degrees.
If $$$y \geq 1$$$, then only deleting one vertex with odd degree would have been enough.
If $$$y=0$$$, then the parity of the edges at the end is determined only by the number of edges whose both endpoints are deleted. In particular, there must be at least two adjacent vertices deleted with even degree.
Thus, an optimal solution either has $$$(x, y) = (0, 1)$$$ or $$$(x, y) = (2, 0)$$$ and the two vertices are adjacent.
One can iterate over all possible solutions with such structure and take the optimal one.
Total time complexity: $$$O(n)$$$.
The picture must consist of some stripes with at least $$$2$$$ rows or at least $$$2$$$ columns.
When $$$n$$$ is odd and all $$$\lfloor \frac{a_i}{m} \rfloor=2$$$, we cannot draw a beautiful picture using row stripes.
Let's first prove hint1 first.
If there is a pair of toroidal neighbors with different colors. For example, $$$col_{x,y}=a$$$ and $$$col_{x+1,y}=b(a\neq b)$$$. Then we will find $$$col_{x-1,y}=col_{x,y+1}=col_{x,y-1}=a$$$,$$$col_{x+2,y}=col_{x+1,y+1}=col_{x+1,y-1}=b$$$ must hold. Then we find another two pairs of toroidal neighbors $$$col_{x,y+1},col_{x+1,y+1}$$$ and $$$col_{x,y-1},col_{x+1,y-1}$$$. Repeat such process, we will find the boundary should be like:
\begin{center} \includegraphics[scale=0.8]{editorial.png} \end{center}
Similar, the boundaries can be vertical lines, but horizontal lines and vertical lines can not exist in one picture.
So the pattern should be row stripes both with at least $$$2$$$ rows or column stripes both with at least $$$2$$$ columns.
Check if one can draw a beautiful picture with row stripes only or with column stripes only. We consider only the case of row stripes, the reasoning is analogous for column stripes.
If it is possible, then $$$\sum_{i=1}^{n} \lfloor \frac{a_i}{m} \rfloor \geq n$$$ must hold.
If $$$n$$$ is even, then such a condition is enough.
If $$$n$$$ is odd, there must be some $$$\lfloor \frac{a_i}{m} \rfloor \geq 3$$$. In this case, you can draw a beautiful picture using such algorithm:
\begin{itemize}
\item Sort $$$a_i$$$ from large to small.
\item Draw $$$2$$$ rows stripes of each color if possible.
\item If the picture still has some rows empty, insert new rows into each stripe.
\end{itemize}
Total time complexity: $$$O(n)$$$.