Ultraviolet A 1016-silly sort (replacement decomposition + greedy)

Source: Internet
Author: User
Ultraviolet A 1016-silly sort

Question Link

Given a sequence, numbers are different. Two numbers can be exchanged each time. The price of the exchange is the sum of the two numbers, and the minimum price of the sequence to increase is required.

Idea: using the replacement decomposition principle, we can consider each cycle of the sequence separately. For each cycle, constant exchange is sure that each number will change at least once, and then use greedy ideas, if we replace the minimum value in a loop each time, the minimum value will be-1 time in length, and the remaining number will be each time. Note that there is another possible optimization method here, it is to change the minimum value in the entire sequence to the cycle, and then change it after replacement. Both of them can be considered.

Code:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int N = 1005;int n, a[N], b[N], id[N], Min;int main() {    int cas = 0;    while (~scanf("%d", &n) && n) {Min = 1000;for (int i = 1; i <= n; i++) {    scanf("%d", &a[i]);    Min = min(Min, a[i]);    b[i] = a[i];}sort(b + 1, b + n + 1);for (int i = 1; i <= n; i++)    id[b[i]] = i;int ans = 0;for (int i = 1; i <= n; i++) {    if (a[i]) {int cnt = 0;int sum = a[i];int now = id[a[i]];int tmp = a[i];a[i] = 0;while (a[now]) {    cnt++;    sum += a[now];    tmp = min(tmp, a[now]);    int save = now;    now = id[a[now]];    a[save] = 0;}ans += min(sum + tmp * cnt - tmp, sum + 2 * (tmp + Min) + Min * cnt - tmp);    }}printf("Case %d: %d\n\n", ++cas, ans);    }    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.