const int maxn = 1100000;
struct Seg
{
    int l, r;
    bool operator< (const Seg& rhs) const
    {
        if (l != rhs.l)
            return l < rhs.l;
        return r < rhs.r;
    }
} x[maxn];
int tot, L, n;
int ipt[maxn];
void fun(bool flag)
{
    if (flag)
        x[tot++] = (Seg){ L - 2 * ipt[0], L };
    else
        x[tot++] = (Seg){ 0, 2 * ipt[0] };
    REP(i, n - 1)
    {
        int l = ipt[i] * 2, r = ipt[i + 1];
        if (l <= r)
        {
            if (flag)
                x[tot++] = (Seg){ L - r, L - l };
            else
                x[tot++] = (Seg){ l, r };
        }
    }
}
int main()
{
    while (~RII(L, n))
    {
        tot = 0;
        REP(i, n)
            RI(ipt[i]);
        sort(ipt, ipt + n);
        fun(false);
        REP(i, n)
            ipt[i] = L - ipt[i];
        sort(ipt, ipt + n);
        fun(true);
        sort(x, x + tot);
        int cnt = 1;
        FF(i, 1, tot)
        {
            int &l1 = x[cnt - 1].l, &r1 = x[cnt - 1].r;
            int &l2 = x[i].l, &r2 = x[i].r;
            if (r1 >= l2)
            {
                r1 = max(r1, r2);
            }
            else
            {
                x[cnt].l = l2;
                x[cnt].r = r2;
                cnt++;
            }
        }
        tot = cnt;
        int ans = 0;
        REP(i, tot)
        {
            ans += x[i].r - x[i].l;
        }
        WI(ans);
    }
    return 0;
}原文:http://www.cnblogs.com/cynchanpin/p/6994702.html