发布网友 发布时间:2023-06-25 23:30
共3个回答
热心网友 时间:2024-12-13 02:35
该程序不局限于你题目中的n、m。在该程序中,n、m可以任意大。
我已运行成功,试了很多结果都正确。
#include<stdio.h>
#define MAX 30
typedef struct node
{
int length;
char s[MAX];
}*pnode;
void sort_class( pnode* P, int left, int right, int n,char c )
{
for ( int i = left; i <= right; i++ )
if ( P[i]->length > n )
break;
if ( i > right )
return;
for ( i = right-1; i >= left; i-- )
{
bool exchange = false;
for ( int j = left; j <= i; j++ )
{
if ( ( P[j]->length <= n && !(P[j+1]->length <= n) && c < P[j+1]->s[n] ) ||
( !(P[j]->length <= n) && P[j+1]->length <= n && P[j]->s[n] < c ) ||
( !(P[j]->length <= n) && !(P[j+1]->length <= n) && P[j]->s[n] < P[j+1]->s[n]) )
{
pnode temp = P[j+1]; P[j+1] = P[j]; P[j] = temp;
exchange = true;
}
}
if ( !exchange )
break;
}
for ( i = left; i <= right; i++ )
{
if ( P[i]->length <= n )
continue;
int start = i;
i++;
while ( i <= right && P[i]->s[n] == P[start]->s[n] )
i++;
i--;
sort_class( P, start, i, n+1, c );
}
}
void sort( pnode* P, int left, int right )
{
for ( int i = right-1; i >= left; i-- )
{
bool exchange = false;
for ( int j = left; j <= i; j++ )
{
if ( P[j]->s[0] < P[j+1]->s[0] )
{
pnode temp = P[j+1]; P[j+1] = P[j]; P[j] = temp;
exchange = true;
}
}
if ( !exchange )
break;
}
for ( i = left; i <= right; i++ )
{
int start = i;
i++;
while ( i <= right && P[i]->s[0] == P[start]->s[0] )
i++;
i--;
sort_class( P, start, i, 1, P[start]->s[0] );
}
}
void main()
{
FILE* fp;
fp = fopen( "input.txt", "r" );
int n;
fscanf( fp, "%d", &n );
pnode* P = new pnode[n];
for ( int i = 0; i < n; i++ )
{
P[i] = new node;
fscanf( fp, "%s", P[i]->s );
for ( int j = 0; P[i]->s[j] != '\0'; j++);
P[i]->length = j;
}
fclose( fp );
fp = fopen( "output.txt" , "w" );
sort( P, 0, n-1 );
for ( i = 0; i < n; i++ )
{
fprintf( fp, "%s ", P[i]->s );
printf( "%s ", P[i]->s );
}
printf("已输出到文件\n");
}
热心网友 时间:2024-12-13 02:36
#include<iostream>热心网友 时间:2024-12-13 02:36
这个可以实现 不知道当n=3的时候 组成的数是1 2 3还是不是确定的? (比如可以不是1 2 3 而是输入的?)