ACM Q476 動態結構 malloc

By
Advertisement
題目詳見:http://luckycat.kshs.kh.edu.tw/homework/q476.htm

基本上單獨僅探討判斷"點"是在哪個"圖"裡面是非常容易的
但是這題會因不同的做法而有難度上的差異(對我而言啦)

其一
如果是將input寫好放在檔案裏面, 再用fpopen的方式讀檔案
只需要判斷字串為何再採取對應的動作即可

其二
直接讓user當下一行一行的input
這種方法好像比較直覺, 但是用C寫起來一點都不直覺
難點在於常用的scanf很難判別使用者輸入不同規則的值...
不過經過滴滴的指引, 透過這篇文章真的是收穫滿滿:
https://www.ptt.cc/man/C_and_CPP/DB9B/DD06/M.1280560435.A.F4A.html
太神辣

其三
當然也可以使用conio.h裡的getche()或getch()來達到判別使用者輸入
不過在Linux裡面並沒有這個函示庫..


本篇的方法著重於動態結構的方法
圖形的structure因為題目有規定最大size,因此宣告長度使用陣列結構的方式即可
點的structure因為沒有限制筆數,所以使用動態陣列


#include <stdio.h>
#include <stdlib.h>

#define size    10
int Q476();

struct shape {
        char    form[1];
        float   x1;
        float   y1;
        float   x2;
        float   y2;
};

struct point {
        float   x;
        float   y;
        struct  point *Next;
};

int Q476()
{
        int             i, j;
        int             scount=0, pcount=0;
        struct shape    shape[size];
        struct point    nolistpoint, *point, *tmppoint;
        char            c1[21+1];

        for ( i=0; i<size; i++ ) {
                gets(c1);
                if ( c1[0] == '*' )     break;
                else if ( c1[0] == 'r' ) {
                        sscanf(c1, "%s%f%f%f%f", &shape[i].form, &shape[i].x1, &shape[i].y1, &shape[i].x2, &shape[i].y2);
                        scount++;
                }
                else    return 0;
        }
        if ( i == 10 ) printf("*\n");
        point = &nolistpoint;
        while ( 0 == 0 ) {
                gets(c1);
                if ( !strcmp(c1, "9999.9 9999.9") ) {
                        break;
                }
                point->Next=malloc(sizeof(struct point));
                point=point->Next;
                sscanf(c1, "%f%f", &point->x, &point->y);
                pcount++;
        }

        int check;
        point = &nolistpoint;
        for ( i=0; i<pcount; i++ ) {
                tmppoint = point;
                free(tmppoint);
                point = point->Next;
                check = 0;
                for ( j=0; j<scount; j++ ) {
                        if ( shape[j].x1 < point->x && point->x < shape[j].x2
                          && shape[j].y2 < point->y && point->y < shape[j].y1 ){
                                printf("Point %d is contained in figure %d\n", i+1, j+1);
                                check = 1;
                        }
                }
                if ( check == 0 )       printf("Point %d is not contained in any figure\n", i+1);
        }
}

0 意見:

張貼留言

技術提供:Blogger.

Latest Photos

Join the Team

Blogger news

Popular Posts