POJ 2128 Leonardo’s Notebook 置換群開方

來源:互聯網
上載者:User

題意:輸入一個字串,由26的大寫字母隨機排列組成。置換的概念如下定義:例如 QWERTYUIOPASDFGHJKLZXCVBNM  表示進過置換換後A用Q替換,B用W替換,C用E置換,····

問你ABCDEFGHIJKLMNOPQRSTUVWXYZ 這樣一個初始字串是否可以經過任意兩次相同的置換得到輸入的字串。

本質上就是問你,輸入的字串所代表的置換是否是任意一個置換的平方?

題解:

1.任意一個長為 L 的置換的k次冪,會把自己分裂成gcd(L,k) 分, 並且每一份的長度都為 L / gcd(l,k)

2.假如 d = gcd(L,K),l = L / gcd(L,k),那麼我們只需要找到d個長為l的迴圈,將他們交錯迴圈串連成一個長為 d * l 的大迴圈, 這樣一個過程就相當於開k次方。

所以在下面的代碼中我們先統計每種長度的迴圈的個數。

然後對每個長度為 len ( 1 <= len <= 26 )度的迴圈都做一下判斷,看能否找到 gcd ( len, 2 )個這樣的迴圈,若找到了,那麼說明這一部分可以開2次方。沒找到就直接返回false.

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;char str[30];int p[30], loop[30];void permute (){    bool flag[30] = { 0 };    memset(loop,0,sizeof(loop));    int now, len, i;    for ( i = 0; i < 26; i++ )    {        if ( flag[i] ) continue;        now = i; len = 0;        while ( flag[now] == 0 )        {            len++;            flag[now] = true;            now = p[now];        }        loop[len]++;    }}bool jugde (){    for ( int len = 2; len <= 26; len += 2 ) //長度為奇數的可以不同判斷,應為gcd(奇數,2) = 1,而他本身的長度就符要求。    {        if ( loop[len] == 0 ) continue;        if ( loop[len] % 2 != 0 ) return false;    }    return true;}int main(){    int t;    scanf("%d",&t);    while ( t-- )    {        scanf("%s",str);        for ( int i = 0; str[i]; i++ )            p[i] = str[i] - 'A';        permute();        if ( jugde() ) printf("Yes\n");        else printf("No\n");    }    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.