poj 1986tarjan模板题
来源:互联网 发布:网游在线人数数据 编辑:程序博客网 时间:2024/06/05 07:46
#include<iostream>
#include<vector>
using namespace std;
const int N=40010;
int pre[N];//并查集
int visit[N];//是否经过
int ancestor[N];//祖先
int dis[N];//储存距离
int result[N];//储存结果
struct tre{
int x,length;
};
vector<tre>tree[N];
struct qu{
int y,index;
};
vector<qu>qury[N];
void init(int n) {//初始化
int i;
for(i=1;i<=n;i++)
tree[i].clear();
for(i=1;i<=n;i++)
qury[i].clear();
memset(visit,0,sizeof(visit));
}
int find(int x) {//路径压缩
if(x!=pre[x])
pre[x]=find(pre[x]);
return pre[x];
}
void infind(int x,int y) {//合并
int f1=find(x);
int f2=find(y);
pre[f1]=f2;
return ;
}
void tarjan(int u,int length) {
visit[u]=1;
dis[u]=length;//直接就可以的到距离
ancestor[u]=u;
pre[u]=u;
int i;
for(i=0;i<tree[u].size();i++) {
int v=tree[u][i].x;
if(visit[v]==0) {
tarjan(v,length+tree[u][i].length);
infind(u,v);
ancestor[find(u)]=u;
}
}
for(i=0;i<qury[u].size();i++) {
int v=qury[u][i].y;
if(visit[v])
result[qury[u][i].index]=dis[u]+dis[v]-2*dis[ancestor[find(v)]];//重点
}
return ;
}
int main() {
int n,m,i,j,k,a,b,c;
char s[2];
while(scanf("%d%d",&n,&m)!=EOF) {
init(n);
for(i=1;i<=m;i++) {
scanf("%d%d%d%s",&a,&b,&c,s);
tre h;
h.x=b;
h.length=c;
tree[a].push_back(h);//储存
h.x=a;
h.length=c;
tree[b].push_back(h);
}
scanf("%d",&k);
for(i=1;i<=k;i++) {
scanf("%d%d",&a,&b);
qu h;
h.y=b;
h.index=i;
qury[a].push_back(h);//储存
h.y=a;
h.index=i;
qury[b].push_back(h);
}
tarjan(1,0);//
for(i=1;i<=k;i++)
printf("%d\n",result[i]);
}
return 0;
}
- poj 1986tarjan模板题
- POJ - 2186 Tarjan的模板题..
- POJ 2186:Popular Cows Tarjan模板题
- poj 1523 SPF(模板题)(Tarjan 关节点的朴素算法)
- poj 1144 Network(模板题)(Tarjan 关节点的朴素算法)
- poj 2186 tarjan求强连通分量(模板题)
- POJ 1236 Network of Schools【tarjan算法】【模板题】
- 【离线Tarjan 模板】LCA tarjan 算法 练习: hdu 2586 + poj 1986
- POJ 1144 Network Tarjan 求无向图的割点的个数 Tarjan 模板题
- HDU1289 Tarjan-模板题
- hdu1269 tarjan模板题
- tarjan缩点模板 poj 2186
- poj 1144 Network (tarjan割点模板)
- POJ 1523 SPF tarjan求割点模板
- LCA Tarjan及倍增模板(POJ 1330)
- poj 2186 DAG+缩点+tarjan模板 (模板待消化
- Uva247(tarjan模板题)
- poj 2186 Popular Cows(强连通分量模板题,tarjan)
- 编译器工具 Flex Bison for Windows 简单入门例子
- eclipse基本使用
- objective-C运行时编程指南之消息
- 海量日志数据,找出出现次数最多的IP地址。
- 1.错误代码:B9735AF4
- poj 1986tarjan模板题
- C#----操作应用程序配置文件
- 2.错误代码:09890235
- 忘记了MySQL的root密码设置方法(自己总结)
- 程序员面试宝典
- windows 下 bison 命令行调用
- 3.错误代码:D5385D18
- XML的基础理解
- 数据字典生成Java代码