題目鏈接 Description The Pizazz Pizzeria prides itself in delivering pizzas to its customers as fast as possible. Unfortunately, due to cutbacks, they can ...
Description
The Pizazz Pizzeria prides itself in delivering pizzas to its customers as fast as possible. Unfortunately, due to cutbacks, they can afford to hire only one driver to do the deliveries. He will wait for 1 or more (up to 10) orders to be processed before he starts any deliveries. Needless to say, he would like to take the shortest route in delivering these goodies and returning to the pizzeria, even if it means passing the same location(s) or the pizzeria more than once on the way. He has commissioned you to write a program to help him.
Input
Input will consist of multiple test cases. The first line will contain a single integer n indicating the number of orders to deliver, where 1 ≤ n ≤ 10. After this will be n + 1 lines each containing n + 1 integers indicating the times to travel between the pizzeria (numbered 0) and the n locations (numbers 1 to n). The jth value on the ith line indicates the time to go directly from location i to location j without visiting any other locations along the way. Note that there may be quicker ways to go from i to j via other locations, due to different speed limits, traffic lights, etc. Also, the time values may not be symmetric, i.e., the time to go directly from location i to j may not be the same as the time to go directly from location j to i. An input value of n = 0 will terminate input.
Output
For each test case, you should output a single number indicating the minimum time to deliver all of the pizzas and return to the pizzeria.
Sample Input
3 0 1 10 10 1 0 1 2 10 1 0 10 10 2 10 0 0
Sample Output
8
題意:貌似是一個人從店裡出發送東西,把n個地方的東西送完了再回到店裡,商店及這n個地方任意兩兩之間的距離給了,即輸入的(n+1)*(n+1)的矩陣,每個點可以到多次,求走的最短路徑值;
思路:先用floyd計算兩點之間的最短距離,定義dp[s][i],s表示已經走過的點,i表示現在正位於的點,dp[s][i]的值表示走完剩餘沒到的點(及加上回商店的路徑長)所需的最短路徑長,從底層開始推到即s=1<<(n+1):0;
代碼如下:
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <cstdlib> using namespace std; const int inf=99999999; int dp[2505][12]; int d[12][12]; int main() { int n; while(scanf("%d",&n)&&n) { for(int i=0;i<=n;i++) for(int j=0;j<=n;j++) scanf("%d",&d[i][j]); for(int k=0;k<=n;k++) for(int i=0;i<=n;i++) for(int j=0;j<=n;j++) d[i][j]=min(d[i][j],d[i][k]+d[k][j]); int t=1<<(n+1); for(int i=0;i<t;i++) for(int j=0;j<=n;j++) dp[i][j]=inf; dp[t-1][0]=0; for(int s=t-1;s>=0;s--) for(int i=0;i<=n;i++) { if(!(s&(1<<i))&&(s||i)) continue;
///白書上沒有這條語句,加上後可以減小運算量。為什麼呢?因為i表示當前所在點,那s狀態集合應該包含i,這樣可以減少很大一部分的計算量,但是還得考慮s=0的情況
///s=0時是為了計算走完所有應送東西的點後,加上從結束的點回商店的距離,總距離最小者即為結果。
///或者也可以直接寫if(!(s&(1<<i))) continue; 這樣就得在最後計算從結束點回商店總距離,即下麵註釋部分代碼; for(int j=0;j<=n;j++) { if(s&(1<<j)) continue; dp[s][i]=min(dp[s][i],dp[s^(1<<j)][j]+d[j][i]); } } printf("%d\n",dp[0][0]); // int tmp=inf; // for(int i=1;i<=n;i++) // { // tmp=min(tmp,dp[(1<<i)][i]+d[i][0]); // } // printf("%d\n",tmp); } return 0; }