poj 3013 Big Christmas Tree(最短路问题)
2013-08-16 10:19
399 查看
http://poj.org/problem?id=3013
题目大意:
意思大概是给你一张图,图中的每个顶点都有权值,顶点之间的边也有权值;
源点为顶点1;
定义连接顶点n(n!=1)的费用为,顶点n到顶点n的最短距离×顶点n的权值;
问构建一棵包含所有顶点的树的最小费用为多少,若是存在无法连接到的点输出No Answer;
思路:
题目不难,简单的最短路的应用;但是要过这题也不容易;
要注意的地方很多:
1、普通Dijkstra会超时,可以用heap优化;
2、边要开的够大,2000000可以过;
3、inf要足够大,太小不行(我在这里wa了很多次),太大会爆;
4、n==1||n==0要输出0,;
题目大意:
意思大概是给你一张图,图中的每个顶点都有权值,顶点之间的边也有权值;
源点为顶点1;
定义连接顶点n(n!=1)的费用为,顶点n到顶点n的最短距离×顶点n的权值;
问构建一棵包含所有顶点的树的最小费用为多少,若是存在无法连接到的点输出No Answer;
思路:
题目不难,简单的最短路的应用;但是要过这题也不容易;
要注意的地方很多:
1、普通Dijkstra会超时,可以用heap优化;
2、边要开的够大,2000000可以过;
3、inf要足够大,太小不行(我在这里wa了很多次),太大会爆;
4、n==1||n==0要输出0,;
#include<iostream> using namespace std; const __int64 inf=20000000000;//要开的足够大; const int N=200000; class Edge { public: int v; int next; __int64 w; }edge ; int ncnt; int num_v,num_e; int head ; __int64 node_w ; __int64 xtime ; __int64 Que ; bool inQue ; void addedge(int u,int v,int w) { edge[ncnt].v=u; edge[ncnt].w=w; edge[ncnt].next=head[v]; head[v]=ncnt++; edge[ncnt].v=v; edge[ncnt].w=w; edge[ncnt].next=head[u]; head[u]=ncnt++; return ; } void spfa(int s) { /*Initial*/ for(int i=0;i<=num_v;i++) xtime[i]=inf; xtime[s]=0; memset(inQue,false,sizeof(inQue)); int front=0; int tail=0; Que[tail++]=s; inQue[s]=true; while(front<tail) { int u=Que[front++]; inQue[u]=false; for(int i=head[u];~i;i=edge[i].next) { int v=edge[i].v; if(xtime[v] > xtime[u]+edge[i].w) { xtime[v]=xtime[u]+edge[i].w; if(!inQue[v]) { Que[tail++]=v; inQue[v]=true; } } } } return ; } int main(int i) { int cases; scanf("%d",&cases); while(cases--) { memset(head,-1,sizeof(head)); ncnt=0; scanf("%d %d",&num_v,&num_e); /*Input & Structure Graph*/ for(i=1;i<=num_v;i++) scanf("%I64d",&node_w[i]); int u,v,w; for(i=1;i<=num_e;i++) { scanf("%d %d %d",&u,&v,&w); addedge(u,v,w); } /*SPFA Algorithm*/ spfa(1); __int64 sum_w=0; bool flag=true; for(i=2;i<=num_v;i++)//从2开始检验,n==1||n==0时答案为0; { if(xtime[i]==inf) { printf("No Answer\n"); flag=false;//如果有不能连接的点,输出No Answer break; } sum_w += xtime[i]*node_w[i]; } if(flag) printf("%I64d\n",sum_w); } return 0; }
相关文章推荐
- poj 3013 big christmas tree
- POJ 3013 Big Christmas Tree
- poj 3013 Big Christmas Tree (最短路)
- POJ 3013 Big Christmas Tree
- poj 3013 Big Christmas Tree(Dijktra或者spfa)
- POJ-3013 Big Christmas Tree 最短路[推荐]
- POJ 3013 Big Christmas Tree 最短路
- poj 3013 Big Christmas Tree
- POJ 3013 Big Christmas Tree(SPFA)
- POJ 3013 Big Christmas Tree(最短Dijkstra+优先级队列优化,SPFA)
- poj 3013 Big Christmas Tree (dij+优先级队列优化 求最短)
- POJ 3013 Big Christmas Tree (最短路)
- poj-3013-Big Christmas Tree-求最短路
- POJ 3013 Big Christmas Tree
- POJ 3013 Big Christmas Tree - from lanshui_Yang
- POJ 3013 Big Christmas Tree(Dijkstra)
- POJ 3013 Big Christmas Tree (spfa)
- POJ 3013 Big Christmas Tree(最短路Dijkstra+优先队列优化,SPFA)
- POJ 3013 Big Christmas Tree
- 最短路 Big Christmas Tree POJ - 3013