poj 1328 Radar Installation,pojradar
Radar InstallationTime Limit: 1000MSMemory Limit: 10000KTotal Submissions: 51377Accepted: 11527
思路 : 每個島都在X軸上有一個區間可以被雷達覆蓋,x1為可覆蓋的左端點,x2為可覆蓋的右端點,x1,x2關於島的X對稱。
先對島以x排序,然後貪心。
將第一個島的區間 len[ i ].right與其後的島與區間len[ k ].left比如果前者大則繼續與後面的比反之則將區間更新到後者的區間範圍 此時ans+1(注意如果有島嶼的區間
len [ k ].right<前者的區間 len[ i ].right 則將區間更新到len[ k ].right) 在繼續比下去;
總之就是讓雷達在滿足當前情況的前提下盡量往右方。
#include<iostream>#include<cstdio>#include<cmath>#include<algorithm>#include<stdlib.h>using namespace std;struct Class{ double x; double y;}zb[1005];struct Std{ double s; double e;}len[1005];double r;int ans,n;bool cmp(Class a,Class b){ return a.x<b.x;}void worklen()//將每個島嶼各自對應的能夠放雷達的地區計算出來{ for(int i=0;i<n;i++) { /*cout<<len[i].s<<" "<<len[i].e<<endl;*/ len[i].s=zb[i].x-sqrt(r*r-(zb[i].y*zb[i].y)); len[i].e=zb[i].x+sqrt(r*r-(zb[i].y*zb[i].y)); }}void work(){ int j; int l=0; for(j=1;j<n;j++) { if(len[j].e<len[l].e) { l=j;//當有第j個島嶼雷達的放置區比l個島嶼的小時 注意要把最小的作為比較標準 } else if(len[l].e<len[j].s) { ans++; l=j; } } return ;}int main(){ int i,flag,t=1; while(cin>>n>>r,n||r) { flag=0; ans=1; for(i=0;i<n;i++) cin>>zb[i].x>>zb[i].y; for(i=0;i<n;i++) if(fabs(zb[i].y)>r) { flag=1; } if(flag) { cout<<"Case "<<t<<": "<<"-1"<<endl; t++; } else { sort(zb,zb+n,cmp); /*for(i=0;i<n;i++) cout<<zb[i].x<<" "<<zb[i].y<<endl;*/ worklen(); work(); cout<<"Case "<<t<<": "<<ans<<endl; t++; } } return 0;}
poj1328 Radar Installation 貪心證明
貪心思路:
先算出每個島的雷達覆蓋區間,按左端點排序,排序完成後,第一個雷達建立在第一個區間的右端點。
而後依次判斷每個區間的左端點,如果在最建立立的雷達右邊,那麼肯定需要一個新雷達,而且也建在該區間右端。
如果左端點在雷達左邊,這個時候要考慮區間的右端在雷達的左邊還是右邊,如果是右邊,那雷達位置就不變,如果在左邊,那現在的雷達是覆蓋不了的,所以要把雷達放在該區間的右端點,這樣能同時覆蓋原來的島和現在的島。
poj1328我什地方錯了,指導
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
const int N = 1000;
const double EPS = 1e-7;
struct E { double a, b; } e[N];
int n, d;
bool ava[N];
double p[N];
inline int dblcmp(double a, double b) {
if( fabs(a-b) < EPS ) return 0;
if( a-b > 0 ) return 1;
return -1;
}
bool operator<(const E& a, const E& b) {
if(dblcmp(a.a, b.a) == 0)
return dblcmp(a.b, b.b) == 1;
return dblcmp(a.a, b.a) == -1;
}
int main() {
int i, j, x, y;
int tc = 0;
while(scanf("%d %d", &n, &d), n + d) {
tc++;
int ok = 1;
for(i = 0; i < n; ++i) {
scanf("%d %d", &x, &y);
if(y > d) ok = 0;
double offset = sqrt ( d * d - y * y );
e[i].a = x - offset, e[i].b = x + offset;
ava[i] = 1;
}
if(!ok) { printf("Case %d: -1\n", tc); continue; }
sort(e, e + n);
int stack[N], top = 0;
stack[top++] = 0;
for(i = 1; i < n; ++i) {
while(top > 0 && dblcmp(e[stack[top-1]].b, e[i].b) != -1) {
ava[stack[--top]] = 0;
}
stack[top++] = i;
}
for(i = 0; !ava[i]; ++i);
p[i] = e[i].b;
int cnt = 1;
for(i = i+1; i < n; ++i) if(ava[i]) {
for(j = i-1; !ava[j]; j--);
if(p[j] >= e[i].a) p[i] = p[j];
else { p[i] = e[i].b; cnt++; }
}
printf("Case %d: %d\n", tc, cnt);
}
return 0;
}...餘下全文>>