这题要用到默慈金数,又涨知识了。
默慈金数:http://blog.csdn.net/acdreamers/article/details/41213667
题解:http://blog.csdn.net/qingshui23/article/details/52068031
在这里默慈金数是用来排除错误走法的。当时我没想明白为啥错误的走法是M[n-2],就在51nod问了一下,回答如下:
using System;
using System.IO;
namespace timeless
{
class Program
{
private static Int64 MAXN = (Int64)1e6+10;
private static Int64 mod = (Int64)1e9 + 7;
private static Int64 extend_gcd(Int64 a, Int64 b, ref Int64 x, ref Int64 y)
{
if (a == 0 && b == 0) return -1;
if (b == 0)
{
x = 1;
y = 0;
return a;
}
Int64 d = extend_gcd(b,a%b,ref y,ref x);
y = y - a / b * x;
return d;
}
private static Int64 mod_reverse(Int64 a)
{
Int64 x = 0,y = 0;
Int64 d = extend_gcd(a,mod,ref x, ref y);
if(d == 1) return (x%mod+mod)%mod;
else return -1;
}
static void Main(string[] args)
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
Int64 n = Convert.ToInt64(sr.ReadLine());
Int64[] ans = new Int64[MAXN];
Int64[] M = new Int64[MAXN];
Int64 x;
M[1] = 1;
M[2] = 2;
for (Int64 i = 3; i <= n; ++i)
{
x = mod_reverse(i+2);
M[i] = (((2 * i + 1) * M[i - 1]) % mod + ((3 * i - 3) * M[i - 2]) % mod) * x;
M[i] = (M[i] % mod + mod) % mod;
}
ans[1] = 1;
ans[2] = 2;
for (Int64 i = 3; i <= n; ++i)
{
ans[i] = (3 * ans[i - 1] - M[i - 2]);
ans[i] = (ans[i] % mod + mod) % mod;
}
sw.WriteLine(ans[n]);
sw.Flush();
sr.Close();
sw.Close();
}
}
}