import * as fs from 'fs';
import { EDEADLK } from 'constants';

// main
function main(input: string[]) {
    // param
    var x: number = 0;
    var n: number = 0;
    var pn: number[] = [];
    var ans: number = 0;
    // init
    [x, n] = input.shift().split(" ").map(x => Number(x));
    if (0 < n) {
        pn = input.shift().split(" ").map(x => Number(x));
    }
    // solve
    var pa = new Array(101).fill(0);
    for (var pnx = 0; pnx < pn.length; pnx++) {
        pa[pn[pnx]] = 1;
    }
    for (var i = 0; i < pa.length; i++) {
        if (pa[x - i] == 0) {
            ans = x - i;
            break;
        }
        if (pa[x + i] == 0) {
            ans = x + i;
            break;
        }
    }
    // answer
    console.log(ans);
}

// graph lib
/*
function GRAPH_enumPattern(cur: number[], pat: number[][]): number[][] {
    var arr = [];
    for (var patx = 0; patx < pat.length; patx++) {
        var pos = [cur[0] + pat[patx][0], cur[1] + pat[patx][1]];
        arr.push(pos);
    }
    return arr;
}
*/

// math lib
/*
function Math_max(arr: number[]): number { return arr.reduce((x, y) => Math.max(x, y)); }
function Math_min(arr: number[]): number { return arr.reduce((x, y) => Math.min(x, y)); }
function Math_gcd(): number {
    var ans = arguments[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < arguments.length; i++) {
        ans = f(ans, arguments[i]);
    }
    return ans
};
function Math_gcdArray(values: number[]): number {
    var ans = values[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < values.length; i++) {
        ans = f(ans, values[i]);
    }
    return ans
};
function Math_lcm(): number {
    var a = arguments
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_lcmArray(values: number[]): number {
    var a = values
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_primeList(value: number): number[] {
    var ans = [];
    var arr = new Array(value).fill(0);
    for (var i = 2; i < value; i++) {
        if (arr[i] == 0) {
            for (var j = i; j < value; j += i) {
                if (arr[j] == 0) arr[j] = i;
            }
        }
    }
    for (var i = 2; i < value; i++) {
        if (arr[i] == i) ans.push(i);
    }
    return ans;
}
function Math_primeFactor(p: number[], value: number): number[][] {
    var ans: number[][] = [];
    var valmax = value / 2;;
    for (var i = 0; i < p.length; i++) {
        var prime = p[i];
        if (valmax < prime) break;
        var count = 0;
        while (value % prime == 0) {
            value /= prime;
            count++;
        }
        if (count != 0) {
            ans.push([prime, count]);
        }
        if (value == 1) break;
    }
    return ans;
}
*/

// union-find lib
/*
var g_uf_root: number[];
var g_uf_count: number[];
function UF_initRoot(num: number) {
    g_uf_root = new Array(num).fill(-1);
    g_uf_count = new Array(num).fill(1);
}
function UF_getRoot(index: number) {
    if (g_uf_root[index] < 0) {
        return index;
    } else {
        var work0: number = UF_getRoot(g_uf_root[index]);
        g_uf_root[index] = work0;
        return work0
    }
}
function UF_mergeRoot(a: number, b: number) {
    var root0: number = UF_getRoot(a);
    var root1: number = UF_getRoot(b);
    if (root0 == root1) return;
    if (root0 > root1) [root0, root1] = [root1, root0];
    g_uf_count[root0] += g_uf_count[root1];
    g_uf_count[root1] = 0;
    g_uf_root[root1] = root0;
}
*/

// entrypoint
function entrypoint() {
    try {
        // linux
        var input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        // windows
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            main(input);
        });
    }
}
entrypoint();


import * as fs from 'fs';
import { EDEADLK } from 'constants';

// main
function main(input: string[]) {
    // param
    var x: number = 0;
    var n: number = 0;
    var pn: number[] = [];
    var ans: number = 0;
    // init
    [x, n] = input.shift().split(" ").map(x => Number(x));
    if (input.length > 0) {
        pn = input.shift().split(" ").map(x => Number(x));
    }
    // solve
    var pa = new Array(101).fill(0);
    for (var pnx = 0; pnx < pn.length; pnx++) {
        pa[pn[pnx]] = 1;
    }
    ans = x;
    for (var i = 0; i < pa.length; i++) {
        if (pa[x - i] == 0) {
            ans = x - i;
            break;
        }
        if (pa[x + i] == 0) {
            ans = x + i;
            break;
        }
    }
    // answer
    console.log(ans);
}

// graph lib
/*
function GRAPH_enumPattern(cur: number[], pat: number[][]): number[][] {
    var arr = [];
    for (var patx = 0; patx < pat.length; patx++) {
        var pos = [cur[0] + pat[patx][0], cur[1] + pat[patx][1]];
        arr.push(pos);
    }
    return arr;
}
*/

// math lib
/*
function Math_max(arr: number[]): number { return arr.reduce((x, y) => Math.max(x, y)); }
function Math_min(arr: number[]): number { return arr.reduce((x, y) => Math.min(x, y)); }
function Math_gcd(): number {
    var ans = arguments[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < arguments.length; i++) {
        ans = f(ans, arguments[i]);
    }
    return ans
};
function Math_gcdArray(values: number[]): number {
    var ans = values[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < values.length; i++) {
        ans = f(ans, values[i]);
    }
    return ans
};
function Math_lcm(): number {
    var a = arguments
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_lcmArray(values: number[]): number {
    var a = values
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_primeList(value: number): number[] {
    var ans = [];
    var arr = new Array(value).fill(0);
    for (var i = 2; i < value; i++) {
        if (arr[i] == 0) {
            for (var j = i; j < value; j += i) {
                if (arr[j] == 0) arr[j] = i;
            }
        }
    }
    for (var i = 2; i < value; i++) {
        if (arr[i] == i) ans.push(i);
    }
    return ans;
}
function Math_primeFactor(p: number[], value: number): number[][] {
    var ans: number[][] = [];
    var valmax = value / 2;;
    for (var i = 0; i < p.length; i++) {
        var prime = p[i];
        if (valmax < prime) break;
        var count = 0;
        while (value % prime == 0) {
            value /= prime;
            count++;
        }
        if (count != 0) {
            ans.push([prime, count]);
        }
        if (value == 1) break;
    }
    return ans;
}
*/

// union-find lib
/*
var g_uf_root: number[];
var g_uf_count: number[];
function UF_initRoot(num: number) {
    g_uf_root = new Array(num).fill(-1);
    g_uf_count = new Array(num).fill(1);
}
function UF_getRoot(index: number) {
    if (g_uf_root[index] < 0) {
        return index;
    } else {
        var work0: number = UF_getRoot(g_uf_root[index]);
        g_uf_root[index] = work0;
        return work0
    }
}
function UF_mergeRoot(a: number, b: number) {
    var root0: number = UF_getRoot(a);
    var root1: number = UF_getRoot(b);
    if (root0 == root1) return;
    if (root0 > root1) [root0, root1] = [root1, root0];
    g_uf_count[root0] += g_uf_count[root1];
    g_uf_count[root1] = 0;
    g_uf_root[root1] = root0;
}
*/

// entrypoint
function entrypoint() {
    try {
        // linux
        var input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        // windows
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            main(input);
        });
    }
}
entrypoint();


# coding: utf-8

a,b,c = input().rstrip().split(" ")

if a[-1] == b[0] and b[-1] == c[0]:
    print("YES")
else:
    print("NO")


A, B, C = input().split()
if A[-1] == B[0] and B[-1] == C[0]:
    print("YES")
else:
    print("NO")


A, B, C = input().split()
if A[-1] == B[0] and B[-1] == C[0]:
  print("YES")
else :
  print("NO")


a,b,c=input().split()
if a[-1]==b[0] and b[-1]==c[0]:
  print("Yes")
else:
  print("No")


a,b,c=list(input().split())
if a[-1]==b[1] and b[-1]==c[1]:
  print("Yes")
else:
  print("No")


a,b,c=input().split()
if a[-1]==b[1] and b[-1]==c[1]:
  print("Yes")
else:
  print("No")


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class Main {

	private static final int MOD = 1000000007;

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		String A = sc.next();
		String B = sc.next();
		String C = sc.next();

		if (A.endsWith(B.substring(0, 1)) && B.endsWith(C.substring(0, 1))) {
			System.out.println("YES");
		} else {
			System.out.println("NO");
		}
	}

	private static boolean isDebug = System.getProperty("sun.desktop") != null;

	private static void debug(Object... o) {
		if (isDebug) {
			System.err.println(Arrays.deepToString(o));
		}
	}

	public static class Scanner {
		private BufferedInputStream inputStream;

		public Scanner(InputStream in) {
			inputStream = new BufferedInputStream(in);
		}

		public int nextInt() throws IOException {
			int num = 0;
			int sign = 1;

			int read = skip();
			if (read == '-') {
				sign = -1;
				read = inputStream.read();
			}

			do {
				num = num * 10 + sign * (read - 0x30);
			} while ((read = inputStream.read()) > 0x20);

			return num;
		}

		public void fill(int[] a) throws IOException {
			for (int i = 0; i < a.length; i++) {
				a[i] = nextInt();
			}
		}

		public void fill(int[] a, int[] b) throws IOException {
			if (a.length != b.length) {
				throw new IllegalArgumentException();
			}

			for (int i = 0; i < a.length; i++) {
				a[i] = nextInt();
				b[i] = nextInt();
			}
		}

		public void fill(int[] a, int[] b, int[] c) throws IOException {
			if (a.length != b.length || b.length != c.length) {
				throw new IllegalArgumentException();
			}

			for (int i = 0; i < a.length; i++) {
				a[i] = nextInt();
				b[i] = nextInt();
				c[i] = nextInt();
			}
		}

		public long nextLong() throws IOException {
			long num = 0;

			int read = skip();
			do {
				num = num * 10 + (read - 0x30);
			} while ((read = inputStream.read()) > 0x20);

			return num;
		}

		public void fill(long[] a) throws IOException {
			for (int i = 0; i < a.length; i++) {
				a[i] = nextLong();
			}
		}

		public void fill(long[] a, long[] b) throws IOException {
			if (a.length != b.length) {
				throw new IllegalArgumentException();
			}

			for (int i = 0; i < a.length; i++) {
				a[i] = nextLong();
				b[i] = nextLong();
			}
		}

		public long[] nextLong(int n) throws IOException {
			long[] array = new long[n];
			for (int i = 0; i < n; i++) {
				array[i] = nextLong();
			}

			return array;
		}

		public String next() throws IOException {
			StringBuilder builder = new StringBuilder();

			int read = skip();
			do {
				builder.append((char) read);
			} while ((read = inputStream.read()) > 0x20);

			return builder.toString();
		}

		private int skip() throws IOException {
			int read;
			while ((read = inputStream.read()) <= 0x20)
				;

			return read;
		}
	}
}


