科林明伦杯”哈尔滨理工大学第七届程序设计团队赛G - Sorting

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.

≤ ≤ 100

 n  100000 (and 1   1000000 for all test cases)

 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);
    }

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值