1. 程式人生 > >HDU 6043 KazaQ's Socks (規律)

HDU 6043 KazaQ's Socks (規律)

n-1 cnblogs sample swe 順序 裏的 this c-s close

Description

KazaQ wears socks everyday.

At the beginning, he has nn pairs of socks numbered from 11 to nn in his closets.

Every morning, he puts on a pair of socks which has the smallest number in the closets.

Every evening, he puts this pair of socks in the basket. If there are n?1n?1 pairs of socks in the basket now, lazy KazaQ
has to wash them. These socks will be put in the closets again in tomorrow evening.

KazaQ would like to know which pair of socks he should wear on the kk-th day.

Input

The input consists of multiple test cases. (about 20002000)

For each case, there is a line contains two numbers n,kn,k (2n109,1k1018)(2≤n≤109,1≤k≤1018).

Output

For each test case, output " Case #xx: yy" in one line (without quotes), where xx indicates the case number starting from 11 and yy denotes the answer of corresponding case. Sample
Sample Input
3 7
3 6
4 9 
 
Sample Output
Case #1: 3
Case #2: 1
Case #3: 2 

題意:

  有n雙襪子,標號1到n放在櫃子裏,每天早上起床穿襪子選標號最小的一雙。然後晚上回來將穿過的扔到籃子裏。當籃子裏的襪子數量為n-1的時候,就把這些襪子洗一下,第二天晚上再放回櫃子裏。問在第K天穿的是哪一個標號的襪子。

思路:

  簡單排一下就會發現一個簡單的規律,前n天肯定都是按標號穿,然後後面幾天因為穿第n雙襪子的時候,所以穿1到n-1號,之後n號襪子在洗所以穿1號襪子。

  然後穿1到n-2號,因為此時n-1號在洗,所以接下來穿的是n號襪子。

  依次類推便可發現襪子穿的標號順序為1、2、...、n 1、2、...、n-1 1、2、...、n、

  由此規律來進行分段,前面n個數直接輸出,後面的分開前後兩部分,取模就可以得出結果了。

  比如:

    一共四雙襪子穿的順序為:(1 2 3 4)( 1 2 3)( 1 2 4)( 1 2 3)( 1 2 4)……

    一共五雙襪子穿的順序為:(1 2 3 4 5)( 1 2 3 4)( 1 2 3 5)( 1 2 3 4)( 1 2 3 5)……

代碼:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<math.h>
using namespace std;
int main()
{
    long long n,k;
    long long ans;
    long long  logo=1;
    while(~scanf("%lld%lld",&n,&k))
    {
        if(k<=n)
            printf("Case #%d: %lld\n",logo++,k);//前n天直接輸出k
        else
        {
            k-=n;
            long long flag;
            flag=k%(n-1);//去余數
            if(flag==0)//如果是最後一天,判斷是穿第n雙還是n-1雙
            {
                if(k/(n-1)%2==1)
                    ans=n-1;
                else
                    ans=n;
            }
            else//如果不是最後一天,則輸出余數
                ans=flag;
            printf("Case #%d: %lld\n",logo++,ans);
        }
    }
}

HDU 6043 KazaQ's Socks (規律)