#516. 「LibreOJ β Round #2」DP 一般看規律 set啟發式合併
阿新 • • 發佈:2019-01-09
題意:給出操作,將序列中所有一個數字替換為另一個,詢問每次操作後距離最近的兩個相同數字的距離。
解法:每個數字只與他的前驅和後繼產生貢獻。構建n個set,每次將較小的暴力合併到大的上面,通過lower_bound來找到他的前驅和後繼。懶得離散化可以用map來存set。
#include <bits/stdc++.h>
using namespace std;
map <int, set<int>> mp;
int n, m, x, ans = 2147483647;
void update(int x, int y){
set<int> ::iterator it = mp[x].lower_bound(y);
if(it != mp[x].end()) ans = min(ans, *it-y);
if(it != mp[x].begin()) it--, ans = min(ans, y-*it);
}
int main()
{
scanf("%d %d", &n,&m);
for(int i=1; i<=n; i++){
scanf("%d", &x);
update(x, i);
mp[x].insert(i);
}
for (int i=1; i<=m; i++){
int a, b;
scanf("%d %d", &a, &b);
if(a == b){
printf("%d\n", ans);
continue;
}
if(mp[a].size()>mp[b].size()) swap(mp[a], mp[b]);
for(set<int>::iterator it=mp[a].begin(); it!=mp[a].end(); it++){
update(b, *it);
mp[b].insert(*it);
}
mp[a].clear();
printf ("%d\n", ans);
}
return 0;
}