import java.io.*;
import java.util.*;

public class Main {

	final static long MOD = 1000000007;
	public static String[] Ws = null;
	public static int wsIndx = 0;
	public static BufferedReader in = null;
	public static void main(String[] args) throws Exception {
		solution(args);
		if(in!=null){
			in.close();
		}
	}

	public static void solution(String[] args) throws Exception{

		char[] a = nextString().toCharArray();
		char[] b = nextString().toCharArray();
		char[] c = nextString().toCharArray();

		String ans = "NO";

		if(a[a.length-1]==b[0]&&b[b.length-1]==c[0])
			ans="YES";

		System.out.println(ans);

	}

	public static boolean isPalindromicStr(String s) {
		int h = 0;
		int t = s.length() - 1;
		while (h <= t) {
			if (s.charAt(h) != s.charAt(t)) {
				break;
			}
			h++;
			t--;
		}
		if (h > t) {
			return true;
		}
		return false;
	}
	public static String[] toStringArray(String s) {
		String[] tmp = new String[s.length()];
		char[] c = s.toCharArray();
		for (int i = 0; i < tmp.length; i++) {
			tmp[i] = String.valueOf(c[i]);
		}
		return tmp;
	}

	public static void check() throws Exception{
		if(in == null){
			in = new BufferedReader(new InputStreamReader(System.in));
		}
		if(Ws==null || Ws.length<=wsIndx){
			Ws = in.readLine().split(" ");
			wsIndx=0;
		}
	}
	public static int nextInt()throws Exception{
		check();
		return Integer.parseInt(Ws[wsIndx++]);
	}

	public static long nextLong()throws Exception{
		check();
		return Long.parseLong(Ws[wsIndx++]);
	}

	public static String nextString()throws Exception{
		check();
		return Ws[wsIndx++];
	}

	public static int[] nextInts()throws Exception{
		check();
		int[] tmp = new int[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Integer.parseInt(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static long[] nextLongs()throws Exception{
		check();
		long[] tmp = new long[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Long.parseLong(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static String[] nextStrings()throws Exception{
		check();
		wsIndx=Ws.length;
		return Ws;
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) {
        try {
            // 標準入力
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            String strArr[] = br.readLine().split(" ");
            String str1 = strArr[0];
            int str1Length = str1.length();
            String str2 = strArr[1];
            int str2Length = str2.length();
            String str3 = strArr[2];
            if (str1.substring(str1Length - 1, str1Length).equals(str2.substring(0, 1)) && str2.substring(str2Length - 1, str2Length).equals(str3.substring(0, 1))) {
            	System.out.println("YES");
            } else {
            	System.out.println("NO");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


import java.util.*;
public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String A = sc.next();
    String B = sc.next();
    String C = sc.next();
    if(a.charAt(a.length()-1) == b.charAt(0) && b.charAt(b.length()-1) == c.charAt(0)) {
		System.out.println("YES");
	}else {
		System.out.println("NO");
	}
  }
}


import java.util.*; import java.io.*; import java.math.*;
public class Main{
	//Don't have to see. start------------------------------------------
	static class InputIterator{
		ArrayList<String> inputLine = new ArrayList<String>(1024);
		int index = 0; int max; String read;
		InputIterator(){
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			try{
				while((read = br.readLine()) != null){
					inputLine.add(read);
				}
			}catch(IOException e){}
			max = inputLine.size();
		}
		boolean hasNext(){return (index < max);}
		String next(){
			if(hasNext()){
				return inputLine.get(index++);
			}else{
				throw new IndexOutOfBoundsException("There is no more input");
			}
		}
	}
	static HashMap<Integer, String> CONVSTR = new HashMap<Integer, String>();
	static InputIterator ii = new InputIterator();//This class cannot be used in reactive problem.
	static PrintWriter out = new PrintWriter(System.out);
	static void flush(){out.flush();}
	static void myout(Object t){out.println(t);}
	static void myerr(Object t){System.err.print("debug:");System.err.println(t);}
	static String next(){return ii.next();}
	static boolean hasNext(){return ii.hasNext();}
	static int nextInt(){return Integer.parseInt(next());}
	static long nextLong(){return Long.parseLong(next());}
	static double nextDouble(){return Double.parseDouble(next());}
	static ArrayList<String> nextStrArray(){return myconv(next(), 8);}
	static ArrayList<String> nextCharArray(){return myconv(next(), 0);}
	static ArrayList<Integer> nextIntArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Integer> ret = new ArrayList<Integer>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Integer.parseInt(input.get(i)));
		}
		return ret;
	}
	static ArrayList<Long> nextLongArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Long> ret = new ArrayList<Long>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Long.parseLong(input.get(i)));
		}
		return ret;
	}
	static String myconv(Object list, int no){//only join
		String joinString = CONVSTR.get(no);
		if(list instanceof String[]){
			return String.join(joinString, (String[])list);
		}else if(list instanceof ArrayList){
			return String.join(joinString, (ArrayList)list);
		}else{
			throw new ClassCastException("Don't join");
		}
	}
	static ArrayList<String> myconv(String str, int no){//only split
		String splitString = CONVSTR.get(no);
		return new ArrayList<String>(Arrays.asList(str.split(splitString)));
	}
	public static void main(String[] args){
		CONVSTR.put(8, " "); CONVSTR.put(9, "\n"); CONVSTR.put(0, "");
		solve();flush();
	}
	//Don't have to see. end------------------------------------------
	static void solve(){//Here is the main function
		ArrayList<String> one = nextStrArray();
		ArrayList<String> A = myconv(one.get(0), 0);
		ArrayList<String> B = myconv(one.get(1), 0);
		ArrayList<String> C = myconv(one.get(2), 0);
		if(A.get(A.size() - 1).equals(B.get(0)) && A.get(B.size() - 1).equals(C.get(0))){
			myout("YES");
		}else{
			myout("NO");
		}
	}
	//Method addition frame start

	//Method addition frame end
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String a = sc.next();
		String b = sc.next();
		String c = sc.next();

		System.out.println(String.valueOf(a.charAt(a.length() - 1)).equals(String.valueOf(b.charAt(0))) &&
				String.valueOf(b.charAt(b.length() - 1)).equals(String.valueOf(c.charAt(0)))? "Yes" : "No");

		sc.close();

	}

}


#include<cstdio>
#include<cstring>
int main()
{
	char a[100],b[100],c[100];
	scanf("%s%s%s",a,b,c);
	int x = strlen(a), y = strlen(b), z = strlen(c);
	if(a[x-1] == b[0] && b[y-1] == c[0]) printf("YES");
	else printf("NO");
	return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>

int main(){
	char a[20],b[20],c[20];

	scanf("%s %s %s",a,b,c);

	if(a[strlen(a)-1]==b[0]&&b[strlen(b)-1]==c[0]){
		printf("YES\n");
	}else{
		printf("NO\n");
	}

	return 0;
}


#include <cstdio>
#include <cstring>
using namespace std;
char s1[20],s2[20],s3[20];
int main() {
	scanf("%s %s %s",s1,s2,s3);
	if (s1[strlen(s1)-1]==s2[0]&&s2[strlen(s2)-1]==s3[0])
		printf("YES\n");
	else printf("NO\n");
	return 0;
}


#include <iostream>

int main () {
	std::string a, b, c;

  std::cin >> a >> b >> c;

  if(a.substr(a.size() -1, 1) == b.substr(0, 1) && b.substr(b.size() -1, 1) == c.substr(0, 1)) {
  	std::cout << "YES" << std::endl;
  }else {
  	std::cout << "NO" << std::endl;
  	std::cout << a.substr(a.size() -1, 1) << std::endl;
  	std::cout << b.substr(0, 1) << std::endl;

  }
}


#include<iostream>
#include<string>
using namespace std;
int main() {
	string a, b, c;
	cin >> a >> b >> c;
	if (a.back() == b[0] && b.back() == c[0]) cout << "YES" << endl;
	cout << "NO" << endl;
	return 0;
}


#include <bits/stdc++.h>

#define debug_input freopen("stdin.in", "r", stdin)
#define debug_output freopen("stdout.out", "w", stdout)
#define FOR(i, a, b) for(int i = a; i <= b; i++)
#define FORALL(i, n) for(int i = 0; i < n; i++)
#define FORD(i, a, b) for(int i = a; i >= b; i--)
#define SORT(a) sort(a.begin(), a.end())
#define REV(a) reverse(a.begin(), a.end())
#define NP(a) next_permutation(a.begin(), a.end())
#define ALL(a) a.begin, a.end()
#define mp make_pair
#define pb push_back
#define endl "\n"
using namespace std;

typedef long long ll;
typedef unsigned long long ull;

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0);

	string a, b, c, s[3];
	cin >> s[0] >> s[1] >> s[2];
	sort(s, s + 3);

	do {
		a = s[0], b = s[1], c = s[2];
		if(a[a.length() - 1] == b[0] && b[b.length()] == c[0]) {
			cout << "YES" << endl;
			return 0;
		}
	} while(next_permutation(s, s + 3));
	cout << "NO" << endl;
	return 0;
}


//
//  main.c
//  abc060_a
//
//  Created by Ding Chao on 4/29/17.
//  Copyright © 2017 Ding Chao. All rights reserved.
//

#include <stdio.h>

int main(int argc, const char * argv[]) {
    // insert code here...
    char end = 0, mid = 0, ini = 0;
    while (mid != ' ') {
        end = mid;
        mid = ini;
        ini = getchar();
    }
    if (end != ini) {
        printf("NO");
        return 0;
    }
    else {
        mid = 0;
        while (mid != ' ') {
            end = mid;
            mid = ini;
            ini = getchar();
        }
        if (end != ini) {
            printf("NO");
        }
        else
            printf("YES");
    }
    return 0;
}


#include <stdio.h>
#include <string.h>

int main () {
    char a[10];
    char b[10];
    char c[10];
    scanf("%s %s %s", a, b, c);
    if (a[strlen(a) - 1] == b[0] && b[strlen(b) - 1] == c[0]) {
        printf("YES\n");
    } else {
        printf("NO\n");
    }
}


