问一个c的问题
H15:编码问题(选作)
成绩: 5 / 折扣: 0.8
设有一个整形数组 A[0..N-1];存放的元素为 0~N-1 (1<N<=10)之间的整数,且 A[i]≠A[j](i≠j)。例如,当N=6时,有:A=(4,3,0,5,1,2)。此时,数组A的编码定义如下:
A[0]编码为0;
A[i]编码为:在A[0],A[1],…,A[i-1]中比A[i]的值小的个数 (i=1,2,…,N-1)
例如上面数组 A的编码为:B=(0,0,0,3,1,2)
若给出数组A,则可求出其编码。同理,若给出数组A的编码,可求出A中的原数据。
输入:
推导方向(取值为1或2,如为1,则表示根据数组求数组编码;如为2,则表示根据编码反求数组)
数组个数
数组或数组编码元素
输出:
数组编码、或数组本身(元素之间以空格分隔)
这个题输入1的时候我会做,输入2的时候不知道怎么办,求助各位,如果时间紧,告诉我思路也可以
[解决办法]
- C/C++ code
#include <stdio.h>#include <stdlib.h>struct node { int no ; //数组下标 int num ;//数值 struct node * next ;};int main(){ int a[] = {0,0,0,3,2,2}; struct node * head = malloc(sizeof(struct node)); struct node * next ; next = malloc(sizeof(struct node)); next->num = 0 ; next->no = 0 ; next->next = NULL ; head->next = next ; struct node * tmp = head ; int i ,nums , add = 0; for(i = 1 ; i < 6 ; i++) { nums = head->next->num ; tmp = head ; next = malloc(sizeof(struct node)); next->no = i ; next->next = NULL ; if(a[i]==0){ next->num = head->next->num - 1; next->next = head->next ; head->next = next ; }else { while(a[i]>0) { nums ++; tmp = tmp->next ; a[i] -- ; } next->next = tmp->next ; next->num = nums ; tmp->next = next ; tmp = next ; while(tmp->next) { tmp->next->num ++ ; tmp = tmp->next ; } } } tmp = head ; nums = head->next->num ; if(nums < 0 ) { add = - nums ; } while(tmp->next){ tmp->next->num += add ; a[tmp->next->no] = tmp->next->num ; //printf("%d , %d.\n" ,tmp->next->no , tmp->next->num); tmp = tmp->next ; } i = 0 ; while(i < 6){ printf("%d \n" ,a[i]); i++ ; }}