#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
long long ans = 0;
vector<vector<pair<int, int>>> g(n + m);
for (int i = 1; i < n + m; i++) {
int p, c;
cin >> p >> c;
--p;
g[p].emplace_back(i, c);
g[i].emplace_back(p, c);
ans += c;
}
long long sum = 0;
for (auto [_, w] : g[0]) {
sum += w;
}
ans -= sum;
long long avg = sum / int(g[0].size());
for (auto [_, w] : g[0]) {
ans += abs(avg - w);
}
cout << ans << '\n';
return 0;
}