AtCoder Beginner Contest 340D - Super Takahashi Bros

23 篇文章 0 订阅

problem link

The n n n stages an their mutual pathways can be intuitively seen as graph, with stages as nodes, and the pathways as edges.

The problem seems to solvable by some clever greedy algorithm due to the semi tree-like structure of the n n n stages. However, an ad-hoc dijkstra shortest path can easily solve the problem with O ( n log ⁡ n ) \mathcal O(n \log n) O(nlogn) time complexity.

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
const long long Maxn=2e5+10;
const long long inf=(1ll<<60);
struct node{
	long long pos,dis;
	bool operator <(const node &x)const
	{
		return x.dis<dis;
	}
};
struct edge{
	long long v,len;
};
vector <edge> e[Maxn];
bool vis[Maxn];
long long dis[Maxn];
long long n;
inline long long read()
{
	long long s=0,w=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
	while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
	return s*w;
}
void work()
{
	priority_queue <node> q;
	fill(dis+2,dis+1+n,inf);
	dis[1]=0;
	q.push(node{1,0});
	while(q.size())
	{
		long long x=q.top().pos;
		q.pop();
		if(x==n)return;
		if(vis[x])continue;
		vis[x]=1;
		for(long long i=0;i<e[x].size();++i)
		{
			long long y=e[x][i].v,len=e[x][i].len;
			if(dis[y]>dis[x]+len)
			{
				dis[y]=dis[x]+len;
				q.push(node{y,dis[y]});
			}
		}
	}
}
int main()
{
	// freopen("in.txt","r",stdin);
	n=read();
	for(long long i=1;i<n;++i)
	{
		long long a=read(),b=read(),x=read();
		e[i].push_back(edge{i+1,a});
		if(x!=i)
		e[i].push_back(edge{x,b});
	}
	work();
	printf("%lld\n",dis[n]);
	return 0;
}
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值