POJ - 1986 题目
思路:tarjan求两个叶子结点间距离,这题莫名tle,后来发现是因为初始化手抖了一下,但是还是没发现为何tle。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#include <ctime>
using namespace std;
//#pragma comment(linker, "/STACK:102400000,102400000")
const int maxn = 1e5 + 50;
struct node
{
int to,w,next;
node(){}
node(int a,int b,int c = -1)
{ to = a; w = b; next = c;}
}edge[maxn << 1] ,query[maxn << 1];
int h[maxn], d[maxn], f[maxn],isRoot[maxn],ans[maxn],h1[maxn];
int col[maxn], anc[maxn] , vis[maxn];
int edgenum = 0,qnum = 0;
int add(int from, int to, int w)
{
edge[edgenum] = node(to,w,h[from]);
h[from] = edgenum ++ ;
return 0;
}
void addq(int a,int b,int id)
{
query[qnum] = node(b,id,h1[a]);
h1[a] = qnum++;
}
int n,m;
void init()
{
edgenum = 0; qnum = 0;
for(int i = 0; i <= n; i++)
h[i] = -1, f[i] = i, isRoot[i] = 0 ,d[i] = 0, col[i] = 0, vis[i] = 0;
for(int i = 0; i <= n; i++)
h1[i] = -1;
}
void getdis(int root)
{
queue<node> q;
q.push(node(root,0,0));
vis[root] = 1;
while(!q.empty())
{
node temp = q.front();
q.pop();
int u = temp.to;
for(int i = h[u] ; i != -1 ; i = edge[i].next)
{
int v = edge[i].to;
if(!vis[v])
{
vis[v] = 1;
d[v] = temp.w + edge[i].w;
q.push(node(v,d[v],0));
}
}
}
}
int getf(int i)
{return i == f[i] ? i : f[i] = getf(f[i]);}
int join(int i,int j)
{
int x = getf(i), y = getf(j);
if(x != y)
f[y] = x;
return 0;
}
void tarjan(int u)
{
anc[u] = u;
for(int i = h[u] ; i != -1 ; i = edge[i].next)
{
int v = edge[i].to;
if(!vis[v])
{
vis[v] = 1;
tarjan(v);
join(u,v);
anc[getf(u)] = u;
vis[v] = 0;
}
}
col[u] = 1;
for(int i = h1[u]; ~i; i = query[i].next)
{
int v = query[i].to, id = query[i].w;
if(col[v])
{
int atemp = d[u] + d[v] - 2*d[anc[getf(v)]];
ans[id] = atemp;
}
}
}
int main()
{
/*clock_t start_time=clock();
freopen("D://in.txt","r",stdin);
freopen("D://out.txt","w",stdout);*/
int a,b,c;
while(~scanf("%d%d",&n,&m))
{
init();
for(int i = 0; i < m ; i++)
{
char s[2];
scanf("%d%d%d%s",&a,&b,&c,s);
add(a, b, c); add(b ,a, c);
isRoot[b] ++; isRoot[a] ++;
}
int root = -1, maxi = 0;
for(int i = 1; i <= n; i++)
{
if(maxi < isRoot[i])
maxi = isRoot[i], root = i;
}
// cout << root << endl;
d[root] = 0;
getdis(root);
int q;
scanf("%d",&q);
for(int i = 0; i < q; i++)
{
scanf("%d%d",&a,&b);
addq(a,b,i); addq(b,a,i);
}
memset(vis , 0 , sizeof(vis));
vis[root] = 1;
tarjan(root);
for(int i = 0; i < q; i++)
printf("%d\n",ans[i]);
}
return 0;
}