Translate

Tuesday 3 February 2015

STONE(Lifting the Stone) spoj problem soluiton

HII guys this is totally geometry based problem there is nothing to code just use formula 
 LOGIC::how to find centroid of a polygon u can this concept or formula given below

The centroid of a non-self-intersecting closed polygon defined by n vertices (x0,y0), (x1,y1), ..., (xn−1,yn−1) is the point (CxCy), where
C_{\mathrm x} = \frac{1}{6A}\sum_{i=0}^{n-1}(x_i+x_{i+1})(x_i\ y_{i+1} - x_{i+1}\ y_i)
C_{\mathrm y} = \frac{1}{6A}\sum_{i=0}^{n-1}(y_i+y_{i+1})(x_i\ y_{i+1} - x_{i+1}\ y_i)
and where A is the polygon's signed area,
A = \frac{1}{2}\sum_{i=0}^{n-1} (x_i\ y_{i+1} - x_{i+1}\ y_i)\;.[13]
In these formulas, the vertices are assumed to be numbered in order of their occurrence along the polygon's perimeter, and the vertex ( xnyn ) is assumed to be the same as (x0y0 ). Note that if the points are numbered in clockwise order the area A, computed as above, will have a negative sign; but the centroid coordinates will be correct even in this case






IF still u have problem to implement this u can refer my solution given below::::








 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
37
38
39
40
41
42
43
44
#include<bits/stdc++.h>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
 int t;
 scanf("%d",&t);
 while(t--)
 {
  int n,i;
  scanf("%d",&n);
  int x[n+1],y[n+1];
  double ans1=0,ans2=0;
  for(i=0;i<n;i++)
  {
   scanf("%d %d",&x[i],&y[i]);
  }
  double A=0,cx=0,cy=0,p;
         x[n]=x[0];
        y[n]=y[0];
  for(i=0;i<=n-1;i++)
  {
  p=(x[i]*y[i+1])-(x[i+1]*y[i]);
  cx+=p*(x[i]+x[i+1]);
  cy+=p*(y[i]+y[i+1]);
  A+=p;
  }
  A/=2;
  cx/=(6*A);
  cy/=(A*6);
  
  if (fabs(cx) < 0.005 - 1e-9) cx = 0;
  if (fabs(cy) < 0.005 - 1e-9) cy = 0;

  printf("%.2f %.2f\n",
    cx + 1e-9 * (cx >= -1e-9 ? 1 : -1),
    cy + 1e-9 * (cy >= -1e-9 ? 1 : -1));
 }
}

1 comment:

Unknown said...

Can you briefly explain the last line
cx + 1e-9 * (cx >= -1e-9 ? 1 : -1)

Working With Java Collections