Reconciled?(AtCoder-2642)
Problem Description
Snuke has N dogs and M monkeys. He wants them to line up in a row.
As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.
How many such arrangements there are? Find the count modulo 109+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.
Constraints
- 1≤N,M≤105
Input
Input is given from Standard Input in the following format:
N M
Output
Print the number of possible arrangements, modulo 109+7.
Example
Sample Input 1
2 2
Sample Output 1
8
We will denote the dogs by A and B, and the monkeys by C and D. There are eight possible arrangements: ACBD, ADBC, BCAD, BDAC, CADB, CBDA, DACB and DBCA.Sample Input 2
3 2
Sample Output 2
12
Sample Input 3
1 8
Sample Output 3
0
Sample Input 4
100000 100000
Sample Output 4
530123477
题意: 有两种动物分别是 n 和 m 个,要排成一行,要求相邻的两个动物种类不同,问有多少种方案
思路:
由于相邻两动物种类不能相同,那么当 |n-m|>1 时,无解,输出 0 即可
那么,还有两种情况:
当 n=m 时:
只考虑 n 的情况下,方案数为 n 的全排列,即有 n!种方案
那么对于这 n 个动物,其中有 n-1 个空可以放 n-1 个动物,剩下的 1 个动物可以放最左边也可以放最右边,方案数为 m 的全排列乘以 2,即有 2*m!种方案
根据乘法原理,答案即为:2*n!*m!
当 |n-m|=1 时:
假设 n>m,那么只考虑 n 的情况下,方案数为 n 的全排列,即有 n!种方案
那么对于这 n 个动物,其中正好有 m 个空可以放 m 个动物,方案数为 m 的全排列,即有 m!种方案
根据乘法原理,答案即为:n!*m!
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 100000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
LL fac[N];
void init(){
fac[0]=1;
fac[1]=1;
for(int i=2;i<=1E5;i++)
fac[i]=fac[i-1]*i%MOD;
}
int main(){
init();
int n,m;
scanf("%d%d",&n,&m);
if(abs(n-m)>1)
printf("0\n");
else if(abs(n-m)==0){
LL res=((fac[n]%MOD*fac[m]%MOD)%MOD)*2%MOD;
printf("%lld\n",res);
}
else{
LL res=(fac[n]%MOD*fac[m]%MOD)%MOD;
printf("%lld\n",res);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探