[置换群] POJ 1026

题意

求经过k此置换后的结果

思路

求出各个循环节的长度然后让k取模
注意输入输出格式

代码

#include 
//#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;
typedef long long ll;

const int INF = 0x7f7f7f7f;
const int maxn = 200 + 10;

int n;
int a[ maxn ];
int cnt[ maxn ];
char mes[ maxn ];
char ans[ maxn ];

//求每个循环节的长度
void getgroup () {
    memset ( cnt, 0, sizeof ( cnt ) );

    for ( int i = 1; i <= n; ++i ) {
        int c = 0, k = i;
        do {
            k = a[ k ];
            c++;
        } while ( k != i );
        cnt[ i ] = c;
    }
}

int main () {
#ifdef LOCAL
    freopen ( "in", "r", stdin );
    // freopen("out","w",stdout);
#endif
    while ( ~scanf ( "%d", &n ) && n ) {
        for ( int i = 1; i <= n; ++i )
            scanf ( "%d", &a[ i ] );
        getgroup ();

        int k;
        while ( ~scanf ( "%d", &k ) && k ) {
            memset ( mes, ' ', sizeof ( mes ) );
            memset ( ans, ' ', sizeof ( ans ) );

            //输入字符串,不够n的地方要补齐空格
            cin.getline ( mes, sizeof ( mes ) );
            int len = strlen ( mes );
            for ( int i = len; i <= n; ++i )
                mes[ i ] = ' ';

            //每个字符都循环找到结果的位置
            for ( int i = 1; i <= n; ++i ) {
                int t = k % cnt[ i ];
                int kk = i;
                while ( t-- )
                    kk = a[ kk ];
                ans[ kk ] = mes[ i ];
            }
            ans[ n + 1 ] = '\0';
            printf ( "%s\n", ans + 1 );
        }
        printf ( "\n" );
    }

    return 0;
}

你可能感兴趣的:(ACM)