HDU2121 Ice_cream's world II [Minimal tree diagram]

Title link: HDU2121 Ice_cream's world II

Meaning of the question: make the smallest tree diagram with n points and m edges. If there are output weights and roots, there is no output impossible;

Analysis: Add a super point and each point has an edge. If there is, then the point connected by the super point must be the root, and there is only one; if there are more than one, then there must be no minimum tree diagram in the original image, because At least one imaginary edge is borrowed (because a point is added, one imaginary edge is necessary), then we set the weight of the imaginary edge as all edge weights and +1 (sum), if ans>=2 *sum, it means that multiple virtual edges are borrowed, otherwise the weight is ans-sum, and the root is the above;

#include<bits/stdc++.h>
#define pb push_back
using namespace std;
typedef long long ll;
const int maxn=1e3+7;
const int maxm=1e6+7;
const int mod=1e9+7;
const int INF=1e9;
int n,m,ff,num=0;
struct edge{int u,v;ll w;} g[maxm];
int pre[maxn],id[maxn],vis[maxn],in[maxn];
ll Directed_MST(int rt,int V,int E)
{
    ll res=0;
    while(1)
    {
        for(int i=0;i<V;i++) in[i]=INF;
        for(int i=0;i<E;i++)
        {
            int u=g[i].u,v=g[i].v;
            if(g[i].w<in[v] && u!=v)
            {
                pre[v]=u;in[v]=g[i].w;
                if(u==rt) ff=i;
            }
        }
        int cnt=0;
        memset(id,-1,sizeof(id));
        memset(vis,-1,sizeof(vis));
        in[rt]=0;
        for(int i=0;i<V;i++)
        {
            res+=1ll*in[i];int v=i;
            while(vis[v]!=i && id[v]==-1 && v!=rt) {vis[v]=i;v=pre[v];}
            if(v!=rt && id[v]==-1)
            {
                for(int u=pre[v];u!=v;u=pre[u]) id[u]=cnt;
                id[v]=cnt++;
            }//缩点
        }
        if(cnt==0) return res;
        for(int i=0;i<V;i++) if(id[i]==-1) id[i]=cnt++;
        for(int i=0;i<E;i++)
        {
            int u=g[i].u,v=g[i].v,w=g[i].w;
            if(id[u]!=id[v]) w-=in[v];
            g[i]={id[u],id[v],w};
        }
        V=cnt;rt=id[rt];
    }
    return res;
}
void rua()
{
    ll sum=1;int kk=m;
    for(int i=0;i<m;i++) scanf("%d%d%lld",&g[i].u,&g[i].v,&g[i].w),sum+=g[i].w;
    for(int i=0;i<n;i++) g[m++]={n,i,sum};
    ll ans=Directed_MST(n,n+1,m);
    if(ans>=2*sum) printf("impossible\n");
    else printf("%lld %d\n",ans-sum,ff-kk);
    printf("\n");
}
int main()
{
    while(~scanf("%d%d",&n,&m)) rua();
    return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_43813163/article/details/104547089