首页 > 代码库 > POJ1026 Cipher 【polya】

POJ1026 Cipher 【polya】

This question is not so difficult.

First,my thoughts were we should use a lot of code to find out the loop block,but there is no need to do that .

you just need to get every new position of char in the string.

Algorithm is also easy , just like how do people think such as how you thinking to find a loop

code is below:

#include <cstdio>
#include <cstring>
#include <cstdlib>
int key[99999];
int getIndex(int* key,int i,int k)
{
	int end=i;
	int j;//loop num
	for(j=1;j<=k;j++)
	{
		i=key[i];
		if(i==end)
		{
			for(int kk=0;kk<(k%j);kk++)
			{
				i=key[i];
			}
			return i;
		}
	}
	return i;
}
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		if(!n) break;
		int tmp,k;
		char word[9999];
		char to[9999];
		for(int i=0;i<n;i++)
		{
			scanf("%d",&tmp);
			key[i]=tmp-1;
		}
		while(scanf("%d",&k)&&k!=0)
		{
			getchar();
			gets(word);
			int len=strlen(word);
			for(int i=len;i<n;i++)
				word[i]=' ';
			for(int i=0;i<n;i++)
			{
				to[getIndex(key,i,k)]=word[i];
			}
			for(int i=n-1;;i--)//there cant be i>=0,because maybe the string are all spaces.And,there is no need to do this, because the ques said you can show string of length n,but i dont know why non-length-n is also ok
				if(to[i]!=' ')
				{
					to[i+1]='\0';
					break;
				}
			//to[n]='\0';
			printf("%s\n",to);
		}
		printf("\n");
	}
	return 0;
}