贴代码在此,有待后续改进。
#include <iostream>
#include<stdio.h>
#include<algorithm>
#include<stdlib.h>
#include<string.h>
#include<stack>
#include<queue>
using namespace std;
#define maxn 2010
#define INF 0xffffff
int w[maxn][maxn] ;
int n , scanfk;
struct Node{
int id, dist ;
bool operator<(const Node &b)const{// 重定义优先级,以小为先,按升序排列
return dist > b.dist ;
}
};
priority_queue<Node>q ;
int pre[maxn] ;
int visited[maxn] ;
Node node[maxn] ;
void Dijkstra(int s){
for(int i =1 ; i<= n ; i++){
node[i].id = i ;
node[i].dist = 999999 ;
pre[i] = -1 ;
visited[i] = 0 ;
}
node[s].dist = 0 ;
q.push(node[s]) ;
while(!q.empty()){
Node now = q.top() ;
q.pop() ;
int nowid = now.id ;
if(visited[nowid])
continue ;
visited[nowid] = 1 ;
for(int j = 1 ; j<= n ; j++){
if(!visited[j] && node[j].dist > now.dist + w[nowid][j]){
node[j].dist = now.dist + w[nowid][j] ;
pre[j] = nowid ;
q.push(node[j]) ;
}
}
}
}
int ma[maxn] ;
int kk ;
int printD(int s, int v){ //打印从源点s到结点v的一条最短路径上的所有结点。
if(v == s){
// printf("%d" , s) ;
ma[kk++] = s ;
}
//else if(pre[v] == -1 )
// printf("no path \n") ;
else{
printD( s, pre[v]) ;
// printf("%d" , v) ;
ma[kk++] = v ;
}
return kk -1 ;
}
int len(int ll){ // 计算从1到ll数组的相互距离
int sumlen = 0 ;
for(int i = 1 ; i<= ll ; i++){
sumlen += 2 * node[ma[i]].dist ;
}
for(int i = 2 ; i <= ll-1 ; i++){
sumlen += 2 * w[ma[i]][ma[i+1]] ;
}
return sumlen ;
}
int main()
{
int t ;
int m , a, b, c , newsta[maxn] ;
scanf("%d" , &t) ;
while( t--){
scanf("%d%d" , &n , &scanfk) ;
while(!pp.empty()) pp.pop() ;
memset(newsta , 999999 , sizeof(newsta) ) ;
for(int i = 1 ; i<= n ;i++){
for(int j =1 ; j<= n ; j++){
if(i == j)
w[i][j]= 0 ;
else w[i][j] = w[j][i] = 99999 ;
}
}
if(n == 0 && m == 0) break ;
for(int i = 1 ; i<= n -1 ; i++){
scanf("%d%d%d" , &a , &b , &c) ;
w[a][b] = w[b][a] = c ;
}
int g = 0 ;
for(int i =1 ; i<= n ; i++){
Dijkstra(i) ;
for(int j = i + 1 ; j<= n ;j++){
kk = 1 ;
memset(ma , 0 , sizeof(ma)) ;
int le = printD( i , j) ;
//cout << "=" << i << ":" << j << endl ;
if(le < scanfk)
continue ;
newsta[g++] = len(scanfk) ;
}
}
sort(newsta , newsta + g ) ;
cout << newsta[0] << endl;
}
return 0;
}
Cities
Accepts: 73
Submissions: 390
Time Limit: 4000/2000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)