BZOJ1576 (最短路+并查集)

 #include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define inline __attribute__((optimize("O2")))
using namespace std; #define maxn 100008
#define maxm 1000008
#define INF 2000000000
#define pa pair<int,int> struct line{
int u,v,w,nt;
}eg[maxm],E[maxm],e[maxm]; int lt[maxn],fa[maxn],n,m,sum=,num=,f[maxn],ans[maxn];
int d[maxn],pd[maxn]; inline void add(int u,int v,int w){
eg[++sum].v=v; eg[sum].w=w; eg[sum].nt=lt[u]; lt[u]=sum;
}
inline void read(int &x){
char ch;
for (ch=getchar();ch<''||ch>'';ch=getchar()); x=ch-;
for (ch=getchar();ch>=''&&ch<='';ch=getchar()) x=x*+ch-;
} /*inline void spfa(){
for (int i=1;i<=n;i++) d[i]=INF;
queue<int> Q;
memset(pd,0,sizeof(pd));
pd[1]=1; d[1]=0; Q.push(1);
while (!Q.empty()){
int u=Q.front();
for (int i=lt[u];i;i=eg[i].nt){
int v=eg[i].v;
if (d[u]+eg[i].w<d[v]){
d[v]=d[u]+eg[i].w;
fa[v]=u;
if (!pd[v]){
Q.push(v);
pd[v]=1;
}
}
}
pd[u]=0;
Q.pop();
}
}*/ inline void dijkstra(){
priority_queue<pa,vector<pa>,greater<pa> > Q;
memset(pd,,sizeof(pd));
for (int i=;i<=n;i++) d[i]=INF;
d[]=; Q.push(make_pair(,));
while (!Q.empty()){
int u=Q.top().second; Q.pop();
if (pd[u]) continue; pd[u]=;
for (int i=lt[u];i;i=eg[i].nt)
if (d[u]+eg[i].w<d[eg[i].v]){
d[eg[i].v]=d[u]+eg[i].w;
fa[eg[i].v]=u;
Q.push(make_pair(d[eg[i].v],eg[i].v));
}
}
} inline bool cmp(line i,line j){
return i.w<j.w;
} inline int find(int x){ return f[x]==x?x:f[x]=find(f[x]); } inline void work(int u,int v,int w){
int x=find(u),y=find(v);
while (x!=y){
if (d[x]<d[y]) swap(x,y);
ans[x]=w-d[x];
num++;
f[x]=fa[x];
x=find(f[x]);
}
} inline int main(){
read(n); read(m);
int x,y,z;
for (int i=;i<=m;i++){
read(x); read(y); read(z);
add(x,y,z); add(y,x,z);
e[i].u=x; e[i].v=y; e[i].w=z;
}
dijkstra();
int cnt=;
for (int i=;i<=m;i++){
int u=e[i].u,v=e[i].v,w=e[i].w;
if (fa[u]!=v && fa[v]!=u){
E[++cnt].u=u;
E[cnt].v=v;
E[cnt].w=d[u]+d[v]+w;
}
}
sort(E+,E+cnt+,cmp);
for (int i=;i<=n;i++) { ans[i]=-; f[i]=i; }
for (int i=;i<=cnt;i++){
work(E[i].u,E[i].v,E[i].w);
if (num==n-) break;
}
for (int i=;i<=n;i++) printf("%d\n",ans[i]);
}
上一篇:重温WCF之一个服务实现多个契约(二)


下一篇:【解决】如何导入导出SharePoint列表和文档库