UVA 1452-Jump(约瑟夫环问题变型)

Description

Download as PDF

Integers 1, 2, 3,..., n are placed on a circle in the increasing order as in the following figure. We want to construct a sequence from these numbers on a circle. Starting with the number 1, we continually go round by picking out each k-th number and send to a sequence queue until all numbers on the circle are exhausted. This linearly arranged numbers in the queue are calledJump(n, k) sequence where 1$ \le$n,k.

Let us compute Jump(10, 2) sequence. The first 5 picked numbers are 2, 4, 6, 8, 10 as shown in the following figure. And 3, 7, 1, 9 and 5 will follow. So we getJump(10, 2) = [2,4,6,8,10,3,7,1,9,5]. In a similar way, we can get easilyJump(13, 3) = [3,6,9,12,2,7,11,4,10,5,1,8,13],Jump(13, 10) = [10,7,5,4,6,9,13,8,3,12,1,11,2] andJump(10, 19) = [9,10,3,8,1,6,4,5,7,2].

UVA 1452-Jump(约瑟夫环问题变型)_第1张图片

Jump(10,2) = [2,4,6,8,10,3,7,1,9,5]

You write a program to print out the last three numbers of Jump(n, k) for n, k given. For example suppose that n = 10,k = 2, then you should print 1, 9 and 5 on the output file. Note thatJump(1, k) = [1].

Input

Your program is to read the input from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case starts with a line containing two integersn and k, where5$ \le$n$ \le$500, 000 and 2$ \le$k$ \le$500, 000.

Output

Your program is to write to standard output. Print the last three numbers of Jump(n, k) in the order of the last third, second and the last first. The following shows sample input and output for three test cases.

Sample Input

3 
10 2 
13 10 
30000 54321

Sample Output

1 9 5 
1 11 2 
10775 17638 23432

约瑟夫环问题的变型。之前对这个问题理解错了,导致比赛的时候死活做不出来。

一个环是被删的数 x =  0;

两个环是被删的数 x = 1-(0+k)%2;

三个环是被删的数 x = (k-1)% 3;

依次类推。。。

!!以后学东西不能这么浮躁了。

CODE:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
const int inf=0xfffffff;
typedef long long ll;
using namespace std;

int main()
{
    //freopen("in.in","r",stdin);
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n,k;
        scanf("%d%d",&n,&k);
        int x;
        x = (k-1)%3;
        for(int i=4;i<=n;i++)
            x = (x+k)%i;
        printf("%d", x+1);
        x = 1-(0+k)%2;
        for(int i=3;i<=n;i++)
            x = (x+k)%i;
        printf(" %d", x+1);
        x = 0;
        for(int i=2;i<=n;i++)
            x = (x+k)%i;
        printf(" %d\n",x+1);
    }
    return 0;
}


你可能感兴趣的:(DP)