#include<stdio.h>
#include<string.h>
int main()
{
	char a[11],b[11],c[11];
	int n=0;
	scanf("%s",a);
	scanf("%s",b);
	scanf("%s",c);
	if(a[strlen(a)-1]==b[0]&&b[strlen(b)-1]==c[0])  printf("YES");
	else printf("NO");
	return 0;
}


#include <stdio.h>

int main (){

    char str[10005];
    scanf("%s", str);
    int flag = 0;
    for(int i = 0;str[i] != '\0';i++){
    	if(str[i] == ' '){
    		if(str[i-1] != str[i+1]){
    			flag = 1;
    			break;
			}
		}
	}
	flag == 0 ? puts("YES") : puts("NO");

    return 0;
}


#include <stdio.h>

int main (){

    char str[1005];
    scanf("%s", str);
    int flag = 0;
    for(int i = 0;str[i] != '\0';i++){
    	if(str[i] == ' '){
    		if(str[i-1] != str[i+1]){
    			flag = 1;
			}
		}
	}
	flag == 0 ? puts("YES") : puts("NO");

    return 0;
}


#include <stdio.h>

int main (){

    char str[1005];
    scanf("%s", str);
    int flag = 0;
    for(int i = 0;str[i] != '\0';i++){
    	if(str[i] == 'a'){
    		if(str[i-1] != str[i+1]){
    			flag = 1;
			}
		}
	}
	flag == 0 ? puts("YES") : puts("NO");

    return 0;
}


function Main(input) {
  input = input.trim()
  input = input.split(" ");
if(input[1].slice( 0,1 )==input[0].slice( -1 )&&input[2].slice( 0,1 )==input[1].slice( -1 )){
  console.log("YES");
}else{
  console.log("NO");
}}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";
const Main = function(input){
	let xs = input.trim().split(' ');
    let z = xs[1].split('');
    let a = xs[0].split('').reverse();
    let b = xs[1].split('').reverse();
    let c = xs[2].split('');

    if(a[0] == z[0] && b[0] == c[0]){
      console.log('YES');
    }else{
      console.log('NO');
    }

}
Main(require('fs').readFileSync('/dev/stdin','utf8'));


"use strict";
const Main = function(input){
	let xs = input.trim().split(' ');
    let a =xs[0].charAt(xs[0].length-1);
    let b =xs[1].charAt(0);
    let c =xs[1].charAt(xs[1].length-1);
    let d =xs[2].charAt(0);

    if(a == b && c == d){
      console.log('YES');
    }else{
      console.log('NO');
    }
}
Main(require('fs').readFileSync('/dev/stdin','utf8'));


function main(input) {
  input = input.trim();
  const [a,b,c] = input.split(" ").map(Number);

  if(a.slice(-1)==b.slice(0,1) && b.slice(-1)==c.slice(0,1)){
    console.log("YES");
  }else{
    console.log("NO");
  }

}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
  input = input.trim();
  const [a,b,c] = input.split(" ").map(Number);

  if(a.slice(-1)==b.slice(0,1) && b.slice(-1)==c.slice(0,1)){
    console.log("Yes");
  }else{
    console.log("No");
  }

}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
	input = input.trim().split(" ");
  var list1 = input[0].split("");
  var list2 = input[1].split("");
  var list3 = input[2].split("");
  if(list1[list1.length - 1] == list2[0] && list2[list1.length - 1] == list3[0]){
     console.log("YES");
     }else{
     console.log("NO");
     }

}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


package main

import "fmt"

func main() {
	var a string
	var b string
	var c string

	fmt.Scan(&a, &b, &c)

	if a[len(a)-1] == b[0] && b[len(b)-1] == c[0] {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}

}


package main

import (
  "fmt"
)

func areChained(s, t string) bool {return s[len(s)-1] == t[0]}

func main() {
  var a [3]string
  for i := 0; i < 3; i++ {fmt.Scan(&a[i])}
  ans := "YES"
  for i := 0; i < 2; i++ {
    if !areChained(a[i], a[i+1]) {
      ans = "NO"
      break
    }
  }
  fmt.Println(ans)
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"reflect"
	"sort"
	"strconv"
	"strings"
	// "regexp"
)

/* sort */
type pair struct {
	index  int64
	p1, p2 interface{}
}
type pairs []pair

func (slice pairs) Len() int {
	return len(slice)
}

func (slice pairs) Less(i, j int) bool {
	return slice[i].index < slice[j].index
}

func (slice pairs) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

/* sort */
type Int64Slice []int64

func (slice Int64Slice) Len() int {
	return len(slice)
}

func (slice Int64Slice) Less(i, j int) bool {
	return slice[i] < slice[j]
}

func (slice Int64Slice) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}
func Int64s(a []int64)                    { sort.Sort(Int64Slice(a)) }
func Int64sSliceAreSorted(a []int64) bool { return sort.IsSorted(Int64Slice(a)) }

const (
	initialBufSize = 1e4
	maxBufSize     = 1e8
	INF            = 1e8
)

var (
	scanner = bufio.NewScanner(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	di      = []int64{-1, 0, 1, 0}
	dj      = []int64{0, -1, 0, 1}
)

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	A, B, C := readString(), readString(), readString()
	if A[len(A)-1] == B[0] && B[len(B)-1] == C[0] {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

/*==========================================
 *             Library
 *==========================================*/
func NextPermutation(x sort.Interface) bool {
	n := x.Len() - 1
	if n < 1 {
		return false
	}
	j := n - 1
	for ; !x.Less(j, j+1); j-- {
		if j == 0 {
			return false
		}
	}
	l := n
	for !x.Less(j, l) {
		l--
	}
	x.Swap(j, l)
	for k, l := j+1, n; k < l; {
		x.Swap(k, l)
		k++
		l--
	}
	return true
}
func doubleAry(h int64, w int64, init int64) (res [][]int64) {
	res = make([][]int64, h)
	for i := int64(0); i < h; i++ {
		res[i] = make([]int64, w)
		for j := int64(0); j < w; j++ {
			res[i][j] = init
		}
	}
	return
}

func aryEq(a []int64, b []int64) bool {
	return reflect.DeepEqual(a, b)
}

func clone(n []int64) (r []int64) {
	r = make([]int64, len(n))
	for i := 0; i < len(n); i++ {
		r[i] = n[i]
	}
	return
}
func write(s string) {
	writer.WriteString(s)
}

func print() {
	writer.Flush()
}

// scanner.Split(bufio.ScanWords) をコメントアウトしないと使用不可
func readLine() (s string) {
	if scanner.Scan() {
		s = scanner.Text()
	}
	return s
}

func readInt() (read int64) {
	scanner.Scan()
	read, err := strconv.ParseInt(scanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return
}

func readFloat() (read float64) {
	scanner.Scan()
	read, err := strconv.ParseFloat(scanner.Text(), 64)
	if err != nil {
		panic(err)
	}
	return
}

func readRunes() (read []rune) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, v)
	}
	return
}

func readString() (read string) {
	scanner.Scan()
	read = scanner.Text()
	return
}

func readStrings() (read []string) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, string(v))
	}
	return
}

func s2i(s string) int64 {
	var intVal, e = strconv.ParseInt(s, 10, 64)
	if e != nil {
		panic(e)
	}
	return intVal
}

func i2s(i int64) string {
	var strVal = strconv.FormatInt(i, 10)
	return strVal
}

func s2f(s string) float64 {
	var floatVal, e = strconv.ParseFloat(s, 64)
	if e != nil {
		panic(e)
	}
	return floatVal
}

func abs(i int64) int64 {
	return int64(math.Abs(float64(i)))
}

func max(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans < v {
			ans = v
		}
	}
	return ans
}
func min(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans > v {
			ans = v
		}
	}
	return ans
}

func sum(i []int64) int64 {
	sum := int64(0)
	for _, val := range i {
		sum += val
	}
	return sum
}

func split(s string) []string {
	return strings.Fields(s)
}

func strAry2intAry(strs []string) []int64 {
	var ret = make([]int64, 0, len(strs))
	for _, str := range strs {
		var intVal = s2i(str)
		ret = append(ret, intVal)
	}
	return ret
}

func intAry2strAry(nums []int64) []string {
	var ret = make([]string, 0, len(nums))
	for _, num := range nums {
		var strVal = i2s(num)
		ret = append(ret, strVal)
	}
	return ret
}

func ary2str(strs []string) string {
	return strings.Join(strs, " ")
}

func reverse(res []int64) []int64 {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}
func reverseStr(res []string) []string {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}

func ini(res []int, init int) {
	if len(res) == 0 {
		return
	}
	res[0] = init
	for i := 0; i < len(res); i++ {
		copy(res[i:], res[:i])
	}
}

//
// func regexpExample() {
//     // Your code here!
//     var str = "13:20"
//     r := regexp.MustCompile(`(\d+):(\d+)`)
//     fmt.Println(r.FindStringSubmatch(str))
// }

// type Country struct {
//     gold int
//     silver int
//     blonze int
// }

// // 複数ソートのサンプル
// func stableSortExample() []Country{
//     var country = []Country {
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:3, blonze:2},
//         {gold:1, silver:3, blonze:3},
//     }
//     sort.SliceStable(country, func(i, j int) bool { return country[i].blonze > country[j].blonze })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].silver > country[j].silver })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].gold > country[j].gold })
//     return country
// }


package main

import (
    "bufio"
    "fmt"
    "math"
    "os"
    "strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
    sc.Split(bufio.ScanWords)
  sc.Scan()
  var a = sc.Text()
  sc.Scan()
  var b = sc.Text()
  sc.Scan()
  var c = sc.Text()

  if(a == b == c) {
    fmt.Println("YES")
  }
  else {
    fmt.Println("NO")
  }
}


package main

import (
  "fmt"
  "strings"
)

