Description:
Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.
In first line there is one integer n (1 ≤ n ≤ 2·105) — number of cafes indices written by Vlad.
In second line, n numbers a1, a2, ..., an (0 ≤ ai ≤ 2·105) are written — indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted.
Print one integer — index of the cafe that Vlad hasn't visited for as long as possible.
5 1 3 2 1 2
3
6 2 1 2 2 4 1
2
In first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer.
In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes.
题目大意:
假设某人去过n个咖啡馆(其中可能会有重复, 因为很喜欢咖啡馆所以他会在咖啡馆打标记。但是他想知道每一次拜访完所有的咖啡馆第一次去的是哪一个。 于是现在给你一个序列代表按时间顺序的咖啡馆标记, 输出他最后一次拜访完所有咖啡馆的第一个咖啡馆是哪个。
在这里举个例子:
比如
3 2 1 2 3
答案就是1, 一共标记过三个咖啡厅, 显然1 2 3去过了所有的咖啡厅里1是最前的。
解题思路:
设一个bool数组记录咖啡馆下标, cnt记录一共去过几个不同的咖啡馆。 从后向前遍历数组, 一旦发现遍历到当前下标的咖啡馆时恰好去过的不同的咖啡馆数 == cnt, 那么直接输出这个下标即可。
代码:
#include <iostream>
#include <sstream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <utility>
#include <string>
#include <cmath>
#include <vector>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
using namespace std;
/*
*ios::sync_with_stdio(false);
*/
typedef long long ll;
typedef unsigned long long ull;
const int inf = 0x7fffffff;
const int mod = 1000000;
const int Max = (int) 2e5 + 9;
bool vis[Max];
int Rank[Max], arr[Max];
int main() {
// definition
int n, cnt = 0, temp = 0, ans;
// initialization
memset(vis, 0 ,sizeof(vis));
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", &arr[i]);
if (!vis[arr[i]]) {
vis[arr[i]] = 1;
cnt++;
}
}
memset(vis, 0, sizeof(vis));
for (int i = n - 1; i >= 0; --i) {
if (!vis[arr[i]]) {
temp++;
ans = arr[i];
vis[arr[i]] = 1;
}
// all the cafes
if (temp == cnt) {
printf("%d\n", ans);
break;
}
}
return 0;
}