1. 程式人生 > >UVA 1193 貪心演算法(區間不交叉)

UVA 1193 貪心演算法(區間不交叉)

這裡寫圖片描述

http://acm.hust.edu.cn/vjudge/problem/32336/origin
題目大意:
海上有很多島p 現在要在x軸上放置雷達,給出雷達範圍和島的位置,問至少
多少個雷達才可以偵查到全部島。
貪心的想法是把雷達偵查範圍儘量的鋪開,偵查的範圍不要重疊,這樣的話就最大化的利用了雷達的偵查範圍,沒有浪費~這很貪心。

#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
struct point
{
    int x,y;
    double
xl,xr; }; bool comp(point a,point b) { return a.x<b.x; } int n,d; point pt[1005]; int solve(){ for(int i=0;i<n;i++) if(pt[i].y>d)return -1; //雷達無法偵查到 sort(pt,pt+n,comp); double r=pt[0].xr; int ans=1; for(int i=1;i<n;i++){ if(pt[i].xl>r){ //當區間不重疊
r=pt[i].xr; ans++; } else if(pt[i].xl<r&&pt[i].xr<r) //區間重疊可以忽略 r=pt[i].xr; } return ans; } int main() { int cas=1; while(scanf("%d%d",&n,&d)==2&&n&&d){ for(int i=0;i<n;i++){ scanf
("%d %d",&pt[i].x,&pt[i].y); double c=sqrt((double)d*(double)d-(double)pt[i].y*(double)pt[i].y); pt[i].xl=(double)pt[i].x-c; //將島變為偵查區間 pt[i].xr=(double)pt[i].x+c; } printf("Case %d: %d\n",cas++,solve()); } }