func main() {
  var a, b, c string

  fmt.Scanf("%s %s %s", &a, &b, &c)

  ans := "Yes"
  if !strings.HasSuffix(a, b[:1]) {
  	ans = "NO"
  }
  if !strings.HasSuffix(b, c[:1]) {
  	ans = "NO"
  }

  fmt.Printf("%s", ans)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var rdr = bufio.NewReaderSize(os.Stdin, 1000000)

func readLine() string {
	buf := make([]byte, 0, 1000000)
	for {
		l, p, e := rdr.ReadLine()
		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}

func main() {
	args := readLine()
	argv := strings.Split(args, " ")
	result := "NO"
	numA, _ := strconv.Atoi(argv[0])
	numB, _ := strconv.Atoi(argv[1])
	numC, _ := strconv.Atoi(argv[2])
	for i := 1; i <= numB; i++ {
		if (numA*i)%numB == numC {
			result = "YES"
			break
		}
	}
	fmt.Println(result)
}


arrays = gets.split(' ')
i = 0
f = []
while i < arrays.size
  word = arrays[i].split('')
  f << word
  i += 1
end
# [["r", "n", "g"],
#  ["g", "o", "r", "i", "l", "l", "a"],
#  ["a", "p", "p", "l", "e"]]

if f[0][-1]==f[1][0] && f[1][-1]==f[2][0]
  puts "YES"
else
  puts "NO"
end


# abc060 A
a, b, c = gets.split.map(&:chomp)
puts a[-1] == b[0] && b[-1] == c[0] ? 'YES' : 'NO'


a,b,c = gets.split
puts a[-1] == b[0] && b[-1] == c[0] ? 'YES' : 'NO'


a, b, c = gets.chomp.split
if a[-1] == b[0] && b[-1] == c[0]
  puts 'YES'
else
  puts 'No'
end


s = gets
puts s.scan(/(.) \1/).size == 2 ? "YES" : "NO"


s = gets
puts s.gsub(/(.) \1/){ $1 } && s.gsub(/(.) \1/){ $1 } ? "YES" : "NO"


#![allow(unused, non_snake_case, dead_code, non_upper_case_globals)]
use std::cmp::*;
use std::collections::*;
use std::mem::*;

fn main() {
    let (r, w, e) = (std::io::stdin(), std::io::stdout(), std::io::stderr());
    let mut io = IO::new(r.lock(), w.lock(), e.lock());
    assert_eq!(!0usize, std::usize::MAX); //🙊
    let (a, b, c) = (io.chars(), io.chars(), io.chars());
    if a.last() == b.first() && b.last() == c.first() {
        io.writeln("YES");
    } else {
        io.writeln("NO");
    }
}

static MOD: i64 = 1000000007;
static INF: i64 = std::i64::MAX >> 1;
// IO
use std::io::*;
struct IO<R: Read, W: Write, E: Write> {
    Read: R,
    Write: BufWriter<W>,
    Error: BufWriter<E>,
}
impl<R: Read, W: Write, E: Write> IO<R, W, E> {
    fn new(r: R, w: W, e: E) -> IO<R, W, E> {
        IO {
            Read: r,
            Write: BufWriter::new(w),
            Error: BufWriter::new(e),
        }
    }
    fn read<T>(&mut self) -> T
    where
        T: std::str::FromStr,
    {
        let next: String = self
            .Read
            .by_ref()
            .bytes()
            .map(|c| c.unwrap() as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect();
        next.parse().ok().unwrap()
    }
    fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
    fn chari(&mut self) -> Vec<i64> {
        self.chars()
            .iter()
            .map(|&c| (c as u8 - b'0') as i64)
            .collect::<Vec<i64>>()
    }
    fn readn<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read::<T>()).collect::<Vec<_>>()
    }
    fn readmat<T: std::str::FromStr>(&mut self, n: usize, m: usize) -> Vec<Vec<T>> {
        (0..n).map(|_| self.readn(m)).collect()
    }
    fn write<S: ToString>(&mut self, val: S) {
        self.Write.write(val.to_string().as_bytes());
    }
    fn writeln<S: ToString>(&mut self, val: S) {
        self.Write.write(val.to_string().as_bytes());
        self.Write.write(b"\n");
    }
    fn debug<S: std::fmt::Debug>(&mut self, val: S) {
        writeln!(self.Error, "(debug) {:?}", &val);
    }
    fn debug2<S: std::fmt::Debug, T: std::fmt::Debug>(&mut self, val1: S, val2: T) {
        writeln!(self.Error, "(debug2) {:?} -> {:?}", val1, val2);
    }
    fn debug3<S: std::fmt::Debug, T: std::fmt::Debug, U: std::fmt::Debug>(
        &mut self,
        val1: S,
        val2: T,
        val3: U,
    ) {
        writeln!(
            self.Error,
            "(debug3) {:?} -> {:?} -> {:?}",
            val1, val2, val3
        );
    }
}


use std::cmp::*;
use std::io::*;
use std::num::*;
use std::str::*;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let s = stdin
        .bytes()
        .map(|c| c.unwrap() as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect::<String>();
    s.parse::<T>().ok().unwrap()
}

fn string() -> String {
    read()
}

fn int() -> i64 {
    read()
}

fn char() -> char {
    read::<String>().pop().unwrap()
}

fn vecchar() -> Vec<char> {
    string().chars().collect()
}

fn vecint(n: i64) -> Vec<i64> {
    let mut vec = Vec::new();
    for i in 0..n {
        vec.push(int())
    }
    vec
}

fn main() {
    let (a, b, c) = (vecchar(), vecchar(), vecchar());
    println!(
        "{}",
        if a.last().unwrap() == &b[0] && b.last().unwrap() == &c[0] {
            "YES"
        } else {
            "NO"
        }
    )
}


macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input!{
        a:chars,
        b:chars,
        c:chars,
    }
    if &a[a.len()-1] == &b[0] && &b[b.len()-1] == &c[0]{
        println!("YES");
    }else{
        println!("NO");
    }
}


use std::str::FromStr;
use std::fmt::Debug;
use std::cmp;
#[allow(dead_code)]
fn read_as_vec<T>() -> Vec<T>
where T: FromStr, <T as FromStr>::Err : Debug{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().split_whitespace().map(|c| T::from_str(c).unwrap()).collect()

}

#[allow(dead_code)]
fn read_as_string() -> String{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

fn main(){
    let line = read_as_string().split_ascii_whitespace().map(|s| s.chars().collect::<Vec<char>>())
        .collect::<Vec<Vec<char>>>();
    let (a, b, c) = (&line[0], &line[1], &line[2]);

    if *a.last().unwrap() == *b.first().unwrap() && *b.last().unwrap() == *c.first().unwrap(){
        println!("YES");
    }else{
        println!("NO");
    }
}


#[allow(unused_imports)]
use std::char::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;

#[allow(unused_macros)]
macro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);}}
#[allow(unused_macros)]
macro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }
#[allow(unused_macros)]
macro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }
#[allow(unused_macros)]
macro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }

#[derive(PartialEq, PartialOrd)]
pub struct Total<T>(pub T);
impl<T: PartialEq> Eq for Total<T> {}
impl<T: PartialOrd> Ord for Total<T> { fn cmp(&self, other: &Total<T>) -> std::cmp::Ordering { self.0.partial_cmp(&other.0).unwrap() }}

#[allow(dead_code)]
const MAX:usize = 100006;
#[allow(dead_code)]
const INF_U32:u32 = 1 << 31;
#[allow(dead_code)]
const INF_I32:i32 = 1 << 30;
#[allow(dead_code)]
const INF_U64:u64 = 1 << 63;
#[allow(dead_code)]
const INF_I64:i64 = 1 << 62;

fn main() {
    input!{a:[chars;3]};
    println!("{}", if a[0][a[0].len()-1] == a[1][0] && a[1][a[1].len()-1] == a[2][0] {"YES"} else {"No"});
}


a, b, c = input().split(' ')
if a[-1] == b[0] and b[-1] == c[0]:
    print('YES')
else:
    print('NO')


