开始的时候看到人家交的代码有8ms 过的,以为是用的新算法,而不是耗时的暴力,但是经过层层优化,我发现暴力并不是想像中的那么耗时阿,虽然没有达到8ms 的境界,但是我的代码着实优化了不少,时间有限,更省时的代码待以后有时间再讨论,暂且贴下目前的代码。
代码如下;
#include <iostream>
using namespace std;
int n, xy[150][2];
int bao (int a, int b)
{
int count = 0;
for(int i = 0; i < 2*n; i++)
{
if(xy[i][0]*a+xy[i][1]*b>0)count++;
else if(xy[i][0]*a+xy[i][1]*b==0)return 0;
}
if(count==n)return 1;
else return 0;
}
int main ()
{
int state = 1;
while(cin>>n&&n)
{
state = 1;
for(int i = 0; i < 2*n; i++)
cin>>xy[i][0]>>xy[i][1];
for(int i = 0; state&&i <= 500; i++)
for(int j = 0; state&&j <= 500; j++)
{
int fa = i, fb = j;
if(state&&bao(fa, fb)) {cout<<fa<<" "<<fb<<endl;state = 0;}
fa = -1*i; fb = -1*j;
if(state&&bao(fa, fb)) {cout<<fa<<" "<<fb<<endl;state = 0;}
fa = -1*i;fb = j;
if(state&&bao(fa, fb)) {cout<<fa<<" "<<fb<<endl;state = 0;}
fa = i; fb = -1*j;
if(state&&bao(fa, fb)) {cout<<fa<<" "<<fb<<endl;state = 0;}
}
}
return 0;
}
耗时92,在ax+by=0中我们遍历的是穿过原点的直线的斜率,而不是a和b,所以只需暴一下a为负或者b为负的时候就可以达到枚举斜率为负的情况的目的了,
#include <iostream>
using namespace std;
int n, xy[150][2];
int bao (int a, int b)
{
int count = 0;
for(int i = 0; i < 2*n; i++)
{
if(xy[i][0]*a+xy[i][1]*b>0)count++;
else if(xy[i][0]*a+xy[i][1]*b==0)return 0;
}
if(count==n)return 1;
else return 0;
}
int main ()
{
int state = 1;
while(cin>>n&&n)
{
state = 1;
for(int i = 0; i < 2*n; i++)
cin>>xy[i][0]>>xy[i][1];
for(int i = 0; state&&i <= 500; i++)
for(int j = 0; state&&j <= 500; j++)
{
int fa = i, fb = j;
if(state&&bao(fa, fb)) {cout<<fa<<" "<<fb<<endl;state = 0;}
fa = i; fb = -1*j;
if(state&&bao(fa, fb)) {cout<<fa<<" "<<fb<<endl;state = 0;}
}
}
return 0;
}
优化后耗时48,读题是如果我们注意到坐标的范围只是(-100,100)中的整数的话,这个程序还能优化,因为斜率存在情况下已知点斜率最大为100(x=1,y=100)。所以我们枚举的斜率也无须超过这个范围,所以代码再次优化:
#include <iostream>
using namespace std;
int n, xy[150][2];
int bao (int a, int b)
{
int count = 0;
for(int i = 0; i < 2*n; i++)
{
if(xy[i][0]*a+xy[i][1]*b>0)count++;
else if(xy[i][0]*a+xy[i][1]*b==0)return 0;
}
if(count==n)return 1;
else return 0;
}
int main ()
{
int state = 1;
while(cin>>n&&n)
{
state = 1;
for(int i = 0; i < 2*n; i++)
cin>>xy[i][0]>>xy[i][1];
for(int i = 0; state&&i <= 100; i++)
for(int j = 0; state&&j <= 100; j++)
{
int fa = i, fb = j;
if(state&&bao(fa, fb)) {cout<<fa<<" "<<fb<<endl;state = 0;}
fa = i; fb = -1*j;
if(state&&bao(fa, fb)) {cout<<fa<<" "<<fb<<endl;state = 0;}
}
}
return 0;
}
此代码就耗时20了 ^_^#