POJ 3126 Prime Path SPFA

Source: Internet
Author: User

 

Question:

Give you two four-digit prime numbers s and t. Each time you change a number, the changed number is also a prime number, and find the minimum number of changes from s to t.

Ideas:

First, obtain all the four-digit prime numbers.

If there is only one difference between two prime numbers, a graph is created (bidirectional)

Finally, find the shortest path (SPFA or BFS)

 

# Include
 
  
# Include
  
   
# Include
   
    
# Define deusing namespace std; const int MAXN = 10000 + 10; const int INF = 0x3ffffff; bool isprimer [MAXN]; int primer [MAXN], num; int head [MAXN], len; struct edge {int to, next;} e [MAXN * 10]; void add (int from, int to) {e [len]. to = to; e [len]. next = head [from]; head [from] = len ++;} // judge whether two numbers have only one digit but different bool judge (char * x, char * y) {int cnt = 0; for (int I = 0; I <4; I ++) if (x [I] = y [I]) cnt ++; return cnt = 3;} int dis [MAXN]; bool vis [MAXN]; int spfa (int s, int t) {for (int I = 1000; I <= 10000; I ++) {dis [I] = INF; vis [I] = 0;} dis [s] = 0; vis [s] = true; queue
    
     
Q; q. push (s); while (! Q. empty () {int cur = q. front (); q. pop (); for (int I = head [cur]; I! =-1; I = e [I]. next) {int to = e [I]. to; if (dis [cur] + 1 <dis [to]) {dis [to] = dis [cur] + 1; if (! Vis [to]) q. push (to) ;}}return dis [t];} int main () {memset (head,-1, sizeof (head); num = len = 0; for (int I = 2; I * I
     
      

 

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.