#include "testlib.h"
#include <vector>
#include <iostream>
#include <string>
#include "testlib.h"

using namespace std;


template<typename T>
string to_string(const T& x) 
{
    stringstream ss;
    ss << x;
    return ss.str();
}

std::string check(InStream &out, const vector<pair<int, int>>& a, long long& max_res) 
{
    vector<pair<int, int>> ans_res;
	int n = 0;
	while (!out.seekEof()) {
		++n;
		int a = out.readInt();
		int b = out.readInt();
		if (b < a) {
			return "Left border of answer is more than right";
		}
		ans_res.push_back({a, b});
	}
	if (ans_res.size() != a.size())
		return "Answer has incorrect number of output lines";
	
	for (int i = 0; i < a.size(); ++i) {
	    if (ans_res[i].first == -1)
	        continue;
		if (!(ans_res[i].first >= a[i].first && ans_res[i].second <= a[i].second)) {
			return "Answer doesn't satisfy input borders";
		}
	}
	sort(ans_res.begin(), ans_res.end());
	bool cor = 1;
	long long now = 0;
	for (int i = 0; i < ans_res.size(); ++i) {
		if (ans_res[i].first == -1)
			continue;
		if (i > 0 && ans_res[i].first < ans_res[i - 1].second) {
			cor = 0;
			break;
		}
		now += ans_res[i].second - ans_res[i].first + 1;
		if (i > 0)
			now -= (ans_res[i].first == ans_res[i - 1].second);
	}
	if (!cor) {
		return "Answer's segments intersect";
	}
	max_res = now;
	return "ok";
}

int main(int argc, char* argv[]) {
    registerTestlibCmd(argc, argv);
    int n;
    n = inf.readInt();
    vector<pair<int, int>> mas(n);
    for (int i = 0; i < n; ++i) {
        mas[i].first = inf.readInt();
        mas[i].second = inf.readInt();
    }
	long long t_ans = 0;
	long long t_cur = 0;
    std::string s_ans = check(ans, mas, t_ans);
    std::string s_cur = check(ouf, mas, t_cur);
    quitif(s_ans != "ok", _fail, s_ans.c_str());
    quitif(s_cur != "ok", _wa, s_cur.c_str());
    quitif(t_ans != t_cur, _wa, "Incorrect answer: need: %d but get: %d", t_ans, t_cur);
    quitf(_ok, "%d", t_ans);
}
