您的位置:首页 > 其它

poj1511(第一次用数组模拟邻接表…

2013-12-14 20:04 639 查看
题意:求出所有点到源点来回的最短距离 。

解法:先求出源点到其他所有点的最短距离 , 再把所有边反向 , 再求源点到所有点的距离 。

由于这题的数据量太大 , 所以只能用数组来模拟邻接表 , 如果用vector会超内存 。

还要注意一点 , 一定要用long long

代码:

#include

#include

#include

#include

#include

using namespace std;

#define MAXN  1000010

#define INF  0xFFFFFFFF

struct edge

{

   
int  to , d , next;

}edges1[2][MAXN];

long long d1[MAXN] , first[2][MAXN];

long long  n , m , sum = 0 , vis[MAXN] ;

void spfa(int s)

{

    int i ,
x;

   
queueq;

    for(i = 1; i
<= n; i++)  d1[i] = INF;

    d1[1] =
0;

    memset(vis ,
0 , sizeof(vis));

   
q.push(1);

    vis[1] =
1;

    edge
e;

   
while(!q.empty())

    {

   
    int u =
q.front(); q.pop();

   
    vis[u] =
0;

   
    x =
first[s][u];

   
    if(x ==
-1)  continue ;

   
    while(x !=
-1)

   
    {

   
   
    e =
edges1[s][x];

   
   
    if(d1[e.to]
> d1[u] + e.d)

   
   
    {

   
   
   
    d1[e.to] =
d1[u] + e.d ;

   
   
   
   
if(!vis[e.to])  {vis[e.to] = 1;
q.push(e.to);}

   
   
    }

   
   
    x =
edges1[s][x].next ;

   
    }

    }

    for(i = 1; i
<= n; i++)

   
    sum +=
d1[i];

}

int main()

{

   //
cout<<INF<<endl;

    int t;

   
cin>>t;

   
while(t--)

    {

   
    scanf("%lld
%lld" , &n , &m);

   
    int i , x ,
y , z;

   
    for(i = 0; i
<= n; i++)

   
   
    first[0][i]
= first[1][i] = -1;

   
    for(i = 0 ;
i < m; i++)

   
    {

   
   
    scanf("%d %d
%d" , &x , &y , &z);

   
   
   
edges1[0][i].to = y , edges1[0][i].d = z;

   
   
   
edges1[0][i].next = first[0][x] ;

   
   
    first[0][x]
= i;

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: