Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 9586 | Accepted: 2917 | |
Case Time Limit: 2000MS |
Description
N children are sitting in a circle to play a game.
The children are numbered from 1 to N in clockwise order. Each of them has a card with a non-zero integer on it in his/her hand. The game starts from the K-th child, who tells all the others the integer on his card and jumps out of the circle. The integer on his card tells the next child to jump out. Let A denote the integer. If A is positive, the next child will be the A-th child to the left. If A is negative, the next child will be the (−A)-th child to the right.
The game lasts until all children have jumped out of the circle. During the game, the p-th child jumping out will get F(p) candies where F(p) is the number of positive integers that perfectly divide p. Who gets the most candies?
Input
Output
Output one line for each test case containing the name of the luckiest child and the number of candies he/she gets. If ties occur, always choose the child who jumps out of the circle first.
Sample Input
4 2 Tom 2 Jack 4 Mary -1 Sam 1
Sample Output
Sam 3
Source
第K个孩子先出圈,如果他手中卡片上的数字A>0,下一个出圈的是他左手边第A个孩子。
A<0,下一个出圈的是他右手边第(-A)个孩子。第p个出圈的孩子会得到F(p)个糖果,F(p)为p的因子数。
输出得到糖果数最多的孩子的名字及糖果数目。
【思路】孩子数目很大(1~500000),于是想到要用线段树来优化,然后就是模拟出圈过程。并更新最大糖果数目。
然后因为是一个圈,编号就每次都要取模,因为取模结果总是0~num-1,而编号确实1~num,所以取模要编号K-1,
求出结果后再K+1。
①A>0, 因为这个人出去了,那么后面的人的编号都会先减一所以这里的要K-2。于是下一个出圈的就应该是剩余孩子中的第((K-2+A)%num+num)%num+1个。
②A<0,因为这个人出去,对前面的人是没有影响的。于是下一个出圈的就应该是剩余孩子中的第((K-1+A)%num+num)%num+1个。
这里的F(p)我是直接数组暴力打表得来的,最后1500MS过了,看网上有一种反素数,更加快,有空去学。
#include<stdio.h>
#include<string.h>
#define N 500005
int ip[N];
struct node
{
int x,y,len;
}a[N*3];
struct pp
{
char name[100];
int id;
}st[N];
void init()
{
int i,j;
memset(ip,0,sizeof(ip));
for(i=1;i<=N;i++)
{
for(j=i;j<=N;j+=i)
ip[j]++;
}
}
void build(int x,int y,int t)
{
a[t].x=x; a[t].y=y;
a[t].len=y-x+1;
if(x==y ) return;
int temp=t<<1,mid=(x+y)>>1;
build(x,mid,temp);
build(mid+1,y,temp+1);
}
int find(int t,int k)
{
a[t].len--;
if(a[t].x==a[t].y)
{
return a[t].x;
}
int temp=t<<1,mid=(a[t].x+a[t].y)>>1;
if(a[temp].len>=k)
return find(temp,k);
else if(a[temp+1].len>=k-a[temp].len)
return find(temp+1,k-a[temp].len);
else
return 0;
}
int main()
{
int n,k,i,num,u,ans,m;
init();
while(scanf("%d%d",&n,&k)!=EOF)
{
build(1,n,1);
for(i=1;i<=n;i++)
scanf("%s%d",st[i].name,&st[i].id);
ans=ip[1]; u=1; num=1; find(1,k); m=k;
while(1)
{
n--; num++;
if(st[k].id>0)
m=((m-2+st[k].id)%n+n)%n+1;
else
m=((m-1+st[k].id)%n+n)%n+1;
k=find(1,m);
if(ip[num]>ans)
{
ans=ip[num];
u=k;
}
if(n==1) break;
}
printf("%s %d\n",st[u].name,ans);
}
return 0;
}