poj 2714 Random Walk
http://poj.org/problem?id=2714
因为每个向量的方向都不同,所以就可以将向量按圆周顺序排一下序,然后枚举每半个圆周的向量和,找出最大值就行了。
这里是用了贪心的思想,尽量将向量放到同一侧,这样就可以尽可能大的构造一个和向量!
View Code
1 #include <cstdio> 2 #include <cmath> 3 #include <algorithm> 4 #include <cstdlib> 5 #include <cstring> 6 7 using namespace std; 8 const int maxn = 101; 9 10 struct vec{ 11 double x; 12 double y; 13 bool operator < (const vec &a) const{ 14 double t = atan2(y, x); 15 double at = atan2(a.y, a.x); 16 17 return t < at; 18 } 19 }v[maxn << 1]; 20 double maxx, maxy; 21 double curx, cury; 22 23 int main(){ 24 int n; 25 double x, y; 26 27 while (~scanf("%d", &n) && n){ 28 for (int i = 0; i < n; i++){ 29 scanf("%lf%lf", &x, &y); 30 v[i << 1].x = x; 31 v[i << 1].y = y; 32 v[i << 1 | 1].x = -x; 33 v[i << 1 | 1].y = -y; 34 } 35 sort(v, v + (n << 1)); 36 curx = cury = 0; 37 for (int i = 0; i < n; i++){ 38 curx += v[i].x; 39 cury += v[i].y; 40 } 41 maxx = curx; 42 maxy = cury; 43 for (int i = 0, end = n << 1; i < end; i++){ 44 int ci = (i + n) % end; 45 46 curx += v[ci].x - v[i].x; 47 cury += v[ci].y - v[i].y; 48 if (curx * curx + cury * cury > maxx * maxx + maxy * maxy) 49 maxx = curx, maxy = cury; 50 } 51 52 printf("Maximum distance = %.3f meters.\n", sqrt((double)maxx * maxx + maxy * maxy)); 53 } 54 55 return 0; 56 }
——written by Lyon