Разбить камни на две кучи так, чтобы вес одной кучи не превышал веса другой более критической массы - C (СИ)

Узнай цену своей работы

Формулировка задачи:

Здраствуйте,уважаемые програмисты!Проблемы с задачкой Условие:Есть куча камней,каждый камень имеет вес,есть критическая масса.Нужно разбить камни на две кучи так,чтобы вес одной кучи не превышал веса другой более критической массы. Кроме stdio.h библиотек не потребуется,массив из кол-ва камней задаётся через дефайн(чтоб не влезать в динамическую память).Собственно проблема возникает уже в считывании массива и я уже в течении недели сижу на этом и даже не дохожу до реализации алгоритма.... (об алгоритме : я думаю,что самый лучший способ - после сортировки массива масс камней,задать обе кучи двумя переменными и прибавлять наибольщий камень к меньшей кучи,начиная с первой.Больший элемент в большую кучу,следующий больший элемент в меньшую вторую кучу.Если кучи равны,то складываем камень с первой кучей) Сегодня сдавать мыслей нет..Решите пожалуйста....Заранее спасибо Начало:
#include<stdio.h>
#define stone_num 3
int main()
{
    double weight[stone_num];
    double crit_mass;
    printf("input crit. mass: ");
    scanf("%lf", &crit_mass);
    while(crit_mass<0)
    {
        printf("Incorrect!Input crit. mass again please: ");
        scanf("%lf", &crit_mass);
    }
    int i;
     for ( i=1; i<stone_num+1; i++ ) 
    {   
            
        printf("Input weight of %d stone: ",i);
        scanf("%lf",&weight[i]);     
        for( i=1; i<stone_num+1; i++)
        {
            printf("weight of %d stone: ",i,weight[i]);
        }
        if( weight[i]<=0 )
        {
             printf("Incorrect!Please input weight again\n");
             scanf("%lf",&weight[i]);
        }
    }
    for( i=0; i<stone_num; i++ )   
    {
        printf("weight of %d stone",i,weight[i]);
    }
    getchar();
    return 0;
}
попытался сделать ещё раз.. ошибка в неуказанной строчке: in function void Bublesort ошибка в 28 строчке помечена *(обе ошибки в одной строчке) ошибка в самом конце Что же не так?
#include <stdio.h>
#define N 10   
void create_weight(int stones[]) 
{
        printf("N stones in heap. They weight:\n");
        for(int i=0;i<N;i++)
        {
             printf(": ",(i+1));
             scanf("%d",&stones[i]);
        }
}
void BubleSort(int stones[]) 
{
int i,j,tmp;
for(i=0;i<N-1;i++)
{        
         for(j=i+1;j<N;j++)
         {
                if(stones[i]<stones[j])
                {       
                        tmp=stones[i];
                        stones[i]=stones[j];
                        stones[j]=tmp;  
                }
         }     
}
void arrange_heaps(int stones[])  *a function-definition is not allowed here before '{' token 
{                                               expected ',' or ';' before '{' token
int sum1=0, sum2=0;
int heap1[N-1],heap2[N-1];             
int a=0, b=0;
int i;
for(i=0;i<N;i++)
{
        if(sum1<=sum2)
        {       heap1[a]=stones[i];
                sum1+=stones[i];
                a++;
        }
        else
        {       
                heap2[b]=stones[i];
                sum2+=stones[i];
                b++;
        }
}
double crit_mass;
    printf("Input crit. mass: ");
    scanf("%lf", &crit_mass);
    while(crit_mass<0)
    {
        printf("Incorrect!Please input crit. mass again: ");
        scanf("%lf", &crit_mass);
    }
if(sum1>=sum2) 
        if(sum1-sum2 <=crit_mass)
        {
             printf("\nheap 1: ");
             for(i=0;i<a;i++)
             {
                 printf("%d",heap1[i]);
                 printf("\nweight 1: ",sum1);
             }    
             printf("\nheap 2: ");
             for(i=0;i<b;i++)
             {    
                 printf("%d",heap2[i]);
                 printf("\nweight 2: ",sum2);
             }
}
else 
{
     printf("heap mass on a lot more different than crit. mass\n");
}
int main()
{
        int weight[N];
        create_weight(weight);
        BubleSort(weight);
        arrange_heaps(weight);
        getchar();
        return 0;
}                                       *expected '}' at end of input
Почему то не работает - мыслей нет
#include <stdio.h>
#define N 10   
void create_weight(int stones[]) ///ñîçäГ*Г*ГЁГҐ Г¬Г*Г±Г±ГЁГўГ* âåñîâ ГЄГ*Г¬Г*ГҐГ©
{
     printf("N stones in heap. They weight:\n");
     for(int i=0;i<N;i++)
     {
          printf("weight of %d stone: ",i+1);
          scanf("%d",&stones[i]);
     }
}
void BubleSort(int stones[]) ///ïóçûðüêîâГ*Гї ñîðòèðîâêГ* ГЇГ® óáûâГ*Г*ГЁГѕ
{
     int i,j,tmp;
     for(i=0;i<N-1;i++)
     {        
          for(j=i+1;j<N;j++)
          {
                if(stones[i]<stones[j])
                {       
                        tmp=stones[i];
                        stones[i]=stones[j];
                        stones[j]=tmp;  
                }
          }     
     }
}     
void arrange_heaps(int stones[]) ///ñîçäГ*Г*ГЁГҐ äâóõ ГЄГіГ· ГЁ Г°Г*ñïðåäåëåГ*ГЁГҐ ГЄГ*Г¬Г*ГҐГ©
{
     int sum1=0, sum2=0;
     int heap1[N-1],heap2[N-1];
     int a=0, b=0;
     int i;
     for(i=0;i<N;i++)
     {
          if(sum1<=sum2)
          {       heap1[a]=stones[i];
                  sum1+=stones[i];
                  a++;
          }
          else
          {       
                  heap2[b]=stones[i];
                  sum2+=stones[i];
                  b++;
          } 
     }
     double crit_mass;
     printf("Input crit. mass: ");
     scanf("%lf", &crit_mass);
     while(crit_mass<0)
     {
         printf("Incorrect!Please input crit. mass again: ");
         scanf("%lf", &crit_mass);
     }
     if(sum1>=sum2)
     { 
         if(sum1-sum2 <=crit_mass)
         {
              printf("\nheap 1: ");
              for(i=0;i<a;i++)
              {
                   printf("%d",heap1[i]);
                   printf("\nweight 1: ",sum1);
              }    
              printf("\nheap 2: ");
              for(i=0;i<b;i++)
              {    
                  printf("%d",heap2[i]);
                  printf("\nweight 2: ",sum2);
              }
         }
     }
     else 
     {
         printf("heap mass on a lot more different than crit. mass\n");
     }
}     
int main()
{
        int weight[N];
        create_weight(weight);
        BubleSort(weight);
        arrange_heaps(weight);
        return 0;
}
Почему то не работает - мыслей нет
#include <stdio.h>
#define N 10   
void create_weight(int stones[]) ///ñîçäГ*Г*ГЁГҐ Г¬Г*Г±Г±ГЁГўГ* âåñîâ ГЄГ*Г¬Г*ГҐГ©
{
     printf("N stones in heap. They weight:\n");
     for(int i=0;i<N;i++)
     {
          printf("weight of %d stone: ",i+1);
          scanf("%d",&stones[i]);
     }
}
void BubleSort(int stones[]) ///ïóçûðüêîâГ*Гї ñîðòèðîâêГ* ГЇГ® óáûâГ*Г*ГЁГѕ
{
     int i,j,tmp;
     for(i=0;i<N-1;i++)
     {        
          for(j=i+1;j<N;j++)
          {
                if(stones[i]<stones[j])
                {       
                        tmp=stones[i];
                        stones[i]=stones[j];
                        stones[j]=tmp;  
                }
          }     
     }
}     
void arrange_heaps(int stones[]) ///ñîçäГ*Г*ГЁГҐ äâóõ ГЄГіГ· ГЁ Г°Г*ñïðåäåëåГ*ГЁГҐ ГЄГ*Г¬Г*ГҐГ©
{
     int sum1=0, sum2=0;
     int heap1[N-1],heap2[N-1];
     int a=0, b=0;
     int i;
     for(i=0;i<N;i++)
     {
          if(sum1<=sum2)
          {       heap1[a]=stones[i];
                  sum1+=stones[i];
                  a++;
          }
          else
          {       
                  heap2[b]=stones[i];
                  sum2+=stones[i];
                  b++;
          } 
     }
     double crit_mass;
     printf("Input crit. mass: ");
     scanf("%lf", &crit_mass);
     while(crit_mass<0)
     {
         printf("Incorrect!Please input crit. mass again: ");
         scanf("%lf", &crit_mass);
     }
     if(sum1>=sum2)
     { 
         if(sum1-sum2 <=crit_mass)
         {
              printf("\nheap 1: ");
              for(i=0;i<a;i++)
              {
                   printf("%d",heap1[i]);
                   printf("\nweight 1: ",sum1);
              }    
              printf("\nheap 2: ");
              for(i=0;i<b;i++)
              {    
                  printf("%d",heap2[i]);
                  printf("\nweight 2: ",sum2);
              }
         }
     }
     else 
     {
         printf("heap mass on a lot more different than crit. mass\n");
     }
}     
int main()
{
        int weight[N];
        create_weight(weight);
        BubleSort(weight);
        arrange_heaps(weight);
        return 0;
}
я думаю тут нужно в конце что-то вроде cin.sync(); cin.get(); только это в с++ с этими потоками,а тут нужно что-то другое...Или всё таки есть проблема в самом алгоритме

Решение задачи: «Разбить камни на две кучи так, чтобы вес одной кучи не превышал веса другой более критической массы»

textual
Листинг программы
double val = 0;
scanf("%lf",&val);

Объяснение кода листинга программы

  1. В начале кода объявлена переменная val типа double и инициализирована значением 0.
  2. Затем происходит чтение значения переменной val с помощью функции scanf().
  3. Ввод значения происходит с клавиатуры, и оно сохраняется в переменной val.
  4. После этого программа продолжает выполняться, и следующим действием будет разбивка камней на две кучи.
  5. Однако, поскольку в коде только объявлена переменная val, но не выполнено никаких действий с ней, то невозможно определить, какая именно задача решается в этом коде.

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 3.6 из 5
Похожие ответы