题目大意:一开始有3堆石子,数量分别为x1,x2,x3,给一个人看,让这个人给出任意2堆石子数量最小差值。这个人不会表达数字,但是他会拿来相同数量的石子代表那个数字,每次拿来的石子成新堆加入前面的石子堆,问多少次后这个人不用再搬石子了。
题目分析:如果石子堆中有2堆数目相等,最小差值就是0,就不用搬石子了。考虑到这个差值是单调不增的,每次把前一次的最小差值加入石子堆,所以新的最小差值在前一次的最小差值和前一次最小值和最小差值之差之间产生,当差值不变时结束。所以维护当前石子堆最小值和当前最小差值2个数就可以了。比赛的时候没仔细分析,一冲动写了个BST才过的。听说这题插入排序也能过。所以这题做法很多,不过最简单的还是第一种。
给出BST代码:
#include <iostream>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
using namespace std;
const int N = 1000005;
typedef __int64 LL;
struct node
{
int l,r;
LL data;
}lcm[N];
int flag;
LL mn;
int ans;
int nums;
LL tmpmn;
void init(int id)
{
lcm[id].l = lcm[id].r = lcm[id].data = -1;
}
void insert(LL num,LL x)
{
if(flag == 0)
return;
if(abs(lcm[num].data - x) < tmpmn)
tmpmn = abs(lcm[num].data - x);
//printf("%d\n",tmpmn);
if(x == lcm[num].data)
{
flag = 0;
return;
}
else
{
if(lcm[num].data > x)
{
if(lcm[num].l == -1)
{
init(nums);
lcm[nums].data = x;
lcm[num].l = nums;
nums ++;
}
else
insert(lcm[num].l,x);
}
else
{
if(lcm[num].r == -1)
{
init(nums);
lcm[nums].data = x;
lcm[num].r = nums;
nums ++;
}
else
insert(lcm[num].r,x);
}
}
}
void dfs(int num)
{
if(num == -1)
return;
dfs(lcm[num].l);
printf("%d ",lcm[num].data);
dfs(lcm[num].r);
}
int main()
{
LL x1,x2,x3;
while(scanf("%I64d%I64d%I64d",&x1,&x2,&x3) != EOF)
{
flag = 1;
init(0);
nums = 1;
lcm[0].data = x1;
insert(0,x2);
insert(0,x3);
mn = abs(x2 - x1);
if(mn > abs(x3 - x1))
mn = abs(x3 - x1);
if(mn > abs(x2 - x3))
mn = abs(x2 - x3);
ans = 1;
tmpmn = 0x7f7f7f7f7f7f7f7fLL;
while(flag)
{
insert(0,mn);
if(tmpmn < mn)
mn = tmpmn;
ans ++;
}
printf("%d\n",ans);
}
return 0;
}