#include <stdio.h>
#include <string.h>
/************************************************************************/
/* the number of the value in each line */
/************************************************************************/
#define VALUENUM 6
#define MAXNUM 20000
#define MAXVALUE VALUENUM*MAXNUM
/************************************************************************/
/* This function is to printf as the determine result */
/************************************************************************/
int ResultPrint(int lineindex, int detres)
{
printf("Collection #%d:\n",lineindex);
if (detres == 1)
{
printf("Can be divided.\n\n");
}
else
printf("Can't be divided.\n\n");
return 1;
}
/************************************************************************/
/* this function is to determine whether the line can be divided */
/************************************************************************/
int DetermineLine(int Value[VALUENUM], int ValueSum)
{
int flag[MAXVALUE];//this flag array is to record the flag during the process
int maxdiv = 0;
int SerDiv = 0;//the middle value of the summation of the value
int i=0,j=0,k=0;
SerDiv = ValueSum/2;
memset(flag,0,sizeof(flag));
flag[0] = 1;
//这里分阶段进行了分析,也就是动态规划。
for (i=0; i<VALUENUM; i++)
{
if (Value[i])
{
for (j=maxdiv; j>=0; j--)
{
if (flag[j])
{
for (k=1; k <= Value[i]; k++)
{
maxdiv += (i+1)*k;
if (maxdiv == SerDiv)
{
return 1;
}
else if (maxdiv > SerDiv)
{
maxdiv = SerDiv;
}
else
{
flag[maxdiv] = 1;
}
}
}
}
}
}
return -1;
}
/************************************************************************/
/* this function is to get the input data */
/************************************************************************/
int ReadInputFile()
{
FILE *fp;
int lineindex = 0; //this is the index of the line
int value[VALUENUM];//this is the array to record the number of the six kinds of marbles with different value from 1 to 6
int valuesum = 10;//this variable is to present the summation of the value in each line
int detres = 0;
int i = 0;
//char ch;
fp = fopen("test.txt","r");
if (fp == NULL)
{
printf("Open the input file failed! \n");
return -1;
}
while (valuesum)
{
lineindex++;
valuesum = 0;
for (i=0; i<VALUENUM; i++)
{
scanf("%d",value+i);
valuesum += (value[i] * (i+1));
}
if (valuesum == 0)
{
//printf("this is the last line of the file!\n");
return -1;
}
else if(valuesum%2)
{
ResultPrint(lineindex,-1);
}
else
{
detres = DetermineLine(value,valuesum);
ResultPrint(lineindex,detres);
}
}
return 1;
}
void main()
{
ReadInputFile();
}
今天写的程序,提交报结果错误,不知道是什么问题,我已经验证了一些数据都是对的啊。
里面的动态规划思想还是蛮好的。