E - Connected?
Time limit : 2sec / Memory limit : 256MB
Score : 700 points
Problem Statement
Snuke is playing a puzzle game. In this game, you are given a rectangular board of dimensions R×C, filled with numbers. Each integer i from 1 through N is written twice, at the coordinates (xi,1,yi,1) and (xi,2,yi,2).
The objective is to draw a curve connecting the pair of points where the same integer is written, for every integer from 1 through N. Here, the curves may not go outside the board or cross each other.
Determine whether this is possible.
Constraints
- 1≤R,C≤108
- 1≤N≤105
- 0≤xi,1,xi,2≤R(1≤i≤N)
- 0≤yi,1,yi,2≤C(1≤i≤N)
- All given points are distinct.
- All input values are integers.
Input
Input is given from Standard Input in the following format:
R C N x1,1 y1,1 x1,2 y1,2 : xN,1 yN,1 xN,2 yN,2
Output
Print YES
if the objective is achievable; print NO
otherwise.
Sample Input 1
4 2 3 0 1 3 1 1 1 4 1 2 0 2 2
Sample Output 1
YES
The above figure shows a possible solution.
Sample Input 2
2 2 4 0 0 2 2 2 0 0 1 0 2 1 2 1 1 2 1
Sample Output 2
NO
Sample Input 3
5 5 7 0 0 2 4 2 3 4 5 3 5 5 2 5 5 5 4 0 3 5 1 2 2 4 4 0 5 4 1
Sample Output 3
YES
Sample Input 4
1 1 2 0 0 1 1 1 0 0 1
Sample Output 4
NO
思路:显然某个点两边都在矩阵边缘上才要考虑,那么将这类点找出来,按矩阵边缘顺时针排序,然后遍历,和栈顶数字相同就出栈,没出现过的就压进栈,最后判断栈是否为空即可,栈不空说明有线相交了。
# include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+3;
int row, col, n, que[maxn<<1];
pair<int, int> arr[maxn<<1];
bool check(int a, int b)
{
if(a==0 || a==row || b==0 || b==col) return true;
return false;
}
int cal(int a, int b)
{
if(a==0) return b;
else if(b==col) return col + a;
else if(a==row) return col + row + col - b;
else return col + col + row + row - a;
}
int main()
{
int a, b, c, d, cnt = 0, icount = 0;
scanf("%d%d%d",&row,&col,&n);
{
while(n--)
{
scanf("%d%d%d%d",&a,&b,&c,&d);
if(check(a, b) && check(c, d))
{
arr[cnt++] = make_pair(cal(a, b), icount);
arr[cnt++] = make_pair(cal(c, d), icount++);
}
}
sort(arr, arr+cnt);
int r=0;
for(int i=0; i<cnt; ++i)
{
if(!r)
que[++r] = arr[i].second;
else if(arr[i].second == que[r])
--r;
else
que[++r] = arr[i].second;
}
if(!r) puts("YES");
else puts("NO");
}
return 0;
}