poj 1511 Invitation Cards
2013-08-30 19:50
621 查看
题意:
给定一个有向图,求原点与各点之间往返的最小距离
用Dijstra会TLE,这里用SPFA+邻接表
建正反两张图,两边SPFA求总和
结果会超出int的范围,用__int 64表示
代码如下:
给定一个有向图,求原点与各点之间往返的最小距离
用Dijstra会TLE,这里用SPFA+邻接表
建正反两张图,两边SPFA求总和
结果会超出int的范围,用__int 64表示
代码如下:
#include<iostream> #include<cstdio> #include<queue> #define inf 1000000005 using namespace std; struct node { int y,cost,next; }edge[1000005]; int dist[1000005],visit[1000005]; int a[1000005],b[1000005],c[1000005],h[1000005]; int n,m; __int64 ans; queue<int> q; __int64 SPFA() { __int64 ans1=0; int i; int x; for(i=1;i<=n;i++) { dist[i]=inf; visit[i]=0; } q.push(1); visit[1]=1;dist[1]=0; while(!q.empty()) { x=q.front(); q.pop(); for(i=h[x];i;i=edge[i].next) { if(dist[edge[i].y]>dist[x]+edge[i].cost) { dist[edge[i].y]=dist[x]+edge[i].cost; if(!visit[edge[i].y]) { visit[edge[i].y]=1;q.push(edge[i].y); } } } } for(i=1;i<=n;i++) ans1+=dist[i]; return ans1; } int main() { int t,i,p; scanf("%d",&t); while(t--) { scanf("%d %d",&n,&m); ans=0;p=0; memset(h,0,sizeof(h)); for(i=0;i<m;i++) { scanf("%d %d %d",&a[i],&b[i],&c[i]); edge[++p].y=b[i]; edge[p].cost=c[i]; edge[p].next=h[a[i]]; h[a[i]]=p; } ans+=SPFA(); p=0; memset(h,0,sizeof(h)); for(i=0;i<m;i++) { edge[++p].y=a[i]; edge[p].cost=c[i]; edge[p].next=h[b[i]]; h[b[i]]=p; } ans+=SPFA(); printf("%I64d\n",ans); } return 0; }
相关文章推荐
- Poj 1511- Invitation Cards(Spfa+邻接表)
- poj 1511 正反向建图
- poj 1511 Invitation Cards
- POJ 1511(邻接表和最短路 SPFA)
- POJ 1511 Invitation Cards (最短路)
- HDU 1535 && POJ 1511 Invitation Cards (SPFA 模板 + 反向建图)
- POJ 1511 spfa
- poj 1511&&zoj 2008 Invitation Cards 最短路+SPFA
- POJ1511 Invitation Cards(spfa模板题)
- POJ 1511 Invitation Cards
- POJ - 1511
- poj 1511 Invitation Cards(最短路)
- POJ - 1511 Invitation Cards
- POJ_1511_最短路径_spfa
- POJ-1511(SPFA找最短路(正向和反向))
- poj 1511 spfa入门
- poj 1511 最短路
- poj 1511&zoj 2008 最短路
- poj 1511&&zoj 2008 Invitation Cards 最短路+SPFA
- zoj 2008 && poj 1511 Invitation Cards