1.题意:
思路:
我们需要考虑的是移动1或者n的位置,而不单单是移动其中的某一个
例如排列为:1 2 4 5 3 这个如果我们只考虑移动1的位置的话得到的最大距离仅为3 但如果我们移动5的位置我们得到的最大值就是4了!!
代码:
#include <iostream>
using namespace std ;
const int N = 110 ;
int arr[N] ;
int main()
{
int n ;
cin >> n ;
if(n == 1 )
{
cout << 0 ;
return 0 ;
}
int ma = 1 , mi = 1 ; // 这个有一个坑点就是我们不能确定是否移动的是最大值或者最小值。
for(int i = 1 ; i <= n ; i ++ )
{
cin >> arr[i] ;
if(arr[i] == n ) ma = i ;
if(arr[i] == 1 ) mi = i ;
}
int dis = max(max(ma - 1 , n - ma ) , max(mi - 1 , n - mi ));
cout << dis ;
return 0 ;
}
问题见注释 。
代码
#include <iostream>
#include <cstring>
#include <cstring>
#include <queue>
using namespace std ;
typedef pair<int,int> PII ;
const int N = 5e4 + 10 , M = 2e5 + 10 , INF = 0x3f3f3f3f;
int h[N] , e[M] , ne[M] , idx , w[M] ;
int n , m ;
int point[6] ;
int dist[6][N] ;
bool st[N] ;
void add(int a , int b , int c )
{
e[idx] = b , ne[idx] = h[a] , w[idx] = c , h[a] = idx ++ ;
}
void dijkstra(int srt , int dist[] )
{
memset(dist , 0x3f , N * 4 ) ; // 注意这里要写的是 N * 4 而不是写 sizeof (N * 4 ) !!!!
memset(st , false , sizeof st ) ;
dist[srt] = 0 ;
priority_queue<PII, vector<PII> , greater<PII> > q ;
q.push({0 , srt}) ;
while(q.size() )
{
auto t = q.top() ;
q.pop() ;
int ver = t.second ;
if(st[ver]) continue ;
st[ver] = true ;
for(int i = h[ver] ; ~i ; i = ne[i] )
{
int j = e[i] ;
if(dist[j] > dist[ver] + w[i] )
{
dist[j] = dist[ver] + w[i] ;
q.push({dist[j] , j } ) ;
}
}
}
}
int dfs(int u , int start , int distance )
{
if(u == 6 ) return distance ;
int res = 0x3f3f3f3f ;
for(int i = 1 ; i <= 5 ; i ++ )
{
if(!st[i] )
{
int next = point[i] ;
st[i] = true ;
res = min(res , dfs(u + 1 , i , dist[start][next] + distance ) ) ;
st[i] = false ;
}
}
return res ;
}
int main()
{
cin >> n >> m ;
point[0] = 1 ;
memset(h , -1 , sizeof h ) ;
for(int i = 1 ; i < 6 ; i ++ ) cin >> point[i] ;
for(int i = 0 ; i < m ; i ++ )
{
int x , y , t ;
cin >> x >> y >> t ;
add(x , y , t ) , add(y , x , t ) ;
}
// debug时写的代码。 (查看是否成功建立链表)
// cout << "*********" << endl ;
// for(int i = 1 ; i <= n ; i ++ )
// {
// cout << i << ' ' ;
// for(int j = h[i] ; ~j ; j = ne[j] ) cout << e[j] << ' ' ;
// cout << endl ;
// }
// cout << "**********" << endl ;
for(int i = 0 ; i < 6 ; i ++ ) dijkstra(point[i] , dist[i] ) ;
memset(st , 0 , sizeof st ) ;
printf("%d" , dfs(1 , 0 , 0 ) ) ;
return 0 ;
}