UVA 11183 Teen Girl Squad 最小树形图

最小树形图模板题

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
using namespace std;
typedef long long LL;
const int N=1e3+;
const int INF=0x3f3f3f3f;
struct Node{
int x,y;
}p[N];
struct Edge{
int u,v,w;
}edge[N*];
int in[N];
int id[N],vis[N],pre[N],n,m;
int zhuliu(int rt,int n,int m){
int ret=;
while(){
for(int i=;i<=n;++i)in[i]=INF;
for(int i=;i<=m;++i){
if(edge[i].u!=edge[i].v&&edge[i].w<in[edge[i].v]){
pre[edge[i].v]=edge[i].u;
in[edge[i].v]=edge[i].w;
}
}
for(int i=;i<=n;++i)
if(i!=rt&&in[i]==INF)return -;
int cnt=;
memset(id,-,sizeof(id));
memset(vis,-,sizeof(vis));
in[rt]=;
for(int i=;i<=n;++i){
ret+=in[i];
int v=i;
while(vis[v]!=i&&id[v]==-&&v!=rt){
vis[v]=i;
v=pre[v];
}
if(v!=rt&&id[v]==-){
++cnt;
for(int u=pre[v];u!=v;u=pre[u])
id[u]=cnt;
id[v]=cnt;
}
}
if(cnt==)break;
for(int i=;i<=n;++i)
if(id[i]==-)id[i]=++cnt;
for(int i=;i<=m;++i){
int u=edge[i].u,v=edge[i].v;
edge[i].u=id[u];
edge[i].v=id[v];
if(id[u]!=id[v])edge[i].w-=in[v];
}
n=cnt;
rt=id[rt];
}
return ret;
}
int main()
{
int T,cas=;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
for(int i=;i<=m;++i){
scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
++edge[i].u,++edge[i].v;
}
printf("Case #%d: ",++cas);
int ans=zhuliu(,n,m);
if(ans==-)printf("Possums!\n");
else printf("%d\n",ans);
}
return ;
}
上一篇:电脑hash破解


下一篇:mysql命令行备份数据库