3 solutions
-
0
#include<iostream> #include<algorithm> #include<cstring> #include<queue> using namespace std; typedef pair<int , int > PII ; const int N = 200010, M = 3*N ; int h[N] , e[M] , ne[M] , idx = 0 , n; PII a[N] ; int dis[N] ; bool st[N] ; void insert( int a , int b)//wu { e[idx] = b; ne[idx] = h[a]; h[a] = idx ++ ; } int bfs() { memset (dis , -1 , sizeof dis ) ; dis [1] = 0 ; queue <int> q ; q.push(1) ; st[1] = true ; while(q.size())//bfs经典代码,路径最短的就会先到 { auto t = q.front(); q.pop() ; for(int i = h[t];i != -1;i = ne[i]) { int j = e[i] ; if( !st[j] ) { dis[j] = dis[t] + 1 ; q.push(j) ; st[j] = true ; } } } return dis[n]; } int main( ) { memset(h , -1 , sizeof h) ; cin >> n ; for( int i = 1;i <= n; i ++)cin >> a[i].first , a[i].second = i ; sort(a + 1 , a + n + 1) ; for( int i = 1 ; i < n ; i++) insert( i , i + 1 ) , insert( i + 1 , i ) ; //前后左右可移动一格,建立无向图 for(int i = 1 ; i < n ; i ++) if(a[i].first == a[i + 1].first) insert(a[i].second , a[i + 1].second) ; //亮度相同正向瞬移建立树 cout << bfs(); return 0; }
Information
- ID
- 7012
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 6
- Tags
- (None)
- # Submissions
- 149
- Accepted
- 12
- Uploaded By