跳到正文

题解

题解:SP1870 MKLABELS - Making Labels

acertainperson约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年5月15日
更新
2026年5月15日
篇幅
约 2 分钟
题目
SP1870

版本

  1. v4当前
  2. v3
  3. v2
  4. v1

SP1870 MKLABELS - Making Labels

解题思路

从样例可以找到规律:

  • N=1N=1,ans=10ans= 1^{0}。
  • N=2N=2,ans=20ans = 2^{0}。
  • N=3N=3,ans=31ans = 3^{1}。
  • N=4N=4,ans=42ans = 4^{2}。
  • N=5N=5,ans=53ans = 5^{3}。

因此可以得出公式:ans=Nmax⁡(0,N−2)ans = N^{\max(0, N-2)}。

也就是输出 NN−2N^{N-2}(N≥2N\ge2),N=1或2N=1\text{或}2 时输出 11。

证明

由 Cayley 公式:NN 个标号顶点构成的树有 NN−2N^{N-2} 棵。

证明:每棵树唯一对应一个长度为 N−2N-2、值域 [1,N][1,N] 的序列,序列总数 NN−2N^{N-2},因此树的数量相同。

复杂度分析

  • 时间复杂度:O(log⁡n)O(\log n)。
  • 空间复杂度:O(1)O(1)。

代码实现

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,ans;
int ksm(int a,int b){
    int r=1;
    while(b){
        if(b&1) r=r*a;
        a=a*a;
        b>>=1;
    }
    return r;
}
signed main(){

    while(scanf("%lld",&n)==1&&n){
        ans++;
        printf("Case %lld, N = %lld, # of different labelings = %lld\n",ans,n,ksm(n,max(0LL,n-2)));
    }

    return 0;
}
原文