Ejemplo n.º 1
0
    void tryput(int i, int bthis, int rstart, int wasted) {
        if (i > maxput) maxput = i;
        if (maxput == optimal) return;
        if (wasted > bwasted[maxput + 1]) return;

        int rlast = 0;
        bool tried = false;
        for (int j = rstart; j < r; j++) {
            if (railused[j]) continue; // already used
            int rlen = rail[j];
            if (rlen == rlast) continue; // same length only try once
            rlast = rlen;

            if (rlen > b[bthis] - bused[bthis]) continue; // space left not enough
            if (bthis > 0 && rlen + bused[bthis] > b[bthis - 1]) continue;

            railused[j] = true;
            bused[bthis] += rlen;
            tryput(i + 1, bthis, j + 1, wasted);
            tried = true;
            bused[bthis] -= rlen;
            railused[j] = false;
        }

        if (!tried) {
            if (bthis + 1 < n) {
                tryput(i, bthis + 1, 0, wasted + b[bthis] - bused[bthis]);
            } 
        } 
    }
Ejemplo n.º 2
0
//a数组存放已得到的序列,usd[k] 表示值是否被使用 
int main()
{
	int k,m;
	while(1)
	{
		for(k=1;k<=20;k++) 
		{//初始化
			a[k]=0;
			used[k]=0;
		}
		scanf("%d",&m);
		if(m == 0)//输入 0 结束 
		   break;
        a[1]=m;
        used[m]=1;//第一个数为m,且标记被使用 
        tryput(2);
        for(k=1;k<=20;k++)
           printf("%d ",a[k]);
        printf("\n");
	} 
} 
Ejemplo n.º 3
0
    void writeOut() {
        qsort(b, n, sizeof(int), icmpn);
        qsort(rail, r, sizeof(int), icmp);
    
        int bsum = 0;
        for (int i = 0; i < n; i++) {
            bleft[i] = b[i];
            bused[i] = 0;
            bsum += b[i];
        }

        bwasted[0] = bsum;

        optimal = 0;
        for (int i = 0; i < r; i++) {
            if (bsum >= rail[i]) {
                bsum -= rail[i];
                optimal++;
                bwasted[optimal] = bsum;
            } else {
                break;
            }
        }
        r = optimal;

        qsort(rail, r, sizeof(int), icmpn);

        for (int i = 0; i < r; i++) {
            railused[i] = false;
        }
    
        maxput = 0;
        
        tryput(0, 0, 0, 0);

        
        fout = fopen("fence8.out", "w"); assert(fout);
        fprintf(fout, "%d\n", maxput);
        fclose(fout);
    }
Ejemplo n.º 4
0
int tryput(int i)//搜索第i项的数 
{
	int j;
	for(j=1;j<=20;j++)//1~20项中查找 
	{
		if(used[j])//如果被使用,查找下一个 
		  continue;
        if(sumisprime(j,i))//是否满足条件 
        {
        	a[i]=j;
        	used[j]=1;//若满足,则保留此数并标记 
        	if(i==20)
        	  return 1;//20项查找完,正确返回 
      	    if(tryput(i+1) != 1)//若第i+1项查找不成功,回溯 
      	    {
    	      	a[i]=0;
    	      	used[j]=0;
  	        }
  	        else
  	          return 1;//若成功,则返回1 
        }
	}
	return 0;
}