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, thei-th house has a plaque containing integerpi (1 ≤ pi ≤ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house numberx. Then he goes to the house whose number is written on the plaque of housex (that is, to house px), then he goes to the house whose number is written on the plaque of housepx (that is, to houseppx), and so on.
We know that:
- When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
- When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
- When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
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 by1000000007 (109 + 7).
The single line contains two space-separated integers n andk (1 ≤ n ≤ 1000, 1 ≤ k ≤ min(8, n)) — the number of the houses and the numberk from the statement.
In a single line print a single integer — the answer to the problem modulo 1000000007 (109 + 7).
5 2
54
7 4
1728
这个题主要是题目有点难懂。
意思是说1.1号出发一定能回到1号
2.前k号出发一定能回到1号
3.k+1到n出发不能回到1号
主要要看懂题目意思是不止走一步,也就是说后面k+1以后的不能走到前k号。
所以后面的n-k个元素每个有n-k种标记法
而前面的只要dfs一下就可以了
#include <iostream>
#include <stdio.h>
using namespace std;
typedef long long LL;
const int M=1005;
const int MO=1000000007;
int tot;
int num[9];
int qp(int m,int n)
{
int r=1;
while(n>0)
{
if(n&1)
r=(LL)r*m%MO; //以后记得把强制类型写在第一个因子前作用于第一个因子
m=(LL)m*m%MO;
n>>=1;
}
return r;
}
bool canfill(int k) //判断组合是否成立前k可以走回1
{
for(int i=1;i<=k;i++)
{
int t=0;
int tmp=num[i];
while(tmp!=1)
{
tmp=num[tmp];
t++;
if(t>9)
return 0;
}
}
return 1;
}
void dfs(int t,int k)
{
if(t>k)
{
if(canfill(k))
tot++;
return;
}
for(int i=1;i<=k;i++)
{
num[t]=i;
dfs(t+1,k);
}
}
void setn()
{
for(int i=0;i<M;i++)
num[i]=0;
}
int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
tot=0;
setn();
dfs(1,k);
tot=(LL)tot*qp(n-k,n-k)%MO;
printf("%d\n",tot);
}
return 0;
}