#include <bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
#define fi first
#define se second
#define lson p << 1
#define rson p << 1 | 1
#define ll long long
const int maxn = 1e6 + 5, inf = 1e9, maxm = 4e4 + 5, base = 37;
const int N = 4e3;
const int mod = 1e9 + 7;
// const int mod = 998244353;
// const __int128 mod = 212370440130137957LL;
int n, m;
int a[maxn];
//long long ? maxn ? n? m?
void solve(){
ll res = 0;
cin >> n >> m;
vector<vector<int>> G(n + 1);
vector<vector<pair<int, int>>> req(n + 1);
vector<int> ind(n + 1), f(n + 1, 1);
for(int i = 1; i <= m; i++){
int x, y, z;
cin >> x >> y >> z;
G[y].pb(x);
G[z].pb(x);
ind[x] += 2;
req[x].pb({y, z});
}
int cnt = 0;
queue<int> q;
for(int i = 1; i <= n; i++){
if(ind[i] == 0){
q.push(i);
cnt++;
f[i] = 1;
}
}
while(!q.empty()){
int u = q.front();
q.pop();
for(auto [x, y] : req[u]){
f[u] = max(f[u], f[x] + f[y]);
}
res += f[u];
if(res > inf){
cout << -1 << '\n';
return;
}
for(auto v : G[u]){
ind[v]--;
if(ind[v] == 0){
q.push(v);
cnt++;
}
}
}
if(cnt != n){
cout << -1 << '\n';
return;
}
cout << res << '\n';
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout << fixed << setprecision(9);
int T = 1;
// cin >> T;
while (T--)
{
solve();
}
return 0;
}
2024广东省赛 I.不等式
最新推荐文章于 2024-11-15 21:18:47 发布