ccf魔数c语言,ccf 201609-4 交通规划

附上代码:

#include#include#include#include#include#include

using namespacestd;#define inf 0xfffffff

intn, m;

typedefstructNODE

{intto;intcost;

friendbool operator < (const NODE &a, const NODE &b) {return a.cost >b.cost;

}

}node;

typedefstructEdge

{int from;intnext;intto;intw;intvalue;

} edge;

edge maps[10000005];int head[100050];int dist[100050];int vids[100050];intcnt;voidcreat ()

{for(int i=0; i<100050; i++)

head[i]=-1;

cnt=0;

}void add(int u,int v,intw)

{

maps[cnt].from =u;

maps[cnt].to=v;

maps[cnt].w=w;

maps[cnt].value=w;

maps[cnt].next=head[u];///一开始放置为-1,-1的条件就可以跳出///下一步接着储存,head[u]的值,就是前面的位置

head[u]=cnt++;///head[u]会得到这条线的值

}int dijkstra(int s,intt)

{for(int i=0; i<100050; i++)

{

vids[i]=0;

dist[i]=inf;

}

priority_queueque;

node begins;

begins.to=s;

begins.cost=0;

que.push(begins);while(!que.empty())

{

node ends=que.top();

que.pop();if(!vids[ends.to])

{

vids[ends.to]=1;

dist[ends.to]=ends.cost;for(int i = head[ends.to]; ~i; i =maps[i].next)

{int to = maps[i].to, w =maps[i].w;

maps[i].w= ends.cost +w;if(!vids[to])

{

node ans;

ans.to=to;

ans.cost=ends.cost+w;

que.push(ans);

}

}

}

}if(dist[t] ==inf)

{return -1;

}else{returndist[t];

}

}bool cmp(const edge & a, const edge &b)

{if(a.w !=b.w)

{return a.w

}return a.value

}int pre[100050];voidInit()

{for(int i=1; i<=m; i++)

pre[i]=i;

}int finds(intx)

{if(pre[x]==x)returnx;else

return pre[x]=finds(pre[x]);

}void unionjoin(int x,inty)

{int u=finds(x);int v=finds(y);if(u==v)return;elsepre[u]=v;

}bool same(int x,inty)

{return finds(x)==finds(y);

}long longkruskal()

{long long ans=0;

sort(maps,maps+ 2 *m,cmp);for(int i = 0; i< 2 * m; i++)

{if(!same(maps[i].from,maps[i].to))

{

unionjoin(maps[i].from,maps[i].to);

ans+=maps[i].value;

}else

continue;

}returnans;

}intmain()

{while(~scanf("%d%d",&n,&m))

{

creat();for(int i = 0; i < m; i ++) {intu, v, w;

scanf("%d%d%d",&u, &v, &w);

add(u, v, w);

add(v, u, w);

}

dijkstra(1, n);

Init();long long re =kruskal();

printf("%lld\n",re);

}return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值