Sgu 407-number of paths in the Empire [DP]

Source: Internet
Author: User

Given N points to form a ring, a point in the middle is 0, and each point is 0 connected to an edge. The question starts from 0, the number of paths passing through m edges enables the return to 0. Each edge of each vertex can go through multiple times.

Number of output paths

Idea: if you do not consider the data size, you can solve this problem by using matrix multiplication. For details, see the ten applications of the matrix. That is suitable for any graph of 100 points.

N <= 1000, m <= 5000 is not allowed, so I thought of a DP Method. DP [I] [J] indicates the number of solutions from step I to step J, transfer. It seems that the time complexity can also be solved.

This question does not return the remainder of the result. In this case, the answer is thousands of digits. ... The time complexity must be counted as the sum of the two numbers !!! Decisive overwrite memory timeout.

Then I thought of a one-dimensional DP. DP [I] [0] indicates the number of solutions from step I to 0, and DP [I] [1] indicates the number of solutions from step I to non-zero.

Transfer: DP [I + 1] [0] + = DP [I] [1];
DP [I + 1] [1] + = DP [I] [0] * n + dp [I] [1] * 2;

In this way, the question is simple.

I am lazy writing Java.

Code:

import java.util.*;import java.math.*;public class Solution{public static void main(String args[]){BigInteger dp[][]=new BigInteger[5010][2];int n,m;Scanner sc=new Scanner(System.in);while(sc.hasNext()){n=sc.nextInt();m=sc.nextInt();for(int i=0;i<=m;i++)for(int j=0;j<2;j++)dp[i][j]=BigInteger.ZERO;dp[0][0]=BigInteger.ONE;for(int i = 0;i < m;i++)    {        dp[i+1][0]=dp[i+1][0].add( dp[i][1]) ;        BigInteger t=new BigInteger(Integer.toString(n));        t=t.multiply(dp[i][0]);        dp[i+1][1]=dp[i+1][1].add(t) ;        dp[i+1][1]=dp[i+1][1].add(dp[i][1]) ;        dp[i+1][1]=dp[i+1][1].add(dp[i][1]) ;    }System.out.println(dp[m][0]);}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.