【模板】最小環
阿新 • • 發佈:2018-12-10
解析:
在一個無向圖裡找出一個由至少三個點組成環,使得環上邊的權值和最小。
程式碼:
#include<cctype>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define ll long long
#define re register
#define gc getchar
#define pc putchar
#define cs const
#define rank Rank
inline
ll getint(){
re ll num=0 ;
re char c;
while(!isdigit(c=gc()));
while(isdigit(c))num=(num<<1)+(num<<3)+(c^48),c=gc();
return num;
}
inline
void outint(ll a){
static char ch[23];
if(a==0)pc('0');
while(a)ch[++ch[0]]=(a-a/10*10)^48,a/=10;
while(ch[0])pc(ch[ch[0]--]);
}
int n,m;
int ans=0x3f3f3f3f ;
int dist[101][101];
int a[101][101];
signed main(){
while(~scanf("%d%d",&n,&m)){
memset(a,0x3f,sizeof a);
ans=0x3f3f3f3f;
for(int re i=1;i<=m;++i){
int u=getint(),v=getint(),val=getint();
a[u][v]=a[v][u]=min(a[u][v],val);
}
memcpy (dist,a,sizeof a);
for(int re k=1;k<=n;++k){
for(int re i=1;i<k;++i){
for(int re j=i+1;j<k;++j){
if(ans>(ll)dist[i][j]+a[j][k]+a[k][i]){
ans=dist[i][j]+a[j][k]+a[k][i];
}
}
}
for(int re i=1;i<=n;++i){
if(i!=k)
for(int re j=1;j<=n;++j){
if(j!=k&&j!=i)
if(dist[i][j]>dist[i][k]+dist[k][j]){
dist[i][j]=dist[i][k]+dist[k][j];
}
}
}
}
if(ans==0x3f3f3f3f)puts("It's impossible.");
else outint(ans),pc('\n');
}
return 0;
}