import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    func count() -> Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
}
extension Array where Element: Comparable {
    func max() -> Element! {
        return self.maxElement()
    }
    func min() -> Element! {
        return self.minElement()
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/

/*************** メインプログラム ***************/

let input = readStringSplit(by: " ").map{$0.toArray()}
let (A, B, C) = (input[0], input[1], input[2])
print(A[A.count-1]==B[0]&&B[B.count-1]==C[0] ? "YES" : "NO")


import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    func count() -> Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
}
extension Array where Element: Comparable {
    func max() -> Element! {
        return self.maxElement()
    }
    func min() -> Element! {
        return self.minElement()
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/

/*************** メインプログラム ***************/

let input = readStringSplit(by: " ").map{$0.toArray()}
let (A, B, C) = (input[0], input[1], input[2])
print(A[A.count()-1]==B[0]&&B[B.count()-1]==C[0] ? "YES" : "NO")


let i=readLine()!.characters.split(" ").map{String($0).characters.map{String($0)}};print(i[0][i[0].characters.count-1]==i[1][0]&&i[1][i[0].characters.count-1]==i[2][0] ?"YES":"NO")


let i=readLine()!.characters.split(" ").map{String($0).characters.map{String($0)}};print(i[0][0]==i[1][i.characters.count-1]&&i[1][0]==i[2][i.characters.count-1] ?"YES":"NO")


const main = (input) => {
  input = input.split(' ');
  const A = input[0];
  const B = input[1];
  const C = input[2];

  const resultA = A.slice(-1);
  const resultB = B.slice(0,1);
  const resultb = B.slice(-1);
  const resultC = C.slice(0,1);

  if (resultA==resultB && resultb==resultC) {
    console.log('YES');
  }else{
    console.log('NO');
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const input=require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);const nin=()=>{const r = input[0];input.shift();return Number(r)};const nrin=(n)=>{const a:number[]=[];rep(n,()=>a.push(nin()));return a};const sin=()=>{const r = input[0];input.shift();return String(r)};const out=(...a)=>{console.log(...a)};const floor=(a)=>{return Math.floor(a)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const rep=(n, callback)=>{for(let i = 0;i < n; i++){callback()}};const strrep=(s, i, v)=>{return s.slice(0, i)+v+s.slice(i+1);};const permutation=({result=[],pre=[],post,n=post.length})=>{if(n>0){post.forEach((_,i)=>{const rest=[...post];const elem=rest.splice(i, 1);permutation({result, pre: [...pre,...elem],post:rest,n:n-1})})}else{result.push(pre)}return result};const sw=(s,a:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<a.length;i+=2){if(op==='=='){if(s==a[i])return a[i+1]}else if(op==='>='){if(s>=a[i])return a[i+1]}else if(op==='<='){if(s<=a[i])return a[i+1]}else if(op==='>'){if(s>a[i])return a[i+1]}else if(op==='<'){if(s<a[i])return a[i+1]}}return a[a.length-1];};const or=(a,...b)=>{for(let i=0;i<b.length;i++)if(a==b[i])return true;return false};const maxindex=(...a)=>{return a.indexOf(Math.max.apply(null,a))};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const ceil=a=>{return Math.ceil(a)};const srin=s=>{const a:string[]=[];rep(s,()=>a.push(sin()));return a};let ssinteger=-1;const ssin=()=>{ssinteger++;return input[0][ssinteger]};
const main = ()=>{
  let[a,b,c]=srin(3)
  out(a[a.length-1]==b[0]&&b[b.length-1]==c[0]?'YES':'NO')
}
main()


const main = (input) => {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	const inpt: Array<string> = input.split(' ');
	let ans = true;
	for (let i = 0; i < 2; i++) {
		ans = inpt[i].charAt(inpt[i].length-1) === inpt[i+1].charAt(0);
		if (!ans) break;
	}

	console.log(ans ? 'YES' : 'NO');
}

// *** debug start ***
const debug = ()  => {
	const input = (<HTMLInputElement>document.getElementById('input')).value;
	input && main(input);
}
// *** debug end ***

//
declare function require(x: string): any;
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input:string) {
  const i = input.split(" ");
  const a = parseInt(i[0], 10);
  const b = parseInt(i[1], 10);
  const c = parseInt(i[2], 10);
  let result = "NO";

  for (let i = 1; i <= 100; i++){
    if ((i*a) % b === c) {
      result = "YES";
      break;
    }
  }
  console.log(result);

}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const input=require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);const nin=()=>{const r = input[0];input.shift();return Number(r)};const nrin=(n)=>{const a:number[]=[];rep(n,()=>a.push(nin()));return a};const sin=()=>{const r = input[0];input.shift();return String(r)};const out=(...a)=>{console.log(...a)};const floor=(a)=>{return Math.floor(a)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const rep=(n, callback)=>{for(let i = 0;i < n; i++){callback()}};const strrep=(s, i, v)=>{return s.slice(0, i)+v+s.slice(i+1);};const permutation=({result=[],pre=[],post,n=post.length})=>{if(n>0){post.forEach((_,i)=>{const rest=[...post];const elem=rest.splice(i, 1);permutation({result, pre: [...pre,...elem],post:rest,n:n-1})})}else{result.push(pre)}return result};const sw=(s,a:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<a.length;i+=2){if(op==='=='){if(s==a[i])return a[i+1]}else if(op==='>='){if(s>=a[i])return a[i+1]}else if(op==='<='){if(s<=a[i])return a[i+1]}else if(op==='>'){if(s>a[i])return a[i+1]}else if(op==='<'){if(s<a[i])return a[i+1]}}return a[a.length-1];};const or=(a,...b)=>{for(let i=0;i<b.length;i++)if(a==b[i])return true;return false};const maxindex=(...a)=>{return a.indexOf(Math.max.apply(null,a))};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const ceil=a=>{return Math.ceil(a)};const srin=s=>{const a:string[]=[];rep(s,()=>a.push(sin()));return a};let ssinteger=-1;const ssin=()=>{ssinteger++;return input[0][ssinteger]};
const main = ()=>{
  let[a,b,c]=srin(3)
  out(a[a.length-1]==b[0]&&b[b.length-1]==c[0]??'YES':'NO')
}
main()


const input=require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);const nin=()=>{const r = input[0];input.shift();return Number(r)};const nrin=(n)=>{const a:number[]=[];rep(n,()=>a.push(nin()));return a};const sin=()=>{const r = input[0];input.shift();return String(r)};const out=(...a)=>{console.log(...a)};const floor=(a)=>{return Math.floor(a)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const rep=(n, callback)=>{for(let i = 0;i < n; i++){callback()}};const strrep=(s, i, v)=>{return s.slice(0, i)+v+s.slice(i+1);};const permutation=({result=[],pre=[],post,n=post.length})=>{if(n>0){post.forEach((_,i)=>{const rest=[...post];const elem=rest.splice(i, 1);permutation({result, pre: [...pre,...elem],post:rest,n:n-1})})}else{result.push(pre)}return result};const sw=(s,a:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<a.length;i+=2){if(op==='=='){if(s==a[i])return a[i+1]}else if(op==='>='){if(s>=a[i])return a[i+1]}else if(op==='<='){if(s<=a[i])return a[i+1]}else if(op==='>'){if(s>a[i])return a[i+1]}else if(op==='<'){if(s<a[i])return a[i+1]}}return a[a.length-1];};const or=(a,...b)=>{for(let i=0;i<b.length;i++)if(a==b[i])return true;return false};const maxindex=(...a)=>{return a.indexOf(Math.max.apply(null,a))};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const ceil=a=>{return Math.ceil(a)};const srin=s=>{const a:string[]=[];rep(s,()=>a.push(sin()));return a};let ssinteger=-1;const ssin=()=>{ssinteger++;return input[0][ssinteger]};
const main = ()=>{
  let[a,b,c]=srin(3)
  out(a[a.length-1]==b[0]&&b[b.length-1]==c[0])
}
main()


def main():
    LRm = open(0).read().split()[2:]
    max_L = max(map(int, LRm[::2]))
    min_M = min(map(int, LRm[1::2]))
    print(min_M - max_L + 1 if max_L <= min_M else 0)
    return

main()


def main():
    LR = open(0).read().split()[2:]
    max_L = max(map(int, LR[::2]))
    min_M = min(map(int, LR[1::2]))
    print(min_M - max_L + 1 if max_L <= min_M else 0)
    return

main()


def main():
    LR = open(0).read().split()[2:]
    MAX_L = max(map(int, LR[::2]))
    MIN_R = min(map(int, LR[1::2]))
    print(MIN_R - MAX_L + 1 if MAX_L <= MIN_R else 0)
    return

main()


n,m = map(int,input().split())
gate = [[int(i) for i in input().split()] for _ in range(m)]

minv = gate[0][0]
maxv = gate[0][1]

for x in gate:
  minv = max(minv,x[0])
  maxv = min(maxv,x[1])

print(maxv-minv+1)


n,m = map(int,input().split())
gate = [[int(i) for i in input().split()] for _ in range(m)]

p = [0] * (10**5)

for y in gate:
  p[y[0]-1:y[1]] = list(map(lambda x:x+1, p[y[0]-1:y[1]]))

cnt = 0

for z in range(n):
  if p[z] == m:
    cnt += 1

print(cnt)


n,m = map(int,input().split())
gate = [[int(i) for i in input().split()] for _ in range(m)]

count = 0

for x in range(1,n+1):
  for y in gate:
    if x < y[0] or y[1] < x:
      break
  else:
    count += 1

print(count)


// Working program using Reader Class
import java.io.*;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main
{
	static class Reader
	{
		final private int BUFFER_SIZE = 1 << 16;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;

		public Reader()
		{
			din = new DataInputStream(System.in);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public Reader(String file_name) throws IOException
		{
			din = new DataInputStream(new FileInputStream(file_name));
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public String readLine() throws IOException
		{
			byte[] buf = new byte[64]; // line length
			int cnt = 0, c;
			while ((c = read()) != -1)
			{
				if (c == '\n')
					break;
				buf[cnt++] = (byte) c;
			}
			return new String(buf, 0, cnt);
		}

		public int nextInt() throws IOException
		{
			int ret = 0;
			byte c = read();

			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
			{
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (neg)
				return -ret;
			return ret;
		}

		public long nextLong() throws IOException
		{
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do {
				ret = ret * 10 + c - '0';
			}
			while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}

		public double nextDouble() throws IOException
		{
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();

			do {
				ret = ret * 10 + c - '0';
			}
			while ((c = read()) >= '0' && c <= '9');

			if (c == '.')
			{
				while ((c = read()) >= '0' && c <= '9')
				{
					ret += (c - '0') / (div *= 10);
				}
			}

			if (neg)
				return -ret;
			return ret;
		}

		private void fillBuffer() throws IOException
		{
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1)
				buffer[0] = -1;
		}

		private byte read() throws IOException
		{
			if (bufferPointer == bytesRead)
				fillBuffer();
			return buffer[bufferPointer++];
		}

		public void close() throws IOException
		{
			if (din == null)
				return;
			din.close();
		}
	}

	public static long power(long l, long m,long p)
    {
		//long p=mod;
        // Initialize result
        long res = 1;

        // Update x if it is more
        // than or equal to p
        l = l % p;

        while (m > 0)
        {
            // If y is odd, multiply x
            // with result
            if((m & 1)==1)
                res = (res * l) % p;

            // y must be even now
            // y = y / 2
            m = m >> 1;
            l = (l * l) % p;
        }
        return (long)res;
    }

	public static long mod=998244353;

	public static int gcd(int a, int b)
    {
      if (b == 0)
        return a;
      return gcd(b, a % b);
    }

	public static long modMult(long a,long b) {
		return ((a%mod)*(b%mod))%mod;
	}

	public static long modAdd(long a,long b) {
		return ((a%mod)+(b%mod))%mod;
	}

	public static class Node implements Comparable<Node>{
		int left;
		int index;
		Node(int l,int r){
			left=l;
			index=r;
		}
		public int compareTo(Node n) {
			return this.left-n.left;
		}
	}

	public static void main(String[] args) throws IOException
	{
		Reader scan=new Reader();
		PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
		int n=scan.nextInt();
		int m=scan.nextInt();
		int min=Integer.MIN_VALUE;
		int max=Integer.MAX_VALUE;
		for(int i=0;i<m;i++) {
			int l=scan.nextInt();
			int r=scan.nextInt();
			max=Math.min(r, max);
			min=Math.max(l, min);
		}
		if(max-min+1<=0) {
			out.print(0);
		}
		else {
			out.print(max-min+1);
		}
		out.close();
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastReader in = new FastReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        CPrison solver = new CPrison();
        solver.solve(1, in, out);
        out.close();
    }

    static class CPrison {
        public void solve(int testNumber, FastReader s, PrintWriter out) {
            int n = s.nextInt();
            int m = s.nextInt();
            int fromRange = 1;
            int toRange = n;
            for (int i = 0; i < m; i++) {
                int from = s.nextInt();
                int to = s.nextInt();
                if (fromRange <= from) {
                    fromRange = from;
                }

                if (toRange >= to) {
                    toRange = to;
                }
            }

            if (toRange < fromRange) {
                out.println(0);
            } else {
                out.println(toRange - fromRange + 1);
            }
        }

    }

    static class FastReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastReader.SpaceCharFilter filter;

        public FastReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}


import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import sun.awt.image.ImageWatched;

import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;

public class Main implements Runnable {
    boolean prime[] = new boolean[100001];
    void sieveOfEratosthenes(int n) {
        for (int i = 0; i < n; i++)
            prime[i] = true;
        for (int p = 2; p * p <= n; p++) {
            if (prime[p] == true) {
                for (int i = p * p; i <= n; i += p)
                    prime[i] = false;
            }
        }
    }
    InputReader c;
    PrintWriter w;
    public void run() {
        c = new InputReader(System.in);
        w = new PrintWriter(System.out);
        int n = c.nextInt();
        int m = c.nextInt();

        int x=c.nextInt(),y=c.nextInt();
        for(int i=1;i<m;i++){
            int u = c.nextInt();
            int v = c.nextInt();
            if(u>x) x= u;
            if(v<y) y = v;
        }
        w.println(max(0,(y-x+1)));

        w.close();
    }
    public static void sortbyColumn(int arr[][], int col){
        Arrays.sort(arr, new Comparator<int[]>()
        {
            public int compare(int[] o1, int[] o2){
                return(Integer.valueOf(o1[col]).compareTo(o2[col]));
            }
        });

    }
    static long gcd(long a, long b){
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
    public static class DJSet {
        public int[] upper;

        public DJSet(int n) {
            upper = new int[n];
            Arrays.fill(upper, -1);
        }

        public int root(int x) {
            return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
        }

        public boolean equiv(int x, int y) {
            return root(x) == root(y);
        }

        public boolean union(int x, int y) {
            x = root(x);
            y = root(y);
            if (x != y) {
                if (upper[y] < upper[x]) {
                    int d = x;
                    x = y;
                    y = d;
                }
                upper[x] += upper[y];
                upper[y] = x;
            }
            return x == y;
        }
    }
    public static int[] radixSort(int[] f) {
        int[] to = new int[f.length];
        {
            int[] b = new int[65537];
            for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
            for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
            for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
            int[] d = f; f = to;to = d;
        }
        {
            int[] b = new int[65537];
            for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
            for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
            for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
            int[] d = f; f = to;to = d;
        }
        return f;
    }
    public void printArray(int[] a){
        for(int i=0;i<a.length;i++)
            w.print(a[i]+" ");
        w.println();
    }
    public int[] scanArrayI(int n){
        int a[] = new int[n];
        for(int i=0;i<n;i++)
            a[i] = c.nextInt();
        return a;
    }
    public long[] scanArrayL(int n){
        long a[] = new long[n];
        for(int i=0;i<n;i++)
            a[i] = c.nextLong();
        return a;
    }
    public void printArray(long[] a){
        for(int i=0;i<a.length;i++)
            w.print(a[i]+" ");
        w.println();
    }
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                }
                catch (IOException e) {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt() {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public double nextDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception {
        new Thread(null, new Main(),"Main",1<<26).start();
    }
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner scanner = new Scanner(System.in);
		final var n = scanner.nextInt();
		final var m = scanner.nextInt();
		var l = 1;
		var r = n;
		for (var i = 1; i <= m; i++) {
			var ll = scanner.nextInt();
			var rr = scanner.nextInt();
//			System.out.println(ll);
			if(l < ll) l = ll;
			if(r > rr) r = rr;
		}
		System.out.println(r - l + 1);
		scanner.close();
	}

}


import java.util.*;
public class Main {
	//定義関数から参照できる変数定義はこの辺
	static int N;
	static int M;
	static int Left_max=-1;
	static int Right_min=100001;

	public static void main(String[] args) {
    	Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		for(int i=1;i<=M;i++){
			Left_max=Math.max(Left_max,sc.nextInt());
			Right_min=Math.min(Right_min,sc.nextInt());
		}

		System.out.println(Right_min-Left_max+1);
		//System.out.print(ans);
    }
}


import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int M = sc.nextInt();
        int[] L = new int[N];
        int[] R = new int[N];
        int max=N+1;
        int min=0;
        for(int i=0; i<N; i++){
            L[i]=sc.nextInt();
            R[i]=sc.nextInt();
            min = Math.max(min,L[i]);
            max = Math.min(max,R[i]);
        }
        //int K = sc.nextInt();
        //long N = sc.nextLong();
        int res = Math.max(max-min+1,0);

        System.out.println(res);
        }
    }


#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);

	int N = getint(), M = getint();

	int saishou = 1e9;
	int saidai = 0;
	rep(i, M) {
		chmax(saidai, getint());
		chmin(saishou, getint());
	}
	if (saidai > saishou) printf("0");
	else printf("%d", saishou - saidai + 1);

	Would you please return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], *ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	int N = getint(), M = getint();

