#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
using namespace std;
#define int long long
void _()
{
int n;
cin >> n;
int ans = 0;
int pref = 0;
priority_queue<int>pq;
for (int i = 1; i <= n; i++) {
int a, b;
cin >> a >> b;
pref += a - b;
if (i == n) break;
int x = pref;
if (x < 0) {
ans += -x;
x = 0;
}
ans += x;
pq.push(x);
pq.push(x);
pq.pop();
}
int extra = pref;
while (!pq.empty()) {
ans -= min(extra, pq.top());
pq.pop();
}
cout << ans << endl;
}
signed main()
{
int tt = 1;
// cin >> tt;
while(tt--)
{
_();
}
}