POJ Space Ant (向量夹角)

http://poj.org/problem?id=1696


水。求出最大余弦值即可。


完整代码:

/*0ms,548KB*/

#include<cstdio>
#include<cstring>
#include<cmath>

double x[55], y[55], dx, dy;
bool vis[55];

///单位化向量
inline void dentity_vector(double nowx, double nowy, double nextx, double nexty)
{
	double len = hypot(nextx - nowx, nexty - nowy);
	dx = (nextx - nowx) / len, dy = (nexty - nowy) / len;
}

///i=(dx,dy),a=(x-nowx,y-nowy)
///注意向量i已经单位化
inline double getcos(double dx, double dy, double nowx, double nowy, double x, double y)
{
	return (dx * (x - nowx) + dy * (y - nowy)) / hypot(x - nowx, y - nowy);
}

int main()
{
	int t, n, i, j, now, next;
	double miny, cos, tmp;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d", &n);
		printf("%d", n);
		miny = 105;
		for (i = 1; i <= n; ++i)
		{
			scanf("%*d%lf%lf", &x[i], &y[i]);
			if (y[i] < miny)
				miny = y[i], now = i;
		}
		memset(vis, 0, sizeof(vis));
		vis[now] = true;
		printf(" %d", now);
		dx = 1.0, dy = 0.0;
		for (i = 2; i <= n; ++i)
		{
			cos = -1.0;
			for (j = 1; j <= n; ++j)
			{
				if (!vis[j])
				{
					double tmp = getcos(dx, dy, x[now], y[now], x[j], y[j]);
					if (tmp > cos)
						cos = tmp, next = j;
				}
			}
			dentity_vector(x[now], y[now], x[next], y[next]);
			now = next;
			vis[now] = true;
			printf(" %d", now);
		}
		putchar(10);
	}
	return 0;
}

你可能感兴趣的:(C++,ACM,poj)