24h購物| | PChome| 登入
2013-11-21 08:43:10| 人氣2,116| 回應0 | 上一篇 | 下一篇

[UVA][greedy] 11330 - Andy's Shoes

推薦 0 收藏 0 轉貼0 訂閱站台

Problem H: Andy's Shoes

Andy has n pairs of shoes in n different colors. At the end of the day he likes to put them back on his shoe rack. He has learned to always put a left shoe together with a right shoe. However, he has not learned about putting pairs of shoes with the same color together. Papa's job is to pair up the shoes. Since Papa is tired from work at the algorithm factory, he wants to do this in the minimal number of steps. One step means to swap two shoes.

Your job is to help Papa.

Input format: As usual, the first line contains the number of test cases. Each test case consists of a single line starting with total number of pairs of shoes n. The following 2n numbers describe the initial arrangement of shoes on the rack. Each shoe is labeled by a positive integer at most 10,000 where two shoes share the same label if and only if they are part of the same pair. Both the left and right shoes of a given pair will be present (remember that left and right shoes alternate).

Output: For each test case, output one line containing a single number - the minimum number of swaps needed to pair up all shoes.

Sample input

2
2 2 1 1 2
4 1 2 3 4 4 1 2 3

Output for sample input

1
3



題目描述:


有 N 雙鞋子,每雙鞋有各自的顏色編號,且不重複。

現在由於相當凌亂地一雙一雙擺好,但是並不是每雙都是同一種顏色。

問最少交換次數將每雙鞋調整成相同顏色。

題目解法:


可以肯定的是,最大交算次數不超過 n。

因為每次交換一定可以使得一雙鞋湊一對,最多操作 n 次。

也就是說,greedy 每次一定要湊出一對。

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int main() {
    int testcase, n;
    int i, x[10005], y[10005];
    int mx[10005], my[10005];
    scanf("%d", &testcase);
    while(testcase--) {
        scanf("%d", &n);
        memset(mx, 0, sizeof(mx));
        memset(my, 0, sizeof(my));
        for(i = 0; i < n; i++) {
            scanf("%d %d", &x[i], &y[i]);
            mx[x[i]] = i, my[y[i]] = i;
        }
        int ret = 0;
        for(i = 0; i < 10005; i++) {
            if(mx[i] != my[i]) {
                int aIdx = my[i];
                y[aIdx] = y[mx[i]];
                my[y[mx[i]]] = aIdx;                
                ret++;
            }
        }
        printf("%d\n", ret);
    }
    return 0;
}

台長: Morris
人氣(2,116) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 教育學習(進修、留學、學術研究、教育概況) | 個人分類: UVA |
此分類下一篇:[UVA][dp] 11361 - Investigating Div-Sum Property
此分類上一篇:[UVA][SSSP] 11374 - Airport Express

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文