- 火烧赤壁
- 2013-12-06 11:30:01 @
n<20000啊
program huoshao;
var a,b:array[-10..20100] of longint;
i,j,k,n,m,ans,head,tail:longint;
procedure qsort(l, h:integer);
var i,j,t,m:integer;
begin
i := l;
j := h;
m := a[(i+j) div 2];
repeat
while a[i] < m do inc(i);
while m < a[j] do dec(j);
if i <= j then
begin
t := a[i];
a[i] := a[j];
a[j] := t;
t:=b[i];
b[i]:=b[j];
b[j]:=t;
inc(i);
dec(j);
end;
until i > j;
if j > l then qsort(l, j);
if i < h then qsort(i, h);
end;
begin
readln(n);
for i:=1 to n do
begin
readln(a[i],b[i]);
end;
qsort(1,n);
head:=a[1];
tail:=-999999999;
for i:=1 to n do
if tail<b[i] then tail:=b[i];
ans:=tail-head;
tail:=b[1];
for i:=1 to n do
begin
if a[i]>tail then ans:=ans-a[i]+tail;
if b[i]>tail then tail:=b[i];
end;
writeln(ans);
end.