G - Cowties POJ - 2137 (用dp解决计算几何问题)

G - Cowties

 POJ - 2137 

N cows (3 <= N <= 100) are eating grass in the middle of a field. So that they don't get lost, Farmer John wants to tie them together in a loop so that cow i is attached to cows i-1 and i+1. Note that cow N will be tied to cow 1 to complete the loop. 

Each cow has a number of grazing spots she likes and will only be happy if she ends up situated at one of these spots. Given that Farmer John must ensure the happiness of his cows when placing them, compute the shortest length of rope he needs to tie them all in a loop. It is possible for different parts of the loop to cross each other. 

Input

* Line 1: The integer N. 

* Lines 2..N+1: Each line describes one cow using several space-separated integers. The first integer is the number of locations S (1 <= S <= 40) which are preferred by that cow. This is followed by 2*S integers giving the (x,y) coordinates of these locations respectively. The coordinates lie in the range -100..100. 

Output

A single line containing a single integer, 100 times the minimum length of rope needed (do not perform special rounding for this result). 

Sample Input

4
1 0 0
2 1 0 2 0
3 -1 -1 1 1 2 2
2 0 1 0 2

Sample Output

400

Hint

[Cow 1 is located at (0,0); cow 2 at (1,0); cow 3 at (1,1); and cow 4 at (0,1).] 

#include<cstdio>
#include<stack>
#include<set>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<iostream>
#include<cmath>
using namespace std;
#define inf 0x3f3f3f3f
typedef long long ll;
const int N=110;
const int nmax = 50010;
const double esp = 1e-8;
const double PI=3.1415926;
struct point
{
    int x,y;
} a[N][N];
int num[N];
double dp[N][N]; //dp[i][j]表示从第0只牛到第i只牛在第j个位置的最小距离
double dis(point p,point q)
{
    return sqrt((1.0*p.x-q.x)*(p.x-q.x)+(p.y-q.y)*(p.y-q.y));
}
int main()
{
    int n;
    double ans=inf;
    scanf("%d",&n);
    for(int i=0; i<n; i++)
    {
        scanf("%d",&num[i]);
        for(int j=0; j<num[i]; j++)
        {
            scanf("%d%d",&a[i][j].x,&a[i][j].y);
        }
    }
    for(int s=0; s<num[0]; s++)
    {
        memset(dp,0x7f,sizeof(dp));  
        //初始化为“无穷大”double型用0x7f,初始化为“无穷大”double型用0xfe;
        dp[0][s]=0; 
        for(int i=0; i<n-1; i++)
        {
            for(int j=0; j<num[i]; j++)
            {
                for(int k=0; k<num[i+1]; k++)
                {
                      dp[i+1][k]=min(dp[i+1][k],dp[i][j]+dis(a[i][j],a[i+1][k]));
                }
            }
        }
        for(int i=0; i<num[n-1]; i++)
        {
            ans=min(ans,dp[n-1][i]+dis(a[0][s],a[n-1][i]));
        }
    }
    printf("%d\n",int(100*ans));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/clz16251102113/article/details/83096992