	int saishou = 1e9;
	int saidai = 0;
	rep(i, M) {
		int L = getint(), R = getint();
		saidai = max(saidai, L);
		saishou = min(saishou, R);
	}
	if (saidai > saishou) co(0);
	else co(saishou - saidai + 1);

	Would you please return 0;
}


//written by NewbieChd
#include <cstdio>
#include <cctype>
#include <algorithm>
using namespace std;

const int BUF = 1000000;
char buf[BUF], *p1, *p2;
inline char getChar() { return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, BUF, stdin), p1 == p2) ? EOF : *p1++; }
inline int read() {
    register int f = 0;
    char c;
    while (!isdigit(c = getChar())) {}
    do
        f = f * 10 + (c ^ 48);
    while (isdigit(c = getChar()));
    return f;
}

const int maxN = 100003;
int l[maxN], r[maxN];

int main() {
    int n = read(), m = read(), i, L = 0, R = n;
    for (i = 1; i <= m; ++i)
        l[i] = read(), r[i] = read(), L = max(l[i], L), R = min(r[i], R);
    printf("%d\n", max(R - L + 1, 0));
    return 0;
}


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

using namespace std;
using ll = long long;

int main() {
  int n, m;
  cin >> n >> m;
  int ml = 1, mr = n;
  rep(i, m) {
    int l, r;
    cin >> l >> r;
    ml = max(ml, l);
    mr - min(mr, r);
  }
  if (mr < ml) {
    cout << 0 << endl;
  } else {
    cout << mr - ml + 1 << endl;
  }
}


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

using namespace std;
using ll = long long;

int main() {
  int n, m;
  cin >> n >> m;
  vector<int> ls, rs;
  rep(i, m) cin >> ls[i] >> rs[i];
  int l = *max_element(ls.begin(), ls.end());
  int r = *min_element(rs.begin(), rs.end());
  if (r < l) {
    cout << 0 << endl;
  } else {
    cout << r - l + 1 << endl;
  }
}


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

using namespace std;
using ll = long long;

int main() {
  int n, m;
  cin >> n >> m;
  vector<int> ls, rs;
  rep(i, m) cin >> ls[i] >> rs[i];
  int l = max_element(ls.begin(), ls.end()) - ls.begin();
  int r = min_element(rs.begin(), rs.end()) - rs.begin();
  if (r < l) {
    cout << 0 << endl;
  } else {
    cout << r - l + 1 << endl;
  }
}


// AtCoder ABC127: C - Prison
// 2019.9.8 bal4u

#include <stdio.h>

//// 高速入力
#if 1
int getchar_unlocked(void);
#define gc() getchar_unlocked()
#else
#define gc() getchar()
#endif

int in() {   // 非負整数の入力
	int n = 0, c = gc();
	do n = 10 * n + (c & 0xf); while ((c = gc()) >= '0');
	return n;
}

int main()
{
	int l, r, ll, rr, N, M;

	N = in(), M = in();
	ll = 1, rr = N;
	while (M--) {
		l = in(), r = in();
		if (l > ll) ll = l;
		if (r < rr) rr = r;
	}
	if (rr >= ll) printf("%d\n", rr-ll+1);
	else puts("0");
	return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void){
  int N,M,l[100005],r[100005],lmax,rmin,i;
  char str[100],*p;

  fgets(str,sizeof(str),stdin);
  p=strtok(str," \n");
  N=atoi(p);
  p=strtok(NULL," \n");
  M=atoi(p);

  for(i=0;i<M;i++){
    fgets(str,sizeof(str),stdin);
  	p=strtok(str," \n");
    l[i]=atoi(p);
    p=strtok(NULL," \n");
  	r[i]=atoi(p);
  }

  lmax=1,rmin=N;

  for(i=0;i<M;i++){
    if(l[i]>lmax){
      lmax=l[i];
    }
    if(r[i]<rmin){
      rmin=r[i];
    }
  }

  if(rmin<lmax){
    printf("0");
  }else{
    printf("%d\n",rmin-lmax+1);
  }

  return 0;
}


#include <stdio.h>
#define min(a, b) ((a)>(b) ? (b) : (a))
#define max(a, b) ((a)<(b) ? (b) : (a))

int main(){
  int n, m;  scanf("%d%d", &n, &m);
  int maxl = 0, minr = n;
  for(int i=0; i<m; i++){
    int l, r;  scanf("%d%d", &l, &r);
    maxl = max(maxl, l);
    minr = min(minr, r);
  }
  int ans = minr - maxl + 1;
  ans = ans>0 ? ans : 0;
  printf("%d\n", ans);

  return 0;
}


#include <stdio.h>
int min(int a, int b){
    if(a<b)return a;
    return b;
}
int main(void){
    int n, m;
    scanf("%d %d", &n, &m);
    int l, r;
    scanf("%d %d", &l, &r);
    for(int i=1; i<m; i++){
        int a, b;
        scanf("%d %d", &a, &b);
        if(l<a)l=a;
        if(b<r)r=b;
    }
    printf("%d\n", min(n, r-l+1));
    return 0;
}


#include <stdio.h>
int main(void){
    int n, m;
    scanf("%d %d", &n, &m);
    int l, r;
    scanf("%d %d", &l, &r);
    for(int i=1; i<m; i++){
        int a, b;
        scanf("%d %d", &a, &b);
        if(l<a)l=a;
        if(b<r)r=b;
    }
    printf("%d\n", r-l+1);
    return 0;
}


#include <iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
//#define ll long long
//#define maxn -99999
using namespace std;
int a[200005];
int book[200005];
//bool cmp(int x,int y)
//{
//	return x>y;
//}
 //int ll=999999999,rr=-999999999;
int main()
{
   int n,m;
   int l,r,t;

   scanf("%d %d",&n,&m);
   t=m;
   memset(book,0,sizeof(book));
   while(t--)
   {
   	 scanf("%d %d",&l,&r);
   	for(int i=l;i<=r;i++)
   	{
   		book[i]++;
	   }
//	   ll=min(ll,l);
//	   rr=max(rr,r);

   }
   //sort(book,book+n,cmp);
   int ans=0;
   for(int i=1;i<=n;i++)
   {
   	 if(book[i]==m)
   	 ans++;
   	 //cout<<book[i]<<endl;
   }
   printf("%d\n",ans);
	return 0;
}


