Advertisement
Guest User

Untitled

a guest
Aug 18th, 2013
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <math.h>
  4. #include <stdlib.h>
  5. #include <stack>
  6. #include <queue>
  7. #include <set>
  8. #include <map>
  9. #include <string>
  10. #include <algorithm>
  11. #include <iostream>
  12. using namespace std;
  13.  
  14. struct P {
  15.     int x, y;
  16.     P(int X = 0, int Y = 0) : x(X), y(Y) {}
  17. } p[4010];
  18.  
  19. struct R {
  20.     P a, b;
  21.     R(P A = P(), P B = P()) : a(A), b(B) {}
  22.     int len() {
  23.         return abs(a.x - b.x) + abs(a.y - b.y);
  24.     }
  25.     bool isHoriz() {
  26.         return a.y == b.y;
  27.     }
  28.     bool between(int x, int a, int b) {
  29.         return ((a <= x && x <= b) || (a >= x && x >= b));
  30.     }
  31.     pair<bool, P> intersects(R &r) {
  32.         if (isHoriz() == r.isHoriz())
  33.             return make_pair(0, P());
  34.         if (isHoriz()) {
  35.             if (between(r.a.x, a.x, b.x) && between(a.y, r.a.y, r.b.y))
  36.                 return make_pair(1, P(r.a.x, a.y));
  37.         } else {
  38.             if (between(r.a.y, a.y, b.y) && between(a.x, r.a.x, r.b.x))
  39.                 return make_pair(1, P(a.x, r.a.y));
  40.         }
  41.         return make_pair(0, P());
  42.     }
  43. } r[4010];
  44.  
  45. int n, l[4000];
  46. vector<int> ans;
  47.  
  48. int sLen(int ra, int rb) {
  49.     return l[rb] - (ra ? l[ra - 1] : 0);
  50. }
  51.  
  52. int main() {
  53.     freopen("input.txt", "r", stdin);
  54.     freopen("output.txt", "w", stdout);
  55.     scanf("%d", &n);
  56.     for (int i = 0; i < n; i++)
  57.         scanf("%d%d", &p[i].x, &p[i].y);
  58.     for (int i = 0; i < n - 1; i++) {
  59.         r[i] = R(p[i], p[i + 1]);
  60.         l[i] = r[i].len() + (i ? l[i - 1] : 0);
  61.         for (int j = 0; j < i - 1; j++) {
  62.             pair <bool, P> inter = r[i].intersects(r[j]);
  63.             if (inter.first)
  64.                 ans.push_back(sLen(j + 1, i - 1) + R(r[i].a, inter.second).len() + R(inter.second, r[j].b).len());
  65.         }
  66.     }
  67.     ans.push_back(l[n - 2]);
  68.     printf("%d", *min_element(ans.begin(), ans.end()));
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement