Travel business Issues

Source: Internet
Author: User

NPC problem, there is no polynomial-time algorithm, but in the algorithm can be done pruning optimization:

1. First write algorithm, missing pruning: The shortest path calculated before the current path >=, the current path does not continue to traverse

#include <cstdio>#include<iostream>#include<cstring>using namespacestd;intN;intmap[ A][ A];intflag[ A];intSolveintstart) {    intI,val, all_visited =1, Min =999999999;  for(i =2; I <= N; i++) {        if(Flag[i]! =0|| Map[start][i] = =0) {            Continue; } all_visited=0; Flag[i]=1;//visitedval = map[start][i] +solve (i); if(Val <min) {min=Val; } Flag[i]=0; }    if(all_visited) {returnmap[start][1]; } Else {        returnmin; }}intMainintargcChar**argv) {    intTC, T, I, J; //freopen ("Input.txt", "R", stdin);CIN >>T;  for(TC =0; TC < T; Tc++) {cin>>N;  for(i =1; I <= N; i++) {             for(j =1; J <= N; J + +) {cin>>Map[i][j]; }} memset (flag,0x00, A*sizeof(int)); printf ("%d\n", Solve (1)); }    return 0;}

2. Optimization algorithm, PATH determination pruning

#include <cstdio>#include<iostream>#include<cstring>using namespacestd;intN, cost, min_cost;intmap[ -][ -];intflag[ -];intsum;voidSolveintstart) {    inti; if(Sum >=N) {if(map[start][1]!=0&& Cost + map[start][1] <min_cost) {Min_cost= Cost + map[start][1]; }        return; }     for(i =2; I <= N; i++) {        if(Flag[i]! =0|| Map[start][i] = =0|| Cost + map[start][i] >=min_cost) {            Continue; } Flag[i]=1;//visitedCost + =Map[start][i]; Sum++;        Solve (i); Sum--; Flag[i]=0; Cost-=Map[start][i]; }}intMainintargcChar**argv) {    intTC, T, I, J; //freopen ("Input.txt", "R", stdin);CIN >>T;  for(TC =0; TC < T; Tc++) {cin>>N;  for(i =1; I <= N; i++) {             for(j =1; J <= N; J + +) {cin>>Map[i][j]; }} memset (flag,0x00, -*sizeof(int)); Cost=0; Min_cost =99999999999; Sum=1; Solve (1); cout<<min_cost<<Endl; }    return 0;}

Notice the red code, don't miss it.

Travel business Issues

Related Article

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.