#include #include #include #include using namespace std; ifstream f ("ctc.in"); ofstream g ("ctc.out"); const int NMAX = 100000 + 1; int n, m, ind_crt, nrcomp; int rez = 0; int s[NMAX]; int lowlink[NMAX], ind[NMAX]; bool in_stack[NMAX]; stack st; vector graf[NMAX]; vector cost[NMAX]; vector < vector > componente; bool e_ciclu[NMAX]; bool comp[NMAX]; bool e_pus[NMAX]; void citeste() { int a, b, c; cin >> n >> m; for (int i = 1; i <= m; i++) { cin >> a >> b >> c; graf[a].push_back(b); cost[a].push_back(c); } } void tarjan(int nod, int suma, int c) { int l = graf[nod].size(), fiu, top; s[nod] = suma; ind[nod] = lowlink[nod] = ++ind_crt; st.push(nod); in_stack[nod] = true; bool ciclu_negativ = false; for (int i = 0; i < l; i++) { fiu = graf[nod][i]; if (!ind[fiu]) tarjan(fiu, suma + c, cost[nod][i]); if (in_stack[fiu]) { lowlink[nod]= min(lowlink[nod], lowlink[fiu]); if (suma + c - s[fiu] + cost[nod][i] < 0) ciclu_negativ = true; } } if (ciclu_negativ) e_ciclu[nod] = true; if (lowlink[nod] == ind[nod]) { nrcomp++; comp[nod] = nrcomp - 1; vector componenta_curenta; do { top = st.top(); st.pop(); in_stack[top] = false; componenta_curenta.push_back(top); } while (top != nod); componente.push_back(componenta_curenta); } } void scrie() { int rez = 0; for (int i = 1; i <= n; i++) if (e_ciclu[i]) { rez += componente[comp[i]].size(); for (int j = 0; j < componente[comp[i]].size(); j++) e_pus[componente[comp[i]][j]] = true; componente[comp[i]].clear(); for (int j = 1; j <= n; j++) { if (e_pus[j]) continue; if (e_ciclu[j]) continue; if (comp[j] == comp[i]) continue; int l = graf[j].size(); for (int k = 0; k < l; k++) { if (comp[graf[j][k]] == comp[i]) { rez++; e_pus[j] = true; break; } } } } cout << rez << '\n'; } int main() { citeste(); for (int i = 1; i <= n; i++) if (!ind[i]) tarjan(i, 0, 0); scrie(); return 0; }