587. Erect the Fence
You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.
You are asked to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed.
Return the coordinates of trees that are exactly located on the fence perimeter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 class Solution { int ccw (vector<int >& a, vector<int >& b, vector<int >& c) { int res = a[0 ] * b[1 ] + b[0 ] * c[1 ] + c[0 ] * a[1 ]; res -= (a[0 ] * c[1 ] + b[0 ] * a[1 ] + c[0 ] * b[1 ]); return res; } public : vector<vector<int >> outerTrees (vector<vector<int >>& trees) { swap (trees[0 ], *min_element (begin (trees),end (trees))); sort (begin (trees) + 1 , end (trees), [&](vector<int >& a, vector<int >& b) { int c = ccw (trees[0 ], a, b); if (c) return c > 0 ; if (a[1 ] == b[1 ]) return a[0 ] < b[0 ]; return a[1 ] > b[1 ]; }); vector<vector<int >> res; for (int i = 0 ; i < trees.size (); i++) { while (res.size () >= 2 and ccw (trees[i], res[res.size () - 2 ], res[res.size () - 1 ]) < 0 ) { res.pop_back (); } res.push_back (trees[i]); } for (int i = trees.size () - 1 ; i >= 0 ; i--) { while (res.size () >= 2 and ccw (trees[i], res[res.size () - 2 ], res[res.size () - 1 ]) < 0 ) { res.pop_back (); } res.push_back (trees[i]); } sort (begin (res), end (res)); res.erase (unique (begin (res),end (res)),end (res)); return res; } };