#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<map>
#define maxn 31
using namespace std;
struct edge{
int u,v,w;
bool operator<(const edge &e)const{ return w<e.w; }
}e[maxn*maxn],dp[maxn];
int key[maxn],minedge[maxn];
int fa[maxn],g[maxn][maxn];
bool tree[maxn][maxn];
int n,m,k,ans;
map<string,int> id;
inline int read(){
register int x(0),f(1); register char c(getchar());
while(c<'0'||'9'<c){ if(c=='-') f=-1; c=getchar(); }
while('0'<=c&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
int get(int x){ return fa[x]==x?x:fa[x]=get(fa[x]); }
inline void kruskal(){
sort(e+1,e+1+m);
for(register int i=1;i<=n;i++) fa[i]=i;
for(register int i=1;i<=m;i++){
int u=e[i].u,v=e[i].v,w=e[i].w;
if(u==1||v==1||get(u)==get(v)) continue;
fa[get(u)]=get(v),tree[u][v]=tree[v][u]=true;
ans+=w;
}
}
void dfs(int u,int pre){
for(register int i=2;i<=n;i++) if(tree[u][i]){
if(i==pre) continue;
if(dp[i].w==-1){
if(dp[u].w>g[u][i]) dp[i]=dp[u];
else{
dp[i].w=g[u][i],dp[i].u=u,dp[i].v=i;
}
}
dfs(i,u);
}
}
inline void solve(){
register int cnt=0;
for(register int i=2;i<=n;i++) if(g[i][1]!=0x3f3f3f3f){
int col=get(i);
if(g[i][1]<minedge[col]) minedge[col]=g[i][1],key[col]=i;
}
for(register int i=1;i<=n;i++) if(minedge[i]!=0x3f3f3f3f){
cnt++,tree[key[i]][1]=tree[1][key[i]]=true;
ans+=g[1][key[i]];
}
for(register int i=cnt+1;i<=k;i++){
memset(dp,-1,sizeof dp);
dp[1].w=-0x3f3f3f3f;
for(register int j=2;j<=n;j++) if(tree[1][j]) dp[j].w=-0x3f3f3f3f;
dfs(1,1);
int d,mini=0x3f3f3f3f;
for(register int j=2;j<=n;j++) if(mini>g[1][j]-dp[j].w){
mini=g[1][j]-dp[j].w,d=j;
}
if(mini>=0) continue;
tree[1][d]=tree[d][1]=true,tree[dp[d].u][dp[d].v]=tree[dp[d].v][dp[d].u]=false;
ans+=mini;
}
}
int main(){
memset(g,0x3f,sizeof g),memset(minedge,0x3f,sizeof minedge);
m=read(),id["Park"]=++n;
for(register int i=1;i<=m;i++){
string a,b; cin>>a>>b;
if(!id[a]) id[a]=++n;
if(!id[b]) id[b]=++n;
e[i].u=id[a],e[i].v=id[b],e[i].w=read();
g[e[i].u][e[i].v]=g[e[i].v][e[i].u]=min(g[e[i].u][e[i].v],e[i].w);
}
k=read();
kruskal(),solve();
printf("Total miles driven: %d\n", ans);
return 0;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章