原题地址
https://vjudge.net/problem/UVA-1594
题意:对一个n元组(a1, a2, … an),可以对于每个数求出它和下一个数的差的绝对值,得到一个新的n元组(|a1-a2|,|a2-a3|…|an-a1|),重复这个过程,得到的序列成为Ducci序列。
例如(8, 11, 2, 7) → (3, 9, 5, 1) → (6, 4, 4, 2) → (2, 0, 2, 4) → (2, 2, 2, 2) → (0, 0, 0, 0).
有的Ducci序列最终会循环,输入n元组(3<=n<=15),判断它最终会变为全0还是会循环,保证1000步内变为0或循环。
解题思路
本题是《算法竞赛入门经典》的习题5-2,可以用模拟+set查重解决。
循环的条件很显然,如果之前出现过的某个n元组,在经过一些迭代后再次出现,那么之后就会陷入循环;只要判断当前的n元组在之前是否出现过即可。
可以用map记录每个n元组出现的次数,当然最方便的还是set集合啦。
n元组本身无法简单表示,所以必须声明结构体来表示n元组对象,并为这个对象赋予一些内部函数,如判断是否全零、计算成为下一个n元组等。
值得注意的是,自定义结构体的比较方式需要自己指定,所以我刚开始重载了”==”比较符,发现在调用s.count()的结果总是不对,于是经过百度,发现只需要重载’<’符号(Set的默认比较使用缺省的less仿函数,该仿函数使用<运算符比较用于决定set底层的红黑树排序),修改之后就AC了。
AC代码
#include <iostream>
#include <algorithm> //abs函数头文件
#include <set>
using namespace std;
const int maxn = 20;
typedef struct node
{
int n;
int num[maxn];
bool operator < (const node &A) const //重载小于比较符,判断之前是否出现过
{
for (int i = 0; i<n; ++i)
if (num[i] != A.num[i])
return num[i] < A.num[i];
return false;
}
bool isZero() //判断当前n元组是否为0
{
for (int i = 0; i < n; ++i)
{
if (num[i] != 0)
return false;
}
return true;
}
void Ducci() //计算到下一个n元组
{
int x = num[0]; //注意num[0]会被修改
for (int i = 0; i<n-1; ++i)
num[i] = abs(num[i+1] - num[i]);
num[n-1] = abs(x - num[n-1]);
}
}n_tuple;
int main()
{
int T;
cin >> T;
set<n_tuple> s;
while(T--)
{
int n;
cin >> n;
s.clear();
n_tuple tmp;
tmp.n = n;
for (int i = 0; i<n; ++i)
cin >> tmp.num[i];
s.insert(tmp);
bool isLoop = true;
int times = 0;
while(times < 1000)
{
times++;
tmp.Ducci(); //产生下一个n元组
//print_tuple(tmp);
if (tmp.isZero()) {isLoop = false; break;} //出现全零元组
if (s.count(tmp)) {isLoop = true; break;} //出现过当前n元组
else
s.insert(tmp);
}
if (isLoop) cout << "LOOP" << endl;
else cout << "ZERO" << endl;
}
return 0;
}