module.exports=function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)t.d(n,o,function(r){return e[r]}.bind(null,o));return n},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.p="",t(t.s=0)}([function(e,r,t){t(1)(t(2).readFileSync("/dev/stdin","UTF-8"))},function(e,r){e.exports=function(e){for(var r=e.split("\n"),t=r[0].split(" "),n=(Number(t[0]),Number(t[1])),o=0,u=999999,i=0;i<n;i++){var f=r[i+1].split(" "),l=Number(f[0]),c=Number(f[1]);l>o&&(o=l),c<u&&(u=c)}var a=u-o+1,p=a>=0?a:0;console.log(p)}},function(e,r){e.exports=require("fs")}]);


// inputに入力データ全体が入る
function Main(input) {
    // 1行目がinput[0], 2行目がinput[1], …に入る
    input = input.split("\n");
    tmp0 = input[0].split(" ");
    N = Number(tmp0[0]);
    M = Number(tmp0[1]);

    lmin=1
    rmax=N
    for(var i=1; i<=M;i++){
        tmp1 = input[i].split(" ")
        L = Number(tmp1[0])
        R = Number(tmp1[1])
        lmin = Math.max(lmin, L)
        rmax = Math.min(rmax, R)
    }
    if(rmax-lmin+1 < 0){
        console.log(0)
    }else{
        console.log(rmax-lmin+1)
    }
  }
  //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//   Main("6 2\n3 6\n1 4\n");


// inputに入力データ全体が入る
function Main(input) {
  // 1行目がinput[0], 2行目がinput[1], …に入る
  inputs = input.split("\n");

  var tmp = inputs[0].split(" ");

  var n = parseInt( tmp[0], 10 );
  var m = parseInt( tmp[1], 10 );

  var max_l = 0;
  var min_r = n;

  for ( var i=1; i<=m; i++){
    var tmp = inputs[i].split(" ");

    var l = parseInt( tmp[0], 10 );
    var r = parseInt( tmp[1], 10 );

    max_l = l > max_l ? l : max_l;
    min_r = r < min_r ? r : min_r;
  }

  if ( max_l > min_r ){
    console.log('%d', 0);
  } else {
    console.log('%d', min_r - max_l + 1);
  }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    const [n,m] = nextIntArray()
    let leftMax = Number.NEGATIVE_INFINITY
    let rightMin = Number.POSITIVE_INFINITY
    while(hasNext()){
        let [l,r] = nextIntArray()
        leftMax = Math.max(leftMax, l)
        rightMin = Math.min(rightMin, r)
    }
    console.log(rightMin-leftMax+1)
}
Main()


"use strict";

function main(input) {
  const args = input.trim().split("\n");
  const n = to_num(args[0].split(" ")[0]);
  const m = to_num(args[0].split(" ")[1]);
  let R = [];
  let L = [];
  args.map((line, index) => {
    if (index === 0) return;
    L.push(to_num(line.split(" ")[0]));
    R.push(to_num(line.split(" ")[1]));
  });

  let maxL = -1000;
  let minR = 1000000;
  for (let i = 0; i < m; i++) {
    maxL = Math.max(maxL, L[i]);
    minR = Math.min(minR, R[i]);
  }
  console.log(Math.max(0, minR - maxL + 1));
}

const to_num = (str) => {
  return parseInt(str, 10);
};
main(require("fs").readFileSync("./dev/stdin", "utf8"));


/*
-------関数一覧--------
arr1dto2d(Array) 一次元配列を二次元配列にします
pf(N)因数分解した結果をオブジェクトで返します
gcd(a,b)最大公約数を返します
lcm(a,b)最小公倍数を返します
num(a,b)a-bを返します。ソート用です
isPrime(n)素数かどうか真偽値で返します
isNumber(n)数かどうか真偽値で返します
arrsum(arr)配列の合計値を返します
nibu(arr,n)n以下で最も大きい数の添字を返します(nを含みます)
br(input)入力を改行で区切ります
*/
const debugMode = false;
const inf = Number.MAX_SAFE_INTEGER;

