uva 10167 - Birthday Cake
题解:由于解太多,随机抓 A、B, 只要有符合就行了; (首先,Ax+By=0必须表示直线,即A、B不能同时为0;另外,要注意到直线不能过输入中的2N个点;检测点在直线的哪一侧,只需要简单的线性规划的知识)
1 #include <cstdio> 2 #include <cstdlib> 3 4 int x[100], y[100]; 5 6 int test(int A, int B, int N) 7 { 8 static int i, pos, neg, tmp; 9 pos = 0, neg = 0; 10 for (i = 2*N-1; i >= 0; i--) 11 { 12 tmp = A*x[i] + B*y[i]; 13 if (tmp > 0) neg ++; 14 else if(tmp < 0) pos ++; 15 else return 0; 16 } 17 return pos == neg; 18 } 19 20 void find(int N) 21 { 22 int A, B; 23 while(1) 24 { 25 A = rand()%1001 - 500; 26 B = rand()%1001 - 500; 27 if(test(A, B, N)) 28 { 29 printf("%d %d\n", A, B); 30 break; 31 } 32 } 33 } 34 35 int main() 36 { 37 int N, i; 38 while(scanf("%d", &N) == 1 && N) 39 { 40 for (i = 2*N-1; i >= 0; i--) 41 scanf("%d %d", &x[i], &y[i]); 42 find(N); 43 } 44 }
枚举:
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 void bruteforce(int &A, int &B, vector<int> &x, vector<int> &y, int n){ 5 for (A = -500; A <= 500; A++){ 6 for (B = -500; B <= 500; B++){ 7 int d = 0, u = 0; 8 for (int i = 0; i < 2 * n; i++){ 9 if (A*x[i] + B*y[i] > 0) u++; 10 if (A*x[i] + B*y[i] < 0) d++; 11 } 12 if (u == n&&d == n) return; 13 } 14 } 15 } 16 int main() 17 { 18 int n; 19 while (cin >> n&&n != 0){ 20 vector<int> x(2*n, 0); 21 vector<int> y(2*n, 0); 22 for (int i = 0; i < 2*n; i++){ 23 cin >> x[i] >> y[i]; 24 } 25 int A, B; 26 bruteforce(A, B, x, y, n); 27 cout << A << ' ' << B << endl; 28 } 29 return 0; 30 }