题意:在图中找一个最小的经过三个以上结点的环
参考:http://blog.csdn.net/olga_jing/article/details/49928443
http://blog.csdn.net/zy691357966/article/details/45673647
用floyd的思想O(n3)处理出解
1 #include<cstdio> 2 #include<cstring> 3 using namespace std; 4 const int inf=2333333; 5 const int maxn=110; 6 const int maxm=10010; 7 int n,m,ans; 8 int Road[maxn][maxn]; 9 int Dist[maxn][maxn]; 10 int read(){ 11 int x=0,f=1; 12 char ch=getchar(); 13 while (ch<‘0‘||ch>‘9‘) { 14 if (ch==‘-‘) f=-1; 15 ch=getchar(); 16 } 17 while (ch>=‘0‘&&ch<=‘9‘){ 18 x=x*10+ch-‘0‘; 19 ch=getchar(); 20 } 21 return x*f; 22 } 23 int min(int a,int b){ 24 return a>b?b:a; 25 } 26 void floyd(){ 27 for (int i=1;i<=n;i++) 28 for (int j=1;j<=n;j++) 29 Dist[i][j]=Road[i][j]; 30 for (int k=1;k<=n;k++){ 31 for (int i=1;i<k;i++) 32 for (int j=i+1;j<k;j++)//注意循环顺序,此时前k-1个点已经处理完毕 33 ans=min(ans,Road[i][k]+Road[k][j]+Dist[i][j]); 34 for (int i=1;i<=n;i++) 35 for (int j=1;j<=n;j++)//一般floyd求最短距离的部分 36 Dist[i][j]=min(Dist[i][j],Dist[i][k]+Dist[k][j]); 37 } 38 } 39 int main(){ 40 //freopen("tour.in","r",stdin); 41 //freopen("tour.out","w",stdout); 42 while (~scanf("%d%d",&n,&m)){ 43 for (int i=0;i<=n;i++){ 44 for (int j=0;j<=n;j++) 45 Road[i][j]=inf; 46 Road[i][i]=0; 47 } 48 ans=inf; 49 for (int i=0;i<m;i++){ 50 int u=read(),v=read(),w=read(); 51 Road[u][v]=Road[v][u]=min(Road[u][v],w); 52 } 53 floyd(); 54 if (ans<inf) printf("%d\n",ans); 55 else printf("No solution.\n"); 56 } 57 return 0; 58 }
时间: 2024-10-21 01:07:53