UV 11330-Andy's shoes (replacement)

Source: Internet
Author: User

Link to the question: Ultraviolet A 11330-Andy's shoes

Andy has a lot of shoes and is lost everywhere. Later, he put all his shoes back in a row, ensuring that the left and right sides of the shoes alternate, but the colors are mixed. How many times can he move his shoes at least.

Solution: it corresponds to the left shoes with an odd number and the right shoes with an even number. A pair of shoes only has one left shoes and one right shoes, so that they do not change to the left shoes, change the right shoe based on the position of the left shoe. The position of the right shoe is a replacement. The replacement cycle is divided into X unrelated cycles, ANS = N-x

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 1e4+5;int n, pos[maxn], v[maxn], arr[maxn];int solve () {    int ret = 0;    memset(v, 0, sizeof(v));    for (int i = 0; i < n; i++) {        if (v[i])            continue;        ret++;        int mv = i;        while (v[mv] == 0) {            v[mv] = 1;            mv = arr[mv];        }    }    return ret;}int main () {    int cas, x;    scanf("%d", &cas);    while (cas--) {        scanf("%d", &n);        for (int i = 0; i < 2 * n; i++) {            if (i&1)                scanf("%d", &arr[i/2]);            else {                scanf("%d", &x);                pos[x] = i/2;            }        }        for (int i = 0; i < n; i++)            arr[i] = pos[arr[i]];        printf("%d\n", n - 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.