1. 程式人生 > >CH1301 鄰值查找【set應用】

CH1301 鄰值查找【set應用】

應用 cout 找到 基本數據結構 約定 urn pch ole 就是

1301 鄰值查找 0x10「基本數據結構」例題

描述

給定一個長度為 n 的序列 A,A 中的數各不相同。對於 A 中的每一個數 A_i,求:
min(1≤j<i) ?|A_i-A_j|
以及令上式取到最小值的 j(記為 P_i)。若最小值點不唯一,則選擇使 A_j 較小的那個

輸入格式

第一行一個整數n,第二行n個數A_1~A_n。

輸出格式

n-1行,每行2個用空格隔開的整數。分別表示當i取2~n時,對應的 min(1≤j<i) ?|A_i-A_j| 和 P_i 的值。

樣例輸入

3
1 5 3

樣例輸出

4 1
2 1

數據範圍與約定

  • 對於30%的數據: n<=100
  • 對於70%的數據: n<=10^4
  • 對於100%的數據: n<=10^5, |A_i|<=10^9

思路:

用set或者是鏈表實現

讀入第i個時,加入set,set中存的就是i之前的所有數,而且set是默認排好序的。

然後find找到i的位置,|Aj-Ai|最小的一定是Ai的前驅或者後繼。

判斷一下就行了。要註意Ai就是set的頭或尾的情況。

奇怪的是,用printf輸出的時候有一點問題不知道是為什麽,用cout就行。

 1 // ConsoleApplication2.cpp : 此文件包含 "main" 函數。程序執行將在此處開始並結束。
 2 //
 3 
 4 
 5 //#include "pch.h"
 6 #include <iostream>
 7
#include <set> 8 #include <cmath> 9 #include <stdio.h> 10 using namespace std; 11 12 int n; 13 const int maxn = 1e5 + 5; 14 struct node { 15 int a; 16 int id; 17 bool operator < (const node &b)const { 18 return a < b.a; 19 } 20 }A[maxn]; 21 set<node>sss;
22 set<node>::iterator after; 23 set<node>::iterator before; 24 25 int main() 26 { 27 scanf("%d", &n); 28 scanf("%d", &A[1].a);A[1].id = 1; 29 sss.clear(); 30 sss.insert(A[1]); 31 for (int i = 2; i <= n; i++) { 32 scanf("%d", &A[i].a); 33 A[i].id = i; 34 sss.insert(A[i]); 35 after = sss.find(A[i]); 36 before = sss.find(A[i]); 37 //cout<<(*after).id<<endl; 38 if (after == sss.begin()) { 39 after++; 40 cout<<abs((*after).a - A[i].a)<<" "<<(*after).id<<endl; 41 //printf("%d %d\n", abs((*after).a - A[i].a), (*after).id); 42 } 43 else if (after++, after == sss.end()) { 44 before--; 45 //node tmp = *before; 46 //printf("%d\n", tmp.a); 47 cout<<abs((*before).a - A[i].a)<<" "<<(*before).id<<endl; 48 //printf("%d %d\n", abs((*before).a - A[i].a), (*before).id); 49 } 50 else { 51 before--; 52 if (abs((*before).a - A[i].a) < abs((*after).a - A[i].a)) { 53 cout<<abs((*before).a - A[i].a)<<" "<<(*before).id<<endl; 54 } 55 else if(abs((*before).a - A[i].a) > abs((*after).a - A[i].a)){ 56 cout<<abs((*after).a - A[i].a)<<" "<<(*after).id<<endl; 57 } 58 else { 59 if ((*before).a < (*after).a) { 60 cout<<abs((*before).a - A[i].a)<<" "<<(*before).id<<endl; 61 } 62 else { 63 cout<<abs((*after).a - A[i].a)<<" "<<(*after).id<<endl; 64 } 65 } 66 } 67 } 68 } 69

CH1301 鄰值查找【set應用】