您的位置:首页 > 其它

POJ 2886 Who Gets the Most Candies?(线段树)

2014-11-11 12:59 337 查看
题意: N个小孩围成一圈,他们被顺时针编号为 1 到 N。每个小孩手中有一个卡片,上面有一个非 0 的数字,游戏从第 K 个小孩开始,他告诉其他小孩他卡片上的数字并离开这个圈,他卡片上的数字
A 表明了下一个离开的小孩,如果 A 是大于 0 的,则下个离开的是左手边第 A 个,如果是小于 0 的,则是右手边的第 A 个小孩。游戏将直到所有小孩都离开,在游戏中,第 p 个离开的小孩将得到 F(p) 个糖果,F(p) 是 p 的约数的个数,问谁将得到最多的糖果。输出最幸运的小孩的名字和他可以得到的糖果。

做法:F(p)预处理一下,跟筛素数很像。线段树上1代表在,0代表离开,点上统计区间和,代表的就是这个区间有几个人还在,查询的操作是插入第几个位置,往右边走就要减去左边区间的人数,这个跟不少题都很像。然后计算下一个是第几个人就自己推公式吧。。别人网上题解的公式我还真没看懂。。

AC代码:

//#pragma comment(linker, "/STACK:102400000,102400000")
#include<cstdio>
#include<ctype.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<vector>
#include<cstdlib>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#include<ctime>
#include<string.h>
#include<string>
#include<sstream>
#include<bitset>
using namespace std;
#define ll long long
#define eps 1e-13
#define NMAX 200005
#define MOD 1000000009
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1)
template<class T>
inline void scan_d(T &ret)
{
char c;
int flag = 0;
ret=0;
while(((c=getchar())<'0'||c>'9')&&c!='-');
if(c == '-')
{
flag = 1;
c = getchar();
}
while(c>='0'&&c<='9') ret=ret*10+(c-'0'),c=getchar();
if(flag) ret = -ret;
}
int T[500005*4];

char name[500005][15];
int w[500005];
int yueme[500005];
void init()
{
for(int i = 1; i <= (int)sqrt(500000.0)+1; i++)
{
for(int j = i+1; (ll)i*(ll)j <= 500000; j++)
yueme[i*j] += 2;
yueme[i*i]++;
}
}

inline void pushup(int rt)
{
T[rt] = T[rt<<1]+T[rt<<1|1];
}
void build(int l, int r, int rt)
{
if(l == r)
{
T[rt] = 1;
return;
}
int mid = (l+r)>>1;
build(lson);
build(rson);
pushup(rt);
}

int updata(int k, int l, int r, int rt)
{
if(l == r)
{
T[rt] = 0;
return l;
}
int mid = (l+r)>>1,i;
if(k <= T[rt<<1]) i = updata(k,lson);
else i = updata(k-T[rt<<1],rson);
pushup(rt);
return i;
}

int main()
{
#ifdef GLQ
freopen("input.txt","r",stdin);
// freopen("o4.txt","w",stdout);
#endif // GLQ
int n,k;
init();
while(~scanf("%d%d",&n,&k))
{
for(int i = 1; i <= n; i++)
scanf("%s %d",name[i],&w[i]);
build(1,n,1);
int ans[2]={0},nct = 1,&ge = T[1];
while(1)
{
int pos = updata(k,1,n,1);
if(ans[1] < yueme[nct])
{
ans[1] = yueme[nct];
ans[0] = pos;
}
if(nct == n) break;
int x1 = k-1,x2 = ge-k+1;
if(nct == n) break;
if(w[pos] > 0)
{
if(w[pos] <= x2) k = x1 + w[pos];
else
{
k = (w[pos]-x2)%(x1+x2);
if(k == 0) k = x1+x2;
}
}
else
{
w[pos] = -w[pos];
if(w[pos] <= x1) k = x1 - w[pos]+1;
else
{
int temp = (w[pos]-x1)%(x1+x2);
if(temp == 0) temp = x1+x2;
k = (x1+x2+1) - temp;
}
}
nct++;
}
printf("%s %d\n",name[ans[0]],ans[1]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: