树剖LCA+SPFA+tarjan找简单环
静态仙人掌最短路
没啥好说的,要分类讨论,细节要处理清楚…(我这个SB细节没弄好WA飞了)
膜:http://blog.youkuaiyun.com/popoqqq/article/details/43876907
#include<cstdio>
#include<queue>
#include<cstring>
#define cmin(u,v) (u)>(v)?(u)=(v):0
#define iabs(x) (x)>0?(x):-(x)
#define N 10005
#define M 300005
#define H 17
using namespace std;
struct edge{int next,to,val;}e[M<<1];
struct pdge{int u, v, val;}s[M];
int n, m, Q, ecnt=1, last[N], dis[N], dfn[N], low[N], timer, top, fa[N][H], bell, dep[N], belong[N], sum[N], pre[N];
bool inq[N], vis[N];
void addedge(int a, int b, int c)
{
e[++ecnt]=(edge){last[a],b,c};
last[a]=ecnt;
}
void SPFA(int s)
{
memset(dis,63,sizeof(dis));
queue<int> q;
dis[s]=0;
q.push(s);
while(!q.empty())
{
int x = q.front(); q.pop();
inq[x]=0;
for(int i = last[x]; i; i=e[i].next)
{
int y=e[i].to;
if(dis[x]+e[i].val<dis[y])
{
dis[y]=dis[x]+e[i].val;
if(!inq[y])
{
inq[y]=1;
q.push(y);
}
}
}
}
}
void pushout(int fat)
{
++bell;
for(;s[top].u!=fat;top--)
{
int u = s[top].u, v = s[top].v, w = s[top].val;
sum[bell]+=w;
pre[u]=pre[v]+w;
fa[v][0]=fat,belong[v]=bell;
fa[u][0]=fat,belong[u]=bell;
}
int u = s[top].u, v = s[top].v, w = s[top].val;
belong[v]=bell;
sum[bell]+=w;
pre[u]=pre[v]+w;
fa[v][0]=fat;
top--;
}
void tarjan(int x, int from)
{
//存边tarjan
dfn[x]=low[x]=++timer;
for(int i = last[x]; i; i=e[i].next)
{
if(i==from)continue;
int y=e[i].to;
if(!dfn[y])
{
s[++top]=(pdge){x,y,e[i].val};
tarjan(y,i^1);
if(low[y]<low[x])low[x]=low[y];
if(low[y]>=dfn[x])//环顶 或 只是更新儿子
{
pushout(x);
}
}
else if(dfn[y]<low[x]){cmin(low[x],dfn[y]); s[++top]=(pdge){x,y,e[i].val};}//返祖边
}
}
void make_edge()
{
memset(last,0,sizeof(last));
ecnt=1;
for(int i = 2; i <= n; i++)
{
addedge(fa[i][0],i,0);
}
}
void dfs(int x)
{
dep[x]=dep[fa[x][0]]+1;
for(int i = 1; 1<<i <= dep[x]; i++)
fa[x][i]=fa[fa[x][i-1]][i-1];
for(int i = last[x]; i; i=e[i].next)
{
int y=e[i].to;
if(dep[y])continue;
fa[y][0]=x;
dfs(y);
}
}
int LCA(int a,int b,int &c,int &d)
{
int past=0;
if(dep[a]<dep[b]) swap(a,b);
past=dis[a]+dis[b]; c=d=b;
for(int i=H-1;i>=0;i--) if(dep[fa[a][i]]>=dep[b]) a=fa[a][i];
if(a==b) return past-2*dis[b];
//如果a,b为祖先关系,那么用dis一定可以更新
for(int i=H-1;i>=0;i--)
if(fa[a][i]!=fa[b][i]) a=fa[a][i],b=fa[b][i];
c=a; d=b;
//如果a,b不是祖先关系, 就判LCA是不是属于环即可
return past-2*dis[fa[a][0]];
}
int main()
{
scanf("%d%d%d",&n,&m,&Q);
for(int i = 1; i <= m; i++)
{
int a, b, c;
scanf("%d%d%d",&a,&b,&c);
addedge(a,b,c);
addedge(b,a,c);
}
SPFA(1);
tarjan(1,0);
make_edge();
dfs(1);
for(;Q--;)
{
int a, b, c, d;
scanf("%d%d",&a,&b);
int tmp = LCA(a,b,c,d);
if(belong[c]==belong[d] && belong[c])
{
int ans = dis[a]+dis[b]-dis[c]-dis[d];
int l1=iabs(pre[c]-pre[d]), l2=sum[belong[c]]-l1;
printf("%d\n",ans+min(l1,l2));
}
else
{
printf("%d\n",tmp);
}
}
}