-
Timus 1009
1009. K-based numbers | |
Time Limit | 1.0 second |
Memory Limit | 16 MB |
Description |
Let’s consider K-based numbers, containing exactly N digits. We define a number to be valid if its K-based notation doesn’t contain two successful zeros. For example:
* 1010230 is a valid 7-digit number; * 1000198 is not a valid number; * 0001235 is not a 7-digit number, it is a 4-digit number. Given two numbers N and K, you are to calculate an amount of valid K based numbers, containing N digits. You may assume that 2 ≤ K ≤ 10; N ≥ 2; N + K ≤ 18. |
Input | The numbers N and K in decimal notation separated by the line break. |
Output | The result in decimal notation. |
这道题主要就是考了下排列组合的知识,我的解决方案如下
C# Code
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
class Timus1009
{
static void Main(string[] args)
{
int N = int.Parse(Console.ReadLine());
int K = int.Parse(Console.ReadLine());
Console.WriteLine(GetSolution(N, K));
}
static double GetSolution(int N, int K)
{
double result = 0;
if (N == 1)
{
result = K - 1;
}
else
{
int maximumZeroes = N / 2;
while (maximumZeroes > 0)
{
int n = N - maximumZeroes;
int m = maximumZeroes;
result += (K - 1) * Math.Pow(K-1, N - 1 - maximumZeroes) * Factor(n) / Factor(m) / Factor(n-m);//n!/(m! * (n - m )! ),不就是组合的公式嘛
maximumZeroes--;
}
result += (K - 1) * Math.Pow(K-1, N - 1);
}
return result;
}
static double Factor(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
else
{
return n * Factor(n - 1);
}
}
}
}
这次又变成C++的通不过老!