Description
You have an integer sequence a1 … an (integers are distinct) and you need to sort it by ascending order. However, you can only swap two integers at a time and the cost is (ai + aj) if you swap ai and aj.
Your task is to calculate the minimum cost of sorting.
Input
There is an integer T on the first line, then T cases follow.
For each case, there is an integer n on the first line, and n integers a1 … an on the second line.
1 ≤ T ≤ 100
1 ≤ n ≤ 100000 (and 1 ≤ ∑n ≤ 1000000 for all test cases)
1 ≤ ai ≤ 109
Output
For each case, print the minimum cost on a single line.
Sample Input
5
3
3 2 1
4
8 1 2 4
5
1 8 9 7 6
6
8 4 5 3 2 7
9
901343232 439583812 852399982 732257750 739673755 979883931 445261874 867592420 875627527
Sample Output
4
17
41
34
9324217281
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#include<stack>
#define eps 1e-8
#define ll long long
const int inf = 0x3f3f3f3f;
const long long mod=1e9+7;
const int nMax=110;
using namespace std;
int t,n;
long long ans;
long long mii;
struct node
{
long long s,t;
}a[100000+10];
int cmp(node a,node b)
{
return a.t<b.t;
}
long long k1,k2,k,kk,mi;
int v[100000+10];
int main()
{
scanf("%d",&t);
while(t--)
{
ans=0;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%lld",&a[i].t);
a[i].s=i;
if(i==0)
mi=a[i].t;
else
mi=min(mi,a[i].t);//所有数字中的最小值
}
sort(a,a+n,cmp);
memset(v,0,sizeof(v));
for(int i=0;i<n;i++)
{
if(!v[i])
{
long long yy=1;
long long p=i;
mii=a[p].t;
v[p]=1;
kk=a[p].t;
while(a[p].s!=i)//找1个循环
{
yy++;
p=a[p].s;
mii=min(mii,a[p].t);//循环中最小的数
kk+=a[p].t;
v[p]=1;
}
k1=kk+mii*(yy-2);
k2=kk+mi*(yy+1)+mii;
k=min(k1,k2);//两种方法比较取小值
ans+=k;
}
}
printf("%lld\n",ans);
}
}