#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
int no_of_transaction,friends;
cin>>no_of_transaction>>friends;
int x,y,amount;
//make 1d array to store the net amount that each person has to take at ana end
int net[100000]={0};
while(no_of_transaction)
{
cin>>x>>y>>amount;
net[x]-=amount;
net[y]+=amount;
}
//iterate over all the node and check whether some transaction is take place
multiset<int> m;
//init a list and sort it=> multiset
for(int i=0;i<friends;i++)
{
if(net[i]!=0)
{
m.insert(net[i]);
}
}
//pop out two person from left and right and try to settle them
int count1=0;
while(!m.empty())
{
auto low=m.begin();
auto high=prev(m.end());
int debit=*low;
int credit=*high;
//erase these element from multiset
m.erase(low);
m.erase(high);
//settlement
int settlement_amount=min(-debit,credit);
count1++;
//transger settleamount from debit to credit
debit+=settlement_amount;
credit-=settlement_amount;
//it is sure one of them becomes is zero
if(debit!=0)
{
m.insert(debit);
}
if(credit!=0)
{
m.insert(credit);
}
}
cout<<count1<<endl;
}