zoukankan      html  css  js  c++  java
  • 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);

        }

    }

  • 相关阅读:
    C++互斥器:Semaphores
    C++互斥器:Mutex
    内联函数(inline)
    C++显式转换
    线程同步控制
    拷贝构造函数——防篡改
    extern关键字
    虚析构、纯虚析构
    类的友元关系
    char 与 unsigned char的本质区别
  • 原文地址:https://www.cnblogs.com/shenfei2031/p/2228857.html
Copyright © 2011-2022 走看看