1 刷油漆问题
给定一个有n根柱子和k种颜色的围栏,找出油漆围栏的方法,使最多两个相邻的柱子具有相同的颜色。因为答案可以是大的,所以返回10^9+7的模。
计算结果:
2 栅栏油漆算法的源程序
using System;
namespace Legalsoft.Truffer.Algorithm
{
public static partial class Number_Sequence
{
public static long Painting_Fence_Number(int n, int k)
{
long[] dp = new long[n + 1];
int mod = 1000000007;
dp[1] = k;
int same = 0;
int diff = k;
for (int i = 2; i <= n; i++)
{
same = diff;
diff = (int)(dp[i - 1] * (k - 1));
diff = diff % mod;
dp[i] = (same + diff) % mod;
}
return dp[n];
}
public static long Painting_Fence_Number_Second(int n, int k)
{
long total = k;
int mod = 1000000007;
long same = 0;
long diff = k;
for (int i = 2; i <= n; i++)
{
same = diff;
diff = total * (k - 1);
diff = diff % mod;
total = (same + diff) % mod;
}
return total;
}
}
}
——————————————————
POWER BY TRUFFER.CN
3 代码格式
using System;
namespace Legalsoft.Truffer.Algorithm
{
public static partial class Number_Sequence
{
public static long Painting_Fence_Number(int n, int k)
{
long[] dp = new long[n + 1];
int mod = 1000000007;
dp[1] = k;
int same = 0;
int diff = k;
for (int i = 2; i <= n; i++)
{
same = diff;
diff = (int)(dp[i - 1] * (k - 1));
diff = diff % mod;
dp[i] = (same + diff) % mod;
}
return dp[n];
}
public static long Painting_Fence_Number_Second(int n, int k)
{
long total = k;
int mod = 1000000007;
long same = 0;
long diff = k;
for (int i = 2; i <= n; i++)
{
same = diff;
diff = total * (k - 1);
diff = diff % mod;
total = (same + diff) % mod;
}
return total;
}
}
}