HDU 5916 - Harmonic Value Description

本文介绍了一种算法,用于解决求解给定序列所有排列中第K小的和谐值对应序列的问题。和谐值定义为序列中每一对相邻元素的最大公约数之和。文章提供了一个构造方法,通过特定顺序排列元素确保得到的目标序列具有正确的和谐值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description
The harmonic value of the permutation p1,p2,⋯pn is
∑i=1n−1gcd(pi.pi+1)

Mr. Frog is wondering about the permutation whose harmonic value is the strictly k-th smallest among all the permutations of [n].


Input
The first line contains only one integer T (1≤T≤100), which indicates the number of test cases.

For each test case, there is only one line describing the given integers n and k (1≤2k≤n≤10000).


Output
For each test case, output one line “Case #x: p1 p2 ⋯ pn”, where x is the case number (starting from 1) and p1 p2 ⋯ pn is the answer.


Sample Input


2
4 1
4 2



Sample Output

Case #1: 4 1 3 2

Case #2: 2 4 1 3


题意:先定义和谐值:一个序列中,将每两个相邻的数都求一遍GCD的全部的和。给出一个序列和一个值 k,将给出的序列进行全排列,求出第 k 小的和谐值所对应的序列。给出一个 T 表示数据组数,每行给出一个 n 和 k,n 表示 1 - n 的序列。

一开始想用 next_permutatiom 函数来做,但是数据真是大的不行。后来发现可以构造出一个序列来,因为相邻的两个数的GCD是1,所以第 k 小的值就是让 k 和 2*k 相邻,其他相邻的数的GCD还是1即可。一开始先摆出 2*k 和 k,然后 k+1 到 n,最后 1 到 k-1。

注意是 k 和 k+1 相邻,不要让 2*k 和 k+1 相邻。


#include <cstdio>

int main()
{
    int T;
    scanf("%d", &T);
    for (int icase = 1; icase <= T; ++icase)
    {
        int n, k;
        scanf("%d%d", &n, &k);
        printf("Case #%d: %d %d", icase, k*2, k);
        for (int i = k+1; i <= n; ++i)
        {
            if (i == 2*k)
                continue;
            printf(" %d", i);
        }
        for (int i = 1; i <= k-1; ++i)
            printf(" %d", i);
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值