HDU 2586 How far away ?

该题一下子就爆栈了,我还只能用G++可以提交,c++还是过不了;

该题是一道LCA,这里就不重复了,(前面已经说了);

#include<cstdio>
#include<iostream>
#include<string.h>
#include<vector>
using namespace std;
class node
{
public:
int en;
int len;
};

vector<node>tree[40024],Qes[40024];
int dis[40024],ans[40024],set[40024],visit[40024],ancestor[40024];
void init( int n )
{
for(int i=0;i<=n;i++)
{
dis[i]=0;
ans[i]=0;
set[i]=i;
visit[i]=0;
tree[i].clear( );
Qes[i].clear( );
}
}
int find( int x )
{
return set[x]==x?x:set[x]=find( set[x] );
}
void Union( int a,int b )
{
set[find( b )]=set[find( a )];
}
void LCA( int num,int d )
{
dis[num]=d;
visit[num]=1;
set[num]=num;
int size=Qes[num].size();
for( int i=0; i<size; i++ )
{
if( visit[Qes[num][i].en] )
{
ans[Qes[num][i].len]=dis[num] + dis[Qes[num][i].en] - 2*dis[find( Qes[num][i].en )];
}
}
size=tree[num].size();
for( int i=0; i<size; i++ )
{
if( !visit[tree[num][i].en] )
{
LCA( tree[num][i].en,tree[num][i].len+d );
set[tree[num][i].en]=num;
}
}
}
int main( )
{
int n,m,Case,x,y,dis;
scanf( "%d",&Case );
while( Case-- )
{
scanf( "%d %d",&n,&m );
init( n>m?n:m );
for( int i=1; i< n ;i++ )
{
scanf( "%d %d %d",&x,&y,&dis );
node T;
T.en=y;
T.len=dis;
tree[x].push_back( T );
T.en=x;
tree[y].push_back( T );
}
for( int i=1;i<=m ;i++ )
{
scanf( "%d %d",&x,&y );
node T;
T.en=y;
T.len=i;
Qes[x].push_back( T );
T.en=x;
Qes[y].push_back( T );
}
LCA( 1, 0 );
for( int i=1;i<=m;i++ )
{
printf( "%d\n",ans[i] );
}
}
return 0;
}

 

你可能感兴趣的:(HDU)