2021.7.21--牛客補題
阿新 • • 發佈:2021-07-21
題目內容:
連結:https://ac.nowcoder.com/acm/contest/18428/C 來源:牛客網 Arup has to make many practice questions for his Computer Science 1 students. Since many of the questions deal with arrays, he has to generate arrays for his students. Since he doesn’t want to give them difficult practice problems, he always guarantees that the arrays (given to the students) have unique values. Namely, no value will appear twice inView Codeany of his arrays. Unfortunately, Arup is too lazy to generate arrays! About 20 years ago when he started teaching Computer Science 1, he made one really long array to reuse but this long array may have duplicate values. When he makes problems, he simply grabs a contiguous subsequence of this longarray to be the array to be used for a problem but he needs to make sure the contiguous subsequence does not contain duplicates. If the long array has terms a[0], a[1], …, a[n-1], a contiguous subsequence of the long array is any sequence of j-i+1 terms a[i], a[i+1], …, a[j] where 0 ≤ i ≤ j ≤ n – 1. Given an array of n integers, determine how many contiguous subsequences of the arraydo not contain any repeated values. Note that two subsequences with the same contents are considered different (i.e., both counted in the total) if they start at different locations of the original long array. 輸入描述: The first input line contains a single positive integer, n (1 ≤ n ≤ 1e5), representing the size of the input array. The following line contains n space separated integers, representing the values of the input array, in the order they appear in the array. Each of the array values will be an integer between 1 and 1e18, inclusive. (Note: 1e5 means 1 times 10 to the fifth power, that is, 100000) 輸出描述: On a line by itself, output the total number of contiguous subsequences of the input array that do not contain any repeated values. 示例1 輸入 複製 5 1 1 2 1 5 輸出 複製 9 示例2 輸入 複製 8 2 12 3 12 3 2 6 9 輸出 複製 22
題意:
給定一個由 n 個整陣列成的陣列,確定該陣列有多少個連續子序列不包含任何重複值。如果具有相同內容的兩個子序列從原始長陣列的不同位置開始,則它們被認為是不同的(即,兩者都計入總數)。
輸入描述: 第一個輸入行包含一個正整數 n (1 ≤ n ≤ 1e5),表示輸入陣列的大小。下面一行包含 n 個空格分隔的整數,表示 輸入陣列,按照它們在陣列中出現的順序。每個陣列值都是 1 到 1e18(含)之間的整數。 (注:1e5 表示 10 次方的 1 次方,即 100000)
輸出描述: 在一行上,輸出輸入陣列的不包含任何重複值的連續子序列的總數。
思路:
採用雙指標 l ,r ,用map<ll,ll>vis陣列做標記,沒重複時使其vis[s[i]]值為0,否則為1,記錄輸入的數是否重複,首先 l=i=0,讓r一直往右走直到有重複數出現,再讓l向右走,l每移動一步可得到r-i個連續子序列,同時也要從陣列刪掉已用完的 vis[s[i]],l==r時,再重複操作。
程式碼:
#include<bits/stdc++.h> using namespace std; typedef long long ll; map<ll,ll>vis; ll s[100010]; int main() { int n; cin>>n; for(int i=0;i<n;i++)cin>>s[i]; int l=0,r=0; ll ct=0; for(int i=0;i<n;i++) { while(vis[s[r]]==0&&r<n) { vis[s[r]]=1; r++; } ct+=r-i; vis.erase(s[i]); } cout<<ct<<endl; }View Code