#include<stdio.h>
#define N 1000
typedef struct {
  int sum;
  int flag;
} CC;
CC C[N];
int A[2000],B[2000];
int main()
{
  int i,n,min=0,m,k,now,sum=0;
  scanf("%d",&n);
  for(i=1;i<n+1;i++){
    scanf("%d",&A[i]);
  }
  
  for(i=0;i<N;i++){
    C[i].sum=0;
    C[i].flag=0;
  }
  for(i=1;i<n+1;i++){
    C[A[i]].sum+=1;
    C[A[i]].flag+=1;
  }
  for(i=0;i<N;i++){
    C[i].sum+=C[i-1].sum;
  }

  for(i=n+1;i>0;i--){
    if(C[A[i]].flag==1){
      k=i;
      now=k;
      m=0;
      B[C[A[k]].sum]=A[k];
      C[A[i]].flag=0;
      min=A[k];
      k=C[A[k]].sum;
      while(now!=k){
        if(m==0)sum+=A[now];
        B[C[A[k]].sum]=A[k];
        C[A[k]].flag=0;
        sum+=A[k];
        if(min>A[k])min=A[k];
        k=C[A[k]].sum;
        m+=1;
      }
      if(m>2)sum+=min*(m-1);
      m=0;
      min=0;
    }
  }
  for(i=1;i<n;i++){
    printf("%d ",B[i]);
  }
  printf("%d",B[i]);
  printf("\n%d\n",sum);
  return 0;
}