zoukankan      html  css  js  c++  java
  • [vijos1046] 观光旅游

    题目链接

    题意:在图中找一个最小的经过三个以上结点的环

    参考:http://blog.csdn.net/olga_jing/article/details/49928443

              http://blog.csdn.net/zy691357966/article/details/45673647

    用floyd的思想O(n³)处理出解

     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
    ",ans);
    55         else printf("No solution.
    ");
    56     }
    57     return 0;
    58 }
    View Code
  • 相关阅读:
    2
    作业5
    实验十
    作业 5 指针应用
    九九乘法表
    实验七(课堂练习)
    实验六 数组 (2)
    实验六 数组
    课堂实验5(求从m到n之间(包括m和n)所有素数的和)
    课堂实验5-2
  • 原文地址:https://www.cnblogs.com/vincent-hwh/p/7337230.html
Copyright © 2011-2022 走看看