Question: The following problem can be solved by dynamic programming. I have got two solutions. The first one is mine, and it only passes a few

The following problem can be solved by dynamic programming. I have got two solutions. The first one is mine, and it only passes a few test cases. But I can't figure out why.

### Problem Statement

N cards, numbered 1 through N, are arranged in a line. For each i (1i

### Input

The input is given from Standard Input in the following format:

N

A_1 B_1

A_2 B_2

A_N B_N

My solution

import sys

MOD = 998244353

input = lambda :sys.stdin.readline().rstrip()

mi = lambda :map(int,input().split())

li = lambda :list(mi())

dpair = lambda a, b, c, d: (a!= c) + (a!=d) + (b!=c) + (b!= d)

N = int(input())

AB = [li() for _ in range(N)]

dp = 2

for i in range(1, N):

# print(dpair(*AB[i-1], *AB[i]))

dp = int (dp * dpair(*AB[i-1], *AB[i]) / 2) % MOD

Correct solution

MOD=998244353

N=int(input()) data=[tuple(map(int,input().split())) for _ in range(N)] dp=[[0,0] for _ in range(N)] dp[0]=[1,1] for i in range(1,N): for pre in range(2): for nxt in range(2): if data[i-1][pre]!=data[i][nxt]: dp[i][nxt]+=dp[i-1][pre] dp[i][0]%=MOD dp[i][1]%=MOD

print((dp[N-1][0]+dp[N-1][1])%MOD)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!