pku 1328 第一周訓練 ——貪心


http://poj.org/problem?id=1328

這個題目就是每個島嶼對應一個雷達區間,然后確定好雷達區間后,然后在將區間的s或者e從小到大排序,然后貪心。

第一種按s從小到大排序:

View Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define maxn 1007
using namespace std;
struct node
{
int x,y;
}tagp[maxn];
struct mode
{
double s,e;
}tagq[maxn];
int cmp(mode a,mode b)
{
return a.s < b.s;
}

int main()
{
//freopen("d.in","r",stdin);
int i,n,d;
int cas = 1;
while (scanf("%d%d",&n,&d))
{
if (!n && !d) break;

for (i = 0; i < n; ++i)
scanf("%d%d",&tagp[i].x,&tagp[i].y);
int flag = 0;
for (i = 0; i < n; ++i)
{
if (tagp[i].y > d)
{
flag = 1;
break;
}
double tmp = sqrt((1.0*d*d) - (1.0*tagp[i].y*tagp[i].y));
double s = 1.0*tagp[i].x - tmp;
double e = 1.0*tagp[i].x + tmp;
tagq[i].s = s;
tagq[i].e = e;

}
if (flag)
{
printf("Case %d: %d\n",cas++,-1);
continue;
}
sort(tagq,tagq + n,cmp);
double e = tagq[0].e;
int count = 1;
for (i = 1; i < n; ++i)
{
if (tagq[i].s > e)
{
count++;
e = tagq[i].e;
}
else
{
if (tagq[i].e < e)//注意新的終點的確定
{
e = tagq[i].e;
}
}
}
printf("Case %d: %d\n",cas++,count);

}
return 0;
}

第二中是按e從小到大排序,這里定義int型來接受double型的數據,悲催死我了。。檢查了很長時間。。就是經典貪心之會場安排,不過還是有點差別的。

View Code
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define maxn 1007
using namespace std;
struct node
{
int x,y;
}tagp[maxn];
struct mode
{
double s,e;
}tagq[maxn];
bool hash[maxn];
int cmp(mode a,mode b)
{
return a.e < b.e;
}
int main()
{
//freopen("d.in","r",stdin);
int i,count;
int n,d;
int cas = 1;
while (scanf("%d%d",&n,&d))
{
if (!n && !d) break;
int flag = 0;
for (i = 0; i < n; ++i)
{
scanf("%d%d",&tagp[i].x,&tagp[i].y);
if (tagp[i].y > d)
{
flag = 1;
}
double tmp = sqrt((1.0*d*d) - 1.0*(tagp[i].y*tagp[i].y));
tagq[i].s = 1.0*tagp[i].x - tmp;
tagq[i].e = 1.0*tagp[i].x + tmp;
}
if (flag)
{
printf("Case %d: %d\n",cas++,-1);
continue;
}
sort(tagq,tagq + n,cmp);
//for (i = 0; i < n; ++i)
//printf("%.2lf %.2lf\n",tagq[i].s,tagq[i].e);
int mark;
memset(hash,false,sizeof(hash));
count = 0;
int j;
j = 0;
while (1)
{
mark = 0;
double e = tagq[j].e;
for(i = 0; i < n; ++i)
{
//printf(">>%.2lf %.2lf\n",tagq[i].s,e);
if (!hash[i] && tagq[i].s <= e)//只有起點小於這個區間的終點的才能公用一個雷達
{
hash[i] = true;
}
}
count++;
for (i = 0; i < n; ++i)
{
if (!hash[i])
{
j = i;
mark = 1;
break;
}
}
if (!mark)
{
printf("Case %d: %d\n",cas++,count);
break;
}
}
}
return 0;
}





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM