3 solutions
-
0
#include <bits/stdc++.h> using namespace std; const int N=4000100; int last[1000005]; int n,a[N],idx,cnt,e[N],ne[N],h[N]; bool vis[N]; void add (int x,int y) { e[idx]=y,ne[idx]=h[x];h[x]=idx++; e[idx]=x,ne[idx]=h[y];h[y]=idx++; } void dxadd (int x,int y) { e[idx]=y,ne[idx]=h[x];h[x]=idx++; } struct node { int value; int cnt; }; int bfs() { vis[1]=1; queue<node> q; q.push({1,0}); while(!q.empty()) { node t=q.front(); if(t.value==n) return t.cnt; q.pop(); for(int i=h[t.value];i!=-1;i=ne[i]) { int v=e[i]; if(!vis[v]) { vis[v]=1; q.push({v,t.cnt+1}); } } } } int main() { cin>>n; memset(h,-1,sizeof h); for(int i=1;i<=n;i++) { cin>>a[i]; if(i>1) add(i-1,i); if(last[a[i]]!=0) dxadd(last[a[i]],i); last[a[i]]=i; } cout<<bfs()<<endl; }
Information
- ID
- 7012
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 6
- Tags
- (None)
- # Submissions
- 149
- Accepted
- 12
- Uploaded By