33,009
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 25 //最后一列长度
char lastColum[] = "1110101001111101000001100"; //最后一列
void sort(char mat[N][N+1]) //对序列按行进行排序
{
int i,j;
int maxIndex;
char temp[N+1];
for(i = 0;i < N;i++)
{
maxIndex = 0;
for(j = 0;j < N-i;j++)
{
if((strcmp(mat[j],mat[maxIndex])) == 1)
{
maxIndex = j;
}
}
if(maxIndex != N - i -1)
{
strcpy(temp,mat[N-i-1]);
strcpy(mat[N-i-1],mat[maxIndex]);
strcpy(mat[maxIndex],temp);
}
}
}
void printMat(char mat[N][N+1]) //打印矩阵
{
int i,j;
for(i = 0;i < N;i++)
{
for(j = 0;j < N;j++)
{
printf("%c ",mat[i][j]);
}
printf("\n");
}
}
void allMoveOneBit(char mat[N][N+1]) //整列的右移一位
{
int i,j;
int nextColum;
int temp[N];
for(j =0 ;j < N; j++)
{
temp[j] = mat[j][N-1];
}
for(i = N-1;i >0;i--)
{
for(j =0 ;j < N; j++)
{
mat[j][i] = mat[j][i - 1];
}
}
for(j = 0;j < N;j++)
{
mat[j][0] = temp[j];
}
}
void moveAndSort(char mat[N][N+1],char ch[]) //右移一次,并且把给定的最后一列复制到新矩阵最后一列
{
int i,j;
for(i = 0;i < N-1 ;i++)
{
allMoveOneBit(mat);
sort(mat);
for(j = 0;j < N;j++)
{
mat[j][N-1] = ch[j];
}
}
}
void initMatrix(char mat[N][N+1],char ch[]) //初始化矩阵,初始化完毕,新矩阵有两列,最后一列和第一列
{
int i,j;
int countOfZero = 0;
for(i = 0;i < N;i++)
{
for(j = 0;j < N;j++)
{
mat[i][j] = '0';
}
}
for(i = 0;i < N;i++)
{
mat[i][N] = '\0';
}
for(i = 0;i < N;i++)
{
mat[i][N-1] = ch[i];
}
for(i = 0;i < N;i++)
{
if(ch[i] == '0')
{
countOfZero++;
}
}
for(i = 0;i <N;i++)
{
if(j > 0)
{
mat[i][0] = '0';
j--;
}
else
{
mat[i][0] = '1';
}
}
}
void findFistSeq(int len,char ch[]) //真正解题的主函数
{
char res[N][N+1];
int i;
initMatrix(res,ch);
moveAndSort(res,ch);
printf("Finally the sequence obtained is:\n");
for(i = 0;i < N;i++)
{
printf("%c ",res[0][i]);
}
putchar('\n');
}
void main()
{
int i;
if(strlen(lastColum) != N)
{
printf("The bad sequence!");
getchar();
exit(0);
}
printf("The source sequence is:\n");
for(i = 0;i < N;i++)
{
printf("%c ",lastColum[i]);
}
putchar('\n');
findFistSeq(N,lastColum);
getchar();
}
The source sequence is:
1 1 1 0 1 0 1 0 0 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0
Finally the sequence obtained is:
0 0 0 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 0 1 0 1 0 1 1
std::string findFistSeq(const std::string &lastCol)
{
int length = lastCol.length(), index0 = length;
char *firstChar = (char*)lastCol.data(), *endChar = firstChar + length;
for(char *next = firstChar; next != endChar; ++next) index0 -= *next & 1;
int *link = new int[length], *link0 = link + index0, *link1 = link + length;
for(int index = length - 1; index >= 0; --index)
{
*(firstChar[index] == '0' ? --link0 : --link1) = index;
}
std::string value(length, (char)'0');
index0 = link[0];
for(char *writeChar = (char*)value.data(), *writeEnd = writeChar + length; writeChar != writeEnd; ++writeChar)
{
*writeChar = firstChar[index0];
index0 = link[index0];
}
delete []link;
return value;
}