1. 程式人生 > >『一本通』貪心

『一本通』貪心

活動安排

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,lst,ans;
 4 struct node{int l,r;}a[1005]; 
 5 bool cmp(node x1,node x2) {return x1.r<x2.r;}
 6 
 7 int main() {
 8     scanf("%d",&n);
 9     for(int i=1;i<=n;i++) 
10      scanf("%d%d",&a[i].l,&a[i].r);
11     sort(a+1
,a+n+1,cmp); 12 for(int i=1;i<=n;i++) 13 if(lst<=a[i].l) ans++,lst=a[i].r; 14 printf("%d",ans); 15 } 16 //貪心(結束時間早的優先)

 

種樹

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,h,ans;
 4 bool vis[30005];
 5 struct node{int b,e,t;}a[30005];
 6 bool cmp(node x1,node x2) {return
x1.e<x2.e;} 7 8 int main() { 9 scanf("%d%d",&n,&h); 10 for(int i=1;i<=h;i++) 11 scanf("%d%d%d",&a[i].b,&a[i].e,&a[i].t); 12 sort(a+1,a+h+1,cmp); 13 for(int i=1;i<=h;i++) { 14 for(int j=a[i].b;j<=a[i].e;j++) 15 if(vis[j]) a[i].t--;
16 if(a[i].t<=0) continue; 17 ans+=a[i].t; 18 int tot=0; 19 for(int j=a[i].e;j>=a[i].b;j--) { 20 if(!vis[j]) tot++,vis[j]=1; 21 if(tot==a[i].t) break; 22 } 23 } 24 printf("%d",ans); 25 } 26 //貪心(在編號大的路段種樹)

 

噴水裝置

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int T,n,l,cnt,ans;
 4 double w;
 5 struct node{double l,r;}a[15005];
 6 inline int read() {
 7     int x=0; char c=getchar();
 8     while(c<'0'||c>'9') c=getchar();
 9     while(c>='0'&&c<='9') x=(x<<3)+(x<<1)+c-'0',c=getchar();
10     return x;
11 }
12 bool cmp(node x1,node x2) {return x1.l<x2.l;}
13 
14 int main() {
15     T=read();
16     while(T--) {
17         cnt=ans=0;
18         n=read(),l=read(),w=read()/2.0;
19         for(int i=1;i<=n;i++) {
20             int x=read(); double r=read();
21             if(r<w) continue; 
22             r=sqrt(r*r-w*w); 
23             a[++cnt].l=x-r,a[cnt].r=x+r;
24         }
25         sort(a+1,a+cnt+1,cmp);
26         if(a[1].l>0) {printf("-1\n"); continue;}
27         int i=1; double rst=0; 
28         while(i<=cnt) {
29             double maxx=-1.0;
30             while(a[i].l<=rst&&i<=cnt) maxx=max(maxx,a[i++].r);
31             if(maxx>rst) {
32                 ans++,rst=maxx;
33                 if(rst>=l) break;
34             }else break;
35         }
36         if(rst<l) {printf("-1\n"); continue;}
37         printf("%d\n",ans);
38     }
39 }
40 //貪心(向右拓展能夠澆灌的最右端點:rst)