Pick-up sticks POJ - 2653
TLE代码
直接暴力搜索太慢了,1e5的数据量过不去。
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int const N = 1e5 + 10;
double const eps = 1e-8;
int sgn(double x) {
if (fabs(x) < eps) return 0;
if (x < 0) return -1;
else return 1;
}
struct P {
double x, y;
P() {}
P(double _x, double _y) : x(_x), y(_y) {}
P operator-(const P &b) const {
return P{x - b.x, y - b.y};
}
double operator^(const P &b) const {
return x * b.y - b.x * y;
}
};
struct L {
P s, e;
L() {}
L(P _s, P _e) : s(_s), e(_e) {}
bool operator&(const L &b) const {
return
max(s.x, e.x) >= min(b.s.x, b.e.x) &&
max(b.s.x, b.e.x) >= min(s.x, e.x) &&
max(s.y, e.y) >= min(b.s.y, b.e.y) &&
max(b.s.y, b.e.y) >= min(s.y, e.y) &&
(sgn((b.s - e) ^ (s - e)) * sgn((b.e - e) ^ (s - e)) <= 0) &&
(sgn((s - b.e) ^ (b.s - b.e)) * sgn((e - b.e) ^ (b.s - b.e)) <= 0);
}
} line[N];
bool vis[N];
int n;
int main() {
while (scanf("%d", &n) && n) {
for (int i = 0; i < n; i++) {
scanf("%lf%lf%lf%lf", &line[i].s.x, &line[i].s.y, &line[i].e.x, &line[i].e.y);
vis[i] = false;
for (int j = 0; j < i; j++) {
vis[j] = line[i] & line[j];
}
}
printf("Top sticks: ");
bool flag = true;
for (int i = 0; i < n; i++) {
if (!vis[i]) {
if (flag) {
printf("%d", i + 1);
flag = false;
} else printf(", %d", i + 1);
}
}
printf(".\n");
}
return 0;
}
AC代码
改成用set就好了。
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;
int const N = 1e5 + 10;
double const eps = 1e-8;
int sgn(double x) {
if (fabs(x) < eps) return 0;
if (x < 0) return -1;
else return 1;
}
struct P {
double x, y;
P() {}
P(double _x, double _y) : x(_x), y(_y) {}
P operator-(const P &b) const {
return P{x - b.x, y - b.y};
}
double operator^(const P &b) const {
return x * b.y - b.x * y;
}
};
struct L {
P s, e;
L() {}
L(P _s, P _e) : s(_s), e(_e) {}
bool operator&(const L &b) const {
return
max(s.x, e.x) >= min(b.s.x, b.e.x) &&
max(b.s.x, b.e.x) >= min(s.x, e.x) &&
max(s.y, e.y) >= min(b.s.y, b.e.y) &&
max(b.s.y, b.e.y) >= min(s.y, e.y) &&
(sgn((b.s - e) ^ (s - e)) * sgn((b.e - e) ^ (s - e)) <= 0) &&
(sgn((s - b.e) ^ (b.s - b.e)) * sgn((e - b.e) ^ (b.s - b.e)) <= 0);
}
} line[N];
int n;
int main() {
while (scanf("%d", &n) && n) {
set<int> st;
for (int i = 0; i < n; i++) {
scanf("%lf%lf%lf%lf", &line[i].s.x, &line[i].s.y, &line[i].e.x, &line[i].e.y);
vector<int> ans;
for (set<int>::iterator it = st.begin(); it != st.end(); it++) {
if (line[*it] & line[i]) ans.push_back(*it);
}
for (vector<int>::iterator it = ans.begin(); it != ans.end(); it++) {
st.erase(*it);
}
st.insert(i);
}
printf("Top sticks: ");
bool flag = true;
for (set<int>::iterator it = st.begin(); it != st.end(); it++) {
if (flag) {
printf("%d", (*it) + 1);
flag = false;
} else printf(", %d", (*it) + 1);
}
printf(".\n");
}
return 0;
}