jiahuimbzuai/CoQuIR huggingface dataset:
//  [typescript]
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()
//  [python]
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()
//  [python]
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()
//  [python]
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()
//  [python]
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)
//  [python]
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)
//  [python]
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)
//  [java]
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();
	}

}
//  [java]
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);
    }
}
//  [java]
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);
        }
    }
//  [cpp]
#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;
}
//  [cpp]
#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;
}
//  [cpp]
//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;
}
//  [cpp]
#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;
  }
}
//  [cpp]
#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;
  }
}
//  [cpp]
#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;
  }
}
//  [c]
// 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;
}
//  [c]
#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;
}
//  [c]
#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;
}
//  [c]
#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;
}
//  [c]
#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;
}
//  [c]
#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;
}
//  [javascript]
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")}]);
//  [javascript]
// 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");
//  [javascript]
// 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"));
//  [javascript]
"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()
//  [javascript]
"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"));
//  [go]
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)
}
//  [go]
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()
}
//  [go]
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]
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)


}
//  [go]
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)


}
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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
//  [rust]
use std::cmp::{max, min};

fn read<T: std::str::FromStr>(
    stdin_lock: &mut std::io::StdinLock,
    buf: &mut Vec<u8>,
    delimiter: u8,
) -> T {
    buf.clear();
    let l = std::io::BufRead::read_until(stdin_lock, delimiter, buf).unwrap();
    buf.truncate(l - 1); // remove delimiter
    let s = unsafe { std::str::from_utf8_unchecked(&buf) };
    s.parse().unwrap_or_else(|_| panic!("read"))
}

fn main() {
    let stdin = std::io::stdin();
    let mut stdin_lock = stdin.lock();
    let mut buf: Vec<u8> = Vec::new();
    let n: i64 = read(&mut stdin_lock, &mut buf, b' ');
    let m: usize = read(&mut stdin_lock, &mut buf, b'\n');
    let mut l: i64 = read(&mut stdin_lock, &mut buf, b' ');
    let mut r: i64 = read(&mut stdin_lock, &mut buf, b'\n');
    for _ in 1..m {
        l = max(l, read(&mut stdin_lock, &mut buf, b' '));
        r = min(r, read(&mut stdin_lock, &mut buf, b'\n'));
    }

    let ans = max(0, min(r, n) - l + 1);
    println!("{}", ans);
}
//  [rust]
use std::cmp::{max, min};

fn read<T: std::str::FromStr>(
    stdin_lock: &mut std::io::StdinLock,
    buf: &mut Vec<u8>,
    delimiter: u8,
) -> T {
    buf.clear();
    let l = std::io::BufRead::read_until(stdin_lock, delimiter, buf).unwrap();
    buf.truncate(l - 1); // remove delimiter
    let s = unsafe { std::str::from_utf8_unchecked(&buf) };
    s.parse().unwrap_or_else(|_| panic!("read"))
}

fn main() {
    let stdin = std::io::stdin();
    let mut stdin_lock = stdin.lock();
    let mut buf: Vec<u8> = Vec::new();
    let n: i32 = read(&mut stdin_lock, &mut buf, b' ');
    let m: usize = read(&mut stdin_lock, &mut buf, b'\n');
    let mut min_x = 1;
    let mut max_x = n;
    for _ in 0..m {
        let l: i32 = read(&mut stdin_lock, &mut buf, b' ');
        let r: i32 = read(&mut stdin_lock, &mut buf, b'\n');
        min_x = max(min_x, l);
        max_x = min(max_x, r);
    }
    let ans = if max_x < min_x { 0 } else { max_x - min_x + 1 };
    println!("{}", ans);
}
//  [rust]
use proconio::{fastout, input};

