IGT笔试题,正整数N等于M个不同的正整数之和的问题

//

//  

//

//  Created by labuser on 10/29/11.

//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.

//

 

#include <stdio.h>

#include "time.h"

//#include <sys/time.h>

 

#define times 7

#define scores 40

#define maxnum 20

 

void cout(int*, int );

void compute(int, int, int*, int);

 

int main (int argc, char* argv[])

{

    int score[times] = {0};

    //struct timeval tv;

    //struct timezone tz;

    //gettimeofday(&tv, &tz);

    //int start, end;

    //start = tv.tv_usec;

    //time_t start,end;

    clock_t start, finish;

    double  duration;

    start = clock();

    //start = time(NULL);

    compute(scores, times - 1, score, times);

    finish = clock();

    duration = (double)(finish - start) / CLOCKS_PER_SEC;

    printf("%f seconds\n", duration);

    //end = time(NULL);

    //gettimeofday(&tv, &tz);

    //end = tv.tv_usec;

    //printf("Spend time: %d microseconds\n", end - start);

    //printf("Spend time: %f seconds\n", difftime(end,start));

    return 0;

}

 

void cout(int* result, int n) {

    int i;

    for (i = n; i > 0; i--) {

        printf("  %d", result[i-1]);

    }

    printf("\n");

}

 

void compute(int score, int num, int* answer, int m)

{

    if (score < 0 || score > (num+1)*10) {

        return;

    }

    if (num == 0) {

        *(answer + num) = score;

        int n = times - 2;

        while (n >= 0 && *(answer + n) > *(answer + n + 1)) {

            --n;

        } 

        if (n == -1){

            cout(answer, m);

            return;

        }

    }

    int i = answer[times] = 1;

    for(i = answer[num+1]; i <= maxnum; ++i) {

        answer[num] = i;

        compute(score - i, num - 1, answer, m);

    }

}

你可能感兴趣的:(笔试题)