Va 1016-Silly Sort (Replacement + greedy)

Source: Internet
Author: User

Va 1016-Silly Sort (Replacement + greedy)

Link: Ultraviolet A 1016-Silly Sort

Given a sequence with a length of n, each operation can exchange the positions of any two numbers. The cost is the sum of the two numbers, and the minimum cost is obtained to arrange the sequence in an ordered order.

Solution: The given sequence is mapped to a replacement based on the number of values to break down the replacement cycle. For each cycle, the minimum value is the minimum one-by-one exchange cost, but it should be considered, you can exchange the minimum value with the minimum value in the sequence, replace it with the minimum value, and finally change it back. Take the best of the two cases.

#include 
  
   #include 
   
    #include using namespace std;const int maxn = 1005;int n, arr[maxn], rec[maxn], pos[maxn];int rep, v[maxn];void init () {    memset(v, 0, sizeof(v));    memset(rec, -1, sizeof(rec));    rep = maxn;    for (int i = 0; i < n; i++) {        scanf("%d", &arr[i]);        pos[i] = arr[i];        rep = min(arr[i], rep);    }    sort(pos, pos + n);    for (int i = 0; i < n; i++)        rec[pos[i]] = i;    for (int i = 0; i < n; i++)        pos[i] = rec[arr[i]];    /*    for (int i = 0; i < n; i++)        printf("%d ", pos[i]);    printf("\n");    */}int solve () {    int ret = 0;    for (int i = 0; i < n; i++) {        if (v[i])            continue;        int j = i, c= 0;        int ans = 0, tmp = maxn;        while (v[j] == 0) {            tmp = min(tmp, arr[j]);            ans += arr[j];            v[j] = 1;            c++;            j = pos[j];        }        ans -= tmp;        ret += ans + min(tmp * (c-1), tmp * 2 + rep * (c+1));    }    return ret;}int main () {    int cas = 1;    while (scanf("%d", &n) == 1 && n) {        init();        printf("Case %d: %d\n\n", cas++, solve());    }    return 0;}
   
  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.