acwing 136 (set對結構體排序)

有n個數,從第二個數開始,要求輸出它前面的數中與當前數的最小的差值,以及那個數的下標。如果差值一樣,輸出較小的那個數的下標。

比如1 5 3 從5開始,5前面只有1,與 1的差值爲4,所以輸出4 1

對於3,和1,5的差值都爲2,但是1更小,輸出1的小標,即輸出2 1

這題可以用pair也可以用結構體,用結構體需要自定義排序方式,和優先隊列定義結構體排序一樣。

先要插入一個極大值和一個極小值,作爲邊界。然後每次輸入一個數,就找出它的前驅和後繼,比較與前驅的差和與後繼的差的大小。輸出小的。然後再把這個數插入set

#pragma warning(disable:4996)
#include<climits>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<string>
using namespace std;
typedef long long ll;
struct node
{
	ll val, id;
	bool operator <(const node x)const
	{
		return val < x.val;
	}//從小到大排序
};
set<node>st;
int main()
{
	ll n, i, j, t1, t2;
	scanf("%lld", &n);
	set<node>::iterator ite,ite1;
	node x, y;
	x.val =INT_MAX; x.id = 0;
	y.val = INT_MIN; y.id = 0;
	//x和y的id不影響結果,隨便什麼都行。
	st.insert(x); st.insert(y);
	for (i = 1; i <= n; i++)
	{
		scanf("%lld", &x.val);
		x.id = i;
		if (i > 1)
		{
			ite = st.upper_bound(x);//x的後繼
			ite1 = ite;
			ite1--;//x的前驅
			t1 = x.val - ite1->val;
			t2 = ite->val - x.val;//兩個差值
			if (t1 <= t2)printf("%lld %lld\n", t1, ite1->id);
			else printf("%lld %lld\n", t2, ite->id);
		}
		st.insert(x);//插入x
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章