1. 程式人生 > >[UVA - 10382] Watering Grass 題解

[UVA - 10382] Watering Grass 題解

oid 輸出 ios -s turn get pan getch 1.2

此文為博主原創題解,轉載時請通知博主,並把原文鏈接放在正文醒目位置。

題目鏈接(vjudge):https://vjudge.net/problem/UVA-10382

題目大意:

輸入包含多組數據。以EOF結束。每組數據給定一個草坪的長L和寬W,草坪的中線上有n個灑水器,給出灑水器的橫坐標和灑水半徑R。

要求選擇最少的灑水器覆蓋整片草坪。如果不能覆蓋,輸出-1.

n<=10000,L,W,R在int範圍內。

樣例輸入:

8 20 2 5 3 4 1 1 2 7 2 10 2 13 3 16 2 19 4 3 10 1 3 5 9 3 6 1 3 10 1 5 3 1 1 9 1

樣例輸出:

6

2

-1

分析:

區間覆蓋的貪心問題。雖然灑水範圍是個圓,但是容易發現真正有效的是圓與草坪相交得到的矩形。

問題轉化為尋找最少的灑水器,使得他們的矩形覆蓋整片草地。

註意:

1.W*W會爆int,註意數據類型轉換。這個害我改了好久QAQ

2.如果灑水器半徑<草坪寬度的一半,可以直接忽略。

AC代碼:

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<algorithm>
 5 #include<cmath>
 6
#include<queue> 7 8 const int MAXN = 10005; 9 10 inline void read(int &x) 11 { 12 char ch = getchar(),c = ch;x = 0; 13 while(ch < 0 || ch > 9) c = ch,ch = getchar(); 14 while(ch <= 9 && ch >= 0) x = (x<<1)+(x<<3)+ch-0,ch = getchar();
15 if(c == -) x = -x; 16 } 17 18 int n,L,w,ans,flag; 19 double tmp,h,last,now; 20 21 inline int Min(int a,int b) 22 {return a<b?a:b;} 23 24 inline int Max(int a,int b) 25 {return a>b?a:b;} 26 27 struct LINE 28 { 29 int mid,area; 30 double l,r; 31 }a[MAXN]; 32 33 int cmp(LINE a,LINE b) 34 { 35 if(a.l == b.l) 36 return a.r > b.r; 37 return a.l < b.l; 38 } 39 40 int main() 41 { 42 while(scanf("%d%d%d",&n,&L,&w) != EOF) 43 { 44 h = double(w/2.0);ans = 0; 45 flag = false;last = 0,now = 0; 46 for(int i = 1;i <= n;++ i) 47 { 48 read(a[i].mid),read(a[i].area); 49 if(a[i].area <= h){ 50 -- i,-- n; 51 continue; 52 } 53 tmp = sqrt((double)a[i].area*a[i].area-(double)w*w/4.0); 54 a[i].l = a[i].mid-tmp; 55 a[i].r = a[i].mid+tmp; 56 } 57 std::sort(a+1,a+1+n,cmp); 58 if(a[1].l > 0){ 59 printf("-1\n"); 60 continue; 61 } 62 for(int i = 1;i <= n+1;++ i) 63 { 64 if(!now && a[i].l > last){ 65 flag = true; 66 ans = -1; 67 break; 68 } 69 else if(a[i].l > last || i == n+1){ 70 ans ++; 71 last = now; 72 now = 0; 73 } 74 if(last >= L) break; 75 if(a[i].l <= last && a[i].r > now) 76 now = a[i].r; 77 } 78 if(flag || last < L) printf("-1\n",ans); 79 else printf("%d\n",ans); 80 } 81 82 return 0; 83 }

[UVA - 10382] Watering Grass 題解