Bus Stop

题目

题意:

大概就是在x轴上(一维),有n个房子的坐标,你要建立公交车站,使得每个房子离最近的车站不过10公里,求最少的车站。

思路:

很简单,之接贪心即可,每次判断当前房子的后20公里有没有房子,有的话继续一直向前,直到没有为止,然后在第一个达不到的房子右侧10处设公交站,接着贪心。

代码:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 int a[2000005];
 8 
 9 int main()
10 {
11     //cout << "Hello world!" << endl;
12     int t;
13     cin>>t;
14     while(t--)
15     {
16         int n;
17         scanf("%d",&n);
18         for(int i=0; i<n; i++)
19             scanf("%d",&a[i]);
20         sort(a,a+n);
21         int cnt=1;
22         int j=0;
23         int i=0;
24         while(i<n)
25         {
26             while(i<n&&a[i]<=a[j]+20)
27                 i++;
28             cnt++;
29             j=i;
30         }
31         printf("%d
",cnt-1);//注意这里
32     }
33     return 0;
34 }
View Code

贴个网上的便输入边判断的代码:

 1 #include<bits/stdc++.h>
 2 #define ll long long
 3 using namespace std;
 4 int main()
 5 {
 6     int T;
 7     scanf("%d",&T);
 8     while(T--)
 9     {
10         int n,x,p=-100,ans=0;
11         scanf("%d",&n);
12         for(int i=1;i<=n;i++)
13         {
14             scanf("%d",&x);
15             if(x>p+10)
16             ans++,p=x+10;
17         }
18         printf("%d
",ans);
19     }
20 }
View Code

唉,英文题目看的我真心难受,阿西吧,继续coding

原文地址:https://www.cnblogs.com/hbhdhd/p/11944641.html