题目背景
一个恐怖组织在一座城市中安放了定时炸弹,其威力巨大,现在这里的警长想知道最坏的情况下会有多少街区受威胁。
题目描述
在一个城市有N*M个街区,每个街区由坐标描述,如图所示:
行 列 1 2 3 … M
1 (1,1) (1,2) (1,3) … (1,M)
2 (2,1) (2,2) (2,3) … (2,M)
3 (3,1) (3,2) (3,3) … (3,M)
… … … … … …
N (N,1) (N,2) (N,3) … (N,M)
现在已知有一个恐怖组织在其中的一个街区安放了定时炸弹,其威力为T,即所有到这个街区的直线距离小于等于T的街区都会受威胁,已知有K个可能的炸弹安放位置,现在这里的警长想知道最坏的情况下会有多少街区受威胁。
输入输出格式
输入格式:
第一行四个正整数N,M,K和T
接下来K行每行两个正整数Xi Yi,描述每个可能安放炸弹的街区。
输出格式:
一个正整数在最坏情况下有多少街区会受威胁。
输入输出样例
输入样例#1:
4 5 3 2
1 2
3 4
4 5
输出样例#1:
11
说明
对于20%的数据 K=1
对于50%的数据 N,M≤1000 K≤20 T≤100
对于100%的数据 N,M≤100000 K≤50 T≤300
思路
一开始50分,TLE。
#include <stdio.h>
#include <iostream>
#include <math.h>
using namespace std;
int a[1001][1001],n,m,t,k,s,maxn;
int tox[5]={0,1,0,-1,0};
int toy[5]={0,0,1,0,-1};
inline double point(int x,int y,int x1,int y1)
{
return sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1));
}
inline void dfs(int x,int y,int i)
{
register int j,l;
if(i>k)
{
return;
}
s=0;
for(int j=max(1,x-t);j<=min(n,x+t);j++)
{
for(int l=max(1,y-t);l<=min(m,y+t);l++)
{
if(point(j,l,x,y)<=t)
{
s++;
}
}
}
if(s>maxn)
{
maxn=s;
}
dfs(x,y,i+1);
return;
}
int main()
{
ios::sync_with_stdio(false);
int i,j,x,y;
cin>>n>>m>>k>>t;
for(i=1;i<=k;i++)
{
cin>>x>>y;
dfs(x,y,1);
}
cout<<maxn<<endl;
return 0;
}
然后改进了一下代码,100.
#include <stdio.h>
#include <iostream>
#include <math.h>
using namespace std;
int a[1001][1001],n,m,t,k,s,maxn,x,y;
int tox[5]={0,1,0,-1,0};
int toy[5]={0,0,1,0,-1};
inline double point(int x,int y,int x1,int y1)
{
return sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1));
}
inline void dfs(int i)
{
register int j,l;
if(i>k)
{
return;
}
cin>>x>>y;
s=0;
for(int j=max(1,x-t);j<=min(n,x+t);j++)
{
for(int l=max(1,y-t);l<=min(m,y+t);l++)
{
if(point(j,l,x,y)<=t)
{
s++;
}
}
}
if(s>maxn)
{
maxn=s;
}
dfs(i+1);
return;
}
int main()
{
ios::sync_with_stdio(false);
int i,j,x,y;
cin>>n>>m>>k>>t;
dfs(1);
cout<<maxn<<endl;
return 0;
}