1 /* 2 题意:有n个商店排成一条直线,有一些商店有先后顺序,问从0出发走到n+1最少的步数 3 贪心:对于区间被覆盖的点只进行一次计算,还有那些要往回走的区间步数*2,再加上原来最少要走n+1步就是答案了 4 详细解释:http://blog.csdn.net/u013625492/article/details/45640735 5 */ 6 #include <cstdio> 7 #include <algorithm> 8 #include <cstring> 9 #include <cmath> 10 using namespace std; 11 12 const int MAXN = 1e3 + 10; 13 const int INF = 0x3f3f3f3f; 14 struct A 15 { 16 int l, r; 17 }a[MAXN]; 18 struct B 19 { 20 int l, r; 21 }b[MAXN]; 22 23 bool cmp(A x, A y) {return x.l < y.l;} 24 25 int main(void) //UVALive 6834 Shopping 26 { 27 // freopen ("C.in", "r", stdin); 28 29 int n, m; 30 while (scanf ("%d%d", &n, &m) == 2) 31 { 32 int cnt = 0; 33 for (int i=1; i<=m; ++i) 34 { 35 int u, v; scanf ("%d%d", &u, &v); 36 if (u > v) continue; 37 a[++cnt].l = u; a[cnt].r = v; 38 } 39 sort (a+1, a+1+cnt, cmp); 40 41 int l = a[1].l; int r = a[1].r; int tot = 0; 42 for (int i=2; i<=cnt; ++i) //区间覆盖 43 { 44 if (r < a[i].l) 45 { 46 b[++tot].l = l; b[tot].r = r; 47 l = a[i].l; r = a[i].r; 48 } 49 else r = max (r, a[i].r); 50 if (i == cnt) {b[++tot].l = l; b[tot].r = r;} 51 } 52 53 int ans = n + 1; 54 for (int i=1; i<=tot; ++i) ans += 2 * (b[i].r - b[i].l); 55 printf ("%d\n", ans); 56 } 57 58 return 0; 59 }
时间: 2024-10-10 23:22:30