转载请注明出处:http://blog.csdn.net/u012860063
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4585
3 2 1 3 3 4 2 0
2 1 3 2 4 2
题意:题意: 有N个依次进入少林, 每次输出, 新进和尚 和 战斗等级与其最接近的旧和尚的ID。 ID , 和 战斗等级都是唯一的。
代码如下:
第一种暴力:
| Run ID | Submit Time | Judge Status | Pro.ID | Exe.Time | Exe.Memory | Code Len. | Language | Author |
| 10902174 | 2014-06-23 20:12:16 | Accepted | 4585 | 218MS | 1892K | 1047B | G++ | 天资4747tym |
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
struct man
{
int id;
int g;
int d;
int num;
} p[100047];
bool cmp1(man a , man b)
{
return a.g < b.g;
}
bool cmp2(man a , man b)
{
return a.num < b.num;
}
int test(int a)
{
if( a < 0)
a = -a;
return a;
}
int main()
{
int n,m,i,j,t;
while(scanf("%d",&n) && n)
{
for(i = 0 ; i < n ; i++)
{
scanf("%d%d",&p[i].id,&p[i].g);
p[i].num = i+1;
}
sort(p,p+n,cmp1);//按等级从小到大
for(i = 0 ; i < n ; i++)
{
p[i].d = 1;
t = 1000000000-p[i].g;
for(j = i+1 ; j < n ; j++)//找比当先和尚等级高且最接近的
{
if(p[i].num > p[j].num)
{
t = test(p[j].g - p[i].g);
p[i].d=p[j].id;
break;
}
}
for(j = i-1 ; j >= 0 ; j--)//找比当前和尚等级低且最接近的
{
if(p[i].num > p[j].num)
{
if(t >= test(p[i].g-p[j].g))
{
p[i].d = p[j].id;
}
break;
}
}
}
sort(p,p+n,cmp2);//按和尚进少林寺的顺序排
for(i = 0 ; i < n ; i++)
{
printf("%d %d\n",p[i].id,p[i].d);
}
}
return 0;
}
第二种(STL):
| Run ID | Submit Time | Judge Status | Pro.ID | Exe.Time | Exe.Memory | Code Len. | Language | Author |
| 10902842 | 2014-06-24 09:50:04 | Accepted | 4585 | 375MS | 6620K | 1054 B | G++ | 天资4747tym |
至少我的代码是这样的!或许是优化不够罢了!
代码如下:
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <climits>
#include <ctype.h>
#include <queue>
#include <stack>
#include <vector>
#include <deque>
#include <set>
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
#define PI acos(-1.0)
#define INF 0x3fffffff
int main()
{
int id,g,n;
map<int,int>m;
set<int>s;
while(~scanf("%d",&n) && n)
{
s.clear ();
m.clear ();
s.insert(1000000000);
m[1000000000]=1;
for(int i = 0 ; i < n ; i++)
{
scanf("%d%d",&id,&g);
printf("%d ",id);
set<int>::iterator it = s.lower_bound(g);
if(it == s.end())
{
it--;
printf("%d\n",m[*it]);
}
else
{
int t = *it;
if(it != s.begin())
{
it--;
if(g - (*it) <= t - g)
{
printf("%d\n",m[*it]);
}
else
{
printf("%d\n",m[t]);
}
}
else
{
printf("%d\n",m[*it]);
}
}
m[g] = id;
s.insert(g);
}
}
return 0;
}
hdu 4585 Shaolin两种方法(暴力和STL),布布扣,bubuko.com
原文地址:http://blog.csdn.net/u012860063/article/details/33758789