【CodeForces - 289D】Polo the Penguin and Houses (带标号的无根树,Cayley定理,Prufer编码)
題干:
Little penguin Polo loves his home village. The village has?n?houses, indexed by integers from 1 to?n. Each house has a plaque containing an integer, the?i-th house has a plaque containing integer?pi?(1?≤?pi?≤?n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number?x. Then he goes to the house whose number is written on the plaque of house?x?(that is, to house?px), then he goes to the house whose number is written on the plaque of house?px?(that is, to house?ppx), and so on.
We know that:
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by?1000000007?(109?+?7).
Input
The single line contains two space-separated integers?n?and?k?(1?≤?n?≤?1000,?1?≤?k?≤?min(8,?n)) — the number of the houses and the number?k?from the statement.
Output
In a single line print a single integer — the answer to the problem modulo?1000000007?(109?+?7).
Examples
Input
5 2Output
54Input
7 4Output
1728題目大意:
給定 n 和k,n 表示有n個房子,然后每個有一個編號,一只鵝要從一個房間中開始走,下一站就是房間的編號,現在要你求出有多少種方法編號并滿足下面的要求:
1.如果從1到k開始走,一定能走到 1。
2.如果從k+1到n 開始走,一定走不到 1.
3.如果從 1 開始走,那么一定能回到1,并且走過房間數不為0.
解題報告:
? 做這個題涉及到一個結論,,(當然不知道這個結論,這題中也可以通過規律看出來)。
? 有一種序列叫,Purfer序列,有一個定理叫Cayley定理。
Cayley定理:有n個節點的完全圖的生成樹的數量是,或者說n個節點的帶標號的無根樹有個。
Prufer編碼:給定一棵帶標號的無根樹,找出編號最小的葉子節點,寫下與它相鄰的節點的編號,然后刪掉這個葉子節點。反復執行這個操作直到只剩兩個節點為止。
感謝wjh大佬的講解orz(鏈接)
所以對于k前面一部分就是k^(k-1)了,,后面一部分很好推出來是(n-k)^(n-k)。求和就行了。
(因為通過題意很容易得出結論,,1~k 和 k+1~n? 這倆區間不能有交集的,,也就是 互相不可達的。所以分開求就好了)
其實前半部分能想成是一棵樹的結構就不容易啊2333.、、
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair #define fi first #define se second using namespace std; const int MAX = 2e5 + 5; ll mod = 1e9 + 7; ll f[MAX],n,k; ll qpow(ll a,ll k) {ll res = 1;while(k) {if(k&1) {res = (res*a)%mod;}k>>=1;a = (a*a)%mod;}return res%mod; } int main() {f[1]=0;f[2]=1;for(int i = 3; i<=1005; i++) {f[i] = (i-1) * ((f[i-1]+f[i-2])%mod)%mod; // printf("%lld\n",f[i]);}cin>>n>>k;printf("%lld\n",(qpow(k,k-1)*qpow(n-k,n-k))%mod);return 0 ;}?
總結
以上是生活随笔為你收集整理的【CodeForces - 289D】Polo the Penguin and Houses (带标号的无根树,Cayley定理,Prufer编码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017交行信用卡排名 交行当季主推的信
- 下一篇: 3.3万兆全球领先!高通发布全新Wi-F