跳到正文

题解

题解:P13796 [SWERC 2023] Nicest view

我是歌者约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟
题目
P13796

版本

  1. v1当前

题目大意

给你 nn 个点,构成一条折线,求折线上左右间隔最大的点对,以分数形式输出。

(一张并不美观的样例图)

解法

从图中我们很容易就看出答案的左右端点,左端点为 11 ,右端点根据 44 与 55 的斜率求出。

仔细观察这个点的性质,我们发现,如果我们从左往右遍历整个数据,其中可能对答案产生贡献的点对一定是遍历到的最高点 ii 到更高点 jj 与 j−1j-1 线段上的某个点。

我们可以用简单的贪心证明这个结论:

如图,由端点 11 这个遍历到的最高点发出的线段一定比最高点 11 到更高点 55 之间所有的点对更长,即更能对答案产生贡献。

此外,这个点对的“视线”一定不会被“阻挡”。因为我们找到的一个点是最高点,在最高点与更高点之间不可能存在比最高点高的点。

一些小问题

虽然我们发现了答案是由遍历到的最高点向更高点发出的,但也存在不能得出答案的情况,如图。

我们如果直接从左往右遍历,只能找到最高点而不能找到更高点,所以我们可以再从右往左遍历一遍,重新记录最高点与更高点。

注意点

  1. 分数形式输出记得约分输出。
  2. 比较答案时记得通分比较。
  3. 手写分数不要炸了。
  4. 记得单独处理答案为 00 和整数时。

代码

C++
#include<bits/stdc++.h>
using namespace std;
long long idx,n,arr[5000100];
long long q=0;
struct node{
	long long son,mother,kk;
}ans;
bool check(node a,node b){//a大于b
	if(a.kk>b.kk){
		return true;
	}
	a.son*=b.mother;
	b.son*=a.mother;
	if(a.son>=b.son&&a.kk==b.kk){
		return true;
	}
	return false;
}
int main(){
	ans.kk=0;ans.mother=0;ans.son=0;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>arr[i];
	}
	for(int idx=2;idx<=n;idx++){
		if(arr[idx-1]>arr[idx]){
			q=idx-1;
			break;
		}
	}
	for(;idx<=n;idx++){
		if(arr[idx]>arr[q]){
			long long k=arr[idx]-arr[idx-1];
			node aans;
			aans.kk=idx-1-q;
			aans.mother=k;
			aans.son=k-arr[idx]+arr[q];
			if(check(aans,ans)) ans=aans;
			q=idx;
		}
	}
	for(idx=n-1;idx>=1;idx--){
		if(arr[idx+1]>arr[idx]){
			q=idx+1;
			break;
		}
	}
	for(;idx>=1;idx--){
		if(arr[idx]>arr[q]){
			long long k=arr[idx]-arr[idx+1];
			node aans;
			aans.kk=q-idx-1;
			aans.mother=k;
			aans.son=k-arr[idx]+arr[q];
			if(check(aans,ans)) ans=aans;
			q=idx;
		}
	}
	ans.son=ans.son+ans.kk*ans.mother;
	long long kkk=__gcd(ans.son,ans.mother);
	ans.son/=kkk;
	ans.mother/=kkk;
    if(ans.mother==1){
        cout<<ans.son;
    }
	else if(ans.mother!=0){
		cout<<ans.son<<"/"<<ans.mother;
	}
	else{
		cout<<0;
	}
	return 0;
}
原文