POJ 2818 密码 解题报告
编号:2818
考查点:简单计算题
思路: 如果不对K优化的话会TLE,密钥数组没个位会有一个循环,先算出循环,然后用k去模除可以AC.。
提交情况: 前面一直TLE,后面出现了PE,因为没理解题意,最后在别人帮助下修正bug,成功AC.。
Source Code:
//
POJ Grids 2818
#include < iostream >
using namespace std;
int num[ 210 ];
int mod[ 210 ];
int index[ 210 ];
char code[ 210 ];
char decode[ 210 ];
int main()
{
int n;
while (cin >> n && n)
{
memset(num, 0 , sizeof num);
for ( int i = 1 ;i <= n;i ++ )
{
cin >> num[i];
}
int k;
while (cin >> k && k)
{
memset(code, ' ' , sizeof code);
memset(decode, ' ' , sizeof decode);
for ( int i = 1 ;i <= n;i ++ )
{
index[i] = i;
}
memset(mod, 0 , sizeof mod);
for ( int i = 1 ;i <= n;i ++ )
{
int temp = index[i];
while ( ++ mod[i])
{
index[i] = num[index[i]];
if (temp == index[i])
break ;
}
}
gets(code);
code[strlen(code)] = ' ' ;
for ( int j = 1 ;j <= n;j ++ )
{
int temp = k % mod[j];
for ( int i = 1 ;i <= temp;i ++ )
{
index[j] = num[index[j]];
}
}
for ( int i = 1 ;i <= n;i ++ )
{
decode[index[i]] = code[i];
}
decode[n + 1 ] = ' \0 ' ;
cout << ( char * )(decode + 1 ) << endl;
}
cout << endl;
}
return 0 ;
}
#include < iostream >
using namespace std;
int num[ 210 ];
int mod[ 210 ];
int index[ 210 ];
char code[ 210 ];
char decode[ 210 ];
int main()
{
int n;
while (cin >> n && n)
{
memset(num, 0 , sizeof num);
for ( int i = 1 ;i <= n;i ++ )
{
cin >> num[i];
}
int k;
while (cin >> k && k)
{
memset(code, ' ' , sizeof code);
memset(decode, ' ' , sizeof decode);
for ( int i = 1 ;i <= n;i ++ )
{
index[i] = i;
}
memset(mod, 0 , sizeof mod);
for ( int i = 1 ;i <= n;i ++ )
{
int temp = index[i];
while ( ++ mod[i])
{
index[i] = num[index[i]];
if (temp == index[i])
break ;
}
}
gets(code);
code[strlen(code)] = ' ' ;
for ( int j = 1 ;j <= n;j ++ )
{
int temp = k % mod[j];
for ( int i = 1 ;i <= temp;i ++ )
{
index[j] = num[index[j]];
}
}
for ( int i = 1 ;i <= n;i ++ )
{
decode[index[i]] = code[i];
}
decode[n + 1 ] = ' \0 ' ;
cout << ( char * )(decode + 1 ) << endl;
}
cout << endl;
}
return 0 ;
}
总结: TLE是个很可恶的事情,要多注意优化问题..。
By Ns517
Time 09.03.04