調試的錯誤就是編程給你最好的東西,因爲在每個錯誤上面都標誌着前進的一步。——CSDN
CodeVS AC 150!
題目
- 時間限制: 1 s
- 空間限制: 32000 KB
- 題目等級 : 鑽石 Diamond
- 題目描述 Description
某鄉有n個村莊(1< n<=15),有一個售貨員,他要到各個村莊去售貨,各村莊之間的路程s(0< s<1000)是已知的,且A村到B村與B村到A村的路大多不同。爲了提高效率,他從商店出發到每個村莊一次,然後返回商店所在的村,假設商店所在的村莊爲1,他不知道選擇什麼樣的路線才能使所走的路程最短。請你幫他選擇一條最短的路。
- 輸入描述 Input Description
村莊數n和各村之間的路程(均是整數)
- 輸出描述 Output Description
最短的路程
- 樣例輸入 Sample Input
3
0 2 1
1 0 2
2 1 0
- 樣例輸出 Sample Output
3
分析
寫了很久,通過輸出路徑才發現狀態壓縮沒有點的先後順序,於是求得比正解小,歸結於
不動腦子調試能力欠缺
錯因:對於優先隊列使用不熟練+對題目/代碼分析不清
說明:圖論題目調試時嘗試輸出路徑;狀態多了以後一定判重;一時調不出來就換換腦子嘗試別的方向
代碼
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
const int MN=21;
struct zt{
int w,p;
int s;
//int cnt;
//int a[20];
};
bool operator <(zt a,zt b){
return a.w>b.w;
}
int t[MN][MN],n,a[71234][16];
priority_queue<zt>q;
void bfs(){
zt k1;
k1.s=0;
k1.w=0;
k1.p=1;
//k1.cnt=0;
//cout<<"k1"<<' '<<k1.p<<' '<<k1.s<<' '<<k1.p<<endl;
q.push(k1);
while(!q.empty()){
zt k=q.top();
q.pop();
// cout<<"k"<<' '<<k.p<<' '<<k.s<<' '<<k.w<<endl;
int i=k.p;
if(k.s!=((1<<n)-1)){
for(int j=1;j<=n;j++){
if(t[i][j]){
if(k.s!=(k.s|(1<<(j-1))))
{
zt k2=k;
k2.w+=t[i][j];
k2.s=k2.s|(1<<(j-1));
k2.p=j;
//k2.a[++k2.cnt]=j;
// cout<<"k2"<<' '<<k2.p<<' '<<k2.s<<' '<<k2.w<<endl;
if(a[k2.s][k2.p]>k2.w){
q.push(k2);
a[k2.s][k2.p]=k2.w;
}
}
}
} //vis[i]=0;
}
else {
if(k.p==1){
cout<<k.w<<endl;
/*for(int i=1;i<=k.cnt;i++){
cout<<k.a[i]<<' ';
}
cout<<endl;
*/
return ;
}
}
}
}
int main(){
cin>>n;
// n++;
memset(a,0x3f,sizeof(a));
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>t[i][j];
}
}
bfs();
return 0;
}