bzoj 1576(dijkstra+并查集)

传送门
题意:给定一个无向图,图中点1到任意一点的最短路唯一,问把到每个点最短路上的最后一条边去掉之后的最短路是多少。
bzoj 1576(dijkstra+并查集)_第1张图片

#include
using namespace std;
const int maxn=1e5+2,maxm=2e5+2,INF=0x3f3f3f3f;
int n,m;
int head[maxn],dis[maxn],fa[maxn],h[maxn],ans[maxn],edge=0;
struct EDGE {
    int u,v,nxt,w;
}e[maxm<<1];
struct A {
    int x,y,z;
    friend bool operator <(const A &ff,const A &hh) {
        return ff.z1];
int cnt=0,temp;
struct NODE {
    int id,dis;
    friend bool operator <(const NODE &ff,const NODE &hh) {
        return ff.dis>hh.dis;
    }
};
inline int read() {
    int x=0;char c=getchar();
    while (c<'0'||c>'9') c=getchar();
    while (c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
    return x;
}
inline void adde(int u,int v,int w) {
    e[edge].u=u,e[edge].v=v,e[edge].w=w,e[edge].nxt=head[u],head[u]=edge++;
    e[edge].u=v,e[edge].v=u,e[edge].w=w,e[edge].nxt=head[v],head[v]=edge++;
}
inline void dijkstra(int source) {
    memset(dis,INF,sizeof(dis)),dis[source]=0;
    priority_queue q;
    NODE a={1,0};
    q.push(a);
    while (!q.empty()) {
        a=q.top();q.pop();
        int p=a.id;
        for (int i=head[p];~i;i=e[i].nxt) {
            int v=e[i].v;
            if (dis[v]>dis[p]+e[i].w) {
                dis[v]=dis[p]+e[i].w,fa[v]=p;
                NODE b={v,dis[v]};
                q.push(b);
            }
        }
    }
}
int num(int p) {
    if (h[p]) return h[p];
    return num(fa[p])+1;
}
int Merge(int x,int y) {
    if (x==y) return x;
    if (h[x]return fa[x]=Merge(fa[x],y);
}
int main() {
//  freopen("bzoj 1576.in","r",stdin);
    memset(head,-1,sizeof(head));
    memset(h,0,sizeof(h));
    memset(ans,-1,sizeof(ans));
    n=read(),m=read();
    for (register int i=1;i<=m;++i) {
        int u=read(),v=read(),w=read();
        adde(u,v,w);
    }
    dijkstra(1);
    fa[1]=h[1]=1;
    for (register int i=2;i<=n;++i)
        h[i]=num(i);
    for (register int i=0;i2) {
        int u=e[i].u,v=e[i].v,w=e[i].w;
        if (dis[u]>dis[v]) u^=v^=u^=v;
        if (dis[u]+w==dis[v]) continue;
        a[++cnt]=(A){u,v,dis[u]+dis[v]+w};
    }
    sort(a+1,a+cnt+1);
    for (register int i=1;i<=cnt;++i) {
        int x=a[i].x,y=a[i].y;
        temp=a[i].z;
        x=Merge(x,y);
    }
    for (register int i=2;i<=n;++i)
        printf("%d\n",ans[i]);
    return 0;
}

你可能感兴趣的:(OI-数据结构)