Stones on Grid

AtCoder
IDarc212_b
Time2000ms
Memory256MB
Difficulty
There is a grid with $N$ rows and $N$ columns. The cell at the $i$\-th row from the top and $j$\-th column from the left is called cell $(i,j)$. You perform the following in order of $i=1,2,\ldots,M$: * Operation $i$ : Choose either to place one stone on cell $(x_i, y_i)$ or not. If you place a stone, a cost of $c_i$ is incurred; otherwise, no cost is incurred. However, **you must place a stone in operation $1$**. Determine whether the following goal can be achieved, and if it can, find the minimum sum of costs incurred. * Goal : For every $i \ (1 \leq i \leq N)$, the number of stones placed in the $i$\-th row is equal to the number of stones placed in the $i$\-th column. ## Constraints * $1 \le N, M \le 2 \times 10^5$ * $1 \le x_i, y_i \le N$ * $1 \le c_i \le 10^9$ * $(x_i, y_i)$ are distinct. * All input values are integers. ## Input The input is given from Standard Input in the following format: $N$ $M$ $x_1$ $y_1$ $c_1$ $x_2$ $y_2$ $c_2$ $\vdots$ $x_M$ $y_M$ $c_M$ [samples]
Samples
Input #1
4 5
2 4 5
4 1 2
2 1 3
3 3 9
1 2 4
Output #1
11

The goal can be achieved by choosing to place a stone in operations $1,2,5$.
The sum of costs in this case is $5+2+4=11$. The total cost cannot be less than $11$ to achieve the goal, so the answer is $11$.
Input #2
3 3
1 1 1000000000
2 2 100000000
3 3 10000000
Output #2
1000000000

You must place a stone in operation $1$.
Input #3
2 1
1 2 10
Output #3
\-1
API Response (JSON)
{
  "problem": {
    "name": "Stones on Grid",
    "description": {
      "content": "There is a grid with $N$ rows and $N$ columns. The cell at the $i$\\-th row from the top and $j$\\-th column from the left is called cell $(i,j)$. You perform the following in order of $i=1,2,\\ldots,M$:",
      "description_type": "Markdown"
    },
    "platform": "AtCoder",
    "limit": {
      "time_limit": 2000,
      "memory_limit": 262144
    },
    "difficulty": "None",
    "is_remote": true,
    "is_sync": true,
    "sync_url": null,
    "sign": "arc212_b"
  },
  "statements": [
    {
      "statement_type": "Markdown",
      "content": "There is a grid with $N$ rows and $N$ columns. The cell at the $i$\\-th row from the top and $j$\\-th column from the left is called cell $(i,j)$. You perform the following in order of $i=1,2,\\ldots,M$:...",
      "is_translate": false,
      "language": "English"
    }
  ]
}
Full JSON Raw Segments