在alternatively sorted的数组中查找元素

这里alternatively sorted的数组是指 奇数位置index上的数升序排列 与 偶数位置index上的数升序排列

如12,2,16,5,18,32,33,38


用2次二分查找就可以达到要求


/*
Given an array which is alternatively sorted. Find an element in it.
e.g. 12,2,16,5,18,32,33,38
*/
#include <algorithm>
#include <iostream>

int binarySearch(int* a, int left, int right, int target)
{
	if(left <= right)
	{
		if(target > a[right] || target < a[left])
			return -1;

		int mid = (left + right) / 2;

		if(mid - left == 1 && right - mid == 1)
			return -1;

		if(a[mid] == target)
			return mid;
		else if(a[mid] > target)
			return binarySearch(a, left, mid - 2, target);
		else
			return binarySearch(a, mid + 2, right, target);
	}
};


int findElemIdx(int* a, int n, int target)
{
	if(n == 0)
		return -1;
	else if(n == 1)
	{
		if(target == a[0])
			return 0;
		else
			return -1;
	}
	else
	{
		int endIdx = n - 1;
		int res;

		int oddIdx, evenIdx;
		if(endIdx % 2 == 1)
		{
			oddIdx = endIdx;
			evenIdx = endIdx - 1;
		}
		else
		{
			evenIdx = endIdx;
			oddIdx = endIdx - 1;
		}

		res = binarySearch(a, 1, oddIdx, target);
		
		if(res == -1)
			res = binarySearch(a, 0, evenIdx, target);

		return res;
	}
};



int main()
{
	int a[] = {12,2,16,5,18,32,33,38};

	int res = findElemIdx(a, 8, 2);
	return 0;
}


c++14 # P14712 [ICPC 2023 Tehran R] Cafebazaar' s Applications ## 题目描述 年末,Cafebazaar 发布了一份列表,包含了其 $n$ 个应用程序各自的用户数量。现在,每个应用程序都渴望通过一张广告图片来展示其成功,这张图片突出显示了包含该应用程序自身在内的一个连续应用子集。此外,为了使图片可信,该子集必须包含至少 $k$ 个应用程序(包括自身)。 对于列表中的每个应用程序,我们需要根据用户数量,确定该应用程序在任意有效子集中可能达到的最小排名。应用程序在子集中的排名定义为:在该子集中,用户数量多于它的应用程序数量加 $1$。 :::align{center} ![](https://cdn.luogu.com.cn/upload/image_hosting/a8dbzpk9.png) ::: ## 输入格式 输入的第一行包含两个整数 $n$ 和 $k$ ($1 \leq k \leq n \leq 10^5$),其中 $n$ 表示应用程序的总数,$k$ 表示广告图片中应用程序的最小数量。接下来的 $n$ 行包含每个应用程序的信息:第 $i$ 行包含 $c_i$,表示第 $i$ 个应用程序的用户数量 ($1 \leq c_i \leq 10^8$)。 ## 输出格式 在输出的一行中,打印 $n$ 个用空格分隔的整数。第 $i$ 个整数应为第 $i$ 个应用程序在广告图片中可能达到的最小排名。 ## 输入输出样例 #1 ### 输入 #1 ``` 7 3 15000000 10000000 30000000 20000000 200000 70000000 100000000 ``` ### 输出 #1 ``` 2 3 1 2 3 1 1 ``` ## 输入输出样例 #2 ### 输入 #2 ``` 3 2 10 10 10 ``` ### 输出 #2 ``` 1 1 1 ``` ## 说明/提示 翻译由 DeepSeek V3 完成
最新发布
12-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值