題意:
n個座標,要求找一個矩形使得儘量多的座標在矩形的邊界上
分析:
考慮最優的情況,如果n多於4,那麼每條邊必然最少有一個頂點,證明略,如果枚舉每條邊界所穿過的頂點,時間複雜度O(N^5),不用說TLE,如果換個角度想,如果只要枚舉y座標的上下界,然後使用統計當前上下界情況下的最大滿足情況的話,難點就是統計
記l[i] :表示第i列之前的存在於邊界上的頂點的個數(不包括第i列的)
記on1[i] :表示第i列不在邊界上的縱座標上的頂點
記on2[i] :表示所有在第i列上的縱座標的頂點
如:
idx: 1 2 3 4 5
1 * * * ----------> min_y
2 * *
3 * ----------> max_y
idx: 1 2 3 4 5
l: 0 1 1 2 2
on1: 0 1 0 1 0
on2: 1 1 1 1 2
那麼其中的一個情況的矩陣包含的頂點數 = l[j]+on2[j]+on1[i]-l[i]
目標使得on1[i]-l[i]儘量的大,這裏是基於DP思想
Code:
#include <set>
#include <map>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <cstdio>
#include <bitset>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
#define DIR 4
#define DIM 2
#define STATUS 2
#define MAXN 100 + 10
#define MAXM 100000 + 10
#define oo (~0u)>>1
#define INF 0x3F3F3F3F
#define REPI(i, s, e) for(int i = s; i <= e; i ++)
#define REPD(i, e, s) for(int i = e; i >= s; i --)
static const double EPS = 1e-5;
typedef struct POINT {
int x, y;
}Point;
Point p[MAXN];
int y[MAXN];
int on1[MAXN];
int on2[MAXN];
int l[MAXN];
inline int cmp(const Point &a, const Point &b)
{
return a.x < b.x;
}
int cal(int n)
{
int ans = 0;
sort(y+1, y+1+n);
sort(p+1, p+1+n, cmp);
int m = unique(y+1, y+1+n)-y;
if( m-1 <= 2 ) { //only two row
return n;
}
REPI(i, 1, m-1) {
REPI(j, i+1, m-1) {
int col = 0;
int y_min = y[i];
int y_max = y[j];
on1[col] = on2[col] = l[col] = 0;
REPI(k, 1, n) {
if( 1 == k || p[k].x != p[k-1].x ) {
col += 1;
on1[col] = on2[col] = 0;
l[col] = l[col-1]+on2[col-1]-on1[col-1];
}
if( p[k].y > y_min && p[k].y < y_max ) {
on1[col] += 1;
}
if( p[k].y >= y_min && p[k].y <= y_max ) {
on2[col] += 1;
}
}
if( col <= 2 ) { //only two col
return n;
}
//cal delta = l[j]+on2[j]-l[i]+on1[i];
int pre = 0;
REPI(k, 1, col) {
ans = max(ans, l[k]+on2[k]+pre);
pre = max(pre, on1[k]-l[k]);
}
}
}
return ans;
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int n, cnt(1);
while( ~scanf("%d", &n) ) {
if( !n ) {
break;
}
REPI(i, 1, n) {
scanf("%d %d", &p[i].x, &p[i].y);
y[i] = p[i].y;
}
printf("Case %d: %d\n", cnt ++, cal(n));
}
return 0;
}