CF1503C Travelling Salesman Problem

CF1503C Travelling Salesman Problem(贪心,势能分析)

首先,每个城市的 \(c_i\) 可以看作是必花的代价。

然后我们考虑对城市进行势能分析:如果海拔增高,势能增加,海拔降低,势能不变。

于是我们考虑额外代价:如果前 \(i\) 个数的 \(a_i+c_i\) 的最大值小于 \(a_{i+1}\) ,那么我们就要扩大势能,变成 \(a_{i+1}\)

最后的答案就是本来的加上扩大的额外代价。

代码如下:

#include<bits/stdc++.h>
using namespace std;
template <typename T>
inline void read(T &x){
	x=0;char ch=getchar();bool f=false;
	while(!isdigit(ch)){if(ch=='-'){f=true;}ch=getchar();}
	while(isdigit(ch)){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
	x=f?-x:x;
	return ;
}
template <typename T>
inline void write(T x){
	if(x<0) putchar('-'),x=-x;
	if(x>9) write(x/10);
	putchar(x%10^48);
	return ;
}
const int N=1e5+5; 
int n;
long long ans;
struct node{
	int a,c;
	bool operator<(const node B)const{return a<B.a;}
}a[N];
int main(){
	read(n);
	for(int i=1;i<=n;i++) read(a[i].a),read(a[i].c),ans+=a[i].c;
	sort(a+1,a+n+1);
	int cur=0;
	for(int i=1;i<=n;i++){
		cur=max(cur,a[i].a+a[i].c);
		if(cur<a[i+1].a) ans+=a[i+1].a-cur;
	}
	write(ans);
	return 0;
}
posted @ 2021-04-16 16:08  __Anchor  阅读(80)  评论(0编辑  收藏  举报