题目链接:这里
Description

Your friend will enjoy shopping. She will walk through a mall along a straight street, where N
individual shops (numbered from 1 to N) are aligned at regular intervals. Each shop has one
door and is located at the one side of the street. The distances between the doors of the adjacent
shops are the same length, i.e. a unit length. Starting shopping at the entrance of the mall, she
visits shops in order to purchase goods. She has to go to the exit of the mall after shopping.
She requires some restrictions on visiting order of shops. Each of the restrictions indicates that
she shall visit a shop before visiting another shop. For example, when she wants to buy a nice
dress before choosing heels, she shall visit a boutique before visiting a shoe store. When the
boutique is farther than the shoe store, she must pass the shoe store before visiting the boutique,
and go back to the shoe store after visiting the boutique.

If only the order of the visiting shops satisfies all the restrictions, she can visit other shops in
any order she likes.

Write a program to determine the minimum required walking length for her to move from the
entrance to the exit.

Assume that the position of the door of the shop numbered k is k units far from the entrance,
where the position of the exit is N + 1 units far from the entrance.
Input

The input consists of a single test case.

N m
c1 d1
.
.
.
cm dm

The first line contains two integers N and m, where N (1 ≤ N ≤ 1000) is the number of shops,
and m (0 ≤ m ≤ 500) is the number of restrictions. Each of the next m lines contains two
integers ci and di (1 ≤ ci < di ≤ N) indicating the i-th restriction on the visiting order, where
she must visit the shop numbered ci after she visits the shop numbered di (i = 1, … , m).
There are no pair of j and k that satisfy cj = ck and dj = dk.
Output

Output the minimum required walking length for her to move from the entrance to the exit.
You should omit the length of her walk in the insides of shops.
Sample Input

10 3

3 7

8 9

2 5
Sample Output

23

题意:
在一条街上有1-n个店,你一开始在0这个位置,你需要访问每个店,并且最后到n+1这个点

然后有m个限制,就给你ci,di

表示你去ci这个店之前,你必须先到di这个点才行

保证di>ci

问你最小距离走多少

解法:
贪心好题。

我们走的话,就走闭环就好了

闭环是什么?这个区间的[l,r]中,l点是被限制的,并且这个区间的最大的限制为r。

那么我们就往回走一次,再走过去就好了

这个贪心显然是正确的。因为这样可以保证重复经过的路最少。

//CF gym 100803C

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1200;
int fa[maxn];

int main(){
    int n, m;
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= n+1; i++) fa[i] = i;
    for(int i = 1; i <= m; i++){
        int x, y;
        scanf("%d%d", &x, &y);
        fa[x] = max(fa[x], y);
    }
    long long ans = n+1;
    int l = 1, r = 1;
    for(int i = 1; i <= n; ){
        r = fa[i];
        int now = i;
        while(now <= r){
            r = max(r, fa[now]);
            now++;
        }
        ans += 2*(r-i);
        i = now;
    }
    printf("%lld\n", ans);
    return 0;
}