#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
template<class T>
void swap(T& a, T& b)
{
a = a + b;
b = a - b;
a = a - b;
}
// пузырьком
void sort_lk(int* by,int* l, int n)
{
int i,j;
for(i = 0;i < n;i++)
for(j = 1;j < n;j++)
if(by[j] > by[j-1])
{
swap(by[j], by[j-1]);
swap(l[j], l[j-1]);
}
}
void insert(int *m, int n, int to, int elem)
{
// printf("ins %d to %d\n", elem, to);
int i;
for(i = n - 1; i >= to; i--)
m[i+1] = m[i];
m[to] = elem;
}
int main()
{
int cl;
int i, j;
int *count, *cname;
int *res, total;
FILE *f;
char filename[32] = "rezult.txt";
// получение инфы
printf("Enter color count:");
scanf("%d",&cl);
if(cl < 1) return 0;
count = (int*)malloc(cl*sizeof(int));
cname = (int*)malloc(cl*sizeof(int));
for(i = 0;i < cl;i++)
{
printf("Enter chips' count for color '%d':", i + 1);
do scanf("%d", count + i); while(count[i] < 0);
cname[i] = i + 1;
}
sort_lk(count, cname, cl);
// определение возможности размещения
j = 0;
for(i = 1; i < cl; i++)
{
j += count[i];
}
total = count[0] + j;
f = fopen(filename,"w");
if(j < count[0])
{
printf("\nImposible!\n");
fprintf(f,"\nImposible!\n");
free(count);
free(cname);
getch();
return(0);
}
printf("\nIt's posible!\n");
fprintf(f,"\nIt's posible!\n");
res = (int*)malloc(total*sizeof(int));
j = 1;
while(count[0] > 0)
{
insert(res,total,0,cname[j]);
insert(res,total,0,cname[0]);
count[0]--;
count[j]--;
if(count[j] < 1) j++;
}
while(j < cl)
{
for(i = 1;res[i] == cname[j] || res[i-1] == cname[j];i++);
insert(res, total, i, cname[j]);
count[j]--;
if(count[j] < 1) j++;
}
fprintf(f,"Result: ");
printf("Result: ");
for(i = 0;i < total;i++)
{
printf("%d ",res[i]);
fprintf(f,"%d ",res[i]);
}
fprintf(f,"\n");
printf("\n");
free(res);
free(count);
free(cname);
fclose(f);
getch();
return(0);
}