Problem A: An antiarithmetic permutation
A permutation of n+1 is a bijective function of the initialn+1 natural numbers: 0, 1, ... n. A permutationp is called antiarithmetic if there is no subsequence of it forming an arithmetic progression of length bigger than 2, i.e. there are no three indices 0 ≤ i < j < k < nsuch that (pi, pj, pk) forms an arithmetic progression.
For example, the sequence (2, 0, 1, 4, 3) is an antiarithmetic permutation of 5. The sequence (0, 5, 4, 3, 1, 2) is not an antiarithmetic permutation of 6 as its first, fifth and sixth term (0, 1, 2) form an arithmetic progression; and so do its second, fourth and fifth term (5, 3, 1).
Your task is to generate an antiarithmetic permutation of n.
Each line of the input file contains a natural number 3 ≤ n ≤ 10000. The last line of input contains 0 marking the end of input. For each n from input, produce one line of output containing an (any will do) antiarithmetic permutation of n in the format shown below.
Sample input
3 5 6 0
Output for sample input
3: 0 2 1 5: 2 0 1 4 3 6: 2 4 3 5 0 1
主要是先确定两个相邻数,再把第三个能形成等差数列的数进行组合。保证子序列不能形成超过两个的等差数列。
#include<iostream>
#include<cstdio>
#include<malloc.h>
#include<cstring>
#include<algorithm>
using namespace std;
int M[11000];
typedef struct T
{
int data;
struct T*next;
} node;
node *newnode()
{
node*u=(node*)malloc(sizeof(node));
if(u!=NULL)u->next=NULL;
return u;
}
T*bulid(int n)
{
int i=2;
node *root=newnode(),*u=newnode();
root->data=0;
u->data=1;
root->next=u;
node *r=root;
while(i<n)
{
r=root;
u=root->next;
while(u!=NULL)
{
int o=r->data > u->data? 2*r->data - u->data:2*u->data - r->data;
if(!M[o]&&o<n)
{
node*s=newnode();
r->next=s;
s->next=u;
s->data=o;
M[o]=1;
i++;
}
if(i>=n)break;
r=u;
u=u->next;
}
}
return root;
}
int main()
{
int n;
while(cin>>n)
{
if(!n)return 0;
else
{
memset(M,0,sizeof(M));
node*u=bulid(n);
cout<<n<<": ";
while(u->next!=NULL)
{
cout<<u->data<<' ';
u=u->next;
}
cout<<u->data<<endl;
}
}
return 0;
}