Sunday, October 6, 2013

Horizontal/Vertical Line Crossings

Archeologists have discovered a very ancient cave, with many pictures on its wall. Each of the picture contains only vertical and horizontal line segments. Experts have analysed these pictures and came to the conclusion that, these are hieroglyphs (like Egyptian writings). To extract the meaning from these glyphs, it is necessary to find out how many of these vertical and horizontal line segments intersect.

Each picture glyph is inscribed in a square of side 100, and each end point of the line segment is assigned an X-Y coordinate pair. All the X and Y values are integers in the range 0 to 100. The vertical line segment is described by an X value and two Y values (X, Y1, Y2). Similarly, a horizontal line segment is described by a Y value and a pair of X values (Y, X1, X2). For example, a horizontal line segment described by a triplet (12, 8, 57) is a segment joining points (8, 12) and (57, 12).

You have to write a program to compute the total number of intersections, given the details of vertical and horizontal line segments. Only the intersections between a pair of horizontal and vertical line segments are counted. Even if one segment is touching another, it is counted as an intersection. (See figure below)


Input Specification:

• The first line has two integers, V and H. V denotes the number of vertical line
   segments and H denotes the number of horizontal line segments in the picture.
• The next V lines describe V vertical line segments each as a triplet of integers (X, Y1, Y2).
• The next H lines describe H horizontal line segments each as a triplet of integers (Y, X1, X2).

Output Specification:

The total number of intersections in the given picture.
Sample Input and Output:
Input:
11
50 20 60
30 40 80
Output:
1
Input:
22
25 25 80
75 25 80
25 25 80
75 25 80
Output:
4
Input:
12
50 0 100
50 0 75
50 25 100
Output:
2

Solution:

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

int main()
{
    int hor[100][3],var[100][3],intrs=0;
    int v,h;
    int i,j;

    scanf("%d %d",&v,&h);
    //Reading vertical
    for(i=0;i<v;i++)
    {
        for(j=0;j<3;j++)
        {
            scanf("%d",&var[i][j]);
        }
    }    

    //Reading hotizontal
    for(i=0;i<h;i++)
    {
        for(j=0;j<3;j++)
        {
            scanf("%d",&hor[i][j]);
        }
    }

   //Comparing horizontal lines vith vertical
    for(i=0;i<h;i++)
    {
        for(j=0;j<v;j++)
        {
            if( (hor[i][1] <= var[j][0]) && (var[j][0] <= hor[i][2]) && (var[j][1] <= hor[i][0]) && (hor[i][0] <= var[j][2]) )
            intrs++;
        }
    }

    printf("%d\n",intrs);
    
    return 0;
}

No comments:

Post a Comment