#[fastout]
fn main() {
    input! {
        n: usize,
        m: usize,
    };

    let mut lr: Vec<(usize, usize, usize)> = Vec::new();
    for _ in 0..m {
        input! {
            l: usize,
            r: usize,
        };

        lr.push((l, r, r - l + 1));
    }

    lr.sort_by(|a, b| a.2.cmp(&b.2));

    let mut v: Vec<usize> = vec![];

    for i in 1..=n {
        v.push(i);
    }

    let mut result = lr[0].2;
    let mut cur_l = lr[0].0;
    let mut cur_r = lr[0].1;

    for i in lr.iter() {
        if cur_l <= i.0 && i.0 <= cur_r {
            result = cur_r - i.0 + 1;
            cur_l = i.0;
        } else if cur_l <= i.1 && i.1 <= cur_r {
            result = cur_r - i.1 + 1;
            cur_r = i.1;
        } else if i.1 <= cur_l && cur_l != i.0 {
            result = 0;
            break;
        } else if cur_r <= i.0 && cur_l != i.1 {
            result = 0;
            break;
        }
    }

    println!("{}", result);
}
//  [rust]
use proconio::{fastout, input};

#[fastout]
fn main() {
    input! {
        n: usize,
        m: usize,
    };

    let mut lr: Vec<(usize, usize, usize)> = Vec::new();
    for _ in 0..m {
        input! {
            l: usize,
            r: usize,
        };

        lr.push((l, r, r - l + 1));
    }

    lr.sort_by(|a, b| a.2.cmp(&b.2));

    let mut v: Vec<usize> = vec![];

    for i in 1..=n {
        v.push(i);
    }

    let mut result = lr[0].2;
    let mut cur_l = lr[0].0;
    let mut cur_r = lr[0].1;

    for i in lr.iter() {
        if cur_l <= i.0 && i.0 <= cur_r {
            result = cur_r - i.0 + 1;
            cur_l = i.0;
        } else if cur_l <= i.1 && i.1 <= cur_r {
            result = cur_r - i.1 + 1;
            cur_r = i.1;
        } else if i.0 <= cur_l && i.1 <= cur_l {
            result = 0;
            break;
        } else if cur_r <= i.0 && cur_r <= i.1 {
            result = 0;
            break;
        }
    }

    println!("{}", result);
}
//  [swift]
// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}
///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }
    
    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {
    
    mutating func remove(_ element: Element) {
        _ = index(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt
    
    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2
        
        if Int(ary[mid])! < key {
            left = mid
            
        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }
    
    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let nm = readInts()
    let (n, m) = (nm[0], nm[1])
    var left = 0
    var right = Int.max
    
    for i in 0..<m {
        let lr = readInts()
        let (l, r) = (lr[0], lr[1])
        
        left = max(left, l)
        right = min(right, r)
    }
    print(max(right - left + 1, 0))
}
main()
//  [swift]
let input = readLine()!.split(separator: " ").map { Int($0)! }

let N = input[0]
let M = input[1]

var intervals: [[Int]] = []

for _ in 0..<M {
  let inp = readLine()!.split(separator: " ").map { Int($0)! }
  intervals.append([inp[0], inp[1]])
}
let startMax = intervals.map { $0[0] }.max()!
let endMin = intervals.map { $0[1] }.min()!

print(max(0, endMin - startMax + 1))
//  [swift]
func readLine_() -> [String] {
    return readLine()!.characters.split(" ").map{String($0)}
}
func readIntSplit() -> [Int] {
    let strs = readLine_()
    return strs.map{Int($0)!}
}

/************** main *****************/
let nm = readIntSplit()
let (n, m) = (nm[0], nm[1])
var (t, b) = (1, n)
for i in 1...m {
    let lr = readIntSplit()
    let (l, r) = (lr[0], lr[1])
    if t < l{
        t = l
    }
    if b > r {
        b = r
    }
}
let ans = b - t + 1
if ans < 0 {
    print(0)
} else {
    print(ans)
}
//  [swift]
// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}
///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }
    
    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {
    
    mutating func remove(_ element: Element) {
        _ = index(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt
    
    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2
        
        if Int(ary[mid])! < key {
            left = mid
            
        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }
    
    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let nm = readInts()
    let (n, m) = (nm[0], nm[1])
    var left = 0
    var right = Int.max
    
    for i in 0..<m {
        let lr = readInts()
        let (l, r) = (lr[0], lr[1])
        
        left = max(left, l)
        right = min(right, r)
    }
    print(right - left + 1)
}
main()
//  [swift]
// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}
///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }
    
    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {
    
    mutating func remove(_ element: Element) {
        _ = index(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt
    
    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2
        
        if Int(ary[mid])! < key {
            left = mid
            
        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }
    
    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let nm = readInts()
    let (m, n) = (nm[0], nm[1])
    var aryIsMasterCard = [Int](repeating: 0, count: m)
    
    for i in 0..<n {
        let lr = readInts()
        let (l, r) = (lr[0], lr[1])
        
        for j in l...r {
            aryIsMasterCard[j - 1] += 1
        }
    }
    print(aryIsMasterCard.filter { $0 == n}.count)
}
main()
//  [swift]
func readIntSplit() -> [Int] {
    return readLine()!.characters.split(" ").map{Int($0)!}
}

/************** main *****************/
let nm = readIntSplit()
let (n, m) = (nm[0], nm[1])
var (t, b) = (1, n)
for i in 1...m {
    let lr = readIntSplit()
    let (l, r) = (lr[0], lr[1])
    if t < l{
        t = l
    }
    if b > r {
        b = r
    }
}
let ans = b - t + 1
if ans < 0 {
    print(0)
} else {
    print(ans)
}
//  [typescript]
const log = console.log;

const createScanFunctions = (input: string) => {
  const str = input.trim();
  const len = str.length;
  let index = 0;

  const scan = () => {
    const startIndex = index;

    while (index < len) {
      const char = str[index];

      if (char === " " || char === "\n")
        return str.substring(startIndex, index++);

      index++;
    }

    return str.substr(startIndex);
  };

  const scanInt = () => parseInt(scan());

  return { scan, scanInt };
};

// ----

function Main(input: string): void {
  const { scanInt } = createScanFunctions(input);

  const n = scanInt();
  const m = scanInt();

  let minCardNo = 1;
  let maxCardNo = n;

  for (let i = 0; i < m; i++) {
    const l = scanInt();
    const r = scanInt();

    if (l > minCardNo) minCardNo = l;
    if (r < maxCardNo) maxCardNo = r;
  }

  log(Math.max(0, maxCardNo - minCardNo + 1));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);let input_i=-1;const tn=():number=>{input_i++;return Number(input[input_i])};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{input_i++;return String(input[input_i])};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(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 sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1]}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const deduplicate=(a):any[]=>{return Array.from(new Set(a))};
const main=()=>{
  let [n,m]=tnn(2)
  let ar=tnn(m*2)
  let j=0,k=n
  for(let i=0;i<m*2;i+=2){
    j=max(ar[i],j)
    k=min(ar[i+1],k)
  }
  to(k-j+1<=0?0:k-j+1)
}
main()
//  [typescript]
export class Main {
  static main(input): string {
    const tmp: string[] = input.split("\n");
    const [n, m]: number[] = tmp[0].split(" ").map(Number);
    let lM: number = 0;
    let rM: number = n;
    for (let i = 1; i <= m; ++i) {
      const t: number[] = tmp[i].split(" ").map(Number);
      if (lM < t[0]) {
        lM = t[0];
      }
      if (t[1] < rM) {
        rM = t[1];
      }
    }
    const t: number = rM - lM;
    return `${t < 0 ? 0 : t + 1}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
// const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);const tn=():number=>{const a=input[0];input.shift();return Number(a)};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{const a=input[0];input.shift();return String(a)};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const tc=():string=>{let a=input[0].split('');const b=a[0];a.shift();if(a.length>0){input[0]=a.join('')}else{input.shift()}return String(b)};const tcc=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(tc())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(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 sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1];}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const objvs =(a)=>{const b=[];for(const v in a){b.push(a[v])}return b};const deduplicate=(a):any[]=>{return Array.from(new Set(a))};
const input = require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);
let input_i = -1;
const tn = () : number => {
    // const a = input[0];
    // input.shift();
    input_i++;
    return Number(input[input_i])
};
const tnn = (n : number) : number[] => {
    const a = [];
    for (let i = 0; i < n; i++) {
        a.push(tn())
    }
    return a
};
const min = (...a) => {
    return Math.min(...a)
};
const max = (...a) => {
    return Math.max(...a)
};
const to = (...arg) => {
    console.log(...arg)
};
const main=()=>{
  let [n,m]=tnn(2)
  let ar=tnn(m*2)
  let j=0,k=n
  for(let i=0;i<m*2;i+=2){
    j=max(ar[i],j)
    k=min(ar[i+1],k)
  }
  to(k-j+1)
}
main()
//  [typescript]
// const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);const tn=():number=>{const a=input[0];input.shift();return Number(a)};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{const a=input[0];input.shift();return String(a)};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const tc=():string=>{let a=input[0].split('');const b=a[0];a.shift();if(a.length>0){input[0]=a.join('')}else{input.shift()}return String(b)};const tcc=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(tc())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(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 sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1];}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const objvs =(a)=>{const b=[];for(const v in a){b.push(a[v])}return b};const deduplicate=(a):any[]=>{return Array.from(new Set(a))};
const input = require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);
let input_i = 0;
const tn = () : number => {
    const a = input[0];
    input.shift();
    return Number(a)
};
const tnn = (n : number) : number[] => {
    const a = [];
    for (let i = 0; i < n; i++) {
        a.push(tn())
    }
    return a
};
const min = (...a) => {
    return Math.min(...a)
};
const max = (...a) => {
    return Math.max(...a)
};
const to = (...arg) => {
    console.log(...arg)
};
const main=()=>{
  let [n,m]=tnn(2)
  let ar=tnn(m*2)
  let j=0,k=n
  for(let i=0;i<m*2;i+=2){
    j=max(ar[i],j)
    k=min(ar[i+1],k)
  }
  to(k-j+1)
}
main()
//  [typescript]
const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);const tn=():number=>{const a=input[0];input.shift();return Number(a)};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{const a=input[0];input.shift();return String(a)};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const tc=():string=>{let a=input[0].split('');const b=a[0];a.shift();if(a.length>0){input[0]=a.join('')}else{input.shift()}return String(b)};const tcc=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(tc())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(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 sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1];}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const objvs =(a)=>{const b=[];for(const v in a){b.push(a[v])}return b};const deduplicate=(a):any[]=>{return Array.from(new Set(a))};
const main=()=>{
  let [n,m]=tnn(2)
  let ar=input
  let j=0,k=n
  for(let i=0;i<m*2;i+=2){
    j=max(ar[i],j)
    k=min(ar[i+1],k)
  }
  to(k-j+1)
}
main()
//  [python]
s,t=input().split()
print(t+s)
//  [python]
S,T = map(str,input().split())
print(T + S)
//  [python]
S, T = input().split()
print(T+S)
//  [python]
S, T = input().split()
print(S + T)
//  [python]
s, t = map(int,input().split())
print(t+s)
//  [python]
s=input()
t=input()
print(t+s)
//  [java]
/*
 *  author : Atul Anand   
 *  created on : Wed Apr 01 2020
 */

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

public class Main{

    public static void main(String[] args) throws IOException {
        String S = in.next();
        String T = in.next();
        print(T+S);
        in.close();
        out.close();
    }

    static int MIN = Integer.MIN_VALUE;
    static int MAX = Integer.MAX_VALUE;
    static Reader in = new Reader();
    static PrintWriter out = new PrintWriter(System.out);

    static void read(int arr[], int N) throws IOException { 
    	for(int i = 0; i < N; i++){ 
    		arr[i] = in.nextInt(); 
    	} 
    }
    
    static void read(long arr[], int N) throws IOException { 
    	for(int i = 0; i < N; i++){ 
    		arr[i] = in.nextLong(); 
    	} 
    }
    
    static void read(String arr[], int N) throws IOException { 
    	for(int i = 0; i < N; i++){ 
    		arr[i] = in.next(); 
    	} 
    }
    
    static void print(Object O) {  
    	out.print(O); 
    }
    
    static void println(Object O) { 
    	out.println(O); 
    }
    
    static void println(int arr[]) { 
    	for(int i = 0; i < arr.length; i++){ 
    		print(arr[i]+" "); 
    	} 
    	println(""); 
    }

    static void println(int arr[][]) { 
    	for(int i = 0; i < arr.length; i++){ 
    		println(arr[i]); 
    	}
    }
    
    static void debug(Object O) { 
    	System.out.println(O); 
    }
}

class Reader {
    BufferedReader reader;
    StringTokenizer tokenizer;

    Reader() {
        reader = new BufferedReader(new InputStreamReader(System.in));
        tokenizer = new StringTokenizer("");
    }

    String next() throws IOException {
        while (!tokenizer.hasMoreTokens() ) { 
            tokenizer = new StringTokenizer(reader.readLine()); 
        }
        return tokenizer.nextToken();
    }

    int nextInt() throws IOException { 
        return Integer.parseInt(next()); 
    }
    
    double nextDouble() throws IOException { 
        return Double.parseDouble(next());
    }
    
    long nextLong() throws IOException { 
        return Long.parseLong(next()); 
    }
    
    String nextLine() throws IOException { 
        return reader.readLine(); 
    }
    
    void close() throws IOException { 
        reader.close(); 
    }
}
//  [java]
import java.util.*;
import java.io.*;
public class Main
{
    public static void main(String []args) throws IOException {
    	FastScanner in  = new FastScanner(System.in);
    	PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
    	solve(in, out);
    	in.close();
    	out.close();
    }
    static long gcd(long a, long b){ return (b==0) ? a : gcd(b, a%b); }
    static int gcd(int a, int b){ return (b==0) ? a : gcd(b, a%b); }
    static class FastScanner{
	BufferedReader reader;
	StringTokenizer st;
	FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
	String next(){while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
	     st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
	String nextLine()  {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
	int    nextInt()   {return Integer.parseInt(next());}
	long   nextLong()  {return Long.parseLong(next());}
	double nextDouble(){return Double.parseDouble(next());}
	char   nextChar()  {return next().charAt(0);}
	int[]  nextIntArray(int n)         {int[] arr= new int[n];   int i=0;while(i<n){arr[i++]=nextInt();}  return arr;}
	long[] nextLongArray(int n)        {long[]arr= new long[n];  int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
	int[]  nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
	long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
	void   close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
    }
    
    /********* SOLUTION STARTS HERE ************/
    
    private static void solve(FastScanner in, PrintWriter out){
        String s = in.next();
        String t = in.next();
        out.println(t+""+s);
    }
    
    /************* SOLUTION ENDS HERE **********/
}
//  [java]
import java.util.*;
public class next
{
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String huruf = scan.next();
        String huruf2 = scan.next();
        System.out.println(huruf2+huruf);
    }
}
//  [cpp]
#include<cstdio>
#include<cstring>

int main()
{
	char a[100],b[100];
	scanf("%s %s",a,b);
	printf("%s%s\n",b,a);
	return 0;
}
//  [cpp]
#include<stdio.h>
int main()
{
  char s[2][101];
  scanf("%s %s",s[0],s[1]);
  printf("%s%s",s[1],s[0]);
  return 0;
}
//  [cpp]
#include <stdio.h>

 char S[110];
 char T[110];

 int main(){
 scanf("%s%s",S,T);
 printf("%s%s\n",T,S);
}
//  [cpp]
#include<stdio.h>
int main (){
	char S[150],T[150];
	scanf("%s %s",S,T);
	printf("%s %s",T,S);
	
	return 0;
}
//  [cpp]
#include<stdio.h>
int main (){
	char S[150],T[150];
	scanf("%s %s",&S,&T);
	printf("%s %s",T,S);
	
	return 0;
}
//  [cpp]
#include<stdio.h>
int main (){
	char A[100],B[100];
	scanf("%s %s",&A,&B);
	printf("%s %s",B,A);
	
	return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

int main(void){
    
    char S[101],T[101];

    scanf("%s",S);
    scanf("%s",T);

    printf("%s%s",T,S);

    return 0;
}
//  [c]
#include<stdio.h>
#include<stdlib.h>
int main(){
  char s[100],t[100];
  scanf("%s %s",s,t);
  printf("%s%s",t,s);
  return 0;
}