```python
def count_no_of_ways(n, k):
    """
    Calculates the number of ways to paint a fence with n posts and k colors
    such that at most 2 adjacent posts have the same color.

    Args:
        n: The number of posts in the fence.
        k: The number of available colors.

    Returns:
        The total number of ways to paint the fence according to the rules.
    """
    if n == 0:
        return 0
    
    # DP state variables:
    # `same`: number of ways to paint up to the current post `i` such that
    #         posts `i` and `i-1` have the same color.
    # `diff`: number of ways to paint up to the current post `i` such that
    #         posts `i` and `i-1` have different colors.

    # Initialization for n=1 post.
    # We can imagine a virtual 0th post. The 1st post will always be
    # different from it. So, for n=1, there are 0 ways to have the same
    # color as the previous post, and k ways to have a different color.
    same = 0
    diff = k

    # Iterate from the 2nd post up to the n-th post.
    for i in range(2, n + 1):
        # Store the previous `diff` value because it's needed for the new `same`.
        prev_diff = diff
        
        # Calculate new `diff`:
        # To have post `i` different from `i-1`, the first `i-1` posts
        # can be painted in any valid way (total_prev = same_prev + diff_prev).
        # For each of these ways, we have `k-1` color choices for post `i`.
        # So, diff_i = (same_{i-1} + diff_{i-1}) * (k - 1)
        diff = (same + diff) * (k - 1)
        
        # Calculate new `same`:
        # To have post `i` the same as `i-1`, post `i-1` must be different
        # from post `i-2` (to avoid 3 consecutive same colors).
        # The number of ways for that is `diff_{i-1}`.
        # We have only 1 color choice for post `i` (must be same as `i-1`).
        # So, same_i = diff_{i-1} * 1
        same = prev_diff

    # The total number of ways for n posts is the sum of the two cases.
    return same + diff
```