function Main(input){
    input = input.split("\n");
    var mem = input[0].split(" ").map(Number);
    var arr = new Array(mem[0]+1).fill(0);
    input.shift();
    input.forEach(function(val){
        var m = val.split(" ").map(Number);
        for(var i=m[0];i<=m[1];i++){
            arr[i]++;
        }
    })
    var sum = 0;
    for(var i=0;i<arr.length;i++){
        if(arr[i]==mem[1]) sum++;
    }
    console.log(sum)
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
function day(y,m,d){
    if(m==1||m==2){
        y--;
        m += 12;
    }
    return 365*y+Math.floor(y/4)-Math.floor(y/100)+Math.floor(y/400)+Math.floor(306*(m+1)/10)+d-429;
}
function zisyozyunn(a){
  var arr = [];
  for(var i=0;i<input[0];i++){
    arr.push(i+1);
  }
  var sum = 0;
  for(var i=0;i<a.length;i++){
    var f = arr.findIndex(val => val==a[i]);
    sum += factorialize(a.length-1-i)*f;
    arr.splice(f,1);
  }
  return sum;
}
function arrsum(arr){
  var sum = 0;
  for (var i=0,len=arr.length; i<len; ++i) {
      sum += arr[i]-0;
  };
  return sum;
}
function debug(val){
  if(debugMode==true){
    console.log(val)
  }
}
function arrMaxPoint(arr){
	var max = Number.MIN_SAFE_INTEGER;
	var point = -1;
	for(var i=0;i<arr.length;i++){
		if(max<arr[i]){
			max = arr[i];
			point = i;
		}
	}
	return point;
}
function arrMinPoint(arr){
	var min = Number.MAX_SAFE_INTEGER;
	var point = -1;
	for(var i=0;i<arr.length;i++){
		if(min>arr[i]){
			min = arr[i];
			point = i;
		}
	}
	return point;
}
function arr1dto2d (arr){
	for(var i=0;i<arr.length;i++){
		arr[i]=arr[i].split("");
		}
	return arr;
}
function isPrime(n){
    if(false===Number.isInteger(n)){
        return false;
    }
    if(n<=1){
        return false;
    }
    if(2===n){
        return true;
    }
    if(0===n%2){
        return false;
    }
    var square_root = Math.floor(Math.sqrt(n));
    for(var i=3; i<=square_root; i+=2){
        if(0===n%i){
            return false;
        }
    }
    return true;
}
function isNumber(val){
	const pat = /^([1-9]\d*|0)$/;
	return pat.test(val);
}
function arr1dto2d (arr){
	for(var i=0;i<arr.length;i++){
		arr[i]=arr[i].split("");
		}
	return arr;
}
function factorialize(num) {
  if (num === 0) { return 1; }
  return num * factorialize(num-1);
}
function arr1dto2d (arr){
	for(var i=0;i<arr.length;i++){
    arr[i]=arr[i].split(" ").map(Number);
    }
  return arr;
}
function rotate(array) {
  const ROW = array.length;
  const COL = array[0].length;
  const row = ROW-1;
  var a = new Array(COL);
  for (var c=0; c<COL; c++) {
    a[c] = new Array(ROW);
    for (var r=0; r<ROW; r++) {
      a[c][r] = array[row-r][c];
    }
  }
  return a;
}
function part_in(base,push,st){
	for(var i=st,p=0;p<push.length;i++,p++){
		base[i] = push[p];
	}
	return base;
}
function part_reverse(arr,s,g){
	var push = arr.slice(s-1,g);
  push.reverse();
	arr = part_in(arr,push,s-1);
	return arr;
}
function zeroPadding(num,length){
    return (num + '000000000000000000000000000000000').slice(0,length);
}
function arrsum(arr){
    var sum = 0;
    for (var i=0,len=arr.length; i<len; ++i) {
        sum += arr[i]-0;
    };
    return sum;
}
function pf(n) {
    var result = {};

    if (n === 1) {
        return {"1":1}
    }

    var init = 2;

    while (n !== 1) {
        var i = init;
        while (i < Number.MAX_SAFE_INTEGER) {
            if (n % i === 0) {
                n /= i;
                if (!(result[i] > 0)) {
                    result[i] = 0;
                }
                result[i]++;
                break;
            }
            i++;
        }
        init = i;
    }
    return result;
}
function gcd(a, b) {
    if (b === 0){
        return a
    }
    return gcd(b, a % b)
}
function lcm(a,b) {
    var g = (n, m) => m ? g(m, n % m) : n
    return a * b / g(a, b)
}
function num(a, b) {
  return a - b;
}
function nibu(a,searchValue){
	var index = -1;

//調べる左端を表す添字(index)
var left = 0;

//調べる右端を表す添字(index)
var right = a.length-1;

//左端と右端にデータがある間は処理を繰り返す
while(left <= right){

    //左右の真ん中を表す添字(index)
    middle =Math.floor((left +right)/2);

    //真ん中の値と探す値を比較する
    if(a[middle]==searchValue){
        //一致した場合、変数に入れて処理終了
        index = middle;
        break;
    }else if(a[middle]<searchValue){
        //探す値より小さい場合、左側にはもっと小さい値しかないので左端の値を真ん中の値の右に移動する
        left = middle +1;
    }else{
        //探す値より大きい場合、右側にはもっと大きい値しかないので右端の値を真ん中の値の左に移動する
        right = middle -1;
    }
}
if(index!=-1) return index;
else return left;
}
function br(input){
  return input.split("\n");
}
function is_sortred(arr){
  var flag = true;
  for(var i=1;i<arr.length;i++){
    if(arr[i-1]>arr[i]){
      flag = false;
      break;
    }
  }
  return flag;
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

var sc = bufio.NewScanner(os.Stdin)

const inf = 1 << 60

func ri() (n int) {
	sc.Scan()
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}

func cumSum(a []int) []int {
	res := make([]int, len(a)+1)
	var sum = 0
	for i := 1; i <= len(res)-1; i++ {
		sum += a[i-1]
		res[i] = sum
	}
	return res
}

func main() {
	sc.Split(bufio.ScanWords)
	n, m := ri(), ri()

	a := make([]int, n+1)
	for i := 0; i < m; i++ {
		l, r := ri()-1, ri()-1
		a[l]++
		a[r+1]--
	}

	cs := cumSum(a)

	ans := 0
	for _, v := range cs {
		if v == m {
			ans++
		}
	}
	fmt.Println(ans)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	_ = nextInt()
	m := nextInt()

	llim := nextInt()
	rlim := nextInt()

	for i := 1; i < m; i++ {
		l := nextInt()
		r := nextInt()

		if rlim < l { //重なってない
			fmt.Println(0)
			return
		}
		if r < llim { //重なってない
			fmt.Println(0)
			return
		}

		llim = max(llim, l)
		rlim = min(rlim, r)

	}

	fmt.Println(rlim - llim + 1)

}
func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

// ---- readfunc
func scanInit() {
	const cap = 64 * 1024
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	num, _ := strconv.Atoi(scanString())
	return num
}

func scanString() string {
	sc.Scan()
	return sc.Text()
}

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	_, m := scanInt(), scanInt()
	ll, rl := scanInt(), scanInt()

	for i := 1; i < m; i++ {
		l, r := scanInt(), scanInt()
		if rl < l || r < ll {
			fmt.Println(0)
			return
		}
		ll = max(ll, l)
		rl = min(rl, r)
	}
	fmt.Println(rl - ll + 1)
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}


//go:generate echo "https://atcoder.jp/contests/abc127/tasks/abc127_c"
package main

import (
	"bufio"
	"fmt"
	"io"
	"math/big"
	"os"
	"strconv"
)

var scan = newScanner(os.Stdin)

func solve(N int, LRs [][]int) int {
	lmax, rmin := 0, N+1
	for _, LR := range LRs {
		chmax(&lmax, LR[0])
		chmin(&rmin, LR[1])
	}
	return rmin - lmax + 1
}

func main() {
	N, M := scan.Int(), scan.Int()
	LRs := make([][]int, M, M)
	for i := range LRs {
		LRs[i] = []int{scan.Int(), scan.Int()}
	}
	fmt.Println(solve(N, LRs))
}

type scanner struct {
	*bufio.Scanner
}

func newScanner(r io.Reader) *scanner {
	s := bufio.NewScanner(r)
	s.Split(bufio.ScanWords)
	s.Buffer(nil, 100000000)
	return &scanner{s}
}

func (s *scanner) String() string {
	s.Scan()
	return s.Text()
}

func (s *scanner) Strings(l int) []string {
	if l == 0 {
		return []string{}
	}
	sl := make([]string, l, l)
	for i := range sl {
		sl[i] = s.String()
	}
	return sl
}

func (s *scanner) Int() int {
	n, _ := strconv.Atoi(s.String())
	return n
}

func (s *scanner) Ints(l int) []int {
	if l == 0 {
		return []int{}
	}
	sl := make([]int, l, l)
	for i := range sl {
		sl[i] = s.Int()
	}
	return sl
}

func (s *scanner) Float64() float64 {
	f, _ := strconv.ParseFloat(s.String(), 64)
	return f
}

func (s *scanner) Float64s(l int) []float64 {
	if l == 0 {
		return []float64{}
	}
	sl := make([]float64, l, l)
	for i := range sl {
		sl[i] = s.Float64()
	}
	return sl
}

func (s *scanner) BigInt() *big.Int {
	n, _ := strconv.ParseInt(s.String(), 10, 64)
	return big.NewInt(n)
}

func (s *scanner) BigInts(l int) []*big.Int {
	if l == 0 {
		return []*big.Int{}
	}
	sl := make([]*big.Int, l, l)
	for i := range sl {
		sl[i] = s.BigInt()
	}
	return sl
}

func iabs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func imax(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func chmax(x *int, v int) {
	*x = imax(*x, v)
}

func imin(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func chmin(x *int, v int) {
	*x = imin(*x, v)
}

func ipow(x, n int) int {
	if n == 0 {
		return 1
	}
	a := ipow(x, n>>1)
	a *= a
	if n&1 != 0 {
		a *= x
	}
	return a
}

func isum(X []int) int {
	s := 0
	for _, x := range X {
		s += x
	}
	return s
}

func factor(n int) map[int]int {
	m := map[int]int{}
	for i := 2; i*i <= n; i++ {
		for n%i == 0 {
			n /= i
			m[i]++
		}
	}
	if n != 1 {
		m[n]++
	}
	return m
}

// mint: https://github.com/atcoder/live_library/blob/master/mint.cpp
type mint int

var mod = 1000000007

func setMintMod(x int) {
	mod = x
}

func newMint(v int) mint {
	return mint((v%mod + mod) % mod)
}

func (x mint) Add(y mint) mint {
	v := x + y
	if v >= mint(mod) {
		return v - mint(mod)
	}
	return v
}

func (x mint) Sub(y mint) mint {
	v := x + mint(mod) - y
	if v >= mint(mod) {
		return v - mint(mod)
	}
	return v
}

func (x mint) Mul(y mint) mint {
	return (x * y) % mint(mod)
}

func (x mint) Pow(p int) mint {
	if p == 0 {
		return mint(1)
	}
	a := x.Pow(p >> 1)
	a = a.Mul(a)
	if p&1 != 0 {
		a = a.Mul(x)
	}
	return a
}

func (x mint) Inverse() mint {
	return x.Pow(mod - 2)
}

func (x mint) Div(y mint) mint {
	return x.Mul(y.Inverse())
}

func (x mint) Neg() mint {
	return newMint(int(-x))
}

type factorial struct {
	fact        []mint
	factInverse []mint
}

func newFactorial(n int) *factorial {
	f := new(factorial)
	f.init(n)
	return f
}

func (f *factorial) init(n int) {
	fact := make([]mint, n+1, n+1)
	fact[0] = newMint(1)
	for i := 1; i <= n; i++ {
		fact[i] = fact[i-1].Mul(newMint(i))
	}

	inv := make([]mint, n+1, n+1)
	inv[n] = fact[n].Inverse()
	for i := n; i >= 1; i-- {
		inv[i-1] = inv[i].Mul(newMint(i))
	}

	f.fact = fact
	f.factInverse = inv
}

func (f *factorial) Get(n int) mint {
	return f.fact[n]
}

func (f *factorial) GetInverse(n int) mint {
	return f.factInverse[n]
}

func (f *factorial) Permutation(n, k int) mint {
	if k < 0 || n < k {
		return 0
	}
	return f.fact[n].Mul(f.factInverse[n-k])
}

func (f *factorial) Combination(n, k int) mint {
	if k < 0 || n < k {
		return 0
	}
	return f.fact[n].Mul(f.factInverse[k]).Mul(f.factInverse[n-k])
}

// sieve: https://github.com/atcoder/live_library/blob/master/prime.cpp
type sieve struct {
	n          int
	primes     []int
	maxFactors []int
}

func newSieve(n int) *sieve {
	s := &sieve{
		n:          n,
		primes:     []int{},
		maxFactors: make([]int, n+1, n+1),
	}
	s.init()
	return s
}

func (s *sieve) init() {
	s.maxFactors[0] = -1
	s.maxFactors[1] = -1
	for i := 2; i <= s.n; i++ {
		if s.maxFactors[i] != 0 {
			continue
		}
		s.primes = append(s.primes, i)
		s.maxFactors[i] = i
		for j := i * i; j <= s.n; j += i {
			if s.maxFactors[j] == 0 {
				s.maxFactors[j] = i
			}
		}
	}
}

func (s *sieve) IsPrime(x int) bool {
	return s.maxFactors[x] == x
}

func (s *sieve) Factor(x int) map[int]int {
	m := map[int]int{}
	for x != 1 {
		m[s.maxFactors[x]]++
		x /= s.maxFactors[x]
	}
	return m
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	var n, m int
	fmt.Scan(&n, &m)

	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	l := make([]int, m)
	r := make([]int, m)
	upper := n
	lower := 0
	for i := 0; i < m; i++ {
		sc.Scan()
		l[i], _ = strconv.Atoi(sc.Text())
		sc.Scan()
		r[i], _ = strconv.Atoi(sc.Text())

		if lower < l[i] {
			lower = l[i]
		}
		if upper > r[i] {
			upper = r[i]
		}
	}
	if upper == lower  {
		fmt.Println(0)
		return
	}

	fmt.Println(upper - lower + 1)

}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	var n, m int
	fmt.Scan(&n, &m)

	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	l := make([]int, m)
	r := make([]int, m)
	upper := n
	lower := 0
	for i := 0; i < m; i++ {
		sc.Scan()
		l[i], _ = strconv.Atoi(sc.Text())
		sc.Scan()
		r[i], _ = strconv.Atoi(sc.Text())

		if lower < l[i] {
			lower = l[i]
		}
		if upper > r[i] {
			upper = r[i]
		}
	}

	fmt.Println(upper - lower + 1)

}


str1 = gets.split
N,M = str1[0].to_i, str1[1].to_i

l = 1
r = N

for x in 1..M
  str1 = gets.split
  li,ri = str1[0].to_i, str1[1].to_i
  if li > l
    l = li
  end
  if ri < r
    r = ri
  end
end

answer = r-l+1
if answer < 0
  answer = 0
end

puts answer


n, m = gets.to_s.split
n, m = n.to_i, m.to_i

card_min = 1
card_max = n

m.times do
  l, r = gets.to_s.split
  l, r = l.to_i, r.to_i
  card_min = l if card_min < l
  card_max = r if card_max > r
end

ans = card_max - card_min + 1

puts ans > 0 ? ans : 0


n, m = gets.split(' ')
n = n.to_i
m = m.to_i

f = 1
s, g = gets.split(' ')
s = s.to_i
g = g.to_i
(m-1).times do
    l, r = gets.split(' ')
    l = l.to_i
    r = r.to_i
    if g < l || r < s then
        f = 0
        break
    elsif l <= s then
        if r <= g then
            g = r
        end
    elsif s <= l then
        if r <= g then
            s = l
            g = r
        else
            s = l
        end
    end
end

if f == 0 then
    print 0
else
    print g-s+1
end


N, M = gets.split.map &:to_i
l, r = gets.split.map &:to_i
min = l
max = r
(M-1).times do
  l, r = gets.split.map &:to_i
  min = l if min < l
  max = r if max > r
end

if N < min
  puts 0
elsif N < max
  puts N - min + 1
else
  puts max - min + 1
end


N, M = gets.split.map &:to_i
l, r = gets.split.map &:to_i
min = l
max = r
(M-1).times do
  l, r = gets.split.map &:to_i
  min = l if min < l
  max = r if max > r
end
puts max - min + 1


N, M = gets.split.map &:to_i
l, r = gets.split.map &:to_i
ans = (l..r).to_a
(M-1).times do
  l, r = gets.split.map &:to_i
  new_l = ans.find_index{ |i| i >= l } ? ans.find_index{ |i| i >= l } : 0
  new_r = ans.find_index{ |i| i > r } ? ans.find_index{ |i| i > r } -1 : -1
  ans = ans.slice(new_l..new_r)
end
puts ans.size