置換羣

【題目地址】HDU 4985  這個題目是出自Best Coder的一場比賽(BestCoder Round #7

【題目大意】題意比較難理解,當時我也沒看懂,看了一下別人的題解,說是置換羣,然後我才明白了這一切……

【代碼】

#include <iostream>
#include <cstdio>
#define MAXN 10+100000

using namespace std;

int arr[MAXN];
bool vis[MAXN];

int main()
{
    freopen("in.txt","r",stdin);
    int n;
    while(cin>>n){
        for(int i = 1; i <= n; i++)
            scanf("%d",&arr[i]);

        for(int i = 1; i <= n; i++){
            vis[i] = false;
        }
        for(int now = 1; now <= n; now++){
            if(vis[now])
                continue;
            printf("(");
            printf("%d",now);

            vis[now] = true;
            now = arr[now];
            while(!vis[now]){
                printf(" %d",now);

                vis[now] = true;
                now = arr[now];
            }
            printf(")");
        }
        printf("\n");
    }
    return 0;
}

【後記】好好體味一下置換羣中應用的技巧

發佈了50 篇原創文章 · 獲贊 8 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章