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;
解法:先求出源点到其他所有点的最短距离 , 再把所有边反向 , 再求源点到所有点的距离 。
由于这题的数据量太大 , 所以只能用数组来模拟邻接表 , 如果用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;
相关文章推荐
- poj 2226
- poj2728最优比率生成树
- poj 1797
- poj 1251
- 余弦:我的渗透利器
- 从数据库存储,文件结构谈到B树,散列
- poj 1364
- poj 1236
- poj 2186 tarjan算法
- poj 3352
- poj 1523 求图的割点
- uva 10972 边—双连通分量
- 强连通分量scc
- uva 10765(无向双连通量)
- FZU 2103 组合概率
- 我的博客今天0岁51天了,我领取了…
- poj 1325
- uva 11865 stream my contest
- uva 11865 stream my contest
- 二分图的最佳完美匹配(和一些变形…