uva 11330,

來源:互聯網
上載者:User

uva 11330,

題目連結:uva 11330 - Andy's Shoes

題目大意:小andy有很多鞋,穿完到處丟,後來他把所有鞋都放回鞋架排成一排,保證了鞋的左右交替,但是顏色混了。問說他至少移動多少次可以將鞋分類好。

解題思路:對應奇數位置為左鞋,偶數位置為右鞋,一雙鞋只有一隻左鞋和一隻右鞋,保證不換左變鞋子,以左鞋的位置為基準換右邊鞋子,對應右邊鞋子的位置即為一個置換,將置換的迴圈分解為x個互不相干的迴圈,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;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.