1. 程式人生 > >UVA1606 Amphiphilic Carbon Molecules

UVA1606 Amphiphilic Carbon Molecules

這道題不知道其實是WR了的,後來看來題解,也有諸多疑問

不懂為什麼空白區域要多加一個點,有大神知道的話,求測試資料或者講解一下,不甚感激。

先貼出我WR的程式碼

#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 1100;
struct Point{
	int x, y;
	double rad;
	bool operator < (const Point &rhs) const {
		return rad < rhs.rad;
	}
}point[maxn], tempPoint[maxn];
int n, color[maxn];
bool left(const Point &a, const Point &b){
	return a.x * b.y >= a.y * b.x;
}
int solve(){
	if(n <= 2) return n;
	int ans = 0;
	for(int i = 0; i < n; ++i){
		int k = 0;
		for(int j = 0; j < n; ++j) if(i != j){
			tempPoint[k++].x = point[j].x - point[i].x;
			tempPoint[k].y = point[j].y - point[i].y;
			if(color[j]){tempPoint[k].x = - tempPoint[k].x; tempPoint[k].y = - tempPoint[k];}
			tempPoint[k].rad = atan2(tempPoint[k].x, tempPoint[k].y);
		}
		sort(tempPoint, tempPoint + k);
		int L = 0, R = 0, cnt = 2;
		while(L < k){
			if(L == R) {R = (R + 1) % k;}
			while(L != R && left(tempPoint[L], tempPoint[R])){++cnt, R++;}
			ans = max(ans, cnt);
			++cnt;
			--cnt;
		}
	}
	return ans;

}
int main(){
	while(scanf("%d", &n) == 1 && n){
		for(int i = 0; i < n; ++i)
			scanf("%d%d%d", &point[i].x, &point[i].y, &color[i]);
		printf("%d\n", solve());
	}
}

題解

#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 1100;
struct Point{
	int x, y;
	double rad;
	bool operator < (const Point &rhs) const {
		return rad < rhs.rad;
	}
}point[maxn], tempPoint[maxn];
int n, color[maxn];
bool left(const Point &a, const Point &b){
	return a.x * b.y >= a.y * b.x;
}
int solve(){
	if(n <= 2) return n;
	int ans = 0;
	for(int i = 0; i < n; ++i){
		int k = 0;
		for(int j = 0; j < n; ++j) if(i != j){
			tempPoint[k].x = point[j].x - point[i].x;
			tempPoint[k].y = point[j].y - point[i].y;
			if(color[j]){tempPoint[k].x = - tempPoint[k].x; tempPoint[k].y = - tempPoint[k].y;} //如果是黑點,將它繞原點旋轉180度即可看做白點處理了
			tempPoint[k].rad = atan2(tempPoint[k].y, tempPoint[k].x);
			++k; 
		}
		sort(tempPoint, tempPoint + k);
		int L = 0, R = 0, cnt = 2;
		while(L < k){
			if(R == L) {R = (R + 1) % k; ++cnt;}  //空區域,暫時多計入一個點, 還是太菜了,不懂為什麼要多加這個點 
			while(R != L && left(tempPoint[L], tempPoint[R])){++cnt; R = (R + 1) % k;}
			++L;
			--cnt;
			ans = max(ans, cnt);
		}
	}
	return ans;

}
int main(){
	while(scanf("%d", &n) == 1 && n){
		for(int i = 0; i < n; ++i)
			scanf("%d%d%d", &point[i].x, &point[i].y, &color[i]);
		printf("%d\n", solve());
	}
	return 0;
}