Problem:
Score : 1200 points

Problem Statement

We have N boxes numbered 1 to N, and M balls numbered 1 to M.
Currently, Ball i is in Box A_i.

You can do the following operation:

Choose a box containing two or more balls, pick up one of the balls from that box, and put it into another box.

Since the balls are very easy to break, you cannot move Ball i more than C_i times in total.
Within this limit, you can do the operation any number of times.

Your objective is to have Ball i in Box B_i for every i (1 \leq i \leq M).
Determine whether this objective is achievable.
If it is, also find the minimum number of operations required to achieve it.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i,B_i \leq N

1 \leq C_i \leq 10^5

In the situation where the objective is achieved, every box contains one or more balls.
That is, for every i (1 \leq i \leq N), there exists j such that B_j=i.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1 C_1
A_2 B_2 C_2
\vdots
A_M B_M C_M

Output

If the objective is unachievable, print -1; if it is achievable, print the minimum number of operations required to achieve it.

Sample Input 1

3 3
1 2 1
2 1 1
1 3 2

Sample Output 1

3

We can achieve the objective in three operations, as follows:

Pick up Ball 1 from Box 1 and put it into Box 2.

Pick up Ball 2 from Box 2 and put it into Box 1.

Pick up Ball 3 from Box 1 and put it into Box 3.

Sample Input 2

2 2
1 2 1
2 1 1

Sample Output 2

-1

Sample Input 3

5 5
1 2 1
2 1 1
1 3 2
4 5 1
5 4 1

Sample Output 3

6

Sample Input 4

1 1
1 1 1

Sample Output 4

0

Solution in C++ (GCC 9.2.1) (judge verdict: Accepted)

#include<bits/stdc++.h>

using namespace std;
#define ll long long

const int N = 100005;
int n, m, cf, cg, cnt, ans, a[N], b[N], c[N], cc[N], d[N], dd[N], f[N], g[N], p[N];
ll sum, cyc;
bool vis[N];
int main() {
	// freopen("C:\\Users\\Cekavis\\Downloads\\01-63.txt", "r", stdin);
	scanf("%d%d", &n, &m);
	for(int i=1; i<=m; ++i){
		scanf("%d%d%d", a+i, b+i, c+i);
		++d[a[i]], ++dd[b[i]], p[a[i]]=b[i], cc[a[i]]=c[i];
		if(a[i]!=b[i]) sum+=c[i]-1, ++ans;
	}
	for(int i=1; i<=m; ++i) if(a[i]==b[i]){
		if(dd[a[i]]>1 || d[a[i]]>1){
			if(c[i]>1) f[++cf]=c[i]-1;
		}
		else if(c[i]>2) g[++cg]=c[i]-2;
	}
	for(int i=1; i<=n; ++i) if(!vis[i] && d[i]==1 && dd[i]==1 && p[i]!=i){
		int u=i;
		ll s=0;
		while(!vis[u] && d[u]==1 && dd[u]==1) vis[u]=1, s+=cc[u]-1, u=p[u];
		if(u==i) ++ans, ++cnt, cyc+=s;
	}
	sort(f+1, f+cf+1, greater<int>()), sort(g+1, g+cg+1, greater<int>());
	int mn=cnt?1e9:0;
	for(int i=sum==cyc, j=0; i<=cf; ++i){
		sum+=f[i];
		while(j<cg && sum<cnt) sum+=g[++j];
		while(j && sum-g[j]>=cnt) sum-=g[j--];
		if(sum>=cnt) mn=min(mn, i+j*2);
	}
	if(mn==1e9) puts("-1"); else printf("%d\n", ans+mn);
	return 0;
}