C - Reconciled?
Time limit : 2sec / Memory limit : 256MB
Score : 300 points
Problem Statement
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.
Sample Input 1
Copy
2 2
Sample Output 1
Copy
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
Copy
3 2
Sample Output 2
Copy
12
Sample Input 3
Copy
1 8
Sample Output 3
Copy
0
Sample Input 4
Copy
100000 100000
Sample Output 4
Copy
530123477
该题是求两种动物不相邻排序方法的个数,所以若两种动物的数量差值大于等于2,则没有这种排序方法;
设s(x)为x的阶乘(对Mod求模),n与m相差大于等于2则输出0,相差为1则输出s(n)*s(m)%Mod,相同则输出s(n)*s(n)*2%Mod。
#include <iostream>
#include <cstdio>
#include <cmath>
#define ll long long
#define MOD 1000000007
using namespace std;
ll s(ll x)
{
ll ans=1,i=1;
while(i<=x)
{
ans=(ans*i)%MOD;
i++;
}
return ans;
}
int main()
{
ll n,m;
while(cin>>n>>m)
{
if(abs(n-m)>=2)
{
printf("0\n");
continue;
}
if(abs(n-m)==1)
{
ll sum=s(n)*s(m)%MOD;
cout<<sum<<endl;
}
else
{
ll sum=s(n)*s(n)*2%MOD;
cout<<sum<<endl;
}
}
return 0;
}