text stringlengths 49 983k |
|---|
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
using namespace std;
#define REP(i,n) for(int i = 0; i < (int)n; i++)
#define FOR(i,a,b) for(int i = a; i < (int)b; i++)
#define pb push_back
#define mp make_pair
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> pi;
typedef long long ll;
typedef unsigned long long ull;
const int IINF = 1<<28;
const ll MOD = 1000000007;
const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
struct P {
vvi v;
int cnt;
vector<pi> space;
};
bool done(vvi a) {
REP(i, 4) {
REP(j, 7) {
if(a[i][j] != (i+1)*10 + j+1)
return false;
}
}
return true;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n; cin >> n;
REP(_, n) {
set <vvi> s;
queue<P> q;
P p;
p.v.resize(4);
REP(i, 4) {
p.v[i].resize(8);
FOR(j, 1, 8) {
cin >> p.v[i][j];
if(p.v[i][j] % 10 == 1) {
p.v[i][j] = 0;
p.space.pb(pi(i, j));
}
}
}
p.v[0][0] = 11;
p.v[1][0] = 21;
p.v[2][0] = 31;
p.v[3][0] = 41;
p.cnt = 0;
q.push(p);
bool flg = false;
while(q.size()) {
p = q.front(); q.pop();
if(done(p.v)) {
flg = true;
break;
}
REP(i, 4) {
P p2(p);
int num = p2.v[p.space[i].first][p.space[i].second-1]+1;
if(num % 10 == 8)
continue;
REP(j, 4) REP(k, 8) {
if(p2.v[j][k] == num) {
p2.v[p2.space[i].first][p2.space[i].second] = num;
p2.v[j][k] = 0;
p2.space[i] = pi(j, k);
if(!s.count(p2.v)) {
p2.cnt++;
q.push(p2);
s.insert(p2.v);
}
break;
}
}
/*
REP(j, 4) {
REP(k, 8)
cout << p2.v[j][k] << ' ';
cout << endl;
}
*/
}
}
cout << (flg ? p.cnt : -1) << endl;
}
return 0;
} |
#include <iostream>
#include <vector>
#include <queue>
#include <set>
#include <cstring>
using namespace std;
class State{
public:
int t[32], pos[50];
int cost;
State(int _t[32], int _pos[50], int _cost){
for(int i = 0; i < 32; i++){
t[i] = _t[i];
}
for(int i = 0; i < 50; i++){
pos[i] = _pos[i];
}
cost = _cost;
}
};
int t2[32];
int pos2[50];
void copy(int t[32], int pos[50]){
for(int i = 0; i < 32; i++){
t2[i] = t[i];
}
for(int i = 0; i < 50; i++){
pos2[i] = pos[i];
}
}
bool finish(int t[32]){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 7; j++){
int val = 10 * (i + 1) + j + 1;
int idx = i * 8 + j;
if(t[idx] != val){
return false;
}
}
}
return true;
}
void solve(const State &start){
queue<State> open;
set<vector<int> > closed;
open.push(start);
while(!open.empty()){
State st = open.front();
open.pop();
vector<int> v(st.t, st.t + 32);
if(closed.find(v) != closed.end()) continue;
closed.insert(v);
if(finish(st.t)){
cout << st.cost << endl;
return;
}
for(int i = 0; i < 32; i++){
if(st.t[i] == 0){
if(st.t[i - 1] == 0) continue;
int val = st.t[i - 1] + 1;
if(st.pos[val] == 0) continue;
copy(st.t, st.pos);
t2[i] = val;
t2[st.pos[val]] = 0;
pos2[val] = i;
open.push(State(t2, pos2, st.cost + 1));
}
}
}
cout << "-1\n";
}
int main(){
int T;
cin >> T;
while(T--){
int t[32];
int pos[50];
memset(t, 0, sizeof(t));
memset(pos, 0, sizeof(pos));
for(int i = 0; i < 4; i++){
for(int j = 1; j < 8; j++){
int idx = i * 8 + j;
cin >> t[idx];
pos[t[idx]] = idx;
}
}
for(int i = 0; i < 4; i++){
int val = 11 + i * 10;
t[i * 8] = val;
t[pos[val]] = 0;
pos[val] = i * 8;
}
solve(State(t, pos, 0));
}
} |
#include<stdio.h>
#include<algorithm>
#include<queue>
#include<set>
using namespace std;
struct wolf{
int c[4][8];
};
int c[10][10];
inline bool operator<(const wolf &a,const wolf &b){
for(int i=0;i<4;i++)for(int j=0;j<8;j++)if(a.c[i][j]!=b.c[i][j])return a.c[i][j]<b.c[i][j];
return false;
}
int main(){
int a;scanf("%d",&a);
while(a--){
for(int i=0;i<4;i++)for(int j=0;j<7;j++){
scanf("%d",&c[i][j+1]);
}
for(int i=0;i<4;i++)c[i][0]=11+i*10;
for(int i=0;i<4;i++)for(int j=1;j<8;j++)if(c[i][j]%10==1)c[i][j]=0;
queue<pair<wolf,int> > Q;
wolf s;
for(int i=0;i<4;i++)for(int j=0;j<8;j++)s.c[i][j]=c[i][j];
Q.push(make_pair(s,0));
set<wolf>S;
S.insert(s);
bool yet=true;
while(Q.size()){
wolf at=Q.front().first;
int cost=Q.front().second;
Q.pop();
bool ok=true;
for(int i=0;i<4;i++)for(int j=0;j<7;j++)if(at.c[i][j]!=11+i*10+j)ok=false;
if(ok){
yet=false;
printf("%d\n",cost);
break;
}
for(int i=0;i<4;i++)for(int j=1;j<8;j++){
if(!at.c[i][j]&&at.c[i][j-1]&&at.c[i][j-1]%10!=7){
int row,col;
for(int k=0;k<4;k++)for(int l=0;l<8;l++)if(at.c[i][j-1]+1==at.c[k][l]){row=k;col=l;}
at.c[row][col]=0;
at.c[i][j]=at.c[i][j-1]+1;
if(!S.count(at)){
S.insert(at);
Q.push(make_pair(at,cost+1));
}
at.c[i][j]=0;
at.c[row][col]=at.c[i][j-1]+1;
}
}
}
if(yet)printf("-1\n");
}
} |
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <utility>
#include <functional>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <climits>
#include <fstream>
using namespace std;
inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v; }
template<class T> inline string toStr(T x) { ostringstream sout; sout << x; return sout.str(); }
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(),(a).rend()
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define REP(i,n) FOR(i,0,(n)-1)
const double EPS = 1e-10;
const double PI = acos(-1.0);
const int INF = INT_MAX / 10;
void show_field(string field) {
REP(i, 4) {
REP(j, 8) {
cout << field[16 * i + 2 * j] << field[16 * i + 2 * j + 1] << " ";
}
cout << endl;
}
}
int main() {
string goal;
REP(i, 4) {
REP(j, 8) {
if (j != 7) {
goal.push_back('1' + i);
goal.push_back('1' + j);
}
else {
goal.push_back('0');
goal.push_back('0');
}
}
}
int n;
cin >> n;
REP(hoge, n) {
vvi field(4, vi(8));
REP(i, 4) {
FOR(j, 1, 7) {
int num;
cin >> num;
if (num % 10 == 1) {
field[num / 10 - 1][0] = num;
}
else {
field[i][j] = num;
}
}
}
string start;
REP(i, 4) {
REP(j, 8) {
if (field[i][j] == 0) {
start.push_back('0');
start.push_back('0');
}
else {
start.push_back('0' + field[i][j] / 10);
start.push_back('0' + field[i][j] % 10);
}
}
}
map<string, int> memo;
queue<string> Q;
Q.push(start);
memo[start] = 0;
bool finished = false;
while (!Q.empty()) {
string s = Q.front();
Q.pop();
if (s == goal) {
finished = true;
break;
}
vi change_pos;
vs change_str;
REP(i, 32) {
if (s[2 * i] == '0') {
if (s[2 * i - 1] != '7') {
string str = s.substr(2 * (i - 1), 2);
str[1]++;
change_pos.push_back(i);
change_str.push_back(str);
}
}
}
int size = change_pos.size();
REP(i, size) {
string str = change_str[i];
REP(j, 32) {
if (s[2 * j] == str[0] && s[2 * j + 1] == str[1]) {
int pos = change_pos[i];
string ns = s;
ns[2 * pos] = str[0];
ns[2 * pos + 1] = str[1];
ns[2 * j] = '0';
ns[2 * j + 1] = '0';
if (memo[ns] == 0) {
memo[ns] = memo[s] + 1;
Q.push(ns);
}
}
}
}
}
if (finished) {
cout << memo[goal] << endl;
}
else {
cout << -1 << endl;
}
}
return 0;
} |
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,k,n) for(int i = (k); i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) a.begin(), a.end()
#define MS(m,v) memset(m,v,sizeof(m))
#define D10 fixed<<setprecision(10)
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;
typedef long double ld;
const int MOD = 1000000007;
const int INF = MOD + 1;
const ld EPS = 1e-10;
template<class T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template<class T> T &chmax(T &a, const T &b) { return a = max(a, b); }
/*--------------------template--------------------*/
int main()
{
int n;
cin >> n;
while (n--)
{
vector<vi> v(4, vi(8));
auto goal = v;
REP(i, 4)REP(j, 7) goal[i][j] = (i+1) * 10 + j + 1;
REP(i, 4)FOR(j, 1, 8)
{
cin >> v[i][j];
if (v[i][j] % 10 == 1)
{
v[v[i][j] / 10 - 1][0] = v[i][j];
v[i][j] = 0;
}
}
queue<pair<vector<vi>, int>> que;
set<vector<vi>> st;
que.push(make_pair(v, 0));
bool f = true;
while (que.size())
{
auto tmp = que.front().first;
int cnt = que.front().second;
que.pop();
if (tmp == goal)
{
f = false;
cout << cnt << endl;
break;
}
REP(i, 4)FOR(j, 1, 8)
{
if (tmp[i][j] == 0 && tmp[i][j - 1] != 0 && tmp[i][j - 1] % 10 != 7)
{
auto nx = tmp;
int t = tmp[i][j - 1] + 1;
REP(ii, 4)REP(jj, 8)
{
if (tmp[ii][jj] == t)
{
nx[ii][jj] = 0;
}
}
nx[i][j] = t;
if (st.count(nx)) continue;
else
{
st.insert(nx);
que.push(make_pair(nx, cnt + 1));
}
}
}
}
if (f) puts("-1");
}
return 0;
} |
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
typedef pair<int,int> pii;
// 各数字の現在の場所
pii numToPlc[101];
// 各場所にある数字
int plcToNum[10][10];
int res;
map<vector<vector<int> >,int > m;
vector<vector<int> > g;
// 引き数で与えられる数字を移動
// 移動できない場合はfalse
bool moveNum(int a){
pii cur=numToPlc[a];
if(a%10==1){
numToPlc[a].first=(a/10)-1;
numToPlc[a].second=0;
plcToNum[(a/10)-1][0]=a;
// 最初の場所はギャップ化する
plcToNum[cur.first][cur.second]=-1;
return true;
}
pii nxtPos=numToPlc[a-1];nxtPos.second++;
// もし移動先がgapでない
if(plcToNum[nxtPos.first][nxtPos.second]!=-1
||nxtPos.second>=8)
return false;
// 移動先がgapの場合、移動を行う
else{
numToPlc[a]=nxtPos;
plcToNum[nxtPos.first][nxtPos.second]=a;
plcToNum[cur.first][cur.second]=-1;
return true;
}
}
// 数字aをpの場所へ移動させる(戻す)
void backNum(int a,pii &p){
pii cur=numToPlc[a];
plcToNum[cur.first][cur.second]=-1;
numToPlc[a]=p;
plcToNum[p.first][p.second]=a;
}
vector<vector<int> > trans(){
vector<vector<int> > res(4,vector<int>(8,-1));
for(int i=1;i<=4;i++){
for(int j=1;j<=7;j++){
pii &p=numToPlc[i*10+j];
res[p.first][p.second]=i*10+j;
}
}
return res;
}
void dfs(int hand){
vector<vector<int> > tmp=trans();
if(g==tmp){
res=min(res,hand);
return;
}
else if(m.find(tmp)!=m.end()&&m[tmp]<=hand)return;
// 最小手数を更新
m[tmp]=hand;
// 全数字動かせるか調べる
for(int i=1;i<=4;i++){
for(int j=2;j<=7;j++){
pii cur=numToPlc[i*10+j];
bool ok=moveNum(i*10+j);
if(ok){
dfs(hand+1);
backNum(i*10+j,cur);
}
}
}
}
int main(){
const int INF=1000000000;
// goalの状態を作成
for(int i=0;i<4;i++)g.push_back(vector<int>(8,-1));
for(int i=0;i<4;i++)
for(int j=0;j<7;j++)
g[i][j]=(i+1)*10+(j+1);
int t;
cin>>t;
while(t--){
m.clear();
res=INF;
memset(plcToNum,-1,sizeof(plcToNum));
for(int i=0;i<4;i++){
for(int j=0;j<7;j++){
int a;
cin>>a;
numToPlc[a].first=i;
numToPlc[a].second=j+1;
plcToNum[i][j+1]=a;
}
}
// 11,21,31,41を左へ移動
for(int i=1;i<=4;i++)moveNum(i*10+1);
// 深さ優先で移動を全通り試す
dfs(0);
if(res==INF)cout<<-1<<endl;
else cout<<res<<endl;
}
return 0;
} |
////////////////////
/// template ///
////////////////////
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <vector>
#include <queue>
#include <string>
#include <complex>
#include <stack>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
using namespace std;
//// MACRO ////
#define REP(i,n) for (int i = 0; i < (n); i++)
#define RREP(i,n) for (int i = (n)-1; i >= 0; i--)
#define FOR(i,s,n) for (int i = (s); i < (n); i++)
#define allof(c) c.begin(), c.end()
#define partof(c,i,n) c.begin() + (i), c.begin() + (i) + (n)
#define EPS 1e-10
#define INF 1000000000
#define countof(a) (sizeof(a)/sizeof(a[0]))
#define PREDIACTE(t,a) [](const t & a) -> bool
#define COMPARISON_T(t) bool(*)(const t &, const t &)
#define COMPARISON(t,a,b) [](const t & a, const t & b) -> bool
//// prime ////
vector<unsigned char> isPrime;
vector<int> primes;
void initPrimes(int n)
{
isPrime = vector<unsigned char>(n + 1, true);
isPrime[0] = isPrime[1] = false;
FOR(i, 2, n + 1)
{
if (!isPrime[i]) continue;
primes.push_back(i);
for (int j = i * 2; j <= n; j += i)
isPrime[j] = false;
}
}
//// Probability ////
// パスカルの三角形(二項定理) 2種類の並べ替えにつかう。
vector<vector<double>> makePascalTriangle(int n, bool probability = false)
{
typedef vector<double> VD;
vector<VD> t;
if (!t.size()) { t.push_back(VD(1, 1)); }
FOR(i, t.size(), n + 1)
{
t.push_back(VD(i + 1));
REP(j, i)
{
double x = t[i - 1][j] * (probability ? 0.5 : 1);
t[i][j] += x;
t[i][j + 1] += x;
}
}
return t;
}
//// iota iterator ////
struct iotait
{
int n;
iotait(int n = 0) : n(n) { }
iotait &operator ++() { ++n; return *this; }
int operator *() { return n; }
};
//// geo ////
struct P3
{
double x, y, z;
P3(double x = 0, double y = 0, double z = 0) : x(x), y(y), z(z) { }
P3 operator +() const { return *this; }
P3 operator +(const P3 &_) const { return P3(x + _.x, y + _.y, z + _.z); }
P3 operator -() const { return P3(-x, -y, -z); }
P3 operator -(const P3 &_) const { return *this + -_; }
P3 operator *(double _) const { return P3(x*_, y*_, z*_); }
P3 operator /(double _) const { return P3(x / _, y / _, z / _); }
double dot(const P3 &_) const { return x*_.x + y*_.y + z*_.z; } // 内積
P3 cross(const P3 &_) const { return P3(y*_.z - z*_.y, z*_.x - x*_.z, x*_.y - y*_.x); } // 外積
double sqlength() const { return x*x + y*y + z*z; } // 二乗長さ
double length() const { return sqrt(sqlength()); } // 長さ
P3 direction() const { return *this / length(); } // 方向ベクトル
};
struct Sphere
{
P3 c;
double r;
Sphere(double x, double y, double z, double r) : c(x, y, z), r(r) { }
bool IntersectWith(const Sphere &rhs) { return (c - rhs.c).length() - (r + rhs.r) < EPS; } // 接してても真。
};
//// bit ////
#ifdef _MSC_VER
inline unsigned __builtin_ctz(unsigned x) { unsigned long r; _BitScanForward(&r, x); return r; }
#endif
inline int next_bit_permutation(int x)
{
int t = x | (x - 1);
return (t + 1) | (unsigned)((~t & -~t) - 1) >> (__builtin_ctz(x) + 1);
}
//// graph ////
struct Path
{
int from;
int to;
double cost;
Path(int from = 0, int to = 0, double cost = 0) : from(from), to(to), cost(cost) { }
bool operator < (const Path &rhs) const { return cost < rhs.cost; }
bool operator >(const Path &rhs) const { return cost > rhs.cost; }
};
// prim //
pair<double, vector<int>> prim(const vector<vector<double>> &costTable)
{
int N = costTable.size();
priority_queue<Path, vector<Path>, greater<Path>> q;
q.push(Path(0, 0, 0));
vector<int> parent(N, -1);
double totalCost = 0;
while (!q.empty())
{
Path cur = q.top(); q.pop();
int i = cur.to;
if (parent[i] != -1) continue;
parent[i] = cur.from;
totalCost += cur.cost;
REP(j, N) if (parent[j] == -1) q.push(Path(i, j, costTable[i][j]));
}
return make_pair(totalCost, parent);
}
// dijkstra //
pair<vector<double>, vector<int>> dijkstra(const vector<vector<Path>> &routes, int start = 0, int goal = -1)
{
int N = routes.size();
priority_queue<Path, vector<Path>, greater<Path>> q;
q.push(Path(start, start, 0));
vector<int> prev(N, -1);
vector<double> cost(N, INF);
while (!q.empty())
{
Path cur = q.top(); q.pop();
int i = cur.to;
if (prev[i] != -1) continue;
prev[i] = cur.from;
cost[i] = cur.cost;
if (i == goal) { break; }
REP(j, routes[i].size())
{
Path next = Path(i, routes[i][j].to, cur.cost + routes[i][j].cost);
if (prev[next.to] == -1)
q.push(next);
}
}
return make_pair(cost, prev);
}
//// i/o ////
template <class T>
class vevector : public vector<vector<T>>
{
public:
vevector(int n = 0, int m = 0) : vector<vector<T>>(n, vector<T>(m)) { };
vevector(int n, int m, const T &initial) : vector<vector<T>>(n, vector<T>(m, initial)) { };
};
template <class T> T read() { T t; cin >> t; return t; }
template <class T> vector<T> read(int n) { vector<T> v; REP(i, n) { v.push_back(read<T>()); } return v; }
template <class T> vevector<T> read(int n, int m) { vevector<T> v; REP(i, n) v.push_back(read<T>(m)); return v; }
template <class T> vevector<T> readjag(int n) { vevector<T> v; REP(i, n) v.push_back(read<T>(read<int>())); return v; }
template <class T> void write(const T &t) { cout << t << endl; }
template <class T> void write(const T &t, const T &t2) { cout << t << ' ' << t2 << endl; }
template <class T> void write(const vector<T> &v)
{
ostringstream ss;
for (auto x : v) ss << x << ' ';
auto s = ss.str();
cout << s.substr(0, s.length() - 1) << endl;
}
struct _Reader { template <class T> _Reader operator ,(T &rhs) { cin >> rhs; return *this; } };
#define READ(t,...) t __VA_ARGS__; _Reader(), __VA_ARGS__
template <class InIt1, class InIt2>
int partial_compare(InIt1 first1, InIt1 last1, InIt2 first2, InIt2 last2)
{
return lexicographical_compare(first1, last1, first2, last2) ? -1
: lexicographical_compare(first2, last2, first1, last1) ? 1
: 0;
}
//// start up ////
void solve();
int main()
{
// freopen("A.in", "r", stdin);
solve();
return 0;
}
////////////////////
/// template end ///
////////////////////
void dump(unsigned char *pv)
{
REP(i, 4)
{
write(vector<int>(pv + i * 8, pv + i * 8 + 8));
}
write("");
}
void solve()
{
int FREE = 0;
union BD
{
unsigned char stt[32];
unsigned long long ull[4];
inline bool operator < (const BD &rhs) const { return lexicographical_compare(ull, ull + 4, rhs.ull, rhs.ull + 4); }
inline bool operator ==(const BD &rhs) const { return equal(stt, stt + 32, rhs.stt); }
static BD fromVector(const vector<int> &v) { BD r = {}; copy_n(v.begin(), 32, r.stt); return r; }
struct hash { size_t operator() (const BD &b) const { return b.ull[0] ^ b.ull[1] ^ b.ull[2] ^ b.ull[3]; } };
};
BD goal;
{
vector<int> goal_;
FOR(i, 1, 5) { FOR(j, 1, 8) goal_.push_back(i * 10 + j); goal_.push_back(FREE); }
goal = BD::fromVector(goal_);
}
auto testcases = read<int>();
REP(testcase, testcases)
{
BD initial;
{
vector<int> table = read<int>(28);
table.insert(table.begin() + 0, FREE);
table.insert(table.begin() + 8, FREE);
table.insert(table.begin() + 16, FREE);
table.insert(table.begin() + 24, FREE);
swap(*find(allof(table), 11), table[0]);
swap(*find(allof(table), 21), table[8]);
swap(*find(allof(table), 31), table[16]);
swap(*find(allof(table), 41), table[24]);
initial = BD::fromVector(table);
}
auto visited = unordered_set<BD, BD::hash>();
int result = -1;
struct Node { BD bd; int step; };
queue<Node> q;
q.push({ initial, 0 });
while (!q.empty())
{
Node cur = q.front(); q.pop();
if (visited.count(cur.bd) > 0) { continue; }
visited.insert(cur.bd);
//dump(cur.bd.stt);
if (cur.bd == goal) { result = cur.step; break; }
REP(i, 4)
{
BD next = cur.bd;
auto it = next.stt;
REP(j, i + 1) it = find(it + 1, next.stt + 32, FREE);
auto it2 = find(next.stt, next.stt + 32, *(it - 1) + 1);
if (it2 != next.stt + 32)
{
swap(*it, *it2);
if (visited.count(next) == 0) q.push({ next, cur.step + 1 });
}
}
}
write(result);
}
} |
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;
struct Data{
void set(int arg_row,int arg_col){
row = arg_row;
col = arg_col;
}
int row,col;
};
struct Info{
int table[4][8],count;
Data sace_loc[4];
Data num_loc[48];
};
map<string,bool> MAP;
int ans_table[4][8];
string makeString(int table[4][8]){
string ret;
for(int row = 0; row < 4; row++){
for(int col = 0; col < 8; col++){
ret.append(to_string(table[row][col]));
}
}
return ret;
}
bool checkClear(int table[4][8]){
for(int row = 0; row < 4; row++){
for(int col = 0; col < 8; col++){
if(table[row][col] != ans_table[row][col])return false;
}
}
return true;
}
void copyInfo(Info& to,Info from){
for(int row = 0; row < 4; row++){
for(int col = 0; col < 8; col++){
to.table[row][col] = from.table[row][col];
}
}
for(int i = 0; i < 4; i++){
to.sace_loc[i] = from.sace_loc[i];
}
for(int i = 0; i < 48; i++)to.num_loc[i] = from.num_loc[i];
}
void func(){
MAP.clear();
Info first;
first.table[0][0] = 0;
first.table[1][0] = 0;
first.table[2][0] = 0;
first.table[3][0] = 0;
for(int row = 0; row < 4; row++){
for(int col = 1; col <= 7; col++){
scanf("%d",&first.table[row][col]);
switch(first.table[row][col]){
case 11:
first.table[0][0] = 11;
first.table[row][col] = 0;
first.sace_loc[0].set(row,col);
break;
case 21:
first.table[1][0] = 21;
first.table[row][col] = 0;
first.sace_loc[1].set(row,col);
break;
case 31:
first.table[2][0] = 31;
first.table[row][col] = 0;
first.sace_loc[2].set(row,col);
break;
case 41:
first.table[3][0] = 41;
first.table[row][col] = 0;
first.sace_loc[3].set(row,col);
break;
default:
first.num_loc[first.table[row][col]].set(row,col);
break;
}
}
}
first.count = 0;
string tmp = makeString(first.table);
MAP[tmp] = true;
queue<Info> Q;
Q.push(first);
int left_num;
Data tmp_data;
while(!Q.empty()){
if(checkClear(Q.front().table)){
printf("%d\n",Q.front().count);
return;
}else{
for(int i = 0; i < 4; i++){
left_num = Q.front().table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col-1];
if(left_num == 0 || left_num%10 == 7)continue;
tmp_data = Q.front().num_loc[left_num+1];
Info next_info;
copyInfo(next_info,Q.front());
next_info.table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col] = left_num+1;
next_info.table[tmp_data.row][tmp_data.col] = 0;
next_info.num_loc[left_num+1].set(Q.front().sace_loc[i].row,Q.front().sace_loc[i].col);
tmp = makeString(next_info.table);
auto at = MAP.find(tmp);
if(at != MAP.end())continue;
MAP[tmp] = true;
next_info.sace_loc[i].set(tmp_data.row,tmp_data.col);
next_info.count = Q.front().count+1;
Q.push(next_info);
}
Q.pop();
}
}
printf("-1\n");
}
int main(){
for(int col = 0; col <= 6; col++)ans_table[0][col] = 11+col;
ans_table[0][7] = 0;
for(int col = 0; col <= 6; col++)ans_table[1][col] = 21+col;
ans_table[1][7] = 0;
for(int col = 0; col <= 6; col++)ans_table[2][col] = 31+col;
ans_table[2][7] = 0;
for(int col = 0; col <= 6; col++)ans_table[3][col] = 41+col;
ans_table[3][7] = 0;
int case_num;
scanf("%d",&case_num);
for(int i = 0; i < case_num; i++)func();
} |
#include<iostream>
#include<sstream>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<complex>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cassert>
#define rep(i,n) for(int i=0;i<(int)n;i++)
#define all(c) (c).begin(),(c).end()
#define mp make_pair
#define pb push_back
#define each(i,c) for(__typeof((c).begin()) i=(c).begin();i!=(c).end();i++)
#define dbg(x) cerr<<__LINE__<<": "<<#x<<" = "<<(x)<<endl
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
const int inf = (int)1e9;
const double INF = 1e12, EPS = 1e-9;
void pv(const vector<vi> &v){
rep(i, 4) rep(j, 8) cerr<<v[i][j]<<(j==7?"\n":" ");
}
int main(){
int cs;
cin >> cs;
vector<vi> goal(4, vi(8));
rep(i, 4) rep(j, 7) goal[i][j] = (i + 1) * 10 + j + 1;
while(cs--){
vector<vi> v(4, vi(8));
rep(i, 4) rep(j, 7){
cin >> v[i][j + 1];
if(v[i][j + 1] % 10 == 1){
int t = v[i][j + 1] / 10 - 1;
swap(v[i][j + 1], v[t][0]);
}
}
if(v == goal){
cout << 0 << endl;
continue;
}
set<vector<vi> > s;
queue<pair<vector<vi>, int> > q;
q.push(mp(v, 0));
s.insert(v);
while(!q.empty()){
v = q.front().first;
int c = q.front().second; q.pop();
int pos[50] = {};
rep(i, 4) rep(j, 8) pos[v[i][j]] = i * 10 + j;
rep(i, 4) rep(j, 8) if(v[i][j] == 0){
int t = v[i][j - 1] + 1;
if(t == 1 || t % 10 == 8) continue;
t = pos[t];
swap(v[i][j], v[t / 10][t % 10]);
if(!s.count(v)){
if(v == goal){
cout << c + 1 << endl;
goto END;
}
s.insert(v);
q.push(mp(v, c + 1));
}
swap(v[i][j], v[t / 10][t % 10]);
}
}
cout << -1 << endl;
END:;
}
return 0;
} |
#include<iostream>
#include<queue>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
typedef vector<int> vi;
int n,y[4],x[4];
vi ans(32);
int main(){
for(int i=0;i<4;i++){
for(int j=0;j<7;j++){
ans[i*8+j] = (i+1)*10 + j+1;
}
ans[i*8+7] = 0;
}
cin >> n;
while(n--){
vi t(32);
for(int i=0;i<4;i++){
for(int j=0;j<7;j++){
int pos = i*8+j+1;
cin >> t[pos];
if(t[pos]%10 == 1){
int id = t[pos]/10-1;
t[id*8] = t[pos];
t[pos] = 0;
}
}
}
queue<vi> q;
q.push(t);
map<vi,int> m;
m[t] = 0;
while(q.size()){
vi v = q.front(); q.pop();
if(v==ans)break;
int num = 0;
for(int i=0;i<4;i++){
for(int j=0;j<8;j++){
if(!v[i*8+j]){
y[num] = i; x[num] = j;
num++;
}
}
}
int dis = m[v];
while(num--){
int ny = y[num], nx = x[num]-1;
int pos = ny*8+nx;
if(!v[pos] || v[pos]%10 == 7)continue;
int val = v[pos]+1, ty,tx;
for(int i=0;i<4;i++){
for(int j=0;j<8;j++){
if(v[i*8+j] == val){
ty = i; tx = j;
}
}
}
swap(v[y[num]*8+x[num]],v[ty*8+tx]);
if(m.find(v)==m.end()){
m[v] = dis + 1;
q.push(v);
}
swap(v[y[num]*8+x[num]],v[ty*8+tx]);
}
}
if(m.find(ans)==m.end())cout << -1 << endl;
else cout << m[ans] << endl;
}
} |
#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <algorithm>
#include <cstring>
#include <functional>
#include <cmath>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);++i)
#define rep1(i,n) for(int i=1;i<=(n);++i)
#define all(c) (c).begin(),(c).end()
#define fs first
#define sc second
#define pb push_back
#define show(x) cout << #x << " " << x << endl
struct state{
int a[4][8];
};
inline bool operator<(const state &l,const state &r){
rep(i,4) rep(j,8) if(l.a[i][j]!=r.a[i][j]) return l.a[i][j]<r.a[i][j];
return false;
}
map<state,int> msi;
state goal;
int bfs(state s){
msi.clear();
queue<state> que;
que.push(s);
msi[s]=0;
while(!que.empty()){
state st=que.front();
que.pop();
bool ok=true;
rep(i,4) rep(j,7) if(st.a[i][j]!=(i+1)*10+j+1){
ok=false;
break;
}
if(ok){
return msi[st];
}
rep(i,4) rep(j,8){
if(st.a[i][j]==0){
state nst=st;
int x=i,y=j-1;
if(y==-1) continue;
if(st.a[x][y]==0) continue;
int s=st.a[x][y];
if(s%10==7) continue;
s++;
int k,h;
rep(kk,4) rep(hh,8) if(st.a[kk][hh]==s) k=kk,h=hh;
nst.a[k][h]=0;
nst.a[i][j]=s;
if(!msi.count(nst)){
msi[nst]=msi[st]+1;
que.push(nst);
}
}
}
}
return -1;
}
int main(){
rep(i,4) rep(j,7){
goal.a[i][j]=(i+1)*10+j+1;
}
rep(i,4) goal.a[i][7]=0;
int t;
cin>>t;
rep(tt,t){
state st;
rep(i,4) rep(j,8) st.a[i][j]=0;
rep(i,4) rep1(j,7){
int aa;
cin>>aa;
if(aa%10!=1) st.a[i][j]=aa;
}
rep(i,4) st.a[i][0]=i*10+11;
cout<<bfs(st)<<endl;
}
} |
#include <cstdio>
#include <algorithm>
#include <cassert>
#include <queue>
#include <cstring>
using namespace std;
struct Board {
char state[4][8];
Board(){}
};
bool operator< (const Board& lhs, const Board& rhs) {
return memcmp(&lhs.state, &rhs.state, sizeof(lhs.state)) < 0;
}
typedef pair<int, Board> heap_t;
typedef unsigned long long hash_t;
//typedef Board key_t;
#define key_t Board
typedef int value_t;
struct HashMap {
static const int TABLE_SIZE = 1<<18;
hash_t hashes[TABLE_SIZE];
value_t values[TABLE_SIZE];
HashMap()
{
memset(hashes, ~0, sizeof(hashes));
}
void clear() {
memset(hashes, ~0, sizeof(hashes));
}
inline hash_t hasher(const key_t &x) const {
hash_t ret = 0;
for (int i = 0; i < 4; ++i) {
//ret = ret * 1000007ULL + ((hash_t*)x.state[i])[0];
for (int j = 0; j < 8; ++j) {
ret = ret * 10000007ULL + hash_t(x.state[i][j] + 1);
}
}
if (ret == ~0ULL) {
ret = 538;
}
return ret;
}
void set (const key_t &x, const value_t &v) {
const hash_t hash = hasher(x);
int sub = hash % TABLE_SIZE;
for (;hashes[sub] != hash && ~hashes[sub]; sub = (sub + 1 == TABLE_SIZE ? 0 : sub + 1)) ;
hashes[sub] = hash;
values[sub] = v;
}
value_t get (const key_t &x) const {
const hash_t hash = hasher(x);
int sub = hash % TABLE_SIZE;
for (;hashes[sub] != hash && ~hashes[sub]; sub = (sub + 1 == TABLE_SIZE ? 0 : sub + 1)) ;
return values[sub];
}
bool containKey(const key_t &x) const {
const hash_t hash = hasher(x);
int sub = hash % TABLE_SIZE;
for (;hashes[sub] != hash && ~hashes[sub]; sub = (sub + 1 == TABLE_SIZE ? 0 : sub + 1)) ;
return hashes[sub] == hash;
}
};
int board[4][8];
void init() {
memset(board, 0, sizeof(board));
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 7; ++j) {
scanf("%d", board[i]+j+1);
}
}
}
int estimateBoard(const Board& x) {
int ans = 0;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 8; ++j) if (x.state[i][j] != -1) {
if (!((x.state[i][j]>>3) == i && (x.state[i][j]&7) == j)) {
++ans;
}
}
}
return ans ? 1 : 0;
}
int solve() {
static HashMap estimate;
estimate.clear();
queue<heap_t> que;
//initHeap();
Board start;
memset(&start.state, ~0, 4*8);
for (int i = 0; i < 4; ++i) {
for (int j = 1; j < 8; ++j) {
if (board[i][j]) {
start.state[i][j] = ((board[i][j]/10 - 1)<<3) | (board[i][j]%10 - 1);
}
if ((start.state[i][j]&7) == 0) {
swap(start.state[start.state[i][j]>>3][0], start.state[i][j]);
}
}
}
estimate.set(start, estimateBoard(start));
que.push(make_pair(estimate.get(start), start));
for (;!que.empty();) {
int dist = que.front().first;
Board cur = que.front().second;
que.pop();
int esti = estimate.get(cur);
if (esti == 0) {
return dist;
}
dist -= esti;
for (int i = 0; i < 4; ++i) {
for (int j = 1; j < 8; ++j) if (cur.state[i][j] == -1) {
char left = cur.state[i][j-1] + 1;
for (int ii = 0; ii < 4; ++ii) {
for (int jj = 1; jj < 8; ++jj) if (cur.state[ii][jj] == left) {
swap(cur.state[ii][jj], cur.state[i][j]);
if (!estimate.containKey(cur)) {
const int add = estimateBoard(cur);
estimate.set(cur, add);
int nd = dist + 1 + add;
que.push(make_pair(nd, cur));
}
swap(cur.state[ii][jj], cur.state[i][j]);
}
}
}
}
}
return -1;
}
int main() {
int T; scanf("%d", &T);
for (int _ = 0; _ < T; ++_) {
init();
printf("%d\n", solve());
}
return 0;
} |
/*
* POJ 2046: Gap
* ?¢?????????????4?\?1???7?????????????????¨4???8????????????????????°?°?1????????????????????¨?¬¬???????????¶???????¬???????????????????????°?????????§????±?????????????????????§??????????????¨????????\???????????????????±???¨??¨????????????????°?????????\??°???
* ?±???????BFS
* ?????????????????¶?????????????¬?????????¨set??????????????????????????¶?????????4????????????????????\???????????°???????????????????????¨????°????????????¬?§????
*/
#include <cstdio>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <unordered_set>
using namespace std;
unordered_set<string> ss;
struct S {
string s;
int p[29];
int b[4];
int d;
S() {}
S(const string &t) : s(t), d(0) {
int cnt = 0;
for (int i = 0; i < 32; ++i) {
if (s[i] == 30) {
b[cnt++] = i;
} else {
p[s[i]] = i;
}
}
}
S(const S &st) : s(st.s), d(st.d) {
memcpy(p, st.p, sizeof(p));
memcpy(b, st.b, sizeof(b));
}
bool operator<(const S &st) const {
return d > st.d;
}
};
priority_queue<S> pq;
int main() {
string target(32, ' ');
int cnt = 0;
for (int i = 0; i < 4; ++i) {
for (int j = 1; j <= 7; ++j) {
target[cnt++] = char(7 * i + j);
}
target[cnt++] = char(30);
}
int T;
scanf("%d", &T);
while (T--) {
ss.clear();
while (!pq.empty()) pq.pop();
cnt = 0;
string s(32, ' ');
for (int i = 0; i < 4; ++i) {
s[cnt++] = char(i * 7 + 1);
for (int j = 0; j < 7; ++j) {
int x;
scanf("%d", &x);
if (x % 10 == 1) {
s[cnt++] = char(30);
} else {
s[cnt++] = char((x / 10 - 1) * 7 + x % 10);
}
}
}
// for (int i = 0; i < 32; ++i) printf("%d ", s[i]);printf("\n");
if (s == target) {
printf("0\n");
continue;
}
pq.push(S(s));
int ans = -1;
while (!pq.empty()) {
S u(pq.top());
pq.pop();
for (int i = 0; i < 4; ++i) {
int bp = u.b[i];
char pre = u.s[bp - 1];
if (pre == 30 || pre % 7 == 0) {
continue;
}
int np = u.p[pre + 1];
S v(u);
v.s[bp] = char(pre + 1);
v.s[np] = char(30);
if (ss.find(v.s) == ss.end()) {
++v.d;
if (v.s == target) {
// for (int i = 0; i < 32; ++i) printf("%d ", u.s[i]);
// printf("---d=%d\n", u.d);
ans = v.d;
goto L;
}
ss.insert(v.s);
v.p[pre + 1] = bp;
v.b[i] = np;
pq.push(v);
}
}
}
L:
printf("%d\n", ans);
}
return 0;
} |
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <queue>
#include <set>
using namespace std;
const int W = 8;
const int H = 4;
int dat[4][8];
struct S {
char dat[4][8];
char pos[4];
int cost;
void show() const {
for(int i = 0; i < H; ++i) {
for(int j = 0; j < W; ++j) {
cout << (int)dat[i][j] << " ";
}
cout << endl;
}
}
void change(int sp, int a) {
for(int i = 0; i < H; ++i) {
for(int j = 0; j < W; ++j) {
if(dat[i][j] == a) {
swap(dat[i][j], dat[pos[sp]/W][pos[sp]%W]);
pos[sp] = (char)(i*W+j);
return;
}
}
}
}
bool operator <(const S &s) const {
for(int i = 0; i < H; ++i) {
for(int j = 0; j < W; ++j) {
if(dat[i][j] != s.dat[i][j]) return dat[i][j] < s.dat[i][j];
}
}
return false;
}
};
bool isCorrect(const S &s) {
for(int i = 0; i < H; ++i) {
for(int j = 0; j < W; ++j) {
if(j+1 == W) {
if(s.dat[i][j]%10 != 8) return false;
} else {
if(s.dat[i][j] != (char)((i+1)*10+j+1)) return false;
}
}
}
return true;
}
int bfs(S s) {
queue<S> que;
set<S> vis;
que.push(s);
vis.insert(s);
while(!que.empty()) {
s = que.front(), que.pop();
bool isChange = false;
for(int i = 0; i < 4; ++i) {
int x = s.pos[i]%W;
int y = s.pos[i]/W;
if(s.dat[y][x-1]%10 >= 7) continue;
S t = s;
++t.cost;
t.change(i, s.dat[y][x-1]+1);
if(vis.find(t) != vis.end()) continue;
isChange = true;
vis.insert(t);
que.push(t);
}
if(!isChange) {
if(isCorrect(s)) return s.cost;
}
}
return -1;
}
int main() {
int T;
cin >> T;
while(T--) {
S s;
s.cost = 0;
for(int i = 0; i < 4; ++i) {
s.dat[i][0] = (char)((i+1)*10+8);
s.pos[i] = (char)(i*W);
}
for(int i = 0; i < H; ++i) {
for(int j = 1; j < W; ++j) {
int in;
cin >> in;
s.dat[i][j] = in;
if(in%10 == 1) {
char tmp = s.pos[in/10-1];
s.pos[in/10-1] = (char)(i*W+j);
swap(s.dat[i][j], s.dat[tmp/W][tmp%W]);
}
}
}
cout << bfs(s) << endl;
}
return 0;
} |
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cmath>
#include <queue>
#include <set>
#include <map>
using namespace std;
#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
const int INF = 1<<29;
struct P {
int dis;
vector<int> ba, aki, mp;
P() {
dis = 0;
ba.resize(32);
mp.resize(32);
}
P(int dis, vector<int> ba, vector<int> aki, vector<int> mp) :
dis(dis), ba(ba), aki(aki), mp(mp) {}
bool goal() {
REP(i, 32) {
if (i%8 != 7 && ba[i] != i) return 0;
}
return 1;
}
};
int main() {
int n;
cin >> n;
while(n--) {
P ini;
REP(i, 4) {
REP(j, 7) {
int a;
cin >> a;
int suit = a/10-1;
int val = a%10-1;
if (val == 0) {
ini.ba[suit*8+val] = suit*8+val;
ini.aki.push_back(i*8+j+1);
ini.ba[i*8+j+1] = -1;
} else {
ini.ba[i*8+j+1] = suit*8 + val;
ini.mp[suit*8+val] = i*8+j+1;
}
}
}
queue<P> Q;
Q.push(ini);
int res = -1;
map<vector<int>, bool> visited;
while(!Q.empty()) {
P now = Q.front();
Q.pop();
if (visited[now.ba]) continue;
visited[now.ba] = 1;
// REP(i, 32) {
// printf("%2d ", now.ba[i]);
// if (i%8==7) cout << endl;
// }
// cout << endl;
if (now.goal()) {
res = now.dis;
break;
}
REP(i,4) {
P next = now;
int hoge = next.ba[next.aki[i]-1]+1;
if (hoge%8 == 7 || hoge == 0) continue;
swap(next.ba[next.aki[i]], next.ba[next.mp[hoge]]);
swap(next.aki[i], next.mp[hoge]);
if (visited[next.ba]) continue;
next.dis++;
Q.push(next);
}
}
cout << res << endl;
}
} |
#include <cstdio>
#include <algorithm>
#include <cassert>
#include <cstring>
using namespace std;
struct Board {
char state[4][8];
Board(){}
};
bool operator< (const Board& lhs, const Board& rhs) {
return memcmp(&lhs.state, &rhs.state, sizeof(lhs.state)) < 0;
}
typedef pair<int, Board> heap_t;
struct HeapNode {
heap_t value;
HeapNode *left, *right, *parent;
HeapNode(){}
HeapNode(heap_t value, HeapNode *left, HeapNode *right, HeapNode *parent):
value(value), left(left), right(right), parent(parent)
{}
};
const int MAX_HEAP = 1<<18;
HeapNode nodes__[MAX_HEAP];
int freeNodeStack__[MAX_HEAP], *lastStack__;
void initHeap(int n = MAX_HEAP) {
for (int i = 0; i < n; ++i) {
freeNodeStack__[i] = n - 1 - i;
}
lastStack__ = freeNodeStack__ + n;
}
inline bool cmpHeap(const heap_t& lhs, const heap_t& rhs) {
return lhs < rhs;
}
HeapNode *allocateHeap() {
return &nodes__[*--lastStack__];
}
void freeHeap(HeapNode *x) {
if (x) {
*lastStack__ = (int)(x - nodes__);
++lastStack__;
}
}
inline bool isRoot(HeapNode *a) {
return !(a->parent || a->right);
}
inline bool isLeft(HeapNode *x) {
//assert(x && x->parent);
return x->parent->left == x;
}
heap_t getMinimum(HeapNode *a) {
//assert(a);
return a->value;
}
HeapNode *makeHeap(heap_t value) {
HeapNode *ret = allocateHeap();
*ret = HeapNode(value, 0, 0, 0);
return ret;
}
HeapNode *meld(HeapNode *a, HeapNode *b) {
if (!(a && b)) {
return a ? a : b;
}
if (!cmpHeap(a->value, b->value)) {
swap(a, b);
}
if (a->left) {
a->left->parent = b;
b->right = a->left;
}
a->left = b;
b->parent = a;
return a;
}
HeapNode *insert(HeapNode *a, const heap_t& value) {
return meld(a, makeHeap(value));
}
HeapNode *meldPair(HeapNode *a) {
if (!(a && a->right)) {
return a;
}
HeapNode *nxt = a->right;
HeapNode *nxtNxt = nxt->right;
if (nxtNxt) {
nxtNxt->parent = 0;
}
a->right = nxt->right = nxt->parent = 0;
return meld( meld(a, nxt), meldPair(nxtNxt) );
}
HeapNode *eraseMinimum(HeapNode *a) {
if (!(a && a->left)) {
return 0;
}
a->left->parent = 0;
return meldPair(a->left);
}
void eraseSubHeap__(HeapNode *x) {
//assert(x && x->parent);
if (isLeft(x)) {
x->parent->left = x->right;
}
else {
x->parent->right = x->right;
}
if (x->right) {
x->right->parent = x->parent;
}
x->parent = x->right = 0;
}
HeapNode *decreaseKey(HeapNode *a, HeapNode *x, const heap_t& newValue) {
//assert(a && isRoot(x));
if (!(x && cmpHeap(newValue, x->value))) {
return a;
}
x->value = newValue;
if (a == x) {
return x;
}
if (isLeft(x) && cmpHeap(x->parent->value, x->value)) {
return a;
}
eraseSubHeap__(x);
return meld(a, x);
}
HeapNode *erase(HeapNode *a, HeapNode *x) {
//assert(a);
if (!x) {
return a;
}
if (a == x) {
return eraseMinimum(a);
}
eraseSubHeap__(x);
x->parent = x->right = 0;
return meld(a, eraseMinimum(x));
}
HeapNode *changeKey(HeapNode *a, HeapNode *x, const heap_t& newValue) {
if (x && !cmpHeap(x->value, newValue)) {
return decreaseKey(a, x, newValue);
}
a = erase(a, x);
x->value = newValue;
x->left = x->right = x->parent = 0;
return meld(a, x);
}
struct Heap {
HeapNode *root;
int size__;
Heap():root(0), size__(0) {}
bool isEmpty() {
return !root;
}
int size() {
return size__;
}
void clear() {
size__ = 0;
if (!root) {
return ;
}
HeapNode *tmp = root;
root = tmp->right;
clear();
root = tmp->left;
clear();
root = 0;
freeHeap(tmp);
}
HeapNode *push(const heap_t& value) {
++size__;
HeapNode *ret = makeHeap(value);
root = meld(root, ret);
return ret;
}
heap_t top() {
return getMinimum(root);
}
void erase(HeapNode *x) {
--size__;
root = ::erase(root, x);
}
void pop() {
--size__;
HeapNode *tmp = root;
root = eraseMinimum(root);
freeHeap(tmp);
}
void decreaseKey(HeapNode *x, const heap_t& newValue) {
root = ::decreaseKey(root, x, newValue);
}
void changeKey(HeapNode *x, const heap_t& newValue) {
root = ::changeKey(root, x, newValue);
}
};
typedef unsigned long long hash_t;
//typedef Board key_t;
#define key_t Board
typedef int value_t;
struct HashMap {
static const int TABLE_SIZE = 1<<18;
hash_t hashes[TABLE_SIZE];
value_t values[TABLE_SIZE];
HashMap()
{
memset(hashes, ~0, sizeof(hashes));
}
void clear() {
memset(hashes, ~0, sizeof(hashes));
}
inline hash_t hasher(const key_t &x) const {
hash_t ret = 0;
for (int i = 0; i < 4; ++i) {
//ret = ret * 1000007ULL + ((hash_t*)x.state[i])[0];
for (int j = 0; j < 8; ++j) {
ret = ret * 10000007ULL + hash_t(x.state[i][j] + 1);
}
}
if (ret == ~0ULL) {
ret = 538;
}
return ret;
}
void set (const key_t &x, const value_t &v) {
const hash_t hash = hasher(x);
int sub = hash % TABLE_SIZE;
for (;hashes[sub] != hash && ~hashes[sub]; sub = (sub + 1 == TABLE_SIZE ? 0 : sub + 1)) ;
hashes[sub] = hash;
values[sub] = v;
}
value_t get (const key_t &x) const {
const hash_t hash = hasher(x);
int sub = hash % TABLE_SIZE;
for (;hashes[sub] != hash && ~hashes[sub]; sub = (sub + 1 == TABLE_SIZE ? 0 : sub + 1)) ;
return values[sub];
}
bool containKey(const key_t &x) const {
const hash_t hash = hasher(x);
int sub = hash % TABLE_SIZE;
for (;hashes[sub] != hash && ~hashes[sub]; sub = (sub + 1 == TABLE_SIZE ? 0 : sub + 1)) ;
return hashes[sub] == hash;
}
};
int board[4][8];
void init() {
memset(board, 0, sizeof(board));
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 7; ++j) {
scanf("%d", board[i]+j+1);
}
}
}
int estimateBoard(const Board& x) {
int ans = 0;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 8; ++j) if (x.state[i][j] != -1) {
if (!((x.state[i][j]>>3) == i && (x.state[i][j]&7) == j)) {
++ans;
}
}
}
return ans ? 1 : 0;
}
int solve() {
static HashMap estimate;
estimate.clear();
Heap que;
initHeap();
Board start;
memset(&start.state, ~0, 4*8);
for (int i = 0; i < 4; ++i) {
for (int j = 1; j < 8; ++j) {
if (board[i][j]) {
start.state[i][j] = ((board[i][j]/10 - 1)<<3) | (board[i][j]%10 - 1);
}
if ((start.state[i][j]&7) == 0) {
swap(start.state[start.state[i][j]>>3][0], start.state[i][j]);
}
}
}
estimate.set(start, estimateBoard(start));
que.push(make_pair(estimate.get(start), start));
for (;!que.isEmpty();) {
int dist = que.root->value.first;
Board cur = que.root->value.second;
que.pop();
int esti = estimate.get(cur);
if (esti == 0) {
return dist;
}
dist -= esti;
for (int i = 0; i < 4; ++i) {
for (int j = 1; j < 8; ++j) if (cur.state[i][j] == -1) {
char left = cur.state[i][j-1] + 1;
for (int ii = 0; ii < 4; ++ii) {
for (int jj = 1; jj < 8; ++jj) if (cur.state[ii][jj] == left) {
swap(cur.state[ii][jj], cur.state[i][j]);
if (!estimate.containKey(cur)) {
const int add = estimateBoard(cur);
estimate.set(cur, add);
int nd = dist + 1 + add;
que.push(make_pair(nd, cur));
}
swap(cur.state[ii][jj], cur.state[i][j]);
}
}
}
}
}
return -1;
}
int main() {
int T; scanf("%d", &T);
for (int _ = 0; _ < T; ++_) {
init();
printf("%d\n", solve());
}
return 0;
} |
//38
#include<iostream>
#include<vector>
#include<queue>
#include<set>
#include<algorithm>
using namespace std;
struct S{
int t;
vector<vector<int> > v;
};
int main(){
int t;
cin>>t;
while(t--){
vector<vector<int> >v(4,vector<int>(8));
for(int i=0;i<4;i++){
v[i][0]=(i+1)*10+1;
for(int j=1;j<=7;j++){
cin>>v[i][j];
if(v[i][j]%10==1){
v[i][j]=0;
}
}
}
S is={0,v};
queue<S> que;
que.push(is);
set<vector<vector<int> > > s;
while(!que.empty()){
S c=que.front();
for(int i=0;i<4;i++){
for(int j=0;j<7;j++){
if(c.v[i][j]!=(i+1)*10+j+1)goto next;
}
if(c.v[i].back())goto next;
}
break;
next:
que.pop();
if(!s.insert(c.v).second)continue;
for(int i=0;i<4;i++){
for(int j=0;j<8;j++){
if(c.v[i][j]||c.v[i][j-1]%10==7)continue;
S ns={c.t+1,c.v};
for(int k=0;k<4;k++){
for(int l=0;l<8;l++){
if(ns.v[k][l]==ns.v[i][j-1]+1){
/*
for(int i=0;i<4;i++){
for(int j=0;j<8;j++){
cout<<ns.v[i][j]<<' ';
}
cout<<endl;
}
*/
swap(ns.v[k][l],ns.v[i][j]);
que.push(ns);
goto nb;
}
}
}
nb:
;
}
}
}
cout<<(que.empty()?-1:que.front().t)<<endl;
}
return 0;
} |
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <set>
#include <sstream>
#include <numeric>
#include <bitset>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
#include <cctype>
#include <cassert>
using namespace std;
typedef long long ll;
static const double EPS = 1e-8;
static const double PI = 4.0 * atan(1.0);
bool ISINT(double x){return fabs(x-(int)x)<EPS;}
bool ISEQ(double x,double y){return fabs(x-y)<EPS;}
string itos(ll x){stringstream ss;ss<<x;return ss.str();}
#define REP(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)
#define EREP(i,a,b) for(int i=a;i<=b;i++)
#define erep(i,n) EREP(i,0,n)
#define foreach(itr,c) for(__typeof(c.begin()) itr=c.begin();itr!=c.end();itr++)
class P{
public:
int cost;
vector<int> v,pos,gap;
P(){}
P(int _cost,vector<int> _v,vector<int> _pos,vector<int> _gap){
cost = _cost;
v = _v;
pos = _pos;
gap = _gap;
}
bool goal(){
rep(i,4){
rep(j,7){
int idx = i * 8 + j;
if(v[idx] / 10 != i + 1 || v[idx] % 10 != j + 1) return false;
}
}
return true;
}
};
int bfs(P start){
queue<P> open;
set<vector<int> > closed;
open.push(start);
closed.insert(start.v);
while(!open.empty()){
P p = open.front(); open.pop();
if(p.goal()){
return p.cost;
}
rep(i,4){
vector<int> nv = p.v;
vector<int> npos = p.pos;
vector<int> ngap = p.gap;
int idx = ngap[i];
int val = nv[idx-1] + 1;
if(npos[val] == 0) continue;
nv[idx] = val;
nv[npos[val]] = 0;
ngap[i] = npos[val];
npos[val] = idx;
if(closed.find(nv) != closed.end()) continue;
closed.insert(nv);
open.push(P(p.cost+1,nv,npos,ngap));
}
}
return -1;
}
int main(void){
int T;
scanf("%d",&T);
while(T--){
vector<int> v(32);
vector<int> pos(50);
vector<int> gap;
rep(i,4){
rep(j,7){
int idx = i * 8 + j + 1;
scanf("%d",&v[idx]);
if(v[idx] % 10 == 1){
int row = v[idx] / 10 - 1;
v[row*8] = v[idx];
v[idx] = 0;
gap.push_back(idx);
}
else{
pos[v[idx]] = idx;
}
}
}
printf("%d\n",bfs(P(0,v,pos,gap)));
}
} |
#define _USE_MATH_DEFINES
#include <algorithm>
#include <cstdio>
#include <functional>
#include <iostream>
#include <cfloat>
#include <climits>
#include <cstring>
#include <cmath>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <time.h>
#include <vector>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> i_i;
typedef pair<ll, int> ll_i;
typedef pair<double, int> d_i;
typedef pair<ll, ll> ll_ll;
typedef pair<double, double> d_d;
struct edge { int u, v; ll w; };
ll MOD = 1000000007;
ll _MOD = 1000000009;
double EPS = 1e-10;
int INF = INT_MAX / 2;
int main() {
int T; cin >> T;
while (T--) {
vector< vector<char> > a(4, vector<char>(8, -1)), b;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 7; j++)
a[i][j] = i * 10 + j;
b = a;
for (int i = 0; i < 4; i++)
for (int j = 1; j < 8; j++) {
int x; cin >> x;
x -= 11;
b[i][j] = (x % 10 ? x : -1);
}
map<vector< vector<char> >, int> m;
m[b] = 0;
queue< vector< vector<char> > > q;
q.push(b);
while (!q.empty()) {
vector< vector<char> > a = q.front(); q.pop();
for (int i = 0; i < 4; i++)
for (int j = 1; j < 8; j++) {
if (a[i][j] != -1) continue;
int x = a[i][j - 1];
if (x == -1 || x % 10 == 6) continue;
vector< vector<char> > b = a;
for (int _i = 0; _i < 4; _i++)
for (int _j = 1; _j < 8; _j++) {
if (a[_i][_j] != x + 1) continue;
b[i][j] = x + 1;
b[_i][_j] = -1;
if (m.count(b)) continue;
m[b] = m[a] + 1;
q.push(b);
}
}
}
cout << (m.count(a) ? m[a] : -1) << endl;
}
} |
#include <bits/stdc++.h>
using namespace std;
typedef pair<vector<int> ,vector<int> > P;
typedef pair<P,int> P2;
vector<int> g;
bool check(vector<int> a) {return a==g;}
int main() {
for(int i=1; i<=4; i++) {
for(int j=1; j<=8; j++) {
if(j==8) g.push_back(0);
else g.push_back(i*10+j);
}
}
int T;
cin >> T;
while(T--) {
vector<int> a(32);
for(int i=0; i<4; i++) {
for(int j=1; j<=7; j++) cin >> a[i*8+j];
}
vector<int> d(4);
for(int i=0; i<32; i++) {
if(i%8==0) continue;
if(a[i]%10==1) {
a[(a[i]/10-1)*8]=a[i];
d[a[i]/10-1]=i;
a[i]=0;
}
}
set<vector<int> > se;
se.insert(a);
queue<P2> que;
que.push(P2(P(a,d),0));
int ans=-1;
while(!que.empty()) {
P2 p=que.front();que.pop();
a=p.first.first;
d=p.first.second;
int cnt=p.second;
if(check(a)) {
ans=cnt;
break;
}
for(int i=0; i<4; i++) {
int x=a[d[i]-1]+1;
if(x==0) continue;
vector<int> a2=a,d2=d;
for(int j=0; j<32; j++) {
if(a2[j]==x) {
a2[j]=0;
a2[d[i]]=x;
d2[i]=j;
break;
}
}
if(se.count(a2)) continue;
se.insert(a2);
que.push(P2(P(a2,d2),cnt+1));
}
}
cout << ans << endl;
}
return 0;
}
|
////////////////////
/// template ///
////////////////////
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <vector>
#include <queue>
#include <string>
#include <complex>
#include <stack>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
using namespace std;
//// MACRO ////
#define REP(i,n) for (int i = 0; i < (n); i++)
#define RREP(i,n) for (int i = (n)-1; i >= 0; i--)
#define FOR(i,s,n) for (int i = (s); i < (n); i++)
#define allof(c) c.begin(), c.end()
#define partof(c,i,n) c.begin() + (i), c.begin() + (i) + (n)
#define EPS 1e-10
#define INF 1000000000
#define countof(a) (sizeof(a)/sizeof(a[0]))
#define PREDIACTE(t,a) [](const t & a) -> bool
#define COMPARISON_T(t) bool(*)(const t &, const t &)
#define COMPARISON(t,a,b) [](const t & a, const t & b) -> bool
//// prime ////
vector<unsigned char> isPrime;
vector<int> primes;
void initPrimes(int n)
{
isPrime = vector<unsigned char>(n + 1, true);
isPrime[0] = isPrime[1] = false;
FOR(i, 2, n + 1)
{
if (!isPrime[i]) continue;
primes.push_back(i);
for (int j = i * 2; j <= n; j += i)
isPrime[j] = false;
}
}
//// Probability ////
// パスカルの三角形(二項定理) 2種類の並べ替えにつかう。
vector<vector<double>> makePascalTriangle(int n, bool probability = false)
{
typedef vector<double> VD;
vector<VD> t;
if (!t.size()) { t.push_back(VD(1, 1)); }
FOR(i, t.size(), n + 1)
{
t.push_back(VD(i + 1));
REP(j, i)
{
double x = t[i - 1][j] * (probability ? 0.5 : 1);
t[i][j] += x;
t[i][j + 1] += x;
}
}
return t;
}
//// iota iterator ////
struct iotait
{
int n;
iotait(int n = 0) : n(n) { }
iotait &operator ++() { ++n; return *this; }
int operator *() { return n; }
};
//// geo ////
struct P3
{
double x, y, z;
P3(double x = 0, double y = 0, double z = 0) : x(x), y(y), z(z) { }
P3 operator +() const { return *this; }
P3 operator +(const P3 &_) const { return P3(x + _.x, y + _.y, z + _.z); }
P3 operator -() const { return P3(-x, -y, -z); }
P3 operator -(const P3 &_) const { return *this + -_; }
P3 operator *(double _) const { return P3(x*_, y*_, z*_); }
P3 operator /(double _) const { return P3(x / _, y / _, z / _); }
double dot(const P3 &_) const { return x*_.x + y*_.y + z*_.z; } // 内積
P3 cross(const P3 &_) const { return P3(y*_.z - z*_.y, z*_.x - x*_.z, x*_.y - y*_.x); } // 外積
double sqlength() const { return x*x + y*y + z*z; } // 二乗長さ
double length() const { return sqrt(sqlength()); } // 長さ
P3 direction() const { return *this / length(); } // 方向ベクトル
};
struct Sphere
{
P3 c;
double r;
Sphere(double x, double y, double z, double r) : c(x, y, z), r(r) { }
bool IntersectWith(const Sphere &rhs) { return (c - rhs.c).length() - (r + rhs.r) < EPS; } // 接してても真。
};
//// bit ////
#ifdef _MSC_VER
inline unsigned __builtin_ctz(unsigned x) { unsigned long r; _BitScanForward(&r, x); return r; }
#endif
inline int next_bit_permutation(int x)
{
int t = x | (x - 1);
return (t + 1) | (unsigned)((~t & -~t) - 1) >> (__builtin_ctz(x) + 1);
}
//// graph ////
struct Path
{
int from;
int to;
double cost;
Path(int from = 0, int to = 0, double cost = 0) : from(from), to(to), cost(cost) { }
bool operator < (const Path &rhs) const { return cost < rhs.cost; }
bool operator >(const Path &rhs) const { return cost > rhs.cost; }
};
// prim //
pair<double, vector<int>> prim(const vector<vector<double>> &costTable)
{
int N = costTable.size();
priority_queue<Path, vector<Path>, greater<Path>> q;
q.push(Path(0, 0, 0));
vector<int> parent(N, -1);
double totalCost = 0;
while (!q.empty())
{
Path cur = q.top(); q.pop();
int i = cur.to;
if (parent[i] != -1) continue;
parent[i] = cur.from;
totalCost += cur.cost;
REP(j, N) if (parent[j] == -1) q.push(Path(i, j, costTable[i][j]));
}
return make_pair(totalCost, parent);
}
// dijkstra //
pair<vector<double>, vector<int>> dijkstra(const vector<vector<Path>> &routes, int start = 0, int goal = -1)
{
int N = routes.size();
priority_queue<Path, vector<Path>, greater<Path>> q;
q.push(Path(start, start, 0));
vector<int> prev(N, -1);
vector<double> cost(N, INF);
while (!q.empty())
{
Path cur = q.top(); q.pop();
int i = cur.to;
if (prev[i] != -1) continue;
prev[i] = cur.from;
cost[i] = cur.cost;
if (i == goal) { break; }
REP(j, routes[i].size())
{
Path next = Path(i, routes[i][j].to, cur.cost + routes[i][j].cost);
if (prev[next.to] == -1)
q.push(next);
}
}
return make_pair(cost, prev);
}
//// i/o ////
template <class T>
class vevector : public vector<vector<T>>
{
public:
vevector(int n = 0, int m = 0) : vector<vector<T>>(n, vector<T>(m)) { };
vevector(int n, int m, const T &initial) : vector<vector<T>>(n, vector<T>(m, initial)) { };
};
template <class T> T read() { T t; cin >> t; return t; }
template <class T> vector<T> read(int n) { vector<T> v; REP(i, n) { v.push_back(read<T>()); } return v; }
template <class T> vevector<T> read(int n, int m) { vevector<T> v; REP(i, n) v.push_back(read<T>(m)); return v; }
template <class T> vevector<T> readjag(int n) { vevector<T> v; REP(i, n) v.push_back(read<T>(read<int>())); return v; }
template <class T> void write(const T &t) { cout << t << endl; }
template <class T> void write(const T &t, const T &t2) { cout << t << ' ' << t2 << endl; }
template <class T> void write(const vector<T> &v)
{
ostringstream ss;
for (auto x : v) ss << x << ' ';
auto s = ss.str();
cout << s.substr(0, s.length() - 1) << endl;
}
struct _Reader { template <class T> _Reader operator ,(T &rhs) { cin >> rhs; return *this; } };
#define READ(t,...) t __VA_ARGS__; _Reader(), __VA_ARGS__
template <class InIt1, class InIt2>
int partial_compare(InIt1 first1, InIt1 last1, InIt2 first2, InIt2 last2)
{
return lexicographical_compare(first1, last1, first2, last2) ? -1
: lexicographical_compare(first2, last2, first1, last1) ? 1
: 0;
}
//// start up ////
void solve();
int main()
{
// freopen("A.in", "r", stdin);
solve();
return 0;
}
////////////////////
/// template end ///
////////////////////
void dump(unsigned char *pv)
{
REP(i, 4)
{
write(vector<int>(pv + i * 8, pv + i * 8 + 8));
}
write("");
}
void solve()
{
int FREE = 0;
union BD
{
unsigned char stt[32];
unsigned long long ull[4];
inline bool operator < (const BD &rhs) const { return lexicographical_compare(ull, ull + 4, rhs.ull, rhs.ull + 4); }
inline bool operator ==(const BD &rhs) const { return equal(ull, ull + 4, rhs.ull); }
static BD fromVector(const vector<int> &v) { BD r = {}; copy_n(v.begin(), 32, r.stt); return r; }
struct hash { size_t operator() (const BD &b) const { return b.ull[0] ^ b.ull[1] ^ b.ull[2] ^ b.ull[3]; } };
};
BD goal;
{
vector<int> goal_;
FOR(i, 1, 5) { FOR(j, 1, 8) goal_.push_back(i * 10 + j); goal_.push_back(FREE); }
goal = BD::fromVector(goal_);
}
auto testcases = read<int>();
REP(testcase, testcases)
{
BD initial;
{
vector<int> table = read<int>(28);
table.insert(table.begin() + 0, FREE);
table.insert(table.begin() + 8, FREE);
table.insert(table.begin() + 16, FREE);
table.insert(table.begin() + 24, FREE);
swap(*find(allof(table), 11), table[0]);
swap(*find(allof(table), 21), table[8]);
swap(*find(allof(table), 31), table[16]);
swap(*find(allof(table), 41), table[24]);
initial = BD::fromVector(table);
}
auto visited = unordered_set<BD, BD::hash>();
int result = -1;
struct Node { BD bd; int step; };
queue<Node> q;
q.push({ initial, 0 });
while (!q.empty())
{
Node cur = q.front(); q.pop();
if (visited.count(cur.bd) > 0) { continue; }
visited.insert(cur.bd);
//dump(cur.bd.stt);
if (cur.bd == goal) { result = cur.step; break; }
REP(i, 4)
{
BD next = cur.bd;
auto it = next.stt;
REP(j, i + 1) it = find(it + 1, next.stt + 32, FREE);
auto it2 = find(next.stt, next.stt + 32, *(it - 1) + 1);
if (it2 != next.stt + 32)
{
swap(*it, *it2);
if (visited.count(next) == 0) q.push({ next, cur.step + 1 });
}
}
}
write(result);
}
} |
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<queue>
using namespace std;
struct Info{
static const int Height = 4;
static const int Width = 8;
short field[Height][Width];
bool operator < (const Info& info) const{
for(int i = 0; i < Height; i++)
for(int j = 0; j < Width; j++)
if(field[i][j] != info.field[i][j]) return field[i][j] < info.field[i][j];
return false;
}
};
struct State{
int t;
Info info;
bool operator < (const State& s) const {
return t > s.t;
}
};
Info Goal;
Info Start;
void print(const Info& info){
for(int i = 0; i < Info::Height; i++){
for(int j = 0; j < Info::Width; j++) cout << info.field[i][j] << " ";
cout << endl;
}
cout << endl;
}
void input(){
for(int i = 0; i < Info::Height; i++) Start.field[i][0] = 0;
for(int i = 0; i < Info::Height; i++)
for(int j = 1; j < Info::Width; j++){
cin >> Start.field[i][j];
if(Start.field[i][j]%10 == 1){
int pos = Start.field[i][j]/10;
swap(Start.field[i][j], Start.field[pos-1][0]);
}
}
// print(Start);
// exit(0);
}
int find(const Info& info, int x, int skip){
int come = 0;
for(int i = 0; i < Info::Height; i++)
for(int j = 0; j < Info::Width; j++)
if(info.field[i][j] == x){
come++;
if(come > skip) return i*Info::Width+j;
}
return -1;
}
bool isInside(int h, int w){return 0<=h&&h<Info::Height&&0<=w&&w<Info::Width;}
void solve(){
map<Info,int> M;
M.clear();
priority_queue<State> Q;
Q.push((State){0,Start});
M[Start] = 0;
while(!Q.empty()){
const State now = Q.top();
Q.pop();
if(M[now.info] < now.t) continue;
for(int i = 0; i < 4; i++){
int blank = find(now.info, 0, i);
const int h = blank/Info::Width;
const int w = blank%Info::Width;
if(!isInside(h,w-1)) continue;
int nexpos = find(now.info, now.info.field[h][w-1]+1, 0);
if(nexpos == -1) continue;
State nex = now;
nex.t++;
swap(nex.info.field[h][w], nex.info.field[nexpos/Info::Width][nexpos%Info::Width]);
if(M.count(nex.info) == 0 || M[nex.info] > nex.t){
M[nex.info] = nex.t;
Q.push(nex);
}
}
}
if(M.count(Goal) == 0) cout << "-1" << endl;
else cout << M[Goal] << endl;
}
int main(){
for(int i = 0; i < Info::Height; i++)
for(int j = 0; j < Info::Width; j++){
if(j == Info::Width-1) Goal.field[i][j] = 0;
else Goal.field[i][j] = (i+1)*10+j+1;
}
int tc;
cin >> tc;
while(tc--){
input();
solve();
}
return 0;
} |
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;
struct Data{
void set(int arg_row,int arg_col){
row = arg_row;
col = arg_col;
}
int row,col;
};
struct Info{
int table[4][8],count;
Data sace_loc[4];
};
map<string,bool> MAP;
int ans_table[4][8];
string makeString(int table[4][8]){
string ret;
for(int row = 0; row < 4; row++){
for(int col = 0; col < 8; col++){
ret.append(to_string(table[row][col])).append(to_string('*'));
}
}
return ret;
}
bool checkClear(int table[4][8]){
for(int row = 0; row < 4; row++){
for(int col = 0; col < 8; col++){
if(table[row][col] != ans_table[row][col])return false;
}
}
return true;
}
void copyInfo(Info& to,Info from){
for(int row = 0; row < 4; row++){
for(int col = 0; col < 8; col++){
to.table[row][col] = from.table[row][col];
}
}
for(int i = 0; i < 4; i++){
to.sace_loc[i] = from.sace_loc[i];
}
}
void func(){
MAP.clear();
Info first;
first.table[0][0] = 0;
first.table[1][0] = 0;
first.table[2][0] = 0;
first.table[3][0] = 0;
for(int row = 0; row < 4; row++){
for(int col = 1; col <= 7; col++){
scanf("%d",&first.table[row][col]);
switch(first.table[row][col]){
case 11:
first.table[0][0] = 11;
first.table[row][col] = 0;
first.sace_loc[0].set(row,col);
break;
case 21:
first.table[1][0] = 21;
first.table[row][col] = 0;
first.sace_loc[1].set(row,col);
break;
case 31:
first.table[2][0] = 31;
first.table[row][col] = 0;
first.sace_loc[2].set(row,col);
break;
case 41:
first.table[3][0] = 41;
first.table[row][col] = 0;
first.sace_loc[3].set(row,col);
break;
}
}
}
first.count = 0;
string tmp = makeString(first.table);
MAP[tmp] = true;
queue<Info> Q;
Q.push(first);
int left_num,tmp_row,tmp_col;
while(!Q.empty()){
if(checkClear(Q.front().table)){
printf("%d\n",Q.front().count);
return;
}else{
for(int i = 0; i < 4; i++){
left_num = Q.front().table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col-1];
if(left_num%7 == 0){
switch(left_num){
case 17:
if(Q.front().sace_loc[i].row == 0 && Q.front().sace_loc[i].col == 7)continue;
break;
case 27:
if(Q.front().sace_loc[i].row == 1 && Q.front().sace_loc[i].col == 7)continue;
break;
case 37:
if(Q.front().sace_loc[i].row == 2 && Q.front().sace_loc[i].col == 7)continue;
break;
case 47:
if(Q.front().sace_loc[i].row == 3 && Q.front().sace_loc[i].col == 7)continue;
break;
}
}
tmp_row = -1;
for(int row = 0; row < 4; row++){
for(int col = 0; col < 8; col++){
if(Q.front().table[row][col] == left_num+1){
tmp_row = row;
tmp_col = col;
break;
}
}
if(tmp_row != -1)break;
}
if(tmp_row == -1)continue;
Info next_info;
copyInfo(next_info,Q.front());
next_info.table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col] = left_num+1;
next_info.table[tmp_row][tmp_col] = 0;
tmp = makeString(next_info.table);
auto at = MAP.find(tmp);
if(at != MAP.end())continue;
MAP[tmp] = true;
next_info.sace_loc[i].set(tmp_row,tmp_col);
next_info.count = Q.front().count+1;
Q.push(next_info);
}
Q.pop();
}
}
printf("-1\n");
}
int main(){
for(int col = 0; col <= 6; col++)ans_table[0][col] = 11+col;
ans_table[0][7] = 0;
for(int col = 0; col <= 6; col++)ans_table[1][col] = 21+col;
ans_table[1][7] = 0;
for(int col = 0; col <= 6; col++)ans_table[2][col] = 31+col;
ans_table[2][7] = 0;
for(int col = 0; col <= 6; col++)ans_table[3][col] = 41+col;
ans_table[3][7] = 0;
int case_num;
scanf("%d",&case_num);
for(int i = 0; i < case_num; i++)func();
} |
#include <iostream>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
using namespace std;
struct Node{
vector<int> pos;
vector<int> emp;
int cost;
Node(){pos.resize(28);cost=0;}
Node getSuccessor(int idx){
Node res = *this;
for(int i = 0 ; i < 28 ; i++){
if( res.pos[i] == res.emp[idx]-1 ){
if( i % 7 == 6 ) continue;
int t = res.emp[idx];
res.emp[idx] = res.pos[i+1];
res.pos[i+1] = t;
return res;
}
}
res.pos.clear();
return res;
}
};
bool operator < (const Node &a,const Node &b){
return a.pos < b.pos;
}
int main(){
int T; cin >> T;
while(T--){
Node fst;
for(int i = 0 ; i < 4 ; i++){
for(int j = 0 ; j < 7 ; j++){
int x; cin >> x; x -= 11;
x = x / 10 * 7 + x % 10;
int y = i * 8 + j + 1;
fst.pos[x] = y;
if( x % 7 == 0 ){
fst.emp.push_back(y);
fst.pos[x] = x / 7 * 8;
}
}
}
queue<Node> Q;
Q.push(fst);
map<Node,bool> done;
vector<int> correct(28);
for(int i = 0 ; i < 28 ; i++) correct[i] = (i / 7) * 8 + i % 7;
while(Q.size()){
Node q = Q.front(); Q.pop();
if( done[q] ) continue;
else done[q] = true;
if( correct == q.pos ){
cout << q.cost << endl;
goto succ;
}
for(int i = 0 ; i < 4 ; i++){
Node get = q.getSuccessor(i);
if( get.pos.size() == 0 ) continue;
get.cost = q.cost + 1;
Q.push(get);
}
}
cout << -1 << endl;
succ:;
}
} |
//include
//------------------------------------------
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <climits>
#include <queue>
using namespace std;
//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;
//container util
//------------------------------------------
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())
//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI = acos(-1.0);
int idx(PII p){
return p.first*10+p.second+11;
}
int main(){
cin.tie(0);
ios_base::sync_with_stdio(false);
int N; cin >> N;
REP(n,N){
VI xs(32);
REP(i,4){
REP(j,7) cin >> xs[i*8+j+1];
xs[i*8] = 0;
}
REP(i,32)
if(xs[i]%10 == 1){
swap(xs[i], xs[(xs[i]/10-1)*8]);
}
map<VI,int> memo;
queue<VI> q;
q.push(xs);
memo[xs] = 0;
int ans = -1;
while(!q.empty()){
xs = q.front(); q.pop();
bool ok = true;
REP(y,4) REP(x,7)
if(xs[y*8+x] != y*10+x+11){
ok = false;
x = y = 100;
}
if(ok){
ans = memo[xs];
break;
}
int d = memo[xs];
REP(y,4) FOR(x,1,8){
int idx = y*8+x;
if(xs[idx] == 0 && xs[idx-1]%10 < 7){
REP(ty,4) FOR(tx,1,8){
int tidx = ty*8+tx;
if(xs[idx-1]+1 == xs[tidx]){
VI tmp = xs;
swap(tmp[idx], tmp[tidx]);
if(!memo.count(tmp)){
q.emplace(tmp);
memo[tmp] = d + 1;
}
ty = tx = 100;
}
}
}
}
}
cout << ans << endl;
}
return 0;
} |
#include <cstdio>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <climits>
#include <cfloat>
using namespace std;
const int INF = INT_MAX / 2;
map<vector<vector<int> >, int> memo;
vector<vector<int> > goal(4, vector<int>(8, 0));
int solve(vector<vector<int> >& card)
{
if(card == goal)
return 0;
if(memo.find(card) != memo.end())
return memo[card];
int ret = INF;
for(int i=0; i<4; ++i){
for(int j=1; j<8; ++j){
if(card[i][j] != 0)
continue;
for(int k=0; k<4; ++k){
for(int l=1; l<8; ++l){
if(card[i][j-1] + 1 == card[k][l]){
swap(card[i][j], card[k][l]);
ret = min(ret, solve(card) + 1);
swap(card[i][j], card[k][l]);
}
}
}
}
}
return memo[card] = ret;
}
int main()
{
for(int i=0; i<4; ++i){
for(int j=0; j<7; ++j){
goal[i][j] = 11 + i*10 + j;
}
}
int d;
cin >> d;
while(--d >= 0){
vector<vector<int> > card(4, vector<int>(8));
for(int i=0; i<4; ++i){
for(int j=1; j<8; ++j){
cin >> card[i][j];
if(card[i][j] % 10 == 1)
card[i][j] = 0;
}
}
for(int i=0; i<4; ++i)
card[i][0] = 11 + 10 * i;
memo.clear();
int ret = solve(card);
if(ret == INF)
cout << -1 << endl;
else
cout << ret << endl;
}
return 0;
} |
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
const string goal = "1112131415161700212223242526270031323334353637004142434445464700";
const int INF = 100000000;
map<string, int> data;
int solve(string str){
int res = INF;
if(str == goal) return 0;
if(data.find(str) != data.end()) return data[str];
for(int i=2;i<str.size();i+=2){
if(str[i] == '0' && str[i+1] == '0'){
if(str[i-1] == '0' || str[i-1] == '7') continue;
for(int j=2;j<str.size();j+=2){
if(str[j] == str[i-2] && (char)(str[j+1]-1) == str[i-1]){
char a = str[j], b = str[j+1];
str[j] = str[j+1] = '0';
str[i] = a;
str[i+1] = b;
res = min(res, solve(str)+1);
str[i] = str[i+1] = '0';
str[j] = a;
str[j+1] = b;
}
}
}
}
data[str] = res;
return res;
}
int main(){
int T;
cin >> T;
while(T--){
data.clear();
string input;
for(int i=0;i<4;i++){
string tmp = "11";
tmp[0] += i;
input += tmp;
for(int j=0;j<7;j++){
string in;
cin >> in;
if(in[1] == '1') input += "00";
else input += in;
}
}
int ans = solve(input);
if(ans == INF) ans = -1;
cout << ans << endl;
}
} |
#include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
template<class T>
using Table = vector<vector<T>>;
const ld eps=1e-9;
//// < "D:\D_Download\Visual Studio 2015\Projects\programing_contest_c++\Debug\a.txt"
map<vector<vector<int>>, int>mp;
vector<vector<int>>goal;
int getans(const vector<vector<int>>&field) {
if (field == goal)return 0;
auto it = mp.find(field);
if (it != mp.end())return it->second;
else {
int ans = 1e5;
vector<vector<int>>nfield(field);
for (int i = 0; i < 4; ++i) {
for (int j = 1; j < 8; ++j) {
if (!field[i][j]) {
int from = field[i][j - 1];
for (int k = 0; k < 4; ++k) {
for (int l = 0; l < 8; ++l) {
if (nfield[k][l] == from + 1) {
swap(nfield[i][j], nfield[k][l]);
ans = min(getans(nfield) + 1,ans);
swap(nfield[i][j], nfield[k][l]);
}
}
}
}
}
}
return mp[field] = ans;
}
}
int main() {
int N; cin >> N;
while (N--) {
mp.clear();
vector<vector<int>>field(4, vector<int>(8));
goal = field;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 7; ++j) {
goal[i][j] = 10 * (i + 1) + j + 1;
}
}
for (int i = 0; i < 4; ++i) {
field[i][0] = i * 10 + 11;
for (int j = 0; j < 7; ++j) {
int a; cin >> a;
if (a % 10 != 1) {
field[i][j + 1] = a;
}
}
}
int ans = getans(field);
if (ans > 9999)ans = -1;
cout << ans << endl;
}
return 0;
} |
#include <cstdio>
#include <vector>
#include <set>
#include <queue>
using namespace std;
int main(){
vector<char> goal(32);
for(int i = 0; i < 4; ++i){
for(int j = 0; j < 7; ++j){
goal[i * 8 + j] = (i + 1) * 10 + j + 1;
}
}
int n;
for( scanf("%d", &n); n--; ){
int x;
vector<char> v(32);
v[0] = 11;
v[8] = 21;
v[16] = 31;
v[24] = 41;
for(int i = 0; i < 4; ++i){
for(int j = 1; j <= 7; ++j){
scanf("%d", &x);
if( x % 10 != 1 ){
v[i * 8 + j] = x;
}
}
}
queue<vector<char> > q;
q.push(v);
q.push( vector<char>() );
set<vector<char> > st;
st.insert(v);
int t = 0;
while(true){
if( q.size() == 1 ){
t = -1;
break;
}
v = q.front();
q.pop();
if( v.empty() ){
++t;
q.push(v);
continue;
}
if( v == goal ){
break;
}
int pos[48] = {};
for(int i = 0; i < 4; ++i){
for(int j = 0; j <= 7; ++j){
int p = i * 8 + j;
pos[ v[p] ] = p;
}
}
for(int i = 0; i < 4; ++i){
for(int j = 1; j <= 7; ++j){
int p = i * 8 + j;
if( v[p] == 0 && v[p - 1] % 10 != 7 ){
vector<char> v2 = v;
x = v[p - 1];
v2[p] = x + 1;
v2[ pos[x + 1] ] = 0;
if( st.find(v2) == st.end() ){
st.insert(v2);
q.push(v2);
}
}
}
}
}
printf("%d\n", t);
}
} |
#include <iostream>
#include <cstring>
#include <climits>
#include <queue>
#include <unordered_set>
using namespace std;
class State
{
public:
/**
* 表格数字
*/
int table[4][8];
/**
* 移动回数
*/
int turn;
State(int card[4][7])
{
for (int i = 0; i < 4; i++)
table[i][0] = (10 * (i + 1) + 1);// 11 21 31 41
for (int i = 0; i < 4; i++)
{
memcpy(table[i] + 1, card[i], 7 * sizeof(int));
}
// 从这种布局开始游戏
for (int i = 0; i < 4; i++)
{
for (int j = 1; j < 8; j++)
{
if (table[i][j] == 11 || table[i][j] == 21 || table[i][j] == 31 || table[i][j] == 41)
table[i][j] = 0;
}
}
turn = 0;
}
State(const State &t)
{
memcpy(table, t.table, sizeof(table));
turn = t.turn;
}
/**
* 可以填充空白
* @param x
* @param y
* @return
*/
bool can_fill_gap(int x, int y)
{
if (table[x][y] != 0)
return false;
else if (table[x][y - 1] == 0 || (table[x][y - 1]) % 10 == 7) // x7 has no successor
return false;
else
return true;
}
/**
* 填充空白
* @param x
* @param y
*/
void fill_gap(int x, int y)
{
int s, sx, sy;
sx = sy = -1;
s = table[x][y - 1] + 1;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 8; j++)
{
if (table[i][j] == s)
{
sx = i;
sy = j;
}
}
}
table[x][y] = table[sx][sy];
table[sx][sy] = 0;
turn++;
}
/**
* 是否是游戏结束状态,即每行都是升序,最后一列全为0
* @return
*/
bool done()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 7; j++)
{
if (table[i][j] != (10 * (i + 1) + (j + 1)))
return false;
}
if (table[i][7] != 0)
return false;
}
return true;
}
bool operator==(const State &s) const
{
int i, j;
for (i = 0; i < 4; i++)
{
for (j = 1; j < 8; j++)
{
if (table[i][j] != s.table[i][j])
return false;
}
}
return true;
}
};
struct StateHash
{
size_t operator()(const State &s) const
{
size_t hash = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 1; j < 8; j++)
{
hash += s.table[i][j];
hash <<= 1;
}
}
return hash;
}
};
int solve(int card[4][7])
{
queue<State> que;
unordered_set<State, StateHash> visited;
//准备BFS
bool end = false;
int ans = INT_MAX;
State init(card);
if (init.done())
return 0;
que.push(init);
visited.insert(init);
//BFS
while (!que.empty() && !end)
{
State s = que.front();
que.pop();
for (int i = 0; i < 4; i++)
{
for (int j = 1; j < 8; j++)
{
if (s.can_fill_gap(i, j))
{
State temp(s);
temp.fill_gap(i, j);
// 结束
if (temp.done())
{
end = true;
ans = temp.turn;
}// 未遍历
else if (visited.find(temp) == visited.end())
{
que.push(temp);
visited.insert(temp);
}
}
}
}
}
if (ans == INT_MAX)
ans = -1;
return ans;
}
int main()
{
int n;
scanf("%d", &n);
while (n--)
{
int card[4][7];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 7; ++j)
{
scanf("%d", &card[i][j]);
}
}
printf("%d\n", solve(card));
}
return 0;
}
|
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <utility>
#include <set>
#include <cctype>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
using namespace std;
#define INF 100000000
typedef long long ll;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};
class P {
public:
int cost;
vector<int> v, pos, gap;
P() {}
P(int cost, vector<int> v, vector<int> pos, vector<int> gap) : cost(cost), v(v), pos(pos), gap(gap) {}
bool goal(vector<int> &v);
};
bool goal(vector<int> &v) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 7; j++) {
int idx = i*8+j;
if (v[idx] / 10 != i+1 || v[idx] % 10 != j+1) return false;
}
}
return true;
}
int bfs(P start) {
queue<P> open;
set<vector<int> > closed;
open.push(start);
closed.insert(start.v);
while (!open.empty()) {
P p = open.front(); open.pop();
for (int i = 0; i < 4; i++) {
vector<int> nv = p.v;
vector<int> npos = p.pos;
vector<int> ngap = p.gap;
int idx = ngap[i];
int val = nv[idx-1] + 1;
if (npos[val] == 0) continue;
nv[idx] = val;
nv[npos[val]] = 0;
ngap[i] = npos[val];
npos[val] = idx;
if (closed.find(nv) != closed.end()) continue;
closed.insert(nv);
if (goal(nv)) {
return p.cost+1;
}
open.push(P(p.cost+1, nv, npos, ngap));
}
}
return -1;
}
int main() {
int T;
cin >> T;
while (T--) {
vector<int> v(32);
vector<int> pos(50);
vector<int> gap;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 7; j++) {
int idx = i*8+j+1;
cin >> v[idx];
if (v[idx] % 10 == 1) {
int row = v[idx] / 10 - 1;
v[row*8] = v[idx];
v[idx] = 0;
gap.push_back(idx);
} else {
pos[v[idx]] = idx;
}
}
}
printf("%d\n", goal(v) ? 0 : bfs(P(0, v, pos, gap)));
}
} |
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
using namespace std;
typedef istringstream ISS;
typedef ostringstream OSS;
typedef vector<string> VS;
typedef vector<int> VI;
typedef vector<VI> VVI;
template<class T> T gcd( T a, T b ) {
return !b ? a : gcd( b, a % b );
}
template<class T> T lcm( T a, T b ) {
return a / gcd( a, b ) * b;
}
template<class T> string print_v( vector<T> v ) {
OSS oss;
for ( typename vector<T>::iterator it_i = v.begin(); it_i != v.end();
++it_i ) {
oss << *it_i << ", ";
}
return oss.str();
}
const int NONE = -1;
// 1ツづつづ?づ?つサツつアツづ可禿シツづゥツづ猟つォツ要ツ素ツつェツつ?づゥツ凝ウツつ「ツづ?づゥツセツδ仰つェツつ?づ?つスツづァ
// ツつサツつアツづ可つサツづ個要ツ素ツづーツ禿シツづェツづゥ
// 1ツづつづ?個ゥツづつつゥツづァツづ按つゥツづ?つスツ湘ェツ債?づ債、ツ催?渉可づ可個ゥツづつつゥツづ?つス
// ツ暗。ツつ、ツ湘ェツ渉環づ可置ツつ「ツづ?つ?づゥツ要ツ素ツづーツ右ツ端ツづ可篠敖づ?づ?つ「ツつュ
bool check( VVI& T ) {
for ( int i = 0; i < 4; ++ i ) {
for ( int j = 0; j < 7; ++ j ) {
if ( T[i][j] != ( i + 1 ) * 10 + j + 1 ) return false;
}
}
for ( int i = 0; i < 4; ++ i ) {
if ( T[i][7] != NONE ) return false;
}
return true;
}
typedef pair <int, VVI> NODE;
typedef queue <NODE> QUEUE;
void print( VVI T ) {
for ( int i = 0; i < 4; ++ i ) {
for ( int j = 0; j < 8; ++ j ) {
cout << T[i][j] << ",";
}
cout << endl;
}
cout << endl;
}
int solve( VVI T ) {
QUEUE Q;
Q.push( NODE( 0, T ) );
set <VVI> H;
H.insert( T );
while ( ! Q.empty() ) {
NODE node = Q.front();
Q.pop();
int step = node.first;
VVI table = node.second;
// cout << "test: " << endl;
// print( table );
if ( check( table ) ) return step;
for ( int r = 0; r < 4; ++ r ) {
for ( int c = 1; c < 8; ++ c ) {
if ( table[r][c] != NONE ) continue;
for ( int i = 0; i < 4; ++ i ) {
for ( int j = 1; j < 8; ++ j ) {
if ( table[r][c-1] + 1 != table[i][j] ) continue;
VVI to = table;
to[r][c] = table[i][j];
to[i][j] = NONE;
if ( H.count( to ) ) goto out;
H.insert( to );
Q.push( NODE( step + 1, to ) );
if ( table[r][c-1] + 1 == table[i][j] ) goto out;
}
}
out:;
}
}
}
return -1;
}
int main() {
int n;
cin >> n;
for ( int lpc = 0; lpc < n; ++ lpc ) {
VVI T( 4, VI( 8, NONE ) );
for ( int i = 0; i < 4; ++ i ) {
for ( int j = 0; j < 7; ++ j ) {
cin >> T[i][j+1];
if ( T[i][j+1] % 10 == 1 ) {
T[i][j+1] = NONE;
}
}
}
for ( int i = 0; i < 4; ++ i ) {
T[i][0] = 10 * ( i + 1 ) + 1;
}
cout << solve( T ) << endl;
}
return 0;
} |
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <queue>
using namespace std;
const string res = "1112131415161700212223242526270031323334353637004142434445464700";
string str;
vector<int> pt;
map<string, bool> mpp;
class St{
public:
int cnt;
string st;
vector<int> vec;
St() {}
St(int _cnt, string _st, vector<int> _vec): cnt(_cnt), st(_st), vec(_vec) {}
};
string conv(int n)
{
stringstream ss;
ss << n;
return ss.str();
}
void func(vector<vector<int> > vec)
{
int t;
str = "";
for(int i = 0; i < 4; ++i){
str += "00";
for(int j = 0; j < 7; ++j) str += conv(vec[i][j]);
}
for(int i = 0; i < 4; ++i)
for(int j = 1; j < 8; ++j)
if(vec[i][j-1]%10 == 1){
t = ((int)(vec[i][j-1]/10)-1)*2*8;
str[t] = str[i*2*8+j*2];
str[t+1] = str[i*2*8+j*2+1];
str[i*2*8+j*2] = '0';
str[i*2*8+j*2+1] = '0';
pt.push_back((i*8*2+j*2));
}
}
int check(string s, char c1, char c2)
{
for(int i = 0; i < 4; ++i)
for(int j = 0, p = i*8*2; j < 8; ++j)
if(s[p+j*2] == c1 && s[p+j*2+1] == c2) return (p+j*2);
return 0;
}
int bfs()
{
queue<St> que;
que.push(St(0, str, pt));
mpp[str] = true;
St st;
int p, q;
char c1, c2;
string s;
vector<int> v;
while(!que.empty()){
st = que.front();
que.pop();
if(st.st == res) return st.cnt;
for(int i = 0; i < 4; ++i){
q = st.vec[i];
c1 = st.st[q-2];
c2 = (char)(st.st[q-1]+1);
if(c2 == '8') continue;
p = check(st.st, c1, c2);
if(p == 0) continue;
s = st.st;
s[q] = c1;
s[q+1] = c2;
s[p] = s[p+1] = '0';
st.vec[i] = p;
if(!mpp[s]){
mpp[s] = true;
que.push(St(st.cnt+1, s, st.vec));
}
st.vec[i] = q;
}
}
return -1;
}
int main()
{
int n, t;
vector<vector<int> > vec;
while(cin>>n)
while(n--){
vec = vector<vector<int> >(4);
for(int i = 0; i < 4; ++i){
vec[i] = vector<int>(7);
for(int j = 0; j < 7; ++j) cin >> vec[i][j];
}
func(vec);
vec.clear();
cout << bfs() << endl;
mpp.clear();
pt.clear();
}
return 0;
} |
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<climits>
#include<algorithm>
#include<vector>
#include<complex>
#include<cassert>
#define REP(i,s,n) for(int i=s;i<n;++i)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-9)
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
using namespace std;
// BEGIN - Library
bool LT(double a,double b) { return !equals(a,b) && a < b; }
bool LTE(double a,double b) { return equals(a,b) || a < b; }
class Point{
public:
double x,y;
Point(double x = 0,double y = 0): x(x),y(y){}
Point operator + (Point p){return Point(x+p.x,y+p.y);}
Point operator - (Point p){return Point(x-p.x,y-p.y);}
Point operator * (double a){return Point(a*x,a*y);}
Point operator / (double a){return Point(x/a,y/a);}
Point operator * (Point a){ return Point(x * a.x - y * a.y, x * a.y + y * a.x); }
bool operator < (const Point& p) const{ return !equals(x,p.x)?x<p.x:(!equals(y,p.y)&&y<p.y); }
bool operator == (const Point& p)const{ return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS; }
};
struct Segment{
Point p1,p2;
Segment(Point p1 = Point(),Point p2 = Point()):p1(p1),p2(p2){}
bool operator < (const Segment& s) const { return ( p2 == s.p2 ) ? p1 < s.p1 : p2 < s.p2; }
bool operator == (const Segment& s) const { return ( s.p1 == p1 && s.p2 == p2 ) || ( s.p1 == p2 && s.p2 == p1 ); }
};
typedef Point Vector;
typedef Segment Line;
typedef vector<Point> Polygon;
ostream& operator << (ostream& os,const Point& a){ return os << "(" << a.x << "," << a.y << ")"; }
ostream& operator << (ostream& os,const Segment& a){ return os << "( " << a.p1 << " , " << a.p2 << " )"; }
double dot(Point a,Point b){ return a.x*b.x + a.y*b.y; }
double cross(Point a,Point b){ return a.x*b.y - a.y*b.x; }
double norm(Point a){ return a.x*a.x+a.y*a.y; }
double abs(Point a){ return sqrt(norm(a)); }
//rad ????§???????????????¢?????§?????????????????¨
Point rotate(Point a,double rad){ return Point(cos(rad)*a.x - sin(rad)*a.y,sin(rad)*a.x + cos(rad)*a.y); }
// ??????????????¢????????????
double toRad(double agl){ return agl*M_PI/180.0; }
// a => prev, b => cur, c=> next
// prev ?????? cur ????????£??? next ????????????????§????????±???????
double getArg(Point a,Point b,Point c){
double arg1 = atan2(b.y-a.y,b.x-a.x);
double arg2 = atan2(c.y-b.y,c.x-b.x);
double arg = fabs( arg1 - arg2 );
while( arg > M_PI ) arg -= 2.0 * M_PI;
return fabs(arg);
}
int ccw(Point p0,Point p1,Point p2){
Point a = p1-p0;
Point b = p2-p0;
if(cross(a,b) > EPS)return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS)return CLOCKWISE;
if(dot(a,b) < -EPS)return ONLINE_BACK;
if(norm(a) < norm(b))return ONLINE_FRONT;
return ON_SEGMENT;
}
bool intersectLL(Line l, Line m) {
return abs(cross(l.p2-l.p1, m.p2-m.p1)) > EPS || // non-parallel
abs(cross(l.p2-l.p1, m.p1-l.p1)) < EPS; // same line
}
bool intersectLS(Line l, Line s) {
return cross(l.p2-l.p1, s.p1-l.p1)* // s[0] is left of l
cross(l.p2-l.p1, s.p2-l.p1) < EPS; // s[1] is right of l
}
bool intersectLP(Line l,Point p) {
return abs(cross(l.p2-p, l.p1-p)) < EPS;
}
bool intersectSS(Line s, Line t) {
return ccw(s.p1,s.p2,t.p1)*ccw(s.p1,s.p2,t.p2) <= 0 &&
ccw(t.p1,t.p2,s.p1)*ccw(t.p1,t.p2,s.p2) <= 0;
}
bool intersectSP(Line s, Point p) {
return abs(s.p1-p)+abs(s.p2-p)-abs(s.p2-s.p1) < EPS; // triangle inequality
}
Point projection(Line l,Point p) {
double t = dot(p-l.p1, l.p1-l.p2) / norm(l.p1-l.p2);
return l.p1 + (l.p1-l.p2)*t;
}
Point reflection(Line l,Point p) {
return p + (projection(l, p) - p) * 2;
}
double distanceLP(Line l, Point p) {
return abs(p - projection(l, p));
}
double distanceLL(Line l, Line m) {
return intersectLL(l, m) ? 0 : distanceLP(l, m.p1);
}
double distanceLS(Line l, Line s) {
if (intersectLS(l, s)) return 0;
return min(distanceLP(l, s.p1), distanceLP(l, s.p2));
}
double distanceSP(Line s, Point p) {
Point r = projection(s, p);
if (intersectSP(s, r)) return abs(r - p);
return min(abs(s.p1 - p), abs(s.p2 - p));
}
double distanceSS(Line s, Line t) {
if (intersectSS(s, t)) return 0;
return min(min(distanceSP(s, t.p1), distanceSP(s, t.p2)),
min(distanceSP(t, s.p1), distanceSP(t, s.p2)));
}
Point crosspoint(Line l,Line m){
double A = cross(l.p2-l.p1,m.p2-m.p1);
double B = cross(l.p2-l.p1,l.p2-m.p1);
if(abs(A) < EPS && abs(B) < EPS){
vector<Point> vec;
vec.push_back(l.p1),vec.push_back(l.p2),vec.push_back(m.p1),vec.push_back(m.p2);
sort(vec.begin(),vec.end());
assert(vec[1] == vec[2]); //???????????°??????????????????
return vec[1];
//return m.p1;
}
if(abs(A) < EPS)assert(false);
return m.p1 + (m.p2-m.p1)*(B/A);
}
//cross product of pq and pr
double cross3p(Point p,Point q,Point r) { return (r.x-q.x) * (p.y -q.y) - (r.y - q.y) * (p.x - q.x); }
//returns true if point r is on the same line as the line pq
bool collinear(Point p,Point q,Point r) { return fabs(cross3p(p,q,r)) < EPS; }
//returns true if point t is on the left side of line pq
bool ccwtest(Point p,Point q,Point r){
return cross3p(p,q,r) > 0; //can be modified to accept collinear points
}
bool onSegment(Point p,Point q,Point r){
return collinear(p,q,r) && equals(sqrt(pow(p.x-r.x,2)+pow(p.y-r.y,2)) + sqrt(pow(r.x-q.x,2) + pow(r.y-q.y,2) ),sqrt(pow(p.x-q.x,2)+pow(p.y-q.y,2)) ) ;
}
double getArea(vector<Point>& vec) {
double sum = 0;
for(int i=0;i<vec.size();i++)
sum += cross(vec[i],vec[(i+1)%vec.size()]);
return fabs(sum)/2.0;
}
typedef pair<double,double> dd;
const double DINF = 1e20;
#define pow2(a) ((a)*(a))
dd calc(double x1,double y1,double vx1,double vy1,
double x2,double y2,double vx2,double vy2,double r){
double VX = (vx1-vx2), X = (x1-x2), VY = (vy1-vy2), Y = (y1-y2);
double a = pow2(VX) + pow2(VY), b = 2*(X*VX+Y*VY), c = pow2(X) + pow2(Y) - pow2(r);
dd ret = dd(DINF,DINF);
double D = b*b - 4 * a * c;
if( LT(D,0.0) ) return ret;
if( equals(a,0.0) ) {
if( equals(b,0.0) ) return ret;
if( LT(-c/b,0.0) ) return ret;
ret.first = - c / b;
return ret;
}
if( equals(D,0.0) ) D = 0;
ret.first = ( -b - sqrt( D ) ) / ( 2 * a );
ret.second = ( -b + sqrt( D ) ) / ( 2 * a );
if( !equals(ret.first,ret.second) && ret.first > ret.second ) swap(ret.first,ret.second);
return ret;
}
const Point ZERO = Point(0,0);
//??????AB??¨?????????cp,??????r????????¨?????±?????¨????????¢???????±???????
inline double calculator_TypeA(Point A,Point B,Point cp,double r){
A = A - cp, B = B - cp;
if( A == ZERO || B == ZERO ) return 0;
double cross_value = cross(A,B);
if( equals(cross_value,0.0) ) return 0;
double sig = LT(cross_value,0.0) ? -1 : 1;
Segment AB = Segment(A,B);
double nearest_distance = distanceLP(AB,ZERO);
double distance_OA = abs(A);
double distance_OB = abs(B);
if( LTE(0.0,r-distance_OA) && LTE(0.0,r-distance_OB) && LTE(0.0,r-nearest_distance) ) {
return sig * fabs( cross_value / 2.0 );
} else if( LTE(0.0,distance_OA-r) && LTE(0.0,distance_OB-r) && LTE(0.0,nearest_distance-r) ) {
return sig * ( r * r * (M_PI-getArg(A,ZERO,B)) ) / 2.0;
} else if( LTE(0.0,distance_OA-r) && LTE(0.0,distance_OB-r) && LT(0.0,r-nearest_distance) ) {
Point proj_p = projection(AB,ZERO);
if( onSegment(AB.p1,AB.p2,proj_p) ) {
Vector e = ( A - B ) / abs( A - B );
dd tmp = calc(A.x,A.y,e.x,e.y,0,0,0,0,r);
Point r_p1 = A + e * tmp.first;
Point r_p2 = A + e * tmp.second;
double ret = r * r * (M_PI-getArg(B,ZERO,A)) / 2.0;
double subtract = r * r * (M_PI-getArg(r_p1,ZERO,r_p2)) / 2.0 - fabs(cross(r_p1,r_p2))/2.0 ;
return sig * ( ret - subtract );
} else {
return sig * ( r * r * (M_PI-getArg(B,ZERO,A)) ) / 2.0;
}
} else {
if( LT(distance_OB-r,0.0) ) swap(A,B);
Vector e = ( A - B ) / abs( A - B );
dd tmp = calc(A.x,A.y,e.x,e.y,0,0,0,0,r);
Point r_p1 = A + e * tmp.first;
Point r_p2 = A + e * tmp.second;
if( onSegment(A,B,r_p2) ) r_p1 = r_p2;
double ret = fabs(cross(r_p1,A)) * 0.5;
ret += r * r * (M_PI-getArg(r_p1,ZERO,B)) * 0.5;
return sig * ret;
}
assert(false);
}
double getCommonAreaPolygonCircle(const Polygon &poly,Point cp,double r){
double sum = 0;
rep(i,(int)poly.size()){
sum += calculator_TypeA(poly[i],poly[(i+1)%(int)poly.size()],cp,r);
}
return fabs(sum);
}
Polygon andrewScan(Polygon s) {
Polygon u,l;
if(s.size() < 3)return s;
sort(s.begin(),s.end());
u.push_back(s[0]);
u.push_back(s[1]);
l.push_back(s[s.size()-1]);
l.push_back(s[s.size()-2]);
for(int i=2;i<(int)s.size();i++)
{
for(int n=u.size();n >= 2 && ccw(u[n-2],u[n-1],s[i]) != CLOCKWISE; n--)
u.pop_back();
u.push_back(s[i]);
}
for(int i=s.size()-3; i>=0 ; i--)
{
for(int n=l.size(); n >= 2 && ccw(l[n-2],l[n-1],s[i]) != CLOCKWISE; n--)
l.pop_back();
l.push_back(s[i]);
}
reverse(l.begin(),l.end());
for(int i = u.size()-2; i >= 1; i--) l.push_back(u[i]);
return l;
}
Point calc_ps(Polygon poly) {
poly = andrewScan(poly);
Point mp = poly[0];
double rate = 1; // 0.5???????????¨???
int max_pos;
double eps = 1e-10; // 1e-20???????????¨???
while( rate > eps ) {
rep(_,60){ // 70???????????¨???
max_pos = 0;
REP(j,1,(int)poly.size()) {
double dist1 = abs(mp-poly[max_pos]);
double dist2 = abs(mp-poly[j]);
if( LT(dist1,dist2) ) max_pos = j;
}
mp.x += ( poly[max_pos].x - mp.x ) * rate;
mp.y += ( poly[max_pos].y - mp.y ) * rate;
}
rate *= 0.5;
}
return mp;
}
Point getCentroidOfConvex(Polygon& poly){
double area = getArea(poly);
int V = poly.size();
assert( !equals(area,0.0) );
double x = 0, y = 0;
rep(i,(int)poly.size()) {
x += ( poly[i].x + poly[(i+1)%V].x ) * ( poly[i].x*poly[(i+1)%V].y - poly[(i+1)%V].x*poly[i].y );
y += ( poly[i].y + poly[(i+1)%V].y ) * ( poly[i].x*poly[(i+1)%V].y - poly[(i+1)%V].x*poly[i].y );
}
return Point(x/(6.0*area),y/(6.0*area));
}
// END - Library
int n,r;
Polygon poly;
void compute() {
double maxi;
Point mp = calc_ps(poly);
maxi = getCommonAreaPolygonCircle(poly,mp,r);
double rate = 1.0;
double eps = 1e-10;
while( LT(eps,rate) ) {
rep(_,70) {
double max_area = -1;
Point np;
rep(i,n) {
Point tp = mp;
tp.x += ( poly[i].x - mp.x ) * rate;
tp.y += ( poly[i].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,tp,r);
if( LT(max_area,area) ) {
max_area = area;
np = tp;
}
}
assert( !equals(max_area,-1) );
mp = np;
if( LT(maxi,max_area) ) maxi = max_area;
}
rate *= 0.5;
}
rep(__,10) {
Point mp = calc_ps(poly);
double rate = 1.0;
double eps = 1e-10;
while( LT(eps,rate) ) {
rep(_,70) {
double max_area = -1;
Point np;
rep(i,n) {
Point tp = mp;
tp.x += ( poly[i].x - mp.x ) * rate;
tp.y += ( poly[i].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,tp,r);
if( LT(max_area,area) ) {
max_area = area;
np = tp;
}
}
if( rand() % 50 == 0 ) {
int v = rand() % n;
np.x = ( poly[v].x - mp.x ) * rate;
np.y = ( poly[v].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,np,r);
if( LT(max_area,area) ) {
max_area = area;
}
}
assert( !equals(max_area,-1) );
mp = np;
if( LT(maxi,max_area) ) maxi = max_area;
}
rate *= 0.5;
}
}
printf("%.10f\n",maxi);
}
int main() {
srand((unsigned int)time(NULL));
cin >> n >> r;
poly.resize(n);
rep(i,n) cin >> poly[i].x >> poly[i].y;
//cout << getArea(poly) << endl;
compute();
return 0;
} |
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<climits>
#include<algorithm>
#include<vector>
#include<complex>
#include<cassert>
#define REP(i,s,n) for(int i=s;i<n;++i)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-9)
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
using namespace std;
// BEGIN - Library
bool LT(double a,double b) { return !equals(a,b) && a < b; }
bool LTE(double a,double b) { return equals(a,b) || a < b; }
class Point{
public:
double x,y;
Point(double x = 0,double y = 0): x(x),y(y){}
Point operator + (Point p){return Point(x+p.x,y+p.y);}
Point operator - (Point p){return Point(x-p.x,y-p.y);}
Point operator * (double a){return Point(a*x,a*y);}
Point operator / (double a){return Point(x/a,y/a);}
Point operator * (Point a){ return Point(x * a.x - y * a.y, x * a.y + y * a.x); }
bool operator < (const Point& p) const{ return !equals(x,p.x)?x<p.x:(!equals(y,p.y)&&y<p.y); }
bool operator == (const Point& p)const{ return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS; }
};
struct Segment{
Point p1,p2;
Segment(Point p1 = Point(),Point p2 = Point()):p1(p1),p2(p2){}
bool operator < (const Segment& s) const { return ( p2 == s.p2 ) ? p1 < s.p1 : p2 < s.p2; }
bool operator == (const Segment& s) const { return ( s.p1 == p1 && s.p2 == p2 ) || ( s.p1 == p2 && s.p2 == p1 ); }
};
typedef Point Vector;
typedef Segment Line;
typedef vector<Point> Polygon;
ostream& operator << (ostream& os,const Point& a){ return os << "(" << a.x << "," << a.y << ")"; }
ostream& operator << (ostream& os,const Segment& a){ return os << "( " << a.p1 << " , " << a.p2 << " )"; }
double dot(Point a,Point b){ return a.x*b.x + a.y*b.y; }
double cross(Point a,Point b){ return a.x*b.y - a.y*b.x; }
double norm(Point a){ return a.x*a.x+a.y*a.y; }
double abs(Point a){ return sqrt(norm(a)); }
//rad ????§???????????????¢?????§?????????????????¨
Point rotate(Point a,double rad){ return Point(cos(rad)*a.x - sin(rad)*a.y,sin(rad)*a.x + cos(rad)*a.y); }
// ??????????????¢????????????
double toRad(double agl){ return agl*M_PI/180.0; }
// a => prev, b => cur, c=> next
// prev ?????? cur ????????£??? next ????????????????§????????±???????
double getArg(Point a,Point b,Point c){
double arg1 = atan2(b.y-a.y,b.x-a.x);
double arg2 = atan2(c.y-b.y,c.x-b.x);
double arg = fabs( arg1 - arg2 );
while( arg > M_PI ) arg -= 2.0 * M_PI;
return fabs(arg);
}
int ccw(Point p0,Point p1,Point p2){
Point a = p1-p0;
Point b = p2-p0;
if(cross(a,b) > EPS)return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS)return CLOCKWISE;
if(dot(a,b) < -EPS)return ONLINE_BACK;
if(norm(a) < norm(b))return ONLINE_FRONT;
return ON_SEGMENT;
}
bool intersectLL(Line l, Line m) {
return abs(cross(l.p2-l.p1, m.p2-m.p1)) > EPS || // non-parallel
abs(cross(l.p2-l.p1, m.p1-l.p1)) < EPS; // same line
}
bool intersectLS(Line l, Line s) {
return cross(l.p2-l.p1, s.p1-l.p1)* // s[0] is left of l
cross(l.p2-l.p1, s.p2-l.p1) < EPS; // s[1] is right of l
}
bool intersectLP(Line l,Point p) {
return abs(cross(l.p2-p, l.p1-p)) < EPS;
}
bool intersectSS(Line s, Line t) {
return ccw(s.p1,s.p2,t.p1)*ccw(s.p1,s.p2,t.p2) <= 0 &&
ccw(t.p1,t.p2,s.p1)*ccw(t.p1,t.p2,s.p2) <= 0;
}
bool intersectSP(Line s, Point p) {
return abs(s.p1-p)+abs(s.p2-p)-abs(s.p2-s.p1) < EPS; // triangle inequality
}
Point projection(Line l,Point p) {
double t = dot(p-l.p1, l.p1-l.p2) / norm(l.p1-l.p2);
return l.p1 + (l.p1-l.p2)*t;
}
Point reflection(Line l,Point p) {
return p + (projection(l, p) - p) * 2;
}
double distanceLP(Line l, Point p) {
return abs(p - projection(l, p));
}
double distanceLL(Line l, Line m) {
return intersectLL(l, m) ? 0 : distanceLP(l, m.p1);
}
double distanceLS(Line l, Line s) {
if (intersectLS(l, s)) return 0;
return min(distanceLP(l, s.p1), distanceLP(l, s.p2));
}
double distanceSP(Line s, Point p) {
Point r = projection(s, p);
if (intersectSP(s, r)) return abs(r - p);
return min(abs(s.p1 - p), abs(s.p2 - p));
}
double distanceSS(Line s, Line t) {
if (intersectSS(s, t)) return 0;
return min(min(distanceSP(s, t.p1), distanceSP(s, t.p2)),
min(distanceSP(t, s.p1), distanceSP(t, s.p2)));
}
Point crosspoint(Line l,Line m){
double A = cross(l.p2-l.p1,m.p2-m.p1);
double B = cross(l.p2-l.p1,l.p2-m.p1);
if(abs(A) < EPS && abs(B) < EPS){
vector<Point> vec;
vec.push_back(l.p1),vec.push_back(l.p2),vec.push_back(m.p1),vec.push_back(m.p2);
sort(vec.begin(),vec.end());
assert(vec[1] == vec[2]); //???????????°??????????????????
return vec[1];
//return m.p1;
}
if(abs(A) < EPS)assert(false);
return m.p1 + (m.p2-m.p1)*(B/A);
}
//cross product of pq and pr
double cross3p(Point p,Point q,Point r) { return (r.x-q.x) * (p.y -q.y) - (r.y - q.y) * (p.x - q.x); }
//returns true if point r is on the same line as the line pq
bool collinear(Point p,Point q,Point r) { return fabs(cross3p(p,q,r)) < EPS; }
//returns true if point t is on the left side of line pq
bool ccwtest(Point p,Point q,Point r){
return cross3p(p,q,r) > 0; //can be modified to accept collinear points
}
bool onSegment(Point p,Point q,Point r){
return collinear(p,q,r) && equals(sqrt(pow(p.x-r.x,2)+pow(p.y-r.y,2)) + sqrt(pow(r.x-q.x,2) + pow(r.y-q.y,2) ),sqrt(pow(p.x-q.x,2)+pow(p.y-q.y,2)) ) ;
}
double getArea(vector<Point>& vec) {
double sum = 0;
for(int i=0;i<vec.size();i++)
sum += cross(vec[i],vec[(i+1)%vec.size()]);
return fabs(sum)/2.0;
}
typedef pair<double,double> dd;
const double DINF = 1e20;
#define pow2(a) ((a)*(a))
dd calc(double x1,double y1,double vx1,double vy1,
double x2,double y2,double vx2,double vy2,double r){
double VX = (vx1-vx2), X = (x1-x2), VY = (vy1-vy2), Y = (y1-y2);
double a = pow2(VX) + pow2(VY), b = 2*(X*VX+Y*VY), c = pow2(X) + pow2(Y) - pow2(r);
dd ret = dd(DINF,DINF);
double D = b*b - 4 * a * c;
if( LT(D,0.0) ) return ret;
if( equals(a,0.0) ) {
if( equals(b,0.0) ) return ret;
if( LT(-c/b,0.0) ) return ret;
ret.first = - c / b;
return ret;
}
if( equals(D,0.0) ) D = 0;
ret.first = ( -b - sqrt( D ) ) / ( 2 * a );
ret.second = ( -b + sqrt( D ) ) / ( 2 * a );
if( !equals(ret.first,ret.second) && ret.first > ret.second ) swap(ret.first,ret.second);
return ret;
}
const Point ZERO = Point(0,0);
//??????AB??¨?????????cp,??????r????????¨?????±?????¨????????¢???????±???????
inline double calculator_TypeA(Point A,Point B,Point cp,double r){
A = A - cp, B = B - cp;
if( A == ZERO || B == ZERO ) return 0;
double cross_value = cross(A,B);
if( equals(cross_value,0.0) ) return 0;
double sig = LT(cross_value,0.0) ? -1 : 1;
Segment AB = Segment(A,B);
double nearest_distance = distanceLP(AB,ZERO);
double distance_OA = abs(A);
double distance_OB = abs(B);
if( LTE(0.0,r-distance_OA) && LTE(0.0,r-distance_OB) && LTE(0.0,r-nearest_distance) ) {
return sig * fabs( cross_value / 2.0 );
} else if( LTE(0.0,distance_OA-r) && LTE(0.0,distance_OB-r) && LTE(0.0,nearest_distance-r) ) {
return sig * ( r * r * (M_PI-getArg(A,ZERO,B)) ) / 2.0;
} else if( LTE(0.0,distance_OA-r) && LTE(0.0,distance_OB-r) && LT(0.0,r-nearest_distance) ) {
Point proj_p = projection(AB,ZERO);
if( onSegment(AB.p1,AB.p2,proj_p) ) {
Vector e = ( A - B ) / abs( A - B );
dd tmp = calc(A.x,A.y,e.x,e.y,0,0,0,0,r);
Point r_p1 = A + e * tmp.first;
Point r_p2 = A + e * tmp.second;
double ret = r * r * (M_PI-getArg(B,ZERO,A)) / 2.0;
double subtract = r * r * (M_PI-getArg(r_p1,ZERO,r_p2)) / 2.0 - fabs(cross(r_p1,r_p2))/2.0 ;
return sig * ( ret - subtract );
} else {
return sig * ( r * r * (M_PI-getArg(B,ZERO,A)) ) / 2.0;
}
} else {
if( LT(distance_OB-r,0.0) ) swap(A,B);
Vector e = ( A - B ) / abs( A - B );
dd tmp = calc(A.x,A.y,e.x,e.y,0,0,0,0,r);
Point r_p1 = A + e * tmp.first;
Point r_p2 = A + e * tmp.second;
if( onSegment(A,B,r_p2) ) r_p1 = r_p2;
double ret = fabs(cross(r_p1,A)) * 0.5;
ret += r * r * (M_PI-getArg(r_p1,ZERO,B)) * 0.5;
return sig * ret;
}
assert(false);
}
double getCommonAreaPolygonCircle(const Polygon &poly,Point cp,double r){
double sum = 0;
rep(i,(int)poly.size()){
sum += calculator_TypeA(poly[i],poly[(i+1)%(int)poly.size()],cp,r);
}
return fabs(sum);
}
Polygon andrewScan(Polygon s) {
Polygon u,l;
if(s.size() < 3)return s;
sort(s.begin(),s.end());
u.push_back(s[0]);
u.push_back(s[1]);
l.push_back(s[s.size()-1]);
l.push_back(s[s.size()-2]);
for(int i=2;i<(int)s.size();i++)
{
for(int n=u.size();n >= 2 && ccw(u[n-2],u[n-1],s[i]) != CLOCKWISE; n--)
u.pop_back();
u.push_back(s[i]);
}
for(int i=s.size()-3; i>=0 ; i--)
{
for(int n=l.size(); n >= 2 && ccw(l[n-2],l[n-1],s[i]) != CLOCKWISE; n--)
l.pop_back();
l.push_back(s[i]);
}
reverse(l.begin(),l.end());
for(int i = u.size()-2; i >= 1; i--) l.push_back(u[i]);
return l;
}
Point calc_ps(Polygon poly) {
poly = andrewScan(poly);
Point mp = poly[0];
double rate = 1; // 0.5???????????¨???
int max_pos;
double eps = 1e-10; // 1e-20???????????¨???
while( rate > eps ) {
rep(_,60){ // 70???????????¨???
max_pos = 0;
REP(j,1,(int)poly.size()) {
double dist1 = abs(mp-poly[max_pos]);
double dist2 = abs(mp-poly[j]);
if( LT(dist1,dist2) ) max_pos = j;
}
mp.x += ( poly[max_pos].x - mp.x ) * rate;
mp.y += ( poly[max_pos].y - mp.y ) * rate;
}
rate *= 0.5;
}
return mp;
}
Point getCentroidOfConvex(Polygon& poly){
double area = getArea(poly);
int V = poly.size();
assert( !equals(area,0.0) );
double x = 0, y = 0;
rep(i,(int)poly.size()) {
x += ( poly[i].x + poly[(i+1)%V].x ) * ( poly[i].x*poly[(i+1)%V].y - poly[(i+1)%V].x*poly[i].y );
y += ( poly[i].y + poly[(i+1)%V].y ) * ( poly[i].x*poly[(i+1)%V].y - poly[(i+1)%V].x*poly[i].y );
}
return Point(x/(6.0*area),y/(6.0*area));
}
// END - Library
int n,r;
Polygon poly;
void compute() {
double maxi;
Point mp = calc_ps(poly);
maxi = getCommonAreaPolygonCircle(poly,mp,r);
double rate = 1.0;
double eps = 1e-10;
while( LT(eps,rate) ) {
rep(_,70) {
double max_area = -1;
Point np;
rep(i,n) {
Point tp = mp;
tp.x += ( poly[i].x - mp.x ) * rate;
tp.y += ( poly[i].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,tp,r);
if( LT(max_area,area) ) {
max_area = area;
np = tp;
}
}
assert( !equals(max_area,-1) );
mp = np;
if( LT(maxi,max_area) ) maxi = max_area;
}
rate *= 0.5;
}
rep(__,3) {
Point mp = calc_ps(poly);
double rate = 1.0;
double eps = 1e-10;
while( LT(eps,rate) ) {
rep(_,70) {
double max_area = -1;
Point np;
rep(i,n) {
Point tp = mp;
tp.x += ( poly[i].x - mp.x ) * rate;
tp.y += ( poly[i].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,tp,r);
if( LT(max_area,area) ) {
max_area = area;
np = tp;
}
}
if( rand() % 50 == 0 ) {
int v = rand() % n;
np.x = ( poly[v].x - mp.x ) * rate;
np.y = ( poly[v].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,np,r);
if( LT(max_area,area) ) {
max_area = area;
}
}
assert( !equals(max_area,-1) );
mp = np;
if( LT(maxi,max_area) ) maxi = max_area;
}
rate *= 0.5;
}
}
printf("%.10f\n",maxi);
}
int main() {
srand((unsigned int)time(NULL));
cin >> n >> r;
poly.resize(n);
rep(i,n) cin >> poly[i].x >> poly[i].y;
//cout << getArea(poly) << endl;
compute();
return 0;
} |
#include <iostream>
#include <complex>
#include <vector>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <map>
using namespace std;
#define x1 jkflwjjkfjekjfe
#define x2 fwekwfefekfje
int iter = log(100 * 100 * 10000) / log(3) + 20;
typedef complex<double> P;
struct L{
P a,b;
};
vector<double> ax,ay;
vector<L> ls;
double R,cx,cy;
bool eq(double a,double b){
return fabs(a-b) < 1e-7;
}
bool eq2(double a,double b){
return fabs(a-b) < 1e-8;
}
pair<double,double> seg(double y){
double x1 = +1e5;
double x2 = -1e5;
for( auto &&l : ls){
if( eq(l.a.imag(),y) ){
x1 = min(x1,l.a.real());
x2 = max(x2,l.a.real());
}
if( eq(l.b.imag(),y) ){
x1 = min(x1,l.b.real());
x2 = max(x2,l.b.real());
}
if( l.a.imag() + 1e-7 < y and y < l.b.imag() - 1e-7 ){
P v = (l.b - l.a);
P p = l.a + v * (y-l.a.imag()) / v.imag();
x1 = min(x1,p.real());
x2 = max(x2,p.real());
}
}
return {x1,x2};
}
double len(pair<double,double> p){
if( p.first < p.second ) return p.second - p.first;
return 0;
}
pair<double,double> merge(const pair<double,double> &a,const pair<double,double> &b){
return {max(a.first,b.first),min(a.second,b.second)};
}
map<double,double> mp;
double g(double y){
if( mp.count(y) ) return mp[y];
if( R - abs(y-cy) < 1e-7 ) return 0;
// for given y, compute the overlapped length of the circle and the polygon.
double t = sqrt(R*R-(cy-y)*(cy-y));
pair<double,double> circle_seg = {cx-t,cx+t};
return mp[y] = len(merge(circle_seg,seg(y)));
}
double simpson(double l,double r){
return (r-l)/6*(g(l)+4*g((l+r)/2)+g(r));
}
double integral(double l,double r,int k=5){
if( l >= r ) return 0;
double m = (l+r)/2;
double A = simpson(l,m) + simpson(m,r);
double B = simpson(l,r);
if( k<=0 and eq2(A,B) ) return A;
else return integral(l,m,k-1) + integral(m,r,k-1);
}
double f(double x,double y){
cx = x;
cy = y;
mp.clear();
double ans = 0;
for(int i = 0 ; i+1 < ay.size() ; i++){
ans += integral(max(cy-R,ay[i]),min(cy+R,ay[i+1]));
}
return ans;
}
double search2(double y){
double ans = 0;
double l,r;
tie(l,r) = seg(y);
for(int i = 0 ; i < iter ; i++){
double a = (2*l+r) / 3;
double b = (l+2*r) / 3;
if( f(a,y) < f(b,y) ){
l = a;
}else{
r = b;
}
}
return f(l,y);
}
double search1(){
double ans = 0;
double l = ay.front(), r = ay.back();
for(int i = 0 ; i < iter ; i++){
double a = (2*l+r) / 3;
double b = (l+2*r) / 3;
if( search2(a) < search2(b) ){
l = a;
}else{
r = b;
}
}
return search2(l);
}
int main(){
int n;
cin >> n >> R;
vector<P> g(n+1);
for(int i = 0 ; i < n ; i++){
double x,y;
cin >> x >> y;
g[i] = P(x,y);
ax.push_back(x);
ay.push_back(y);
}
g[n] = g[0];
for(int i = 0 ; i < n ; i++){
ls.push_back({g[i],g[i+1]});
if( ls.back().a.imag() > ls.back().b.imag() ) swap(ls.back().a,ls.back().b);
}
sort(ax.begin(),ax.end());
sort(ay.begin(),ay.end());
ax.erase(unique(ax.begin(),ax.end()),ax.end());
ay.erase(unique(ay.begin(),ay.end()),ay.end());
//printf("%.10lf\n",f(0,0));
//return 0;
printf("%.10lf\n",search1());
} |
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
template<class T> using V = vector<T>;
using D = double;
const D PI = acos(D(-1)), EPS = 1e-10;
int sgn(D a) { return (abs(a) <= EPS) ? 0 : (a < 0 ? -1 : 1); }
int sgn(D a, D b) { return sgn(a-b); }
struct Pt2 {
D x, y;
Pt2(D _x = D(), D _y = D()) : x(_x), y(_y) {}
Pt2 operator+(const Pt2 &r) const { return Pt2(x+r.x, y+r.y); }
Pt2 operator-(const Pt2 &r) const { return Pt2(x-r.x, y-r.y); }
Pt2 operator*(const Pt2 &r) const { return Pt2(x*r.x-y*r.y, x*r.y+y*r.x); }
Pt2 operator-() const { return Pt2(-x, -y); }
bool operator<(const Pt2 &r) const { return 2*sgn(x, r.x)+sgn(y, r.y)<0; }
bool operator==(const Pt2 &r) const { return sgn((*this-r).rabs()) == 0; }
D norm() const { return x*x + y*y; }
D abs() const { return sqrt(norm()); }
D rabs() const { return max(std::abs(x), std::abs(y)); } // robust abs
D arg() const { return atan2(y, x); }
};
using P = Pt2;
struct L {
P s, t;
L(P _s = P(), P _t = P()) : s(_s), t(_t) {}
P vec() const { return t-s; }
D abs() const { return vec().abs(); }
D arg() const { return vec().arg(); }
};
D cross(P a, P b) { return a.x*b.y - a.y*b.x; }
D dot(P a, P b) { return a.x*b.x + a.y*b.y; }
// cross(a, b) is too small?
int sgncrs(P a, P b) {
D cr = cross(a, b);
if (abs(cr) <= (a.rabs() + b.rabs()) * EPS) return 0;
return (cr < 0) ? -1 : 1;
}
// -2, -1, 0, 1, 2 : front, clock, on, cclock, back
int ccw(P b, P c) {
int s = sgncrs(b, c);
if (s) return s;
if (!sgn(c.rabs()) || !sgn((c-b).rabs())) return 0;
if (dot(b, c) < 0) return 2;
if (dot(-b, c-b) < 0) return -2;
return 0;
}
int ccw(P a, P b, P c) { return ccw(b-a, c-a); }
int ccw(L l, P p) { return ccw(l.s, l.t, p); }
P project(const L &l, const P &p) {
P v = l.vec();
return l.s + v * (dot(v, p-l.s) / v.norm());
}
D distLP(const L &l, const P &p) {
return abs(cross(l.vec(), p-l.s)) / l.abs();
}
int crossLL(const L &l, const L &m, P &r) {
D cr1 = cross(l.vec(), m.vec()), cr2 = cross(l.vec(), l.t - m.s);
if (sgncrs(l.vec(), m.vec()) == 0) {
r = l.s;
if (sgncrs(l.vec(), l.t - m.s)) return 0;
return -1;
}
r = m.s + m.vec() * (cr2 / cr1);
return 1;
}
using Pol = V<P>;
struct C {
P p; D r;
C(P _p = P(), D _r = D()) : p(_p), r(_r) {}
};
//need Intersect/distLP, r.sはよりl.sに近い
int crossCL(const C &c, const L &l, L &r) {
D u = distLP(l, c.p);
int si = sgn(u, c.r);
if (si == 1) return 0;
P v = project(l, c.p);
P di = (si == 0) ? P(0, 0) : l.vec() * (sqrt(c.r*c.r - u*u) / l.abs());
r = L(v-di, v+di);
if (si == 0) return 1;
return 2;
}
//need Intersect/distLP, r.sはよりl.sに近い
int crossCS(const C &c, const L &s, L &l) {
if (!crossCL(c, s, l)) return 0;
bool f1 = !ccw(s, l.s), f2 = !ccw(s, l.t);
if (f1 && f2) return 2;
if (!f1 && !f2) return 0;
if (f1) l.t = l.s;
else l.s = l.t;
return 1;
}
// C(P(0, 0), r)とTri((0, 0), a, b)の共有面積
D area2CT(const C &c, const P &_a, const P &_b) {
P a = _a - c.p, b = _b - c.p; D r = c.r;
if (a == b) return 0;
auto single = [&](P x, P y, bool tri) {
if (tri) return cross(x, y);
else return r * r * ((y * P(x.x, -x.y)).arg());
};
bool ia = sgn(a.abs(), r) != 1, ib = sgn(b.abs(), r) != 1;
if (ia && ib) return single(a, b, true);
L l;
if (!crossCS(C(P(0, 0), r), L(a, b), l)) return single(a, b, false);
return single(a, l.s, ia) + single(l.s, l.t, true) + single(l.t, b, ib);
}
// p, cの共有面積
D area2CPol(const C &c, const Pol &po) {
D sm = 0;
P a, b = po.back();
for (auto p: po) {
a = b; b = p;
sm += area2CT(c, a, b);
}
return sm;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << setprecision(20);
int n; D r;
cin >> n >> r;
Pol pol;
D ymi = 1e100, yma = -1e100;
for (int i = 0; i < n; i++) {
D x, y;
cin >> x >> y;
pol.push_back(P(x, y));
ymi = min(ymi, y);
yma = max(yma, y);
}
auto calc = [&](D y) {
D xmi = 1e100, xma = -1e100;
P a, b = pol.back();
for (int i = 0; i < n; i++) {
a = b; b = pol[i];
P p;
if (crossLL(L(a, b), L(P(0, y), P(1, y)), p) == 0) continue;
if (ccw(a, b, p) != 0) continue;
xmi = min(xmi, p.x); xma = max(xma, p.x);
}
D lw = xmi, up = xma;
for (int ph = 0; ph < 30; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
D z1 = area2CPol(C(P(md1, y), r), pol) / 2;
D z2 = area2CPol(C(P(md2, y), r), pol) / 2;
if (z1 < z2) {
lw = md1;
} else {
up = md2;
}
}
return area2CPol(C(P(lw, y), r), pol) / 2;
};
D lw = ymi, up = yma;
for (int ph = 0; ph < 30; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
if (calc(md1) < calc(md2)) {
lw = md1;
} else {
up = md2;
}
}
cout << calc(lw) << endl;
return 0;
}
|
#include<bits/stdc++.h>
#define inf 400
#define linf 1e18
#define eps (1e-9)
#define mod 1000000007
#define pi M_PI
#define phi (1.0+sqrt(5))/2.0
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(),(a).end()
#define pd(a) printf("%.10f\n",(double)(a))
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define RFOR(i,a,b) for(int i=(a)-1;(b)<=i;i--)
#define equals(a,b) (fabs((a)-(b))<eps)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<double,int> pdi;
typedef vector<int> vi;
typedef vector<pii> vpi;
class Point{
public:
double x,y;
Point(double x=0,double y=0):x(x),y(y){}
Point operator+(Point p){ return Point(x+p.x,y+p.y);}
Point operator-(Point p){ return Point(x-p.x,y-p.y);}
Point operator*(double k){ return Point(x*k,y*k);}
Point operator/(double k){ return Point(x/k,y/k);}
bool operator<(Point p)const{ return (x!=p.x ? x<p.x : y<p.y);}
bool operator==(Point p)const{ return fabs(x-p.x)<eps && fabs(y-p.y)<eps;}
double abs(){ return sqrt(norm());}
double norm(){ return (x*x+y*y);}
};
typedef Point Vector;
typedef vector<Point> Polygon;
class Segment{
public:
Point p1,p2;
Segment(Point p1=Point(),Point p2=Point()):p1(p1),p2(p2){}
};
typedef Segment Line;
class Circle{
public:
Point c;
double r;
Circle(Point c=Point(),double r=0.0):c(c),r(r){}
};
double norm(Vector a){ return (a.x*a.x+a.y*a.y);}
double abs(Vector a){ return sqrt(norm(a));}
double dot(Vector a,Vector b){ return (a.x*b.x+a.y*b.y);}
double cross(Vector a,Vector b){ return (a.x*b.y-a.y*b.x);}
bool in(Circle c,Point p){
if(abs(c.c-p)-c.r<-eps)return true;
return false;
}
Point project(Segment s,Point p){
Vector base=(s.p2-s.p1);
double r=(dot(p-s.p1,base)/base.norm());
return (s.p1+base*r);
}
int ccw(Point p0,Point p1,Point p2){
Vector a=p1-p0;
Vector b=p2-p0;
if(cross(a,b)>eps)return 1;
if(cross(a,b)<-eps)return -1;
if(dot(a,b)<-eps)return 2;
if(a.norm()<b.norm())return -2;
return 0;
}
double getDistanceLP(Line l,Point p){
return abs(cross(l.p2-l.p1,p-l.p1)/abs(l.p2-l.p1));
}
double getDistanceSP(Segment s,Point p){
if(dot(s.p2-s.p1,p-s.p1)<0.0)return abs(p-s.p1);
if(dot(s.p1-s.p2,p-s.p2)<0.0)return abs(p-s.p2);
return getDistanceLP(s,p);
}
bool intersect(Circle c,Segment s){
if(getDistanceSP(s,c.c)-c.r<-eps)return true;
return false;
}
double getAngle(Vector a,Vector b){
double tmp=dot(a,b)/(abs(a)*abs(b));
if(tmp<-1.0)tmp=-1.0;
if(1.0<tmp)tmp=1.0;
return acos(tmp)*180.0/pi;
}
pair<Point,Point> getCrossPoints(Circle c,Line l){
Vector pr=project(l,c.c);
Vector e=(l.p2-l.p1)/abs(l.p2-l.p1);
double base=sqrt(c.r*c.r-norm(pr-c.c));
return mp(pr+e*base,pr-e*base);
}
Point getCrossPointSC(Circle c,Segment s){
Point res;
pair<Point,Point> pp=getCrossPoints(c,s);
if(ccw(s.p1,s.p2,pp.f)==0){
res=pp.f;
if(ccw(s.p1,s.p2,pp.s)==0 && abs(s.p1-pp.s)<abs(s.p1-pp.f))res=pp.s;
}
else res=pp.s;
return res;
}
double getCommonAreaTC(Point a,Point b,Circle c){
double res=abs(cross(a-c.c,b-c.c)/2.0);
if(equals(0.0,res))return 0.0;
if(in(c,a) && !in(c,b)){
Point p1=getCrossPointSC(c,Segment(b,a));
Point p2=getCrossPointSC(c,Segment(b,c.c));
res+=(c.r*c.r*pi)*(getAngle(p1-c.c,p2-c.c)/360.0);
res-=abs(cross(p1-c.c,p2-c.c)/2.0);
res-=abs(cross(p2-b,p1-b)/2.0);
}
else if(!in(c,a) && in(c,b)){
Point p1=getCrossPointSC(c,Segment(a,c.c));
Point p2=getCrossPointSC(c,Segment(a,b));
res+=(c.r*c.r*pi)*(getAngle(p1-c.c,p2-c.c)/360.0);
res-=abs(cross(p1-c.c,p2-c.c)/2.0);
res-=abs(cross(p2-a,p1-a)/2.0);
}
else if(!in(c,a) && !in(c,b)){
if(intersect(c,Segment(a,b))){
pair<Point,Point> pp=getCrossPoints(c,Segment(a,b));
Point m=pp.f+(pp.s-pp.f)/2.0;
res=abs(getCommonAreaTC(a,m,c))+abs(getCommonAreaTC(m,b,c));
}
else res=(c.r*c.r*pi)*(getAngle(a-c.c,b-c.c)/360.0);
}
if(cross(a-c.c,b-c.c)<0.0)res=-res;
return res;
}
double getCommonAreaPC(Polygon p,Circle c){
double res=0.0;
int n=p.size();
FOR(i,0,n)res+=getCommonAreaTC(p[i],p[(i+1)%n],c);
return abs(res);
}
int n,r;
Polygon p;
Point g(0,0);
double check(Point a){
Vector v=(g-a);
v=v/abs(v);
double R=0.0,L=inf;
FOR(k,0,50){
double m1=(L*phi+R)/(1.0+phi);
double m2=(L+R*phi)/(1.0+phi);
double res1=getCommonAreaPC(p,Circle(a+v*m1,r));
double res2=getCommonAreaPC(p,Circle(a+v*m2,r));
if(res2-res1<-eps)R=m2;
else L=m1;
}
return getCommonAreaPC(p,Circle(a+v*R,r));
}
double solve(){
FOR(i,0,n)g=g+p[i];
g=g/n;
double res=0.0;
FOR(i,0,n){
Point a=p[i],b=p[(i+1)%n];
Vector v=b-a;
v=v/abs(v);
double R=0.0,L=inf*2;
FOR(k,0,50){
double m1=(L*phi+R)/(1.0+phi);
double m2=(L+R*phi)/(1.0+phi);
double res1=check(a+v*(m1-inf));
double res2=check(a+v*(m2-inf));
if(res2-res1<-eps)R=m2;
else L=m1;
}
res=max(res,check(a+v*(R-inf)));
}
return res;
}
int main()
{
cin>>n>>r;
FOR(i,0,n){
int x,y;
cin>>x>>y;
p.pb(Point(x,y));
}
pd(solve());
return 0;
} |
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
#define EPS (1e-10)
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define PI 3.141592653589793238
// COUNTER CLOCKWISE
static const int CCW_COUNTER_CLOCKWISE = 1;
static const int CCW_CLOCKWISE = -1;
static const int CCW_ONLINE_BACK = 2;
static const int CCW_ONLINE_FRONT = -2;
static const int CCW_ON_SEGMENT = 0;
//Intercsect Circle & Circle
static const int ICC_SEPERATE = 4;
static const int ICC_CIRCUMSCRIBE = 3;
static const int ICC_INTERSECT = 2;
static const int ICC_INSCRIBE = 1;
static const int ICC_CONTAIN = 0;
struct Point{
double x,y;
Point(){}
Point(double x,double y) :x(x),y(y){}
Point operator+(Point p) {return Point(x+p.x,y+p.y);}
Point operator-(Point p) {return Point(x-p.x,y-p.y);}
Point operator*(double k){return Point(x*k,y*k);}
Point operator/(double k){return Point(x/k,y/k);}
double norm(){return x*x+y*y;}
double abs(){return sqrt(norm());}
bool operator < (const Point &p) const{
return x!=p.x?x<p.x:y<p.y;
//grid-point only
//return !equals(x,p.x)?x<p.x:!equals(y,p.y)?y<p.y:0;
}
bool operator == (const Point &p) const{
return fabs(x-p.x)<EPS && fabs(y-p.y)<EPS;
}
};
struct EndPoint{
Point p;
int seg,st;
EndPoint(){}
EndPoint(Point p,int seg,int st):p(p),seg(seg),st(st){}
bool operator<(const EndPoint &ep)const{
if(p.y==ep.p.y) return st<ep.st;
return p.y<ep.p.y;
}
};
istream &operator >> (istream &is,Point &p){
is>>p.x>>p.y;
return is;
}
ostream &operator << (ostream &os,Point p){
os<<fixed<<setprecision(12)<<p.x<<" "<<p.y;
return os;
}
bool sort_x(Point a,Point b){
return a.x!=b.x?a.x<b.x:a.y<b.y;
}
bool sort_y(Point a,Point b){
return a.y!=b.y?a.y<b.y:a.x<b.x;
}
typedef Point Vector;
typedef vector<Point> Polygon;
istream &operator >> (istream &is,Polygon &p){
for(int i=0;i<(int)p.size();i++) is>>p[i];
return is;
}
struct Segment{
Point p1,p2;
Segment(){}
Segment(Point p1, Point p2):p1(p1),p2(p2){}
};
typedef Segment Line;
istream &operator >> (istream &is,Segment &s){
is>>s.p1>>s.p2;
return is;
}
struct Circle{
Point c;
double r;
Circle(){}
Circle(Point c,double r):c(c),r(r){}
};
istream &operator >> (istream &is,Circle &c){
is>>c.c>>c.r;
return is;
}
double norm(Vector a){
return a.x*a.x+a.y*a.y;
}
double abs(Vector a){
return sqrt(norm(a));
}
double dot(Vector a,Vector b){
return a.x*b.x+a.y*b.y;
}
double cross(Vector a,Vector b){
return a.x*b.y-a.y*b.x;
}
Point orth(Point p){return Point(-p.y,p.x);}
bool isOrthogonal(Vector a,Vector b){
return equals(dot(a,b),0.0);
}
bool isOrthogonal(Point a1,Point a2,Point b1,Point b2){
return isOrthogonal(a1-a2,b1-b2);
}
bool isOrthogonal(Segment s1,Segment s2){
return equals(dot(s1.p2-s1.p1,s2.p2-s2.p1),0.0);
}
bool isParallel(Vector a,Vector b){
return equals(cross(a,b),0.0);
}
bool isParallel(Point a1,Point a2,Point b1,Point b2){
return isParallel(a1-a2,b1-b2);
}
bool isParallel(Segment s1,Segment s2){
return equals(cross(s1.p2-s1.p1,s2.p2-s2.p1),0.0);
}
Point project(Segment s,Point p){
Vector base=s.p2-s.p1;
double r=dot(p-s.p1,base)/norm(base);
return s.p1+base*r;
}
Point reflect(Segment s,Point p){
return p+(project(s,p)-p)*2.0;
}
double arg(Vector p){
return atan2(p.y,p.x);
}
Vector polar(double a,double r){
return Point(cos(r)*a,sin(r)*a);
}
int ccw(Point p0,Point p1,Point p2);
bool intersectSS(Point p1,Point p2,Point p3,Point p4);
bool intersectSS(Segment s1,Segment s2);
bool intersectPS(Polygon p,Segment l);
int intersectCC(Circle c1,Circle c2);
bool intersectSC(Segment s,Circle c);
double getDistanceLP(Line l,Point p);
double getDistanceSP(Segment s,Point p);
double getDistanceSS(Segment s1,Segment s2);
Point getCrossPointSS(Segment s1,Segment s2);
Point getCrossPointLL(Line l1,Line l2);
Polygon getCrossPointCL(Circle c,Line l);
Polygon getCrossPointCC(Circle c1,Circle c2);
int contains(Polygon g,Point p);
Polygon andrewScan(Polygon s);
Polygon convex_hull(Polygon ps);
double diameter(Polygon s);
bool isConvex(Polygon p);
double area(Polygon s);
Polygon convexCut(Polygon p,Line l);
Line bisector(Point p1,Point p2);
Vector translate(Vector v,double theta);
vector<Line> corner(Line l1,Line l2);
vector<vector<pair<int, double> > >
segmentArrangement(vector<Segment> &ss, Polygon &ps);
int ccw(Point p0,Point p1,Point p2){
Vector a = p1-p0;
Vector b = p2-p0;
if(cross(a,b) > EPS) return CCW_COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS) return CCW_CLOCKWISE;
if(dot(a,b) < -EPS) return CCW_ONLINE_BACK;
if(a.norm()<b.norm()) return CCW_ONLINE_FRONT;
return CCW_ON_SEGMENT;
}
bool intersectSS(Point p1,Point p2,Point p3,Point p4){
return (ccw(p1,p2,p3)*ccw(p1,p2,p4) <= 0 &&
ccw(p3,p4,p1)*ccw(p3,p4,p2) <= 0 );
}
bool intersectSS(Segment s1,Segment s2){
return intersectSS(s1.p1,s1.p2,s2.p1,s2.p2);
}
bool intersectPS(Polygon p,Segment l){
int n=p.size();
for(int i=0;i<n;i++)
if(intersectSS(Segment(p[i],p[(i+1)%n]),l)) return 1;
return 0;
}
int intersectCC(Circle c1,Circle c2){
if(c1.r<c2.r) swap(c1,c2);
double d=abs(c1.c-c2.c);
double r=c1.r+c2.r;
if(equals(d,r)) return ICC_CIRCUMSCRIBE;
if(d>r) return ICC_SEPERATE;
if(equals(d+c2.r,c1.r)) return ICC_INSCRIBE;
if(d+c2.r<c1.r) return ICC_CONTAIN;
return ICC_INTERSECT;
}
bool intersectSC(Segment s,Circle c){
return getDistanceSP(s,c.c)<=c.r;
}
int intersectCS(Circle c,Segment s){
if(norm(project(s,c.c)-c.c)-c.r*c.r>EPS) return 0;
double d1=abs(c.c-s.p1),d2=abs(c.c-s.p2);
if(d1<c.r+EPS&&d2<c.r+EPS) return 0;
if((d1<c.r-EPS&&d2>c.r+EPS)||(d1>c.r+EPS&&d2<c.r-EPS)) return 1;
Point h=project(s,c.c);
if(dot(s.p1-h,s.p2-h)<0) return 2;
return 0;
}
double getDistanceLP(Line l,Point p){
return abs(cross(l.p2-l.p1,p-l.p1)/abs(l.p2-l.p1));
}
double getDistanceSP(Segment s,Point p){
if(dot(s.p2-s.p1,p-s.p1) < 0.0 ) return abs(p-s.p1);
if(dot(s.p1-s.p2,p-s.p2) < 0.0 ) return abs(p-s.p2);
return getDistanceLP(s,p);
}
double getDistanceSS(Segment s1,Segment s2){
if(intersectSS(s1,s2)) return 0.0;
return min(min(getDistanceSP(s1,s2.p1),getDistanceSP(s1,s2.p2)),
min(getDistanceSP(s2,s1.p1),getDistanceSP(s2,s1.p2)));
}
Point getCrossPointSS(Segment s1,Segment s2){
for(int k=0;k<2;k++){
if(getDistanceSP(s1,s2.p1)<EPS) return s2.p1;
if(getDistanceSP(s1,s2.p2)<EPS) return s2.p2;
swap(s1,s2);
}
Vector base=s2.p2-s2.p1;
double d1=abs(cross(base,s1.p1-s2.p1));
double d2=abs(cross(base,s1.p2-s2.p1));
double t=d1/(d1+d2);
return s1.p1+(s1.p2-s1.p1)*t;
}
Point getCrossPointLL(Line l1,Line l2){
double a=cross(l1.p2-l1.p1,l2.p2-l2.p1);
double b=cross(l1.p2-l1.p1,l1.p2-l2.p1);
if(abs(a)<EPS&&abs(b)<EPS) return l2.p1;
return l2.p1+(l2.p2-l2.p1)*(b/a);
}
Polygon getCrossPointCL(Circle c,Line l){
Polygon ps;
Point pr=project(l,c.c);
Vector e=(l.p2-l.p1)/abs(l.p2-l.p1);
if(equals(getDistanceLP(l,c.c),c.r)){
ps.emplace_back(pr);
return ps;
}
double base=sqrt(c.r*c.r-norm(pr-c.c));
ps.emplace_back(pr+e*base);
ps.emplace_back(pr-e*base);
return ps;
}
Polygon getCrossPointCS(Circle c,Segment s){
Line l(s);
Polygon res=getCrossPointCL(c,l);
if(intersectCS(c,s)==2) return res;
if(res.size()>1u){
if(dot(l.p1-res[0],l.p2-res[0])>0) swap(res[0],res[1]);
res.pop_back();
}
return res;
}
Polygon getCrossPointCC(Circle c1,Circle c2){
Polygon p(2);
double d=abs(c1.c-c2.c);
double a=acos((c1.r*c1.r+d*d-c2.r*c2.r)/(2*c1.r*d));
double t=arg(c2.c-c1.c);
p[0]=c1.c+polar(c1.r,t+a);
p[1]=c1.c+polar(c1.r,t-a);
return p;
}
// IN:2 ON:1 OUT:0
int contains(Polygon g,Point p){
int n=g.size();
bool x=false;
for(int i=0;i<n;i++){
Point a=g[i]-p,b=g[(i+1)%n]-p;
if(fabs(cross(a,b)) < EPS && dot(a,b) < EPS) return 1;
if(a.y>b.y) swap(a,b);
if(a.y < EPS && EPS < b.y && cross(a,b) > EPS ) x = !x;
}
return (x?2:0);
}
Polygon andrewScan(Polygon s){
Polygon u,l;
if(s.size()<3) return s;
sort(s.begin(),s.end());
u.push_back(s[0]);
u.push_back(s[1]);
l.push_back(s[s.size()-1]);
l.push_back(s[s.size()-2]);
for(int i=2;i<(int)s.size();i++){
for(int n=u.size();n>=2&&ccw(u[n-2],u[n-1],s[i])!=CCW_CLOCKWISE;n--){
u.pop_back();
}
u.push_back(s[i]);
}
for(int i=s.size()-3;i>=0;i--){
for(int n=l.size();n>=2&&ccw(l[n-2],l[n-1],s[i])!=CCW_CLOCKWISE;n--){
l.pop_back();
}
l.push_back(s[i]);
}
reverse(l.begin(),l.end());
for(int i=u.size()-2;i>=1;i--) l.push_back(u[i]);
return l;
}
Polygon convex_hull(Polygon ps){
int n=ps.size();
sort(ps.begin(),ps.end(),sort_y);
int k=0;
Polygon qs(n*2);
for(int i=0;i<n;i++){
while(k>1&&cross(qs[k-1]-qs[k-2],ps[i]-qs[k-1])<0) k--;
qs[k++]=ps[i];
}
for(int i=n-2,t=k;i>=0;i--){
while(k>t&&cross(qs[k-1]-qs[k-2],ps[i]-qs[k-1])<0) k--;
qs[k++]=ps[i];
}
qs.resize(k-1);
return qs;
}
double diameter(Polygon s){
Polygon p=s;
int n=p.size();
if(n==2) return abs(p[0]-p[1]);
int i=0,j=0;
for(int k=0;k<n;k++){
if(p[i]<p[k]) i=k;
if(!(p[j]<p[k])) j=k;
}
double res=0;
int si=i,sj=j;
while(i!=sj||j!=si){
res=max(res,abs(p[i]-p[j]));
if(cross(p[(i+1)%n]-p[i],p[(j+1)%n]-p[j])<0.0){
i=(i+1)%n;
}else{
j=(j+1)%n;
}
}
return res;
}
bool isConvex(Polygon p){
bool f=1;
int n=p.size();
for(int i=0;i<n;i++){
int t=ccw(p[(i+n-1)%n],p[i],p[(i+1)%n]);
f&=t!=CCW_CLOCKWISE;
}
return f;
}
double area(Polygon s){
double res=0;
for(int i=0;i<(int)s.size();i++){
res+=cross(s[i],s[(i+1)%s.size()])/2.0;
}
return abs(res);
}
double area(Circle c1,Circle c2){
double d=abs(c1.c-c2.c);
if(c1.r+c2.r<=d+EPS) return 0;
if(d<=abs(c1.r-c2.r)){
double r=min(c1.r,c2.r);
return PI*r*r;
}
double rc=(d*d+c1.r*c1.r-c2.r*c2.r)/(2*d);
double th=acos(rc/c1.r);
double ph=acos((d-rc)/c2.r);
return c1.r*c1.r*th+c2.r*c2.r*ph-d*c1.r*sin(th);
}
Polygon convexCut(Polygon p,Line l){
Polygon q;
for(int i=0;i<(int)p.size();i++){
Point a=p[i],b=p[(i+1)%p.size()];
if(ccw(l.p1,l.p2,a)!=-1) q.push_back(a);
if(ccw(l.p1,l.p2,a)*ccw(l.p1,l.p2,b)<0)
q.push_back(getCrossPointLL(Line(a,b),l));
}
return q;
}
Line bisector(Point p1,Point p2){
Circle c1=Circle(p1,abs(p1-p2)),c2=Circle(p2,abs(p1-p2));
Polygon p=getCrossPointCC(c1,c2);
if(cross(p2-p1,p[0]-p1)>0) swap(p[0],p[1]);
return Line(p[0],p[1]);
}
Vector translate(Vector v,double theta){
Vector res;
res.x=cos(theta)*v.x-sin(theta)*v.y;
res.y=sin(theta)*v.x+cos(theta)*v.y;
return res;
}
vector<Line> corner(Line l1,Line l2){
vector<Line> res;
if(isParallel(l1,l2)){
double d=getDistanceLP(l1,l2.p1)/2.0;
Vector v1=l1.p2-l1.p1;
v1=v1/v1.abs()*d;
Point p=l2.p1+translate(v1,90.0*(PI/180.0));
double d1=getDistanceLP(l1,p);
double d2=getDistanceLP(l2,p);
if(abs(d1-d2)>d){
p=l2.p1+translate(v1,-90.0*(PI/180.0));
}
res.push_back(Line(p,p+v1));
}else{
Point p=getCrossPointLL(l1,l2);
Vector v1=l1.p2-l1.p1,v2=l2.p2-l2.p1;
v1=v1/v1.abs();
v2=v2/v2.abs();
res.push_back(Line(p,p+(v1+v2)));
res.push_back(Line(p,p+translate(v1+v2,90.0*(PI/180.0))));
}
return res;
}
Polygon tangent(Circle c1,Point p2){
Circle c2=Circle(p2,sqrt(norm(c1.c-p2)-c1.r*c1.r));
Polygon p=getCrossPointCC(c1,c2);
sort(p.begin(),p.end());
return p;
}
vector<Line> tangent(Circle c1,Circle c2){
vector<Line> ls;
if(c1.r<c2.r) swap(c1,c2);
double g=norm(c1.c-c2.c);
if(equals(g,0)) return ls;
Point u=(c2.c-c1.c)/sqrt(g);
Point v=orth(u);
for(int s=1;s>=-1;s-=2){
double h=(c1.r+s*c2.r)/sqrt(g);
if(equals(1-h*h,0)){
ls.emplace_back(c1.c+u*c1.r,c1.c+(u+v)*c1.r);
}else if(1-h*h>0){
Point uu=u*h,vv=v*sqrt(1-h*h);
ls.emplace_back(c1.c+(uu+vv)*c1.r,c2.c-(uu+vv)*c2.r*s);
ls.emplace_back(c1.c+(uu-vv)*c1.r,c2.c-(uu-vv)*c2.r*s);
}
}
return ls;
}
double closest_pair(Polygon &a,int l=0,int r=-1){
if(r<0){
r=a.size();
sort(a.begin(),a.end(),sort_x);
}
if(r-l<=1) return abs(a[0]-a[1]);
int m=(l+r)>>1;
double x=a[m].x;
double d=min(closest_pair(a,l,m),closest_pair(a,m,r));
inplace_merge(a.begin()+l,a.begin()+m,a.begin()+r,sort_y);
Polygon b;
for(int i=l;i<r;i++){
if(fabs(a[i].x-x)>=d) continue;
for(int j=0;j<(int)b.size();j++){
double dy=a[i].y-next(b.rbegin(),j)->y;
if(dy>=d) break;
d=min(d,abs(a[i]-*next(b.rbegin(),j)));
}
b.emplace_back(a[i]);
}
return d;
}
vector<vector<pair<int, double> > >
segmentArrangement(vector<Segment> &ss, Polygon &ps){
int n=ss.size();
for(int i=0;i<n;i++){
ps.emplace_back(ss[i].p1);
ps.emplace_back(ss[i].p2);
for(int j=i+1;j<n;j++)
if(intersectSS(ss[i],ss[j]))
ps.emplace_back(getCrossPointSS(ss[i],ss[j]));
}
sort(ps.begin(),ps.end());
ps.erase(unique(ps.begin(),ps.end()),ps.end());
vector<vector<pair<int, double> > > G(ps.size());
for(int i=0;i<n;i++){
vector<pair<double,int> > ls;
for(int j=0;j<(int)ps.size();j++)
if(getDistanceSP(ss[i],ps[j])<EPS)
ls.emplace_back(make_pair(norm(ss[i].p1-ps[j]),j));
sort(ls.begin(),ls.end());
for(int j=0;j+1<(int)ls.size();j++){
int a=ls[j].second,b=ls[j+1].second;
G[a].emplace_back(b,abs(ps[a]-ps[b]));
G[b].emplace_back(a,abs(ps[a]-ps[b]));
}
}
return G;
}
int manhattanIntersection(vector<Segment> ss,const int INF){
const int BTM = 0;
const int LFT = 1;
const int RGH = 2;
const int TOP = 3;
int n=ss.size();
vector<EndPoint> ep;
for(int i=0;i<n;i++){
if(ss[i].p1.y==ss[i].p2.y){
if(ss[i].p1.x>ss[i].p2.x) swap(ss[i].p1,ss[i].p2);
ep.emplace_back(ss[i].p1,i,LFT);
ep.emplace_back(ss[i].p2,i,RGH);
}else{
if(ss[i].p1.y>ss[i].p2.y) swap(ss[i].p1,ss[i].p2);
ep.emplace_back(ss[i].p1,i,BTM);
ep.emplace_back(ss[i].p2,i,TOP);
}
}
sort(ep.begin(),ep.end());
set<int> bt;
bt.insert(INF);
int cnt=0;
for(int i=0;i<n*2;i++){
if(ep[i].st==TOP){
bt.erase(ep[i].p.x);
}else if(ep[i].st==BTM){
bt.emplace(ep[i].p.x);
}else if(ep[i].st==LFT){
auto b=bt.lower_bound(ss[ep[i].seg].p1.x);
auto e=bt.upper_bound(ss[ep[i].seg].p2.x);
cnt+=distance(b,e);
}
}
return cnt;
}
double area(Polygon ps,Circle c){
if(ps.size()<3u) return 0;
function<double(Circle, Point, Point)> dfs=
[&](Circle c,Point a,Point b){
Vector va=c.c-a,vb=c.c-b;
double f=cross(va,vb),res=0;
if(equals(f,0.0)) return res;
if(max(abs(va),abs(vb))<c.r+EPS) return f;
Vector d(dot(va,vb),cross(va,vb));
if(getDistanceSP(Segment(a,b),c.c)>c.r-EPS)
return c.r*c.r*atan2(d.y,d.x);
auto u=getCrossPointCS(c,Segment(a,b));
if(u.empty()) return res;
if(u.size()>1u&&dot(u[1]-u[0],a-u[0])>0) swap(u[0],u[1]);
u.emplace(u.begin(),a);
u.emplace_back(b);
for(int i=1;i<(int)u.size();i++)
res+=dfs(c,u[i-1],u[i]);
return res;
};
double res=0;
for(int i=0;i<(int)ps.size();i++)
res+=dfs(c,ps[i],ps[(i+1)%ps.size()]);
return res/2;
}
struct Precision{
Precision(){
cout<<fixed<<setprecision(12);
}
}precision_beet;
//INSERT ABOVE HERE
signed main(){
int n;
double r;
cin>>n>>r;
Polygon ps(n);
for(int i=0;i<n;i++) cin>>ps[i];
Point g(0,0);
for(Point p:ps) g=g+p;
g=g/n;
double ans=0;
const int MAX = 50;
auto calc=
[&](double d)->double{
double res=0;
{
double L=0,R=100;
for(int k=0;k<MAX;k++){
double M1=L+(R-L)/3,M2=M1+(R-L)/3;
Point c1=g+Vector(d,M1);
Point c2=g+Vector(d,M2);
double a1=area(ps,Circle(c1,r));
double a2=area(ps,Circle(c2,r));
chmax(res,a1);
chmax(res,a2);
if(a2<EPS) R=M2;
else if(a1<a2) L=M1;
else R=M2;
}
}
{
double L=0,R=100;
for(int k=0;k<MAX;k++){
double M1=L+(R-L)/3,M2=M1+(R-L)/3;
Point c1=g+Vector(d,-M1);
Point c2=g+Vector(d,-M2);
double a1=area(ps,Circle(c1,r));
double a2=area(ps,Circle(c2,r));
chmax(res,a1);
chmax(res,a2);
if(a2<EPS) R=M2;
else if(a1<a2) L=M1;
else R=M2;
}
}
chmax(ans,res);
//cout<<d<<":"<<res<<endl;
return res;
};
{
double L=0,R=100;
for(int k=0;k<MAX;k++){
double M1=L+(R-L)/3,M2=M1+(R-L)/3;
if(calc(M2)<EPS) R=M2;
else if(calc(M1)<calc(M2)) L=M1;
else R=M2;
}
}
{
double L=0,R=100;
for(int k=0;k<MAX;k++){
double M1=L+(R-L)/3,M2=M1+(R-L)/3;
if(calc(-M2)<EPS) R=M2;
else if(calc(-M1)<calc(-M2)) L=M1;
else R=M2;
}
}
cout<<ans<<endl;
return 0;
}
|
#include <bits/stdc++.h>
#define cout if (1) cout
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> pii;
#define pb push_back
// area de calota na altura h : 2.pi.R.h
// volume de calota na altura h : pi.h/6 * (3r^2 + h^2)
// XXX marks risky behaviour and TODO marks untested functions
typedef double cood; cood eps = 1e-8; cood inf = 1./0.;
const double pi = acos(-1.);
inline ll sq (ll x) { return x*x; }
inline double sq (double x) { return x*x; }
struct vec { // vector
cood x, y;
vec () : x(0), y(0) {} vec (cood a, cood b) : x(a), y(b) {}
inline vec operator - (vec o) { return vec(x - o.x, y - o.y); }
inline vec operator + (vec o) { return vec(x + o.x, y + o.y); }
inline vec operator * (cood o) { return vec(x * o, y * o); }
inline vec operator / (cood o) { return vec(x / o, y / o); }
inline cood operator ^ (vec o) { return x * o.y - y * o.x; }
inline cood operator * (vec o) { return x * o.x + y * o.y; }
inline cood cross (vec a, vec b) { return ((*this)-a) ^ ((*this)-b); } // |(this)a|sen(angle)
inline cood inner (vec a, vec b) { return ((*this)-a) * ((*this)-b); } // |(this)a|cos(angle)
inline double angle (vec a, vec b) { return atan2(cross(a,b),inner(a,b)); } // ccw angle from (this)a to (this)b in range [-pi,pi]
inline int ccw (vec a, vec b) { cood o = cross(a,b); return (eps < o) - (o < -eps); } // this is to the (1 left, 0 over, -1 right) of ab
inline int dir (vec a, vec b) { cood o = inner(a,b); return (eps < o) - (o < -eps); } // a(this) is to the (1 same, 0 none, -1 opposite) direction of ab
inline cood sq (vec o = vec()) { return inner(o,o); }
inline double nr (vec o = vec()) { return sqrt(sq(o)); }
inline vec proj (vec a, vec b) { return a + (b-a)*(a.inner((*this),b) / a.sq(b)); }
inline vec rotate (double a) { return vec(cos(a) * x - sin(a) * y, sin(a) * x + cos(a) * y); } // ccw by a radians
inline vec rot90 () { return vec(-y,x); } // rotate(pi/2)
inline bool operator < (const vec & o) const { return (x != o.x)?(x < o.x):(y > o.y); } // lex compare (inc x, dec y)
// full ccw angle from compare beginning upwards (this+(0,1)) around (*this)
// incresing distance on ties
bool compare (vec a, vec b) {
if ((a < (*this)) != (b < (*this))) return a < (*this);
int o = ccw(a,b); if (o) return o > 0;
return a.dir((*this),b) < 0;
}
bool in_seg (vec a, vec b) { return ccw(a,b) == 0 && dir(a,b) <= 0; } // tips included
double dist2_lin (vec a, vec b) { return double(::sq(cross(a,b)))/a.sq(b); } // see cir.has_inter_lin
double dist2_seg (vec a, vec b) { return a.dir((*this),b) == (b.dir((*this),a)) ? dist2_lin(a,b) : min(sq(a),sq(b)); }
};
struct lin { // line
cood a, b, c; // a*x + b*y = c
lin () {} lin (cood x, cood y, cood z) : a(x), b(y), c(z) {}
lin (vec s, vec t) : a(t.y - s.y), b(s.x - t.x), c(a * s.x + b * s.y) {}
inline lin parll (vec p) { return lin{a, b, a*p.x + b * p.y}; }
inline lin perp () { return lin{-b, a, c}; }
vec inter (lin o) {
cood d = a * o.b - o.a * b;
if (-eps <= d && d <= eps) throw 1; // parallel
return vec((o.b * c - b * o.c) / d, (a * o.c - o.a * c) / d);
}
bool contains (vec v) { return abs(a*v.x + b*v.y - c) <= eps; }
vec at_x (cood x) { return vec(x,(c-a*x)/b); }
vec at_y (cood y) { return vec((c-b*y)/a,y); }
};
struct cir { // circle
vec c; cood r;
cir () {} cir (vec v, cood d) : c(v), r(d) {}
cir (vec u, vec v, vec w) {
vec mv = (u+v)/2; lin s(mv, mv+(v-u).rot90());
vec mw = (u+w)/2; lin t(mw, mw+(w-u).rot90());
c = s.inter(t); r = c.nr(u);
}
inline bool contains (vec w) { return c.sq(w) <= sq(r) + eps; } // border included
inline bool has_inter (cir o) { return c.sq(o.c) <= sq(r + o.r) + eps; } // borders included
inline bool has_border_inter (cir o) { return has_inter(o) && c.sq(o.c) + eps >= sq(r - o.r); }
inline bool has_inter_lin (vec a, vec b) { return a.sq(b) <= eps ? contains(a) : sq(c.cross(a,b)) <= sq(r)*a.sq(b) + eps; } // borders included XXX overflow
inline bool has_inter_seg (vec a, vec b) { return has_inter_lin(a,b) && (contains(a) || contains(b) || a.dir(c,b)*b.dir(c,a) != -1); } // borders and tips included XXX overflow
inline double arc_area (vec a, vec b) { return c.angle(a,b)*r*r/2; } // smallest arc, ccw positive
inline double arc_len (vec a, vec b) { return c.angle(a,b)*r; } // smallest arc, ccw positive
pair<vec,vec> border_inter (cir o) {
if (!has_border_inter(o)) throw 0;
double a = (sq(r) + o.c.sq(c) - sq(o.r))/(2*o.c.nr(c));
vec v = (o.c - c)/o.c.nr(c); vec m = c + v * a;
double h = sqrt(sq(r) - sq(a)); h = h!=h?0:h;
return pair<vec,vec>(m + v.rot90()*h, m - v.rot90()*h);
}
pair<vec,vec> border_inter_lin (vec a, vec b) { // first is closest to a than second
if (a.dir(b,c) == -1) swap(a,b);
if (!has_inter_lin(a,b)) throw 0;
double d2 = c.dist2_lin(a,b); vec p = (b-a)/a.nr(b);
double h = sqrt(r*r - d2); h = h!=h?0:h;
double y = sqrt(c.sq(a) - d2); y = y!=y?0:y;
return pair<vec,vec>(a + p*(y-h), a + p*(y+h));
}
double triang_inter (vec a, vec b) { // ccw oriented, this with (c,a,b)
if (c.sq(a) > c.sq(b)) return -triang_inter(b,a);
if (contains(b)) return c.cross(a,b)/2;
if (!has_inter_seg(a,b)) return arc_area(a,b);
pair<vec,vec> itr = border_inter_lin(b,a); // order important
if (contains(a)) return c.cross(a,itr.first)/2 + arc_area(itr.first,b);
return arc_area(a,itr.second) + c.cross(itr.second,itr.first)/2 + arc_area(itr.first,b);
}
};
bool inter_seg (vec a, vec b, vec c, vec d) {
if (a.in_seg(c, d) || b.in_seg(c, d) || c.in_seg(a, b) || d.in_seg(a, b)) return true;
return (c.ccw(a, b) * d.ccw(a, b) == -1 && a.ccw(c, d) * b.ccw(c, d) == -1);
}
double dist2_seg (vec a, vec b, vec c, vec d){return inter_seg(a,b,c,d)?0.:min({ a.dist2_seg(c,d), b.dist2_seg(c,d), c.dist2_seg(a,b), d.dist2_seg(a,b) });} // TODO
ostream& operator<<(ostream& os, vec o) { return os << '(' << o.x << ", " << o.y << ')'; }
ostream& operator<<(ostream& os, lin o) { return os << '[' << o.a << "x + " << o.b << "y = " << o.c << ']'; }
ostream& operator<<(ostream& os, cir o) { return os << '[' << o.c << o.r << ']'; }
double polygon_inter (vector<vec> & p, cir c) { // signed area
return inner_product(p.begin(), p.end()-1, p.begin()+1, c.triang_inter(*p.rbegin(),*p.begin()), std::plus<double>(), [&c] (vec a, vec b) { return c.triang_inter(a,b); });
}
const int N = 13;
int n;
ll r;
vector<vec> v(N);
double solve (double y) {
double lo = 100, hi = 0;
for (int i = 0; i < n; i++) {
if (abs(v[i].y - v[i+1].y) <= eps) {
if (abs(v[i].y - y) <= eps) {
lo = min(lo, v[i].x);
lo = min(lo, v[i+1].x);
hi = max(hi, v[i].x);
hi = max(hi, v[i+1].x);
}
} else if (min(v[i].y,v[i+1].y) - eps <= y && y <= max(v[i].y,v[i+1].y) + eps) {
double x = lin(v[i],v[i+1]).at_y(y).x;
lo = min(lo, x);
hi = max(hi, x);
}
}
if (lo > hi) return 0;
int ts = 70;
while (ts--) {
double q1 = (lo + lo + hi)/3;
double q2 = (lo + hi + hi)/3;
if (abs(polygon_inter(v, cir(vec(q1,y),r))) > abs(polygon_inter(v, cir(vec(q2,y),r))))
hi = q2;
else
lo = q1;
}
//cout << lo << " " << y << " : " << abs(polygon_inter(v, cir(vec(lo,y),r))) << endl;
return abs(polygon_inter(v, cir(vec(lo,y),r)));
}
int main () {
while (scanf("%d %lld", &n, &r) != EOF) {
double lo = 100, hi = 0;
for (int i = 0; i < n; i++) {
scanf("%lf %lf", &v[i].x, &v[i].y);
lo = min(lo, v[i].y);
hi = max(hi, v[i].y);
}
v[n] = v[0];
int ts = 80;
while (ts--) {
double q1 = (lo + lo + hi)/3;
double q2 = (lo + hi + hi)/3;
if (solve(q1) < solve(q2))
lo = q1;
else
hi = q2;
}
printf("%.6f\n", solve(lo));
}
}
|
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<climits>
#include<algorithm>
#include<vector>
#include<complex>
#include<cassert>
#define REP(i,s,n) for(int i=s;i<n;++i)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-9)
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
using namespace std;
// BEGIN - Library
bool LT(double a,double b) { return !equals(a,b) && a < b; }
bool LTE(double a,double b) { return equals(a,b) || a < b; }
class Point{
public:
double x,y;
Point(double x = 0,double y = 0): x(x),y(y){}
Point operator + (Point p){return Point(x+p.x,y+p.y);}
Point operator - (Point p){return Point(x-p.x,y-p.y);}
Point operator * (double a){return Point(a*x,a*y);}
Point operator / (double a){return Point(x/a,y/a);}
Point operator * (Point a){ return Point(x * a.x - y * a.y, x * a.y + y * a.x); }
bool operator < (const Point& p) const{ return !equals(x,p.x)?x<p.x:(!equals(y,p.y)&&y<p.y); }
bool operator == (const Point& p)const{ return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS; }
};
struct Segment{
Point p1,p2;
Segment(Point p1 = Point(),Point p2 = Point()):p1(p1),p2(p2){}
bool operator < (const Segment& s) const { return ( p2 == s.p2 ) ? p1 < s.p1 : p2 < s.p2; }
bool operator == (const Segment& s) const { return ( s.p1 == p1 && s.p2 == p2 ) || ( s.p1 == p2 && s.p2 == p1 ); }
};
typedef Point Vector;
typedef Segment Line;
typedef vector<Point> Polygon;
ostream& operator << (ostream& os,const Point& a){ return os << "(" << a.x << "," << a.y << ")"; }
ostream& operator << (ostream& os,const Segment& a){ return os << "( " << a.p1 << " , " << a.p2 << " )"; }
double dot(Point a,Point b){ return a.x*b.x + a.y*b.y; }
double cross(Point a,Point b){ return a.x*b.y - a.y*b.x; }
double norm(Point a){ return a.x*a.x+a.y*a.y; }
double abs(Point a){ return sqrt(norm(a)); }
//rad ????§???????????????¢?????§?????????????????¨
Point rotate(Point a,double rad){ return Point(cos(rad)*a.x - sin(rad)*a.y,sin(rad)*a.x + cos(rad)*a.y); }
// ??????????????¢????????????
double toRad(double agl){ return agl*M_PI/180.0; }
// a => prev, b => cur, c=> next
// prev ?????? cur ????????£??? next ????????????????§????????±???????
double getArg(Point a,Point b,Point c){
double arg1 = atan2(b.y-a.y,b.x-a.x);
double arg2 = atan2(c.y-b.y,c.x-b.x);
double arg = fabs( arg1 - arg2 );
while( arg > M_PI ) arg -= 2.0 * M_PI;
return fabs(arg);
}
int ccw(Point p0,Point p1,Point p2){
Point a = p1-p0;
Point b = p2-p0;
if(cross(a,b) > EPS)return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS)return CLOCKWISE;
if(dot(a,b) < -EPS)return ONLINE_BACK;
if(norm(a) < norm(b))return ONLINE_FRONT;
return ON_SEGMENT;
}
bool intersectLL(Line l, Line m) {
return abs(cross(l.p2-l.p1, m.p2-m.p1)) > EPS || // non-parallel
abs(cross(l.p2-l.p1, m.p1-l.p1)) < EPS; // same line
}
bool intersectLS(Line l, Line s) {
return cross(l.p2-l.p1, s.p1-l.p1)* // s[0] is left of l
cross(l.p2-l.p1, s.p2-l.p1) < EPS; // s[1] is right of l
}
bool intersectLP(Line l,Point p) {
return abs(cross(l.p2-p, l.p1-p)) < EPS;
}
bool intersectSS(Line s, Line t) {
return ccw(s.p1,s.p2,t.p1)*ccw(s.p1,s.p2,t.p2) <= 0 &&
ccw(t.p1,t.p2,s.p1)*ccw(t.p1,t.p2,s.p2) <= 0;
}
bool intersectSP(Line s, Point p) {
return abs(s.p1-p)+abs(s.p2-p)-abs(s.p2-s.p1) < EPS; // triangle inequality
}
Point projection(Line l,Point p) {
double t = dot(p-l.p1, l.p1-l.p2) / norm(l.p1-l.p2);
return l.p1 + (l.p1-l.p2)*t;
}
Point reflection(Line l,Point p) {
return p + (projection(l, p) - p) * 2;
}
double distanceLP(Line l, Point p) {
return abs(p - projection(l, p));
}
double distanceLL(Line l, Line m) {
return intersectLL(l, m) ? 0 : distanceLP(l, m.p1);
}
double distanceLS(Line l, Line s) {
if (intersectLS(l, s)) return 0;
return min(distanceLP(l, s.p1), distanceLP(l, s.p2));
}
double distanceSP(Line s, Point p) {
Point r = projection(s, p);
if (intersectSP(s, r)) return abs(r - p);
return min(abs(s.p1 - p), abs(s.p2 - p));
}
double distanceSS(Line s, Line t) {
if (intersectSS(s, t)) return 0;
return min(min(distanceSP(s, t.p1), distanceSP(s, t.p2)),
min(distanceSP(t, s.p1), distanceSP(t, s.p2)));
}
Point crosspoint(Line l,Line m){
double A = cross(l.p2-l.p1,m.p2-m.p1);
double B = cross(l.p2-l.p1,l.p2-m.p1);
if(abs(A) < EPS && abs(B) < EPS){
vector<Point> vec;
vec.push_back(l.p1),vec.push_back(l.p2),vec.push_back(m.p1),vec.push_back(m.p2);
sort(vec.begin(),vec.end());
assert(vec[1] == vec[2]); //???????????°??????????????????
return vec[1];
//return m.p1;
}
if(abs(A) < EPS)assert(false);
return m.p1 + (m.p2-m.p1)*(B/A);
}
//cross product of pq and pr
double cross3p(Point p,Point q,Point r) { return (r.x-q.x) * (p.y -q.y) - (r.y - q.y) * (p.x - q.x); }
//returns true if point r is on the same line as the line pq
bool collinear(Point p,Point q,Point r) { return fabs(cross3p(p,q,r)) < EPS; }
//returns true if point t is on the left side of line pq
bool ccwtest(Point p,Point q,Point r){
return cross3p(p,q,r) > 0; //can be modified to accept collinear points
}
bool onSegment(Point p,Point q,Point r){
return collinear(p,q,r) && equals(sqrt(pow(p.x-r.x,2)+pow(p.y-r.y,2)) + sqrt(pow(r.x-q.x,2) + pow(r.y-q.y,2) ),sqrt(pow(p.x-q.x,2)+pow(p.y-q.y,2)) ) ;
}
double getArea(vector<Point>& vec) {
double sum = 0;
for(int i=0;i<vec.size();i++)
sum += cross(vec[i],vec[(i+1)%vec.size()]);
return fabs(sum)/2.0;
}
typedef pair<double,double> dd;
const double DINF = 1e20;
#define pow2(a) ((a)*(a))
dd calc(double x1,double y1,double vx1,double vy1,
double x2,double y2,double vx2,double vy2,double r){
double VX = (vx1-vx2), X = (x1-x2), VY = (vy1-vy2), Y = (y1-y2);
double a = pow2(VX) + pow2(VY), b = 2*(X*VX+Y*VY), c = pow2(X) + pow2(Y) - pow2(r);
dd ret = dd(DINF,DINF);
double D = b*b - 4 * a * c;
if( LT(D,0.0) ) return ret;
if( equals(a,0.0) ) {
if( equals(b,0.0) ) return ret;
if( LT(-c/b,0.0) ) return ret;
ret.first = - c / b;
return ret;
}
if( equals(D,0.0) ) D = 0;
ret.first = ( -b - sqrt( D ) ) / ( 2 * a );
ret.second = ( -b + sqrt( D ) ) / ( 2 * a );
if( !equals(ret.first,ret.second) && ret.first > ret.second ) swap(ret.first,ret.second);
return ret;
}
const Point ZERO = Point(0,0);
//??????AB??¨?????????cp,??????r????????¨?????±?????¨????????¢???????±???????
inline double calculator_TypeA(Point A,Point B,Point cp,double r){
A = A - cp, B = B - cp;
if( A == ZERO || B == ZERO ) return 0;
double cross_value = cross(A,B);
if( equals(cross_value,0.0) ) return 0;
double sig = LT(cross_value,0.0) ? -1 : 1;
Segment AB = Segment(A,B);
double nearest_distance = distanceLP(AB,ZERO);
double distance_OA = abs(A);
double distance_OB = abs(B);
if( LTE(0.0,r-distance_OA) && LTE(0.0,r-distance_OB) && LTE(0.0,r-nearest_distance) ) {
return sig * fabs( cross_value / 2.0 );
} else if( LTE(0.0,distance_OA-r) && LTE(0.0,distance_OB-r) && LTE(0.0,nearest_distance-r) ) {
return sig * ( r * r * (M_PI-getArg(A,ZERO,B)) ) / 2.0;
} else if( LTE(0.0,distance_OA-r) && LTE(0.0,distance_OB-r) && LT(0.0,r-nearest_distance) ) {
Point proj_p = projection(AB,ZERO);
if( onSegment(AB.p1,AB.p2,proj_p) ) {
Vector e = ( A - B ) / abs( A - B );
dd tmp = calc(A.x,A.y,e.x,e.y,0,0,0,0,r);
Point r_p1 = A + e * tmp.first;
Point r_p2 = A + e * tmp.second;
double ret = r * r * (M_PI-getArg(B,ZERO,A)) / 2.0;
double subtract = r * r * (M_PI-getArg(r_p1,ZERO,r_p2)) / 2.0 - fabs(cross(r_p1,r_p2))/2.0 ;
return sig * ( ret - subtract );
} else {
return sig * ( r * r * (M_PI-getArg(B,ZERO,A)) ) / 2.0;
}
} else {
if( LT(distance_OB-r,0.0) ) swap(A,B);
Vector e = ( A - B ) / abs( A - B );
dd tmp = calc(A.x,A.y,e.x,e.y,0,0,0,0,r);
Point r_p1 = A + e * tmp.first;
Point r_p2 = A + e * tmp.second;
if( onSegment(A,B,r_p2) ) r_p1 = r_p2;
double ret = fabs(cross(r_p1,A)) * 0.5;
ret += r * r * (M_PI-getArg(r_p1,ZERO,B)) * 0.5;
return sig * ret;
}
assert(false);
}
double getCommonAreaPolygonCircle(const Polygon &poly,Point cp,double r){
double sum = 0;
rep(i,(int)poly.size()){
sum += calculator_TypeA(poly[i],poly[(i+1)%(int)poly.size()],cp,r);
}
return fabs(sum);
}
Polygon andrewScan(Polygon s) {
Polygon u,l;
if(s.size() < 3)return s;
sort(s.begin(),s.end());
u.push_back(s[0]);
u.push_back(s[1]);
l.push_back(s[s.size()-1]);
l.push_back(s[s.size()-2]);
for(int i=2;i<(int)s.size();i++)
{
for(int n=u.size();n >= 2 && ccw(u[n-2],u[n-1],s[i]) != CLOCKWISE; n--)
u.pop_back();
u.push_back(s[i]);
}
for(int i=s.size()-3; i>=0 ; i--)
{
for(int n=l.size(); n >= 2 && ccw(l[n-2],l[n-1],s[i]) != CLOCKWISE; n--)
l.pop_back();
l.push_back(s[i]);
}
reverse(l.begin(),l.end());
for(int i = u.size()-2; i >= 1; i--) l.push_back(u[i]);
return l;
}
Point calc_ps(Polygon poly) {
poly = andrewScan(poly);
Point mp = poly[0];
double rate = 1; // 0.5???????????¨???
int max_pos;
double eps = 1e-10; // 1e-20???????????¨???
while( rate > eps ) {
rep(_,60){ // 70???????????¨???
max_pos = 0;
REP(j,1,(int)poly.size()) {
double dist1 = abs(mp-poly[max_pos]);
double dist2 = abs(mp-poly[j]);
if( LT(dist1,dist2) ) max_pos = j;
}
mp.x += ( poly[max_pos].x - mp.x ) * rate;
mp.y += ( poly[max_pos].y - mp.y ) * rate;
}
rate *= 0.5;
}
return mp;
}
Point getCentroidOfConvex(Polygon& poly){
double area = getArea(poly);
int V = poly.size();
assert( !equals(area,0.0) );
double x = 0, y = 0;
rep(i,(int)poly.size()) {
x += ( poly[i].x + poly[(i+1)%V].x ) * ( poly[i].x*poly[(i+1)%V].y - poly[(i+1)%V].x*poly[i].y );
y += ( poly[i].y + poly[(i+1)%V].y ) * ( poly[i].x*poly[(i+1)%V].y - poly[(i+1)%V].x*poly[i].y );
}
return Point(x/(6.0*area),y/(6.0*area));
}
// END - Library
int n,r;
Polygon poly;
void compute() {
double maxi;
Point mp = calc_ps(poly);
maxi = getCommonAreaPolygonCircle(poly,mp,r);
double rate = 1.0;
double eps = 1e-10;
while( LT(eps,rate) ) {
rep(_,70) {
double max_area = -1;
Point np;
rep(i,n) {
Point tp = mp;
tp.x += ( poly[i].x - mp.x ) * rate;
tp.y += ( poly[i].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,tp,r);
if( LT(max_area,area) ) {
max_area = area;
np = tp;
}
}
assert( !equals(max_area,-1) );
mp = np;
if( LT(maxi,max_area) ) maxi = max_area;
}
rate *= 0.5;
}
rep(__,5) {
Point mp = calc_ps(poly);
double rate = 1.0;
double eps = 1e-10;
while( LT(eps,rate) ) {
rep(_,70) {
double max_area = -1;
Point np;
rep(i,n) {
Point tp = mp;
tp.x += ( poly[i].x - mp.x ) * rate;
tp.y += ( poly[i].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,tp,r);
if( LT(max_area,area) ) {
max_area = area;
np = tp;
}
}
if( rand() % 50 == 0 ) {
int v = rand() % n;
np.x = ( poly[v].x - mp.x ) * rate;
np.y = ( poly[v].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,np,r);
if( LT(max_area,area) ) {
max_area = area;
}
}
assert( !equals(max_area,-1) );
mp = np;
if( LT(maxi,max_area) ) maxi = max_area;
}
rate *= 0.5;
}
}
printf("%.10f\n",maxi);
}
int main() {
srand((unsigned int)time(NULL));
cin >> n >> r;
poly.resize(n);
rep(i,n) cin >> poly[i].x >> poly[i].y;
//cout << getArea(poly) << endl;
compute();
return 0;
} |
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
template<class T> using V = vector<T>;
using D = double;
const D PI = acos(D(-1)), EPS = 1e-10;
int sgn(D a) { return (abs(a) <= EPS) ? 0 : (a < 0 ? -1 : 1); }
int sgn(D a, D b) { return sgn(a-b); }
//relative sign
// int rsgn(D a, D f) {
// if (abs(a) <= f*EPS) return 0;
// return (a < 0) ? -1 : 1;
// }
struct Pt2 {
D x, y;
Pt2(D _x = D(), D _y = D()) : x(_x), y(_y) {}
Pt2 operator+(const Pt2 &r) const { return Pt2(x+r.x, y+r.y); }
Pt2 operator-(const Pt2 &r) const { return Pt2(x-r.x, y-r.y); }
Pt2 operator*(const Pt2 &r) const { return Pt2(x*r.x-y*r.y, x*r.y+y*r.x); }
Pt2 operator*(const D &r) const { return Pt2(x*r, y*r); }
Pt2 operator/(const D &r) const { return Pt2(x/r, y/r); }
Pt2& operator+=(const Pt2 &r) { return *this=*this+r; }
Pt2& operator-=(const Pt2 &r) { return *this=*this-r; }
Pt2& operator*=(const Pt2 &r) { return *this=*this*r; }
Pt2& operator*=(const D &r) { return *this=*this*r; }
Pt2& operator/=(const D &r) { return *this=*this/r; }
Pt2 operator-() const { return Pt2(-x, -y); }
bool operator<(const Pt2 &r) const { return 2*sgn(x, r.x)+sgn(y, r.y)<0; }
bool operator==(const Pt2 &r) const { return sgn((*this-r).rabs()) == 0; }
D norm() const { return x*x + y*y; }
D abs() const { return sqrt(norm()); }
D rabs() const { return max(std::abs(x), std::abs(y)); } // robust abs
D arg() const { return atan2(y, x); }
pair<D, D> to_pair() const { return make_pair(x, y); }
static Pt2 polar(D le, D th) { return Pt2(le*cos(th), le*sin(th)); }
};
ostream& operator<<(ostream& os, const Pt2 &p) {
return os << "P(" << p.x << ", " << p.y << ")";
}
using P = Pt2;
struct L {
P s, t;
L(P _s = P(), P _t = P()) : s(_s), t(_t) {}
P vec() const { return t-s; }
D abs() const { return vec().abs(); }
D arg() const { return vec().arg(); }
};
ostream& operator<<(ostream& os, const L &l) {
return os << "L(" << l.s << ", " << l.t << ")";
}
D cross(P a, P b) { return a.x*b.y - a.y*b.x; }
D dot(P a, P b) { return a.x*b.x + a.y*b.y; }
// cross(a, b) is too small?
int sgncrs(P a, P b) {
D cr = cross(a, b);
if (abs(cr) <= (a.rabs() + b.rabs()) * EPS) return 0;
return (cr < 0) ? -1 : 1;
}
// -2, -1, 0, 1, 2 : front, clock, on, cclock, back
int ccw(P b, P c) {
int s = sgncrs(b, c);
if (s) return s;
if (!sgn(c.rabs()) || !sgn((c-b).rabs())) return 0;
if (dot(b, c) < 0) return 2;
if (dot(-b, c-b) < 0) return -2;
return 0;
}
int ccw(P a, P b, P c) { return ccw(b-a, c-a); }
int ccw(L l, P p) { return ccw(l.s, l.t, p); }
P project(const L &l, const P &p) {
P v = l.vec();
return l.s + v * (dot(v, p-l.s) / v.norm());
}
bool insSL(const L &s, const L &l) {
int a = ccw(l, s.s), b = ccw(l, s.t);
return (a%2 == 0 || b%2 == 0 || a != b);
}
bool insSS(const L &s, const L &t) {
int a = ccw(s, t.s), b = ccw(s, t.t);
int c = ccw(t, s.s), d = ccw(t, s.t);
if (a*b <= 0 && c*d <= 0) return true;
return false;
}
D distLP(const L &l, const P &p) {
return abs(cross(l.vec(), p-l.s)) / l.abs();
}
D distSP(const L &s, const P &p) {
P q = project(s, p);
if (ccw(s, q) == 0) return (p - q).abs();
else return min((s.s - p).abs(), (s.t - p).abs());
}
int crossLL(const L &l, const L &m, P &r) {
D cr1 = cross(l.vec(), m.vec()), cr2 = cross(l.vec(), l.t - m.s);
if (sgncrs(l.vec(), m.vec()) == 0) {
r = l.s;
if (sgncrs(l.vec(), l.t - m.s)) return 0;
return -1;
}
r = m.s + m.vec() * (cr2 / cr1);
return 1;
}
using Pol = V<P>;
struct C {
P p; D r;
C(P _p = P(), D _r = D()) : p(_p), r(_r) {}
};
//need Intersect/distLP, r.sはよりl.sに近い
int crossCL(const C &c, const L &l, L &r) {
D u = distLP(l, c.p);
int si = sgn(u, c.r);
if (si == 1) return 0;
P v = project(l, c.p);
P di = (si == 0) ? P(0, 0) : l.vec() * (sqrt(c.r*c.r - u*u) / l.abs());
r = L(v-di, v+di);
if (si == 0) return 1;
return 2;
}
//need Intersect/distLP, r.sはよりl.sに近い
int crossCS(const C &c, const L &s, L &l) {
if (!crossCL(c, s, l)) return 0;
bool f1 = ccw(s, l.s) == 0, f2 = ccw(s, l.t) == 0;
if (f1 && f2) return 2;
if (!f1 && !f2) return 0;
if (f1) l.t = l.s;
else l.s = l.t;
return 1;
}
// C(P(0, 0), r)とTri((0, 0), a, b)の共有面積
D area2CT(const C &c, const P &_a, const P &_b) {
P a = _a - c.p, b = _b - c.p; D r = c.r;
if (a == b) return 0;
auto single = [&](P x, P y, bool tri) {
if (tri) return cross(x, y);
else return r * r * ((y * P(x.x, -x.y)).arg());
};
bool ia = sgn(a.abs(), r) != 1, ib = sgn(b.abs(), r) != 1;
if (ia && ib) return single(a, b, true);
L l;
if (!crossCS(C(P(0, 0), r), L(a, b), l)) return single(a, b, false);
// if (ia) l.s = l.t;
// else if (ib) l.t = l.s;
assert(ccw(a, b, l.s) == 0); assert(ccw(a, b, l.t) == 0);
return single(a, l.s, ia) + single(l.s, l.t, true) + single(l.t, b, ib);
}
// p, cの共有面積
D area2CPol(const C &c, const Pol &po) {
D sm = 0;
P a, b = po.back();
for (auto p: po) {
a = b; b = p;
sm += area2CT(c, a, b);
}
return sm;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << setprecision(20);
int n; D r;
cin >> n >> r;
Pol pol;
D ymi = 1e100, yma = -1e100;
for (int i = 0; i < n; i++) {
D x, y;
cin >> x >> y;
pol.push_back(P(x, y));
ymi = min(ymi, y);
yma = max(yma, y);
}
auto calc = [&](D y) {
D xmi = 1e100, xma = -1e100;
P a, b = pol.back();
for (int i = 0; i < n; i++) {
a = b; b = pol[i];
P p;
if (crossLL(L(a, b), L(P(0, y), P(1, y)), p) == 0) continue;
if (ccw(a, b, p) != 0) continue;
xmi = min(xmi, p.x); xma = max(xma, p.x);
}
D lw = xmi, up = xma;
for (int ph = 0; ph < 30; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
D z1 = area2CPol(C(P(md1, y), r), pol) / 2;
D z2 = area2CPol(C(P(md2, y), r), pol) / 2;
if (z1 < z2) {
lw = md1;
} else {
up = md2;
}
}
return area2CPol(C(P(lw, y), r), pol) / 2;
};
D lw = ymi, up = yma;
for (int ph = 0; ph < 30; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
if (calc(md1) < calc(md2)) {
lw = md1;
} else {
up = md2;
}
}
cout << calc(lw) << endl;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
template<class T> using V = vector<T>;
using D = double;
const D PI = acos(D(-1)), EPS = 1e-10;
int sgn(D a) { return (abs(a) <= EPS) ? 0 : (a < 0 ? -1 : 1); }
int sgn(D a, D b) { return sgn(a-b); }
//relative sign
// int rsgn(D a, D f) {
// if (abs(a) <= f*EPS) return 0;
// return (a < 0) ? -1 : 1;
// }
struct Pt2 {
D x, y;
Pt2(D _x = D(), D _y = D()) : x(_x), y(_y) {}
Pt2 operator+(const Pt2 &r) const { return Pt2(x+r.x, y+r.y); }
Pt2 operator-(const Pt2 &r) const { return Pt2(x-r.x, y-r.y); }
Pt2 operator*(const Pt2 &r) const { return Pt2(x*r.x-y*r.y, x*r.y+y*r.x); }
Pt2 operator*(const D &r) const { return Pt2(x*r, y*r); }
Pt2 operator/(const D &r) const { return Pt2(x/r, y/r); }
Pt2& operator+=(const Pt2 &r) { return *this=*this+r; }
Pt2& operator-=(const Pt2 &r) { return *this=*this-r; }
Pt2& operator*=(const Pt2 &r) { return *this=*this*r; }
Pt2& operator*=(const D &r) { return *this=*this*r; }
Pt2& operator/=(const D &r) { return *this=*this/r; }
Pt2 operator-() const { return Pt2(-x, -y); }
bool operator<(const Pt2 &r) const { return 2*sgn(x, r.x)+sgn(y, r.y)<0; }
bool operator==(const Pt2 &r) const { return sgn((*this-r).rabs()) == 0; }
D norm() const { return x*x + y*y; }
D abs() const { return sqrt(norm()); }
D rabs() const { return max(std::abs(x), std::abs(y)); } // robust abs
D arg() const { return atan2(y, x); }
pair<D, D> to_pair() const { return make_pair(x, y); }
static Pt2 polar(D le, D th) { return Pt2(le*cos(th), le*sin(th)); }
};
ostream& operator<<(ostream& os, const Pt2 &p) {
return os << "P(" << p.x << ", " << p.y << ")";
}
using P = Pt2;
struct L {
P s, t;
L(P _s = P(), P _t = P()) : s(_s), t(_t) {}
P vec() const { return t-s; }
D abs() const { return vec().abs(); }
D arg() const { return vec().arg(); }
};
ostream& operator<<(ostream& os, const L &l) {
return os << "L(" << l.s << ", " << l.t << ")";
}
D cross(P a, P b) { return a.x*b.y - a.y*b.x; }
D dot(P a, P b) { return a.x*b.x + a.y*b.y; }
// cross(a, b) is too small?
int sgncrs(P a, P b) {
D cr = cross(a, b);
if (abs(cr) <= (a.rabs() + b.rabs()) * EPS) return 0;
return (cr < 0) ? -1 : 1;
}
// -2, -1, 0, 1, 2 : front, clock, on, cclock, back
int ccw(P b, P c) {
int s = sgncrs(b, c);
if (s) return s;
if (!sgn(c.rabs()) || !sgn((c-b).rabs())) return 0;
if (dot(b, c) < 0) return 2;
if (dot(-b, c-b) < 0) return -2;
return 0;
}
int ccw(P a, P b, P c) { return ccw(b-a, c-a); }
int ccw(L l, P p) { return ccw(l.s, l.t, p); }
P project(const L &l, const P &p) {
P v = l.vec();
return l.s + v * (dot(v, p-l.s) / v.norm());
}
bool insSL(const L &s, const L &l) {
int a = ccw(l, s.s), b = ccw(l, s.t);
return (a%2 == 0 || b%2 == 0 || a != b);
}
bool insSS(const L &s, const L &t) {
int a = ccw(s, t.s), b = ccw(s, t.t);
int c = ccw(t, s.s), d = ccw(t, s.t);
if (a*b <= 0 && c*d <= 0) return true;
return false;
}
D distLP(const L &l, const P &p) {
return abs(cross(l.vec(), p-l.s)) / l.abs();
}
D distSP(const L &s, const P &p) {
P q = project(s, p);
if (ccw(s, q) == 0) return (p - q).abs();
else return min((s.s - p).abs(), (s.t - p).abs());
}
int crossLL(const L &l, const L &m, P &r) {
D cr1 = cross(l.vec(), m.vec()), cr2 = cross(l.vec(), l.t - m.s);
if (sgncrs(l.vec(), m.vec()) == 0) {
r = l.s;
if (sgncrs(l.vec(), l.t - m.s)) return 0;
return -1;
}
r = m.s + m.vec() * (cr2 / cr1);
return 1;
}
using Pol = V<P>;
struct C {
P p; D r;
C(P _p = P(), D _r = D()) : p(_p), r(_r) {}
};
//need Intersect/distLP, r.sはよりl.sに近い
int crossCL(const C &c, const L &l, L &r) {
D u = distLP(l, c.p);
int si = sgn(u, c.r);
if (si == 1) return 0;
P v = project(l, c.p);
P di = (si == 0) ? P(0, 0) : l.vec() * (sqrt(c.r*c.r - u*u) / l.abs());
r = L(v-di, v+di);
if (si == 0) return 1;
return 2;
}
//need Intersect/distLP, r.sはよりl.sに近い
int crossCS(const C &c, const L &s, L &l) {
if (!crossCL(c, s, l)) return 0;
bool f1 = ccw(s, l.s) == 0, f2 = ccw(s, l.t) == 0;
if (f1 && f2) return 2;
if (!f1 && !f2) return 0;
if (f1) l.t = l.s;
else l.s = l.t;
return 1;
}
// C(P(0, 0), r)とTri((0, 0), a, b)の共有面積
D area2CT(const C &c, const P &_a, const P &_b) {
P a = _a - c.p, b = _b - c.p; D r = c.r;
if (a == b) return 0;
auto single = [&](P x, P y, bool tri) {
if (tri) return cross(x, y);
else return r * r * ((y * P(x.x, -x.y)).arg());
};
bool ia = sgn(a.abs(), r) != 1, ib = sgn(b.abs(), r) != 1;
if (ia && ib) return single(a, b, true);
// if (sgn(r, distSP(L(a, b), P(0, 0))) != 1) return single(a, b, false);
L l;
if (!crossCS(C(P(0, 0), r), L(a, b), l)) return single(a, b, false);
if (ia) l.s = l.t;
else if (ib) l.t = l.s;
assert(ccw(a, b, l.s) == 0); assert(ccw(a, b, l.t) == 0);
return single(a, l.s, ia) + single(l.s, l.t, true) + single(l.t, b, ib);
}
// p, cの共有面積
D area2CPol(const C &c, const Pol &po) {
D sm = 0;
P a, b = po.back();
for (auto p: po) {
a = b; b = p;
sm += area2CT(c, a, b);
}
return sm;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << setprecision(20);
int n; D r;
cin >> n >> r;
Pol pol;
D ymi = 1e100, yma = -1e100;
for (int i = 0; i < n; i++) {
D x, y;
cin >> x >> y;
pol.push_back(P(x, y));
ymi = min(ymi, y);
yma = max(yma, y);
}
auto calc = [&](D y) {
D xmi = 1e100, xma = -1e100;
P a, b = pol.back();
for (int i = 0; i < n; i++) {
a = b; b = pol[i];
P p;
if (crossLL(L(a, b), L(P(0, y), P(1, y)), p) == 0) continue;
if (ccw(a, b, p) != 0) continue;
xmi = min(xmi, p.x); xma = max(xma, p.x);
}
D lw = xmi, up = xma;
for (int ph = 0; ph < 30; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
D z1 = area2CPol(C(P(md1, y), r), pol) / 2;
D z2 = area2CPol(C(P(md2, y), r), pol) / 2;
if (z1 < z2) {
lw = md1;
} else {
up = md2;
}
}
return area2CPol(C(P(lw, y), r), pol) / 2;
};
D lw = ymi, up = yma;
for (int ph = 0; ph < 30; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
if (calc(md1) < calc(md2)) {
lw = md1;
} else {
up = md2;
}
}
cout << calc(lw) << endl;
return 0;
}
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef double db;
typedef unsigned char uchar;
using namespace std;
int getint(int x=0) { scanf("%d",&x); return x; }
ll getll(ll x=0) { scanf("%lld", &x); return x; }
double getdb(double x=0) { scanf("%lf",&x); return x; }
// ====================================================1========
const int INF = (1<<30)-1;
const ll LINF = (1L<<62)-1;
const double eps = 1e-10;
struct point;
struct point
{
db x,y;
point() : x(0),y(0) { }
point(db x, db y) : x(x),y(y) { }
db len() { return sqrt(x*x+y*y); }
db len2() { return x*x+y*y; }
point operator()(point b) const { return point(b.x-x, b.y-y); }
point norm() { double l = len(); return point(x/l, y/l); }
void out(const char* s = "") { printf("(%.2f, %.2f) %s", x, y, s); }
point operator-() { return point(-x, -y); }
};
point operator+(point a, point b) { return point(a.x + b.x, a.y + b.y); }
point operator-(point a, point b) { return point(a.x - b.x, a.y - b.y); }
db operator*(point a, point b) { return a.x * b.y - a.y * b.x; }
db operator&(point a, point b){ return a.x * b.x + a.y * b.y; }
point operator*(point a, db f) { return point(a.x * f, a.y * f); }
point operator*(db f, point a) { return point(a.x * f, a.y * f); }
point operator/(point a, db f) { return point(a.x / f, a.y / f); }
db Area(point a, point b, point c) { return abs(c(a)*c(b)*0.5); }
db Angle(point a, point b) { return acos((a&b)/a.len()/b.len()); }
db DistP2L(point c, point a, point b) { return Area(a,b,c) * 2.0 / a(b).len(); }
db ArcArea(db r, db angle) { return angle * r * r / 2.0; }
db ArcArea(db r, point c, point a, point b) { return ArcArea(r, Angle(c(a), c(b))); }
point rot90(point c) { return point(-c.y, c.x); }
db IntArea(db r, point c, point a,point b)
{
if( c(a).len() < eps ||
c(b).len() < eps ||
a(b).len() < eps)
return 0;
bool ain = c(a).len() < r;
bool bin = c(b).len() < r;
if(ain && bin)
{
//printf("!!!");
return abs(c(a) * c(b) * 0.5);
}
db d = DistP2L(c, a, b);
//printf("d:%.8f ", d);
if(!ain && !bin)
{
//printf("xx");
if(d < r) // line intersect!
{
db m = sqrt(r*r-d*d);
point dir = rot90(a(b)).norm() * d;
if(DistP2L(c + dir, a, b) > eps)
dir = - dir;
point ita = c + dir + a(b).norm() * m;
point itb = c + dir + b(a).norm() * m;
if((ita(a) & ita(b)) >= 0) // two points are on the same side.
{
//printf("^");
return ArcArea(r, c, a, b);
}
//printf("-");
db Tar = m * d;
if(a(ita).len() > a(itb).len()) swap(ita, itb);
db Aar = ArcArea(r, c, a, ita);
db Bar = ArcArea(r, c, b, itb);
// a.out(); b.out("\n");
// ita.out(); itb.out("\n");
// a(ita).out(); a(itb).out("\n");
// c(a).out(); c(itb).out(); c(ita).out("\n");
// printf("angle: %.6f\n", Angle(c(a), c(ita)));
// printf(" r:%.2f d:%.2f m:%.2f t:%.2f a:%.2f b:%.2f\n", r, d, m, Tar, Aar, Bar);
return Tar + Aar + Bar;
}
else // line not intersect.
{
//printf(".");
return ArcArea(r, c, a, b);
}
}
//printf("x. ");
if(!ain && bin) swap(a, b);
point dir = rot90(a(b)).norm() * d;
if(DistP2L(c + dir, a, b) > eps) dir = - dir;
db m = sqrt(r*r-d*d);
point ita = c + dir + a(b).norm() * m;
return a(ita).len() * d * 0.5 + ArcArea(r, c, b, ita);
}
int n;
db r;
point p[50];
db GetIntArea(point c)
{
db res = 0.0;
for(int i=1; i<=n; i++)
{
point a = p[i];
point b = p[i-1];
if(c(a).len() <= eps || c(b).len() <= eps) continue;
if(a(c) * c(b) > eps) // positive triangle.
res += IntArea(r, c, a, b);
else if(a(c) * c(b) < eps)
res -= IntArea(r, c, a, b);
//printf("(%.2f, %.2f)-(%.2f, %.2f) %.8f ", a.x, a.y, b.x, b.y, IntArea(r, c, a, b));
//printf("%.8f\n", res);
}
//printf("%.2f\n", res);
return res;
}
double randdb() { return (db)rand() / RAND_MAX; }
int main()
{
n = getint();
r = getint();
for(int i=1; i<=n; i++)
{
p[i].x = getint();
p[i].y = getint();
}
p[0] = p[n];
// Sim Anealling.
srand(12512);
db Tbegin = 1e2;
db Tend = 1e-6;
db T = Tbegin;
db rate = 0.99995;
int cnt = 0;
int tcnt = 0;
point mvbase = point(0.01, 0.01);
point curp = p[1];
db curmax = GetIntArea(curp);
while(T >= Tend)
{
point nxtp = curp + point(
(randdb() - 0.5) * 2.0 * mvbase.x * T,
(randdb() - 0.5) * 2.0 * mvbase.y * T);
db v = GetIntArea(nxtp);
db dist = v - curmax;
//nxtp.out(""); printf("v:%.4f dist:%.4f T:%.6f, p:%.4f\n", v, dist, T, exp(dist / T));
if(dist > eps || (dist < -eps && randdb() > exp(dist / T))
)
{
curmax = v;
curp = nxtp;
tcnt++;
}
T *= rate;
//T -= 1e-6;
cnt++;
}
//printf("SA count:%d, transfer count:%d\n", cnt, tcnt);
printf("%.6f\n", curmax);
// printf("%.8f\n", IntArea(1, {0, 0}, {1, 0}, {0, 1})); // 0.5 .
// printf("%.8f\n", IntArea(1, {0, 0}, {2, 0}, {0, 2}));
// printf("%.8f\n", IntArea(1, {0, 0}, {1.00000001, 0}, {0, 0.5}));
// printf("res, %.8f\n", IntArea(1, {5.44, -0.62}, {0, 0}, {100, 1}));
// printf("res, %.8f\n", IntArea(1, {5.44, -0.62}, {100, 1}, {99, 1}));
// printf("res, %.8f\n", IntArea(1, {5.44, -0.62}, {99, 1}, {0, 0}));
// printf("res, %.8f\n", IntArea(1, {98.21, 0.39}, {0, 0}, {100, 1}));
// printf("res, %.8f\n", IntArea(1, {98.21, 0.39}, {100, 1}, {99, 1}));
// printf("res, %.8f\n", IntArea(1, {98.21, 0.39}, {99, 1}, {0, 0}));
return 0;
} |
#include <bits/stdc++.h>
#define cout if (0) cout
// XXX without explanation marks untested functions
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> pii;
#define pb push_back
// NOT STANDART FROM HERE
// area de calota 2.pi.R.h (h altura)
// volume de calota pi.h/6 * (3r^2 + h^2)
typedef double cood;
cood eps = 1e-8;
// tests for double were made with eps = 1e-8
double eps_d = 1e-8; // necessary even in integer geometry, should be eps otherwise
const double pi = acos(-1.);
inline ll sq (ll x)
{ return x*x; }
inline double sq (double x)
{ return x*x; }
struct vec { // vector
// === BASIC ===
cood x, y;
vec () : x(0), y(0) {}
vec (cood a, cood b) : x(a), y(b) {}
friend ostream& operator<<(ostream& os, vec o);
vec operator - (vec o)
{ return vec(x - o.x, y - o.y); }
vec operator + (vec o)
{ return vec(x + o.x, y + o.y); }
vec operator * (cood o)
{ return vec(x * o, y * o); }
vec operator / (cood o)
{ return vec(x / o, y / o); }
cood operator ^ (vec o)
{ return x * o.y - y * o.x; }
cood operator * (vec o)
{ return x * o.x + y * o.y; }
// positive is (*this)b is clockwise from (*this)a
double angle (vec a, vec b)
{ return atan2((a-(*this))^(b-(*this)), (a-(*this))*(b-(*this))); }
cood sq (vec o = vec())
{ return ((*this)-o)*((*this)-o); }
double nr (vec o = vec())
{ return sqrt(sq(o)); }
cood cross (vec a, vec b) // ccw signed area (positive if this is to the left of ab)
{ return (b - a) ^ ((*this) - a); }
int ccw (vec a, vec b) // which side is this from ab? (1 left, 0 over, -1 right)
{ cood o = cross(a, b); return (eps < o) - (o < -eps); }
int dir (vec a, vec b) // direction of (this)a relative to (this)b (-1 opposite, 0 none, 1 same)
{ cood o = ((*this) - a)*((*this) - b); return (eps < o) - (o < -eps); }
cood inner (vec s, vec t) // (p-s)*(t-s) where p = this projected on st
{ return ((*this) - s) * (t - s); }
vec proj (vec s, vec t) // projection of this point over line st
{ return s + (t - s)*(inner(s,t) / t.sq(s)); }
vec rotate (double a) // rotate ccw by a (fails with ll)
{ return vec(cos(a) * x - sin(a) * y, sin(a) * x + cos(a) * y); }
vec rot90 () // rotate pi/2 ccw
{ return vec(-y, x); }
// === ADVANCED ===
// ordering that defines the compare method
// used only there, change it accordingly
// sorts increasing on y and, then increasing on x
bool operator < (const vec & o) const {
if (y != o.y)
return y < o.y;
return x < o.x;
}
// full ordering (ccw angle from this+(1,0), distance to this)
// is a < b?
// PRECISION : ok with double if norm in [-1e9,5e3]
bool compare (vec a, vec b) {
if (((*this) < a) != ((*this) < b))
return (*this) < a;
int o = ccw(a,b);
if (o) return o > 0;
return a.dir((*this),b) < 0;
}
// is this inside segment st? (tip of segment included, change for dr < 0 otherwise)
bool in_seg (vec s, vec t)
{ return (ccw(s,t) == 0) && (dir(s,t) <= 0); }
// squared distance from this to line defined by st
double dist2_lin (vec s, vec t)
{ return double(::sq(cross(s,t))) / t.sq(s); }
// squared distance from this to segment st
double dist2_seg (vec s, vec t)
{ return s.dir((*this),t) == t.dir((*this),s) ? dist2_lin(s,t) : min(sq(s),sq(t)); }
// is this inside (borders included) the convex polygon v of size n?
// if yes, prec is the vec that this on acw order from v[0] or 0 if there is no such
// if not, prec is the predecessor of this when added to poly and succ is the sucessor
// p should be a vector with [0..n-1]
// n should be >= 2
bool in_conv_poly (vec v[], int n, const vector<int> & p, int & prec, int & succ) {
if (nr(v[0]) <= eps) {
prec = 0;
return 1;
}
if (n == 2) {
if (in_seg(v[0],v[1]))
return (prec = 1);
if (ccw(v[0],v[1]) > 0) {
prec = 1;
succ = 0;
} else if (ccw(v[0],v[1]) < 0) {
prec = 0;
succ = 1;
} else {
prec = succ = (v[0].dir((*this),v[1]) < 0);
}
return 0;
}
if (ccw(v[0],v[1]) > 0 || ccw(v[0],v[n-1]) < 0) {
// case where v[0] is not removed
// last diagonal before or over this
int di = lower_bound(p.begin() + 1, p.end(), -1, [this,v] (int i, int j) {
assert(j == -1);
return ccw(v[0],v[i]) >= 0;
}) - p.begin() - 1;
// is this inside the polygon?
prec = di;
if (di == n-1) {
// last segment
if (ccw(v[0],v[n-1]) == 0 && ccw(v[n-2],v[n-1]) >= 0)
return 1;
} else {
// inside otherwise
if (ccw(v[di],v[di+1]) >= 0)
return 1;
}
// last that stays before (or eq to) di
prec = lower_bound(p.begin() + 1, p.begin() + di + 1, -1, [this,v] (int i, int j) {
assert(j == -1);
return ccw(v[i-1],v[i]) > 0;
}) - p.begin() - 1;
// first that stays after di
succ = lower_bound(p.begin() + di + 1, p.end(), -1, [this,v,n] (int i, int j) {
assert(j == -1);
return ccw(v[(i+1)%n],v[i]) >= 0;
}) - p.begin();
if (succ == n) succ = 0;
} else {
// case where v[0] is removed
// first diagonal before of over this
// di is certainly not removed
int di = lower_bound(p.begin() + 1, p.end() - 1, -1, [this,v] (int i, int j) {
assert(j == -1);
return ccw(v[0],v[i]) < 0;
}) - p.begin();
// first that stays (<= di)
succ = lower_bound(p.begin(), p.begin() + di, -1, [this,v] (int i, int j) {
assert(j == -1);
return ccw(v[i+1],v[i]) >= 0;
}) - p.begin();
// last that stays (>= di)
prec = lower_bound(p.begin() + di + 1, p.end(), -1, [this,v] (int i, int j) {
assert(j == -1);
return ccw(v[i-1],v[i]) > 0;
}) - p.begin() - 1;
}
return 0;
}
};
ostream& operator<<(ostream& os, vec o)
{ return os << '(' << o.x << ", " << o.y << ')'; }
struct lin { // line
cood a, b, c; // a*x + b*y = c
lin () {}
lin (cood x, cood y, cood z) : a(x), b(y), c(z) {}
lin (vec s, vec t) : a(t.y - s.y), b(s.x - t.x), c(a * s.x + b * s.y) {}
lin parll (vec p) // parallel to this through p
{ return lin(a, b, a * p.x + b * p.y); }
lin perp ()
{ return lin(-b, a, c); }
vec inter (lin o) {
cood d = a * o.b - o.a * b;
if (d < eps && -eps < d) throw 0; // parallel
return vec((o.b * c - b * o.c) / d, (a * o.c - o.a * c) / d);
}
};
struct cir { // circle
vec c; cood r;
// borders included
bool contains (vec w)
{ return c.sq(w) <= sq(r) + eps; }
bool has_inter (cir o)
{ return c.sq(o.c) <= sq(r + o.r) + eps; }
bool has_inter_lin (vec s, vec t)
{ return c.dist2_lin(s,t) <= sq(r) + eps_d; }
bool has_inter_seg (vec s, vec t)
{ return c.dist2_seg(s,t) <= sq(r); }
// borders not included
bool contains (cir o)
{ return (o.r < r - eps && c.sq(o.c) < sq(r - o.r) - eps); }
// ccw oriented area of arc from a to b
double arc_area (vec a, vec b) {
double ang = c.angle(a,b);
return r*r*ang*.5;
}
// double only
pair<vec,vec> inter_pts (cir o) {
assert(has_inter(o) && !contains(o)); // fully contained case
double d = c.nr(o.c);
double a = (r*r + d*d - o.r*o.r) / (2.*d); // r*cos(ans,v,c.v)
double h = sqrt(r*r - a*a);
if (h != h) h = 0;
vec p = o.c - c;
return pair<vec,vec>(c + p*(a/d) + (p.rot90()*(h/d)), c + p*(a/d) - (p.rot90()*(h/d)));
}
// double only XXX careful precision
pair<vec,vec> inter_pts (vec s, vec t) {
assert(has_inter_lin(s,t));
double h2 = c.dist2_lin(s,t);
double d = sqrt(c.sq(t) - h2);
if (d != d) d = 0;
vec p = (s-t);
vec m = t + p*(d/p.nr());
vec m_b = t - p*(d/p.nr());
if (m_b.sq(c) < m.sq(c))
m = m_b;
d = sqrt(r*r - h2);
if (d != d) d = 0;
pair<vec,vec> res(m + p*(d/p.nr()), m - p*(d/p.nr()));
if (res.first.sq(t) > res.second.sq(t))
swap(res.first, res.second);
return res;
}
// double only XXX not tested
// signed area of intersection of this with triangle (this.c,a,b)
double inter (vec a, vec b) {
cout << c << " with " << a << "," << b << ": ";
double res = 0.;
bool inv = 0;
if (contains(b)) {
swap(a,b);
inv = 1;
cout << "[inv] ";
}
if (contains(b)) {
cout << "contains both";
res = c.cross(a,b)*.5;
} else if (contains(a)) {
cout << "contains " << a;
pair<vec,vec> rt = inter_pts(a,b);
cout << endl << "[[" << rt.first << " " << rt.second << endl;
vec q = rt.first;
if (!q.in_seg(a,b) || (a.sq(q) <= eps && rt.second.in_seg(a,b)))
//if (rt.second.dist2_seg(a,b) < q.dist2_seg(a,b))
q = rt.second;
cout << " inter at " << q;
res += c.cross(a,q)*.5;
res += arc_area(q,b);
} else if (has_inter_seg(a, b)) {
cout << "inter seg";
pair<vec,vec> rt = inter_pts(b,a);
res += arc_area(a,rt.first);
res += c.cross(rt.first,rt.second)*.5;
res += arc_area(rt.second,b);
} else {
cout << "arc only";
res += arc_area(a,b);
}
if (inv) res = -res;
cout << " = " << res << endl;
return res;
}
double area (vec a, vec b) {
double aa = c.nr(a), bb = c.nr(b), cc = sqrt(c.dist2_seg(a,b));
if (aa <= r + eps && bb <= r + eps) return .5*abs((a-c)^(b-c));
if (cc >= r - eps) return .5*abs(r*r*c.angle(a,b));
if (aa > bb + eps) { swap(a,b); swap(aa,bb); }
double A = a.sq(b), B = 2.*((a-b)*(b-c)), C = b.sq(c) - r*r;
double t = B*B-4*A*C;
if (abs(t) <= eps) t = 0;
else t = sqrt(t);
double x1 = .5*(-B-t)/A, x2 = .5*(-B+t)/A;
vec p1 = a*x1 + b*(1-x1), p2 = a*x2 + b*(1-x2);
if (aa < r - eps) return area(a,p1) + area(p1,b);
return area(a,p2) + area(p2,p1) + area(p1,b);
}
// double only XXX not tested
// signed area of intersection of this with polygon
double inter (vector<vec> & p) {
double res = 0;
for (int i = 0; i < p.size(); i++) {
//res += area(p[i],p[(i+1)%p.size()]) * c.ccw(p[i],p[(i+1)%p.size()]);
res += inter(p[i],p[(i+1)%p.size()]);
}
return res;
}
};
// do the segments ab and cd intersect? (borders included) XXX
bool inter_seg (vec a, vec b, vec c, vec d) {
if (a.in_seg(c, d) || b.in_seg(c, d) || c.in_seg(a, b) || d.in_seg(a, b))
return true;
return (c.ccw(a, b) * d.ccw(a, b) == -1 && a.ccw(c, d) * b.ccw(c, d) == -1);
}
// squared distance from segments ab and cd XXX
double dist2_seg (vec a, vec b, vec c, vec d)
{ return inter_seg(a,b,c,d) ? 0. : min({ a.dist2_seg(c,d), b.dist2_seg(c,d), c.dist2_seg(a,b), d.dist2_seg(a,b) }); }
// brd = do points on the border belong to convex?
// computes convex hull of given vector (inplace)
// returns size of convex hull
int graham (vec v[], int n, int brd) {
for (int i = 1; i < n; i++) {
if (v[i].x < v[0].x || (v[i].x == v[0].x && v[i].y < v[0].y))
swap(v[0], v[i]);
}
sort(v+1, v+n, [v] (vec a, vec b) {
int o = b.ccw(v[0], a);
if (o) return (o == 1);
return v[0].sq(a) < v[0].sq(b);
});
if (brd) {
int s = n-1;
while (s > 1 && v[s].ccw(v[s-1],v[0]) == 0)
s--;
for (int i = s; i < n - 1 - (i - s); i++)
swap(v[i], v[n-1-(i-s)]);
}
int s = 0;
for (int i = 0; i < n; i++) {
if (s && v[s-1].x == v[i].x && v[s-1].y == v[i].y) continue;
while (s >= 2 && v[s-1].ccw(v[s-2],v[i]) >= brd)
s--;
v[s++] = v[i];
}
return s;
}
const int N = 1e2+7;
int n;
double r;
vector<vec> v;
double x[2], y[2];
double solve (double x) {
double lo = 200, hi = -100.;
for (int i = 0; i < n; i++) {
int j = (i+1)%n;
lin ln(v[i],v[j]);
vec it(x, (ln.c - ln.a*x)/ln.b);
cout << it << " ";
if (it.in_seg(v[i],v[j]) && it.y == it.y && abs(it.y) < 200) {
lo = min(lo, it.y);
hi = max(hi, it.y);
}
if (abs(v[i].x - x) <= eps_d) {
cout << v[i] << "! ";
lo = min(lo, v[i].y);
hi = max(hi, v[i].y);
}
}
hi = min(hi, 200.); lo = max(lo, -100.);
cout << x << " [" << lo << " " << hi << "]" << endl;
int ts = 60;
while (ts--) {
double q1 = (lo+lo+hi)/3;
double q2 = (lo+hi+hi)/3;
double r1 = abs(cir({ vec(x,q1), r }).inter(v));
double r2 = abs(cir({ vec(x,q2), r }).inter(v));
if (r1 < r2)
lo = q1;
else
hi = q2;
}
return abs(cir({ vec(x,lo), r }).inter(v));
}
int main () {
while (scanf("%d %lf", &n, &r) != EOF) {
cout << n << endl;
v = vector<vec>(n);
x[0] = 200;
x[1] = -100;
for (int i = 0; i < n; i++) {
scanf("%lf %lf", &v[i].x, &v[i].y);
cout << v[i] << " ";
x[0] = min(x[0],v[i].x);
x[1] = max(x[1],v[i].x);
}
cout << endl;
double lo = x[0], hi = x[1];
//int ts = 60;
int ts = 50;
while (ts--) {
double q1 = (lo+lo+hi)/3;
double q2 = (lo+hi+hi)/3;
if (solve(q1) < solve(q2))
lo = q1;
else
hi = q2;
}
double res = solve(lo);
for (int i = 0; i < n; i++)
res = max(res, abs(cir({ v[i], r }).inter(v)));
printf("%.20f\n", res);
}
} |
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
struct P {
double x, y;
P() {
}
P(double _x, double _y) :
x(_x), y(_y) {
}
P operator+(const P&p) const {
return P(x + p.x, y + p.y);
}
P operator-(const P&p) const {
return P(x - p.x, y - p.y);
}
P operator*(double d) const {
return P(x * d, y * d);
}
P operator/(double d) const {
return P(x / d, y / d);
}
double det(const P&p) const {
return x * p.y - y * p.x;
}
double dot(const P&p) const {
return x * p.x + y * p.y;
}
double alpha() const {
return atan2(y, x);
}
P rot90() const {
return P(-y, x);
}
void read() {
scanf("%lf%lf", &x, &y);
}
void write() const {
printf("(%lf,%lf)", x, y);
}
double abs() {
return sqrt(abs2());
}
double abs2() {
return x * x + y * y;
}
P unit() {
return *this / abs();
}
};
#define cross(p1,p2,p3) ((p2.x-p1.x)*(p3.y-p1.y)-(p3.x-p1.x)*(p2.y-p1.y))
const double EPS = 1e-8; //you should change it according to problem, nevertheless, it mustn't be a constant value some times.
inline int sign(double a) {
return a < -EPS ? -1 : a > EPS;
}
#define crossOp(p1,p2,p3) (sign(cross(p1,p2,p3)))
P isSS(P p1, P p2, P q1, P q2) {
double a1 = cross(q1,q2,p1), a2 = -cross(q1,q2,p2);
return (p1 * a2 + p2 * a1) / (a1 + a2);
}
int n;
double x[12],y[12],r;
bool onLine(P p, P q, P x){
return (x-p).dot(x-q) <= EPS;
}
vector<P> isCS(P c,double r,P p, P q){
double d = cross(q,p,c) / (p-q).abs();
vector<P> ret;
if(d>=r+EPS)
return ret;
P dir = (q-p).rot90();
P pq = (p-q);
pq = pq/pq.abs();
dir = dir / dir.abs();
P mid = c + dir * d;
double h = sqrt(max(r*r-d*d,0.0));
if(onLine(p,q,mid + pq*h))
ret.push_back(mid + pq*h);
if(onLine(p,q,mid - pq*h))
ret.push_back(mid - pq*h);
return ret;
}
double rad(P p,P q){
return atan2(p.det(q),p.dot(q));
}
double calc(P p, P q){
bool inp = p.abs2() <= r*r;
bool inq = q.abs2() <= r*r;
if(inp && inq){
return p.det(q)/2;
}
if(inp && !inq){
return -calc(q,p);
}
vector<P> is = isCS(P(0,0),r,p,q);
if(!inp && inq){
P m = is[0];
return r*r*rad(p,m)/2 + m.det(q)/2;
}
if(!inp && !inq){
if(is.empty())
return r*r*rad(p,q)/2;
return r*r*(rad(p,is[0]) + rad(is[1],q))/2 + is[0].det(is[1])/2;
}
}
double calcArea(double cx,double cy){
P ps[12];
rep(i,n) ps[i].x=x[i]-cx,ps[i].y=y[i]-cy;
ps[n] = ps[0];
double area = 0;
rep(i,n){
P p=ps[i],q=ps[i+1];
area += calc(p,q);
}
return area;
}
double ffy(double x){
double l=*min_element(y,y+n),r=*max_element(y,y+n);
rep(it,100){
double ll=(l*2+r)/3,rr=(l+r*2)/3;
if(calcArea(x,ll)>calcArea(x,rr))
r=rr;
else
l=ll;
}
return calcArea(x,l);
}
double ffx(){
double l=*min_element(x,x+n),r=*max_element(x,x+n);
rep(it,100){
double ll=(l*2+r)/3,rr=(l+r*2)/3;
if(ffy(ll)>ffy(rr))
r=rr;
else
l=ll;
}
return ffy(l);
}
double pi=acos(-1.);
double fuck() {
double rx=0,ry=0;
rep(i,n) rx=rx+x[i],ry=ry+y[i];
rx/=n; ry/=n; double c=calcArea(rx,ry);
double step=100;
rep(r1,100) {
rep(r2,300) {
double ang=(rand()%100001)*1e-5*2*pi;
while (1) {
double px=rx+step*cos(ang),py=ry+step*sin(ang);
double f=calcArea(px,py);
if (f>c) c=f,rx=px,ry=py;
else break;
}
}
// printf("%.10f\n",c);
step*=0.5;
}
return c;
}
int main(){
cin>>n>>r;
rep(i,n) cin>>x[i]>>y[i];
printf("%0.10lf\n",fuck());
} |
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<climits>
#include<algorithm>
#include<vector>
#include<complex>
#include<cassert>
#define REP(i,s,n) for(int i=s;i<n;++i)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-9)
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
using namespace std;
// BEGIN - Library
bool LT(double a,double b) { return !equals(a,b) && a < b; }
bool LTE(double a,double b) { return equals(a,b) || a < b; }
class Point{
public:
double x,y;
Point(double x = 0,double y = 0): x(x),y(y){}
Point operator + (Point p){return Point(x+p.x,y+p.y);}
Point operator - (Point p){return Point(x-p.x,y-p.y);}
Point operator * (double a){return Point(a*x,a*y);}
Point operator / (double a){return Point(x/a,y/a);}
Point operator * (Point a){ return Point(x * a.x - y * a.y, x * a.y + y * a.x); }
bool operator < (const Point& p) const{ return !equals(x,p.x)?x<p.x:(!equals(y,p.y)&&y<p.y); }
bool operator == (const Point& p)const{ return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS; }
};
struct Segment{
Point p1,p2;
Segment(Point p1 = Point(),Point p2 = Point()):p1(p1),p2(p2){}
bool operator < (const Segment& s) const { return ( p2 == s.p2 ) ? p1 < s.p1 : p2 < s.p2; }
bool operator == (const Segment& s) const { return ( s.p1 == p1 && s.p2 == p2 ) || ( s.p1 == p2 && s.p2 == p1 ); }
};
typedef Point Vector;
typedef Segment Line;
typedef vector<Point> Polygon;
ostream& operator << (ostream& os,const Point& a){ return os << "(" << a.x << "," << a.y << ")"; }
ostream& operator << (ostream& os,const Segment& a){ return os << "( " << a.p1 << " , " << a.p2 << " )"; }
double dot(Point a,Point b){ return a.x*b.x + a.y*b.y; }
double cross(Point a,Point b){ return a.x*b.y - a.y*b.x; }
double norm(Point a){ return a.x*a.x+a.y*a.y; }
double abs(Point a){ return sqrt(norm(a)); }
//rad ????§???????????????¢?????§?????????????????¨
Point rotate(Point a,double rad){ return Point(cos(rad)*a.x - sin(rad)*a.y,sin(rad)*a.x + cos(rad)*a.y); }
// ??????????????¢????????????
double toRad(double agl){ return agl*M_PI/180.0; }
// a => prev, b => cur, c=> next
// prev ?????? cur ????????£??? next ????????????????§????????±???????
double getArg(Point a,Point b,Point c){
double arg1 = atan2(b.y-a.y,b.x-a.x);
double arg2 = atan2(c.y-b.y,c.x-b.x);
double arg = fabs( arg1 - arg2 );
while( arg > M_PI ) arg -= 2.0 * M_PI;
return fabs(arg);
}
int ccw(Point p0,Point p1,Point p2){
Point a = p1-p0;
Point b = p2-p0;
if(cross(a,b) > EPS)return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS)return CLOCKWISE;
if(dot(a,b) < -EPS)return ONLINE_BACK;
if(norm(a) < norm(b))return ONLINE_FRONT;
return ON_SEGMENT;
}
bool intersectLL(Line l, Line m) {
return abs(cross(l.p2-l.p1, m.p2-m.p1)) > EPS || // non-parallel
abs(cross(l.p2-l.p1, m.p1-l.p1)) < EPS; // same line
}
bool intersectLS(Line l, Line s) {
return cross(l.p2-l.p1, s.p1-l.p1)* // s[0] is left of l
cross(l.p2-l.p1, s.p2-l.p1) < EPS; // s[1] is right of l
}
bool intersectLP(Line l,Point p) {
return abs(cross(l.p2-p, l.p1-p)) < EPS;
}
bool intersectSS(Line s, Line t) {
return ccw(s.p1,s.p2,t.p1)*ccw(s.p1,s.p2,t.p2) <= 0 &&
ccw(t.p1,t.p2,s.p1)*ccw(t.p1,t.p2,s.p2) <= 0;
}
bool intersectSP(Line s, Point p) {
return abs(s.p1-p)+abs(s.p2-p)-abs(s.p2-s.p1) < EPS; // triangle inequality
}
Point projection(Line l,Point p) {
double t = dot(p-l.p1, l.p1-l.p2) / norm(l.p1-l.p2);
return l.p1 + (l.p1-l.p2)*t;
}
Point reflection(Line l,Point p) {
return p + (projection(l, p) - p) * 2;
}
double distanceLP(Line l, Point p) {
return abs(p - projection(l, p));
}
double distanceLL(Line l, Line m) {
return intersectLL(l, m) ? 0 : distanceLP(l, m.p1);
}
double distanceLS(Line l, Line s) {
if (intersectLS(l, s)) return 0;
return min(distanceLP(l, s.p1), distanceLP(l, s.p2));
}
double distanceSP(Line s, Point p) {
Point r = projection(s, p);
if (intersectSP(s, r)) return abs(r - p);
return min(abs(s.p1 - p), abs(s.p2 - p));
}
double distanceSS(Line s, Line t) {
if (intersectSS(s, t)) return 0;
return min(min(distanceSP(s, t.p1), distanceSP(s, t.p2)),
min(distanceSP(t, s.p1), distanceSP(t, s.p2)));
}
Point crosspoint(Line l,Line m){
double A = cross(l.p2-l.p1,m.p2-m.p1);
double B = cross(l.p2-l.p1,l.p2-m.p1);
if(abs(A) < EPS && abs(B) < EPS){
vector<Point> vec;
vec.push_back(l.p1),vec.push_back(l.p2),vec.push_back(m.p1),vec.push_back(m.p2);
sort(vec.begin(),vec.end());
assert(vec[1] == vec[2]); //???????????°??????????????????
return vec[1];
//return m.p1;
}
if(abs(A) < EPS)assert(false);
return m.p1 + (m.p2-m.p1)*(B/A);
}
//cross product of pq and pr
double cross3p(Point p,Point q,Point r) { return (r.x-q.x) * (p.y -q.y) - (r.y - q.y) * (p.x - q.x); }
//returns true if point r is on the same line as the line pq
bool collinear(Point p,Point q,Point r) { return fabs(cross3p(p,q,r)) < EPS; }
//returns true if point t is on the left side of line pq
bool ccwtest(Point p,Point q,Point r){
return cross3p(p,q,r) > 0; //can be modified to accept collinear points
}
bool onSegment(Point p,Point q,Point r){
return collinear(p,q,r) && equals(sqrt(pow(p.x-r.x,2)+pow(p.y-r.y,2)) + sqrt(pow(r.x-q.x,2) + pow(r.y-q.y,2) ),sqrt(pow(p.x-q.x,2)+pow(p.y-q.y,2)) ) ;
}
double getArea(vector<Point>& vec) {
double sum = 0;
for(int i=0;i<vec.size();i++)
sum += cross(vec[i],vec[(i+1)%vec.size()]);
return fabs(sum)/2.0;
}
typedef pair<double,double> dd;
const double DINF = 1e20;
#define pow2(a) ((a)*(a))
dd calc(double x1,double y1,double vx1,double vy1,
double x2,double y2,double vx2,double vy2,double r){
double VX = (vx1-vx2), X = (x1-x2), VY = (vy1-vy2), Y = (y1-y2);
double a = pow2(VX) + pow2(VY), b = 2*(X*VX+Y*VY), c = pow2(X) + pow2(Y) - pow2(r);
dd ret = dd(DINF,DINF);
double D = b*b - 4 * a * c;
if( LT(D,0.0) ) return ret;
if( equals(a,0.0) ) {
if( equals(b,0.0) ) return ret;
if( LT(-c/b,0.0) ) return ret;
ret.first = - c / b;
return ret;
}
if( equals(D,0.0) ) D = 0;
ret.first = ( -b - sqrt( D ) ) / ( 2 * a );
ret.second = ( -b + sqrt( D ) ) / ( 2 * a );
if( !equals(ret.first,ret.second) && ret.first > ret.second ) swap(ret.first,ret.second);
return ret;
}
const Point ZERO = Point(0,0);
//??????AB??¨?????????cp,??????r????????¨?????±?????¨????????¢???????±???????
inline double calculator_TypeA(Point A,Point B,Point cp,double r){
A = A - cp, B = B - cp;
if( A == ZERO || B == ZERO ) return 0;
double cross_value = cross(A,B);
if( equals(cross_value,0.0) ) return 0;
double sig = LT(cross_value,0.0) ? -1 : 1;
Segment AB = Segment(A,B);
double nearest_distance = distanceLP(AB,ZERO);
double distance_OA = abs(A);
double distance_OB = abs(B);
if( LTE(0.0,r-distance_OA) && LTE(0.0,r-distance_OB) && LTE(0.0,r-nearest_distance) ) {
return sig * fabs( cross_value / 2.0 );
} else if( LTE(0.0,distance_OA-r) && LTE(0.0,distance_OB-r) && LTE(0.0,nearest_distance-r) ) {
return sig * ( r * r * (M_PI-getArg(A,ZERO,B)) ) / 2.0;
} else if( LTE(0.0,distance_OA-r) && LTE(0.0,distance_OB-r) && LT(0.0,r-nearest_distance) ) {
Point proj_p = projection(AB,ZERO);
if( onSegment(AB.p1,AB.p2,proj_p) ) {
Vector e = ( A - B ) / abs( A - B );
dd tmp = calc(A.x,A.y,e.x,e.y,0,0,0,0,r);
Point r_p1 = A + e * tmp.first;
Point r_p2 = A + e * tmp.second;
double ret = r * r * (M_PI-getArg(B,ZERO,A)) / 2.0;
double subtract = r * r * (M_PI-getArg(r_p1,ZERO,r_p2)) / 2.0 - fabs(cross(r_p1,r_p2))/2.0 ;
return sig * ( ret - subtract );
} else {
return sig * ( r * r * (M_PI-getArg(B,ZERO,A)) ) / 2.0;
}
} else {
if( LT(distance_OB-r,0.0) ) swap(A,B);
Vector e = ( A - B ) / abs( A - B );
dd tmp = calc(A.x,A.y,e.x,e.y,0,0,0,0,r);
Point r_p1 = A + e * tmp.first;
Point r_p2 = A + e * tmp.second;
if( onSegment(A,B,r_p2) ) r_p1 = r_p2;
double ret = fabs(cross(r_p1,A)) * 0.5;
ret += r * r * (M_PI-getArg(r_p1,ZERO,B)) * 0.5;
return sig * ret;
}
assert(false);
}
double getCommonAreaPolygonCircle(const Polygon &poly,Point cp,double r){
double sum = 0;
rep(i,(int)poly.size()){
sum += calculator_TypeA(poly[i],poly[(i+1)%(int)poly.size()],cp,r);
}
return fabs(sum);
}
Polygon andrewScan(Polygon s) {
Polygon u,l;
if(s.size() < 3)return s;
sort(s.begin(),s.end());
u.push_back(s[0]);
u.push_back(s[1]);
l.push_back(s[s.size()-1]);
l.push_back(s[s.size()-2]);
for(int i=2;i<(int)s.size();i++)
{
for(int n=u.size();n >= 2 && ccw(u[n-2],u[n-1],s[i]) != CLOCKWISE; n--)
u.pop_back();
u.push_back(s[i]);
}
for(int i=s.size()-3; i>=0 ; i--)
{
for(int n=l.size(); n >= 2 && ccw(l[n-2],l[n-1],s[i]) != CLOCKWISE; n--)
l.pop_back();
l.push_back(s[i]);
}
reverse(l.begin(),l.end());
for(int i = u.size()-2; i >= 1; i--) l.push_back(u[i]);
return l;
}
Point calc_ps(Polygon poly) {
poly = andrewScan(poly);
Point mp = poly[0];
double rate = 1; // 0.5???????????¨???
int max_pos;
double eps = 1e-10; // 1e-20???????????¨???
while( rate > eps ) {
rep(_,60){ // 70???????????¨???
max_pos = 0;
REP(j,1,(int)poly.size()) {
double dist1 = abs(mp-poly[max_pos]);
double dist2 = abs(mp-poly[j]);
if( LT(dist1,dist2) ) max_pos = j;
}
mp.x += ( poly[max_pos].x - mp.x ) * rate;
mp.y += ( poly[max_pos].y - mp.y ) * rate;
}
rate *= 0.5;
}
return mp;
}
Point getCentroidOfConvex(Polygon& poly){
double area = getArea(poly);
int V = poly.size();
assert( !equals(area,0.0) );
double x = 0, y = 0;
rep(i,(int)poly.size()) {
x += ( poly[i].x + poly[(i+1)%V].x ) * ( poly[i].x*poly[(i+1)%V].y - poly[(i+1)%V].x*poly[i].y );
y += ( poly[i].y + poly[(i+1)%V].y ) * ( poly[i].x*poly[(i+1)%V].y - poly[(i+1)%V].x*poly[i].y );
}
return Point(x/(6.0*area),y/(6.0*area));
}
// END - Library
int n,r;
Polygon poly;
void compute() {
double maxi;
Point mp = calc_ps(poly);
maxi = getCommonAreaPolygonCircle(poly,mp,r);
double rate = 1.0;
double eps = 1e-10;
while( LT(eps,rate) ) {
rep(_,70) {
double max_area = -1;
Point np;
rep(i,n) {
Point tp = mp;
tp.x += ( poly[i].x - mp.x ) * rate;
tp.y += ( poly[i].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,tp,r);
if( LT(max_area,area) ) {
max_area = area;
np = tp;
}
}
assert( !equals(max_area,-1) );
mp = np;
if( LT(maxi,max_area) ) maxi = max_area;
}
rate *= 0.5;
}
rep(__,1) {
Point mp = calc_ps(poly);
double rate = 1.0;
double eps = 1e-10;
while( LT(eps,rate) ) {
rep(_,70) {
double max_area = -1;
Point np;
rep(i,n) {
Point tp = mp;
tp.x += ( poly[i].x - mp.x ) * rate;
tp.y += ( poly[i].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,tp,r);
if( LT(max_area,area) ) {
max_area = area;
np = tp;
}
}
if( rand() % 50 == 0 ) {
int v = rand() % n;
np.x = ( poly[v].x - mp.x ) * rate;
np.y = ( poly[v].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,np,r);
if( LT(max_area,area) ) {
max_area = area;
}
}
assert( !equals(max_area,-1) );
mp = np;
if( LT(maxi,max_area) ) maxi = max_area;
}
rate *= 0.5;
}
}
printf("%.10f\n",maxi);
}
int main() {
srand((unsigned int)time(NULL));
cin >> n >> r;
poly.resize(n);
rep(i,n) cin >> poly[i].x >> poly[i].y;
//cout << getArea(poly) << endl;
compute();
return 0;
} |
#include <bits/stdc++.h>
using namespace std;
#define SZ(a) int((a).size())
#define mp make_pair
#define pb push_back
typedef vector<int> VI;
typedef pair<int,int> PII;
typedef long long LL;
typedef unsigned long long ULL;
const LL mod=1e9+7;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const double EPS=1e-6;
inline void read(LL& x){int f=1;char c;while(((c=getchar())<'0'||c>'9')&&c!='-');c=='-'?(f=-1,x=0):(x=c-'0');while((c=getchar())>='0'&&c<='9')x=x*10+c-'0';x*=f;}
inline void read(int& x){LL t;read(t);x=t;}
/*----------------------精度控制--------------------------*/
const double eps=1e-7;
//1:>0 0:=0 -1:<0
int dcmp(double x){
if(fabs(x)<eps) return 0;
return x<0?-1:1;
}
/*------------------点、???体-------------------*/
struct Point{
double x,y;
Point(double x=0.0,double y=0.0):x(x),y(y){}
void Read(){ scanf("%lf%lf",&x,&y); }
void Write(){ printf("%.10f %.10f\n",x,y); }
bool operator<(const Point &b) const{//水平序
return !dcmp(x-b.x)? y<b.y:x<b.x;
}
/*friend bool operator<(CPoint a,CPoint b){//?角排序
double tmp=cross(Pts[0],a,b);
if(!dcmp(tmp)) return dist(Pts[0],a)<dist(Pts[0],b);
return tmp>0;
}*/
};
//a->b
struct Line{
Point a,b;
Line(Point a,Point b):a(a),b(b){}
Line(){}
void Read(){ a.Read(); b.Read(); }
void Write(){ a.Write(); b.Write(); }
};
/*---------------------点、?相?----------------------*/
Point operator +(Point a,Point b){ return Point(a.x+b.x,a.y+b.y); }
Point operator -(Point a,Point b){ return Point(a.x-b.x,a.y-b.y); }
Point operator *(Point a,double k){ return Point(k*a.x,k*a.y); }
Point operator *(double k,Point a){ return Point(k*a.x,k*a.y); }
double operator *(Point a,Point b){ return a.x*b.x+a.y*b.y; }
Point operator /(Point a,double k){ return Point(a.x/k,a.y/k); }
double operator ^(Point a,Point b){ return a.x*b.y-a.y*b.x; }
double cross(Point a,Point b){ return a.x*b.y-a.y*b.x; }
double cross(Point a,Point b,Point c){ return cross(b-a,c-a); }
double dot(Point a,Point b){ return a.x*b.x+a.y*b.y; }
double dot(Point a,Point b,Point c){ return dot(b-a,c-a); }
double length(Point p){ return sqrt(p*p); }
Point unit(Point p){ return 1.0/length(p)*p; }
//求p在n方向上投影?度
double project(Point p,Point n){ return p*unit(n); }
double area(Point a,Point b){ return a^b*0.5; }
double distPP(Point p,Point q){ return length(p-q); }
double distPL(Point p,Line l){ return fabs((p-l.a)^(p-l.b))/length(l.a-l.b); }
double distPS(Point p,Line s){
if(dcmp(dot(s.b-s.a,p-s.a))<0) return length(p-s.a);
if(dcmp(dot(s.a-s.b,p-s.b))<0) return length(p-s.b);
return distPL(p,s);
}
//b?a逆??旋?alpha后得到的点
Point rotateP(Point a,Point b,double alpha){
Point p=b-a;
return Point(a.x+p.x*cos(alpha)-p.y*sin(alpha),a.y+p.x*sin(alpha)+p.y*cos(alpha));
}
//b?a逆??旋?alpha后得到的向量
Point rotateV(Point a,Point b,double alpha){
Point p=b-a;
return unit(Point(p.x*cos(alpha)-p.y*sin(alpha),p.x*sin(alpha)+p.y*cos(alpha)));
}
//0:online 1:left -1:right
int sideOfL(Point p,Line l){
double res=(p-l.a)^(p-l.b);
return dcmp(res);
}
//求?p的l的垂?
Line vertical(Point p,Line l){
return Line(p,p+rotateV(l.b,l.a,PI/2));
}
//垂足
Point root(Point p,Line l){
return l.a+project(p-l.a,l.b-l.a)*unit(l.b-l.a);
}
//?向量?角
double angleVV(Point a,Point b){ return acos(project(a,b)/length(a)); }
//?直??角
double angleLL(Line l,Line m){
return acos(fabs(project(l.b-l.a,m.b-m.a)/length(l.b-l.a)));
}
//判断点p是否在?段ab上
bool PointOnS(Point p,Line l){
return !dcmp(cross(p-l.a,l.b-l.a))&&dcmp((p-l.a)*(p-l.b))<=0;
}
//求直?交点
Point getCrossLL(Line l,Line m){
double t=cross(m.b-m.a,l.a-m.a)/cross(l.b-l.a,m.b-m.a);
return l.a+(l.b-l.a)*t;
}
//判断?段是否相交
bool crossSS(Line l,Line m){
return sideOfL(l.a,m)*sideOfL(l.b,m)<=0&&sideOfL(m.a,l)*sideOfL(m.b,l)<=0;
}
/*----------------------多?形相?--------------------------*/
//0:outside 1:inside 2:online
int PointInPoly(Point t,Point *p,int n){
int num=0,d1,d2,k;
p[n]=p[0];
for(int i=0;i<n;i++){
if(PointOnS(t,Line(p[i],p[i+1]))) return 2;
k=dcmp(cross(p[i],p[i+1],t));
d1=dcmp(p[i].y-t.y);
d2=dcmp(p[i+1].y-t.y);
if(k>0&&d1<=0&&d2>0) num++;
if(k<0&&d2<=0&&d1>0) num--;
}
return num!=0;
}
//clockwise:>0 anticlockwise:<0
double PolyArea(Point *p,int n){
double pa=0.0;p[n]=p[0];
for(int i=0;i<n;i++) pa+=area(p[i],p[i+1]);
return pa;
}
//求多?形周?
double PolyPerimeter(Point *p,int n){
double pp=0.0;p[n]=p[0];
for(int i=0;i<n-1;i++) pp+=distPP(p[i],p[i+1]);
return pp;
}
//求多?形重心
Point PolyCore(Point *p,int n){
double pa=PolyArea(p,n);
if(!dcmp(pa)) return Point(0,0);
Point ans(0,0);p[n]=p[0];
for(int i=0;i<n;i++) ans=ans+(p[i]+p[i+1])*cross(p[i],p[i+1]);
return ans/pa/6;
}
/*----------------------凸包----------------------------*/
//Graham-scan st:anticlockwise
//<=:strict <:Non-strict
int Graham(Point *p,Point *st,int n){
if(n<3) return 0;
sort(p,p+n);
int m=0;
for(int i=0;i<n;i++){
while(m>1&&dcmp(cross(st[m-2],st[m-1],p[i]))<0) m--;
st[m++]=p[i];
}
int k=m;
for(int i=n-2;i>=0;i--){
while(m>k&&dcmp(cross(st[m-2],st[m-1],p[i])<0)) m--;
st[m++]=p[i];
}
return m-1;
}
//clockwise:> anticlockwise:<
double CHDiameter(Point *p,int n,Line &l){
double maxd=0.0;
if(n<=1){
l.a=l.b=p[0];
return maxd;
}
for(int i=0,j=1;i<n;i++){
while(cross(p[i],p[(i+1)%n],p[j])
>cross(p[i],p[(i+1)%n],p[(j+1)%n])){
j=(j+1)%n;
}
double d=distPP(p[i],p[j]);
if(dcmp(d-maxd)>=0){
maxd=d;
l.a=p[i];
l.b=p[j];
}
d=distPP(p[(i+1)%n],p[(j+1)%n]);
if(dcmp(d-maxd)>=0){
maxd=d;
l.a=p[i];
l.b=p[j];
}
}
return maxd;
}
bool PointInCH(Point *p,int n,Point a){
int l=0,r=n-1,m,res=-1;
bool fg=false;
int pos;
double flag[2];
while(l<=r){
m=(l+r)/2;
flag[0]=cross(p[0]-a,p[0]-p[m]);
if(!dcmp(flag[0])){
fg=true;
pos=m;
break;
}
flag[1]=cross(p[0]-a,p[0]-p[m+1]);
if(!dcmp(flag[1])){
fg=true;
pos=m+1;
break;
}
if(dcmp(flag[0])*dcmp(flag[1])<0){
res=m;
break;
}
if(dcmp(flag[0])<0&&dcmp(flag[1])<0) l=m+1;
else r=m-1;
}
if(fg){
if(dcmp((p[0]-a)*(p[pos]-a))<=0) return true;
return false;
}
if(res==-1) return false;
return dcmp(cross(p[m]-a,p[m]-p[m+1]))<=0;
}
/*---------------------整点多?形---------------------------*/
int gcd(int a,int b){
return b==0?a :gcd(b,a%b);
}
//整点多?形?界整点数
int Border_Int_Point_Num(Point *Pts,int n){
int num=gcd(abs(int(Pts[0].x-Pts[n-1].x)),abs(int(Pts[0].y-Pts[n-1].y)));;
for(int i=0;i<n-1;i++){
num+=gcd(abs(int(Pts[i+1].x-Pts[i].x)),abs(int(Pts[i+1].y-Pts[i].y)));
}
return num;
}
//整点多?形内部整点数
int Inside_Int_Point_Num(Point *Pts,int n){
return abs(int(PolyArea(Pts,n)))+1-Border_Int_Point_Num(Pts,n)/2;
}
/*-----------------------------半平面交-------------------------------*/
//有方向的直?
//p->p+v
struct Vector{
Point p,v;
double ang;
Vector(Point p,Point v):p(p),v(v){
ang=atan2(v.y,v.x);
}
Vector(){}
bool operator<(const Vector &l) const{
return ang<l.ang;
}
};
//判断点p是否在直?L左?
bool onLeft(Vector L,Point p){
return cross(L.v,p-L.p)>0;
}
//得到a与b?直?的交点
Point getCrossVV(Vector a,Vector b){
Point u=a.p-b.p;
double t=cross(b.v,u)/cross(a.v,b.v);
return a.p+a.v*t;
}
//所有直?左半平面的交
int HPCross(Vector *L,int n,Point *poly){
sort(L,L+n);
int f=0,l=0;
Point *p=new Point[n];
Vector *q=new Vector[n];
q[0]=L[0];
for(int i=1;i<n;i++){
while(f<l&&!onLeft(L[i],p[l-1])) l--;
while(f<l&&!onLeft(L[i],p[f])) f++;
q[++l]=L[i];
if(!dcmp(cross(q[l].v,q[l-1].v))){
l--;
if(onLeft(q[l],L[i].p)) q[l]=L[i];
}
if(f<l) p[l-1]=getCrossVV(q[l-1],q[l]);
}
while(f<l&&!onLeft(q[f],p[l-1])) l--;
if(l-f<=1) return 0;
p[l]=getCrossVV(q[l],q[f]);
int m=0;
for(int i=f;i<=l;i++) poly[m++]=p[i];
return m;
}
//向内??r
#define maxn 100005
Vector l[maxn];
bool retract(Vector *L,int n,double r,Point *poly){
for(int i=0;i<n;i++){
Point v=rotateV(L[i].p,L[i].p+L[i].v,PI/2);
l[i]=Vector(L[i].p+r*v,L[i].v);
}
int cnt=HPCross(l,n,poly);
return cnt;
}
/*---------------------三角形相?---------------------------*/
//三角形重心
//到三?点距?的平方和最小的点
//到三?距?之?最大的点
Point TCore(Point a,Point b,Point c){
return (a+b+c)/3;
}
//三角形外心
Point TCircum(Point a,Point b,Point c){
Point cp;
double a1=b.x-a.x;
double b1=b.y-a.y;
double a2=c.x-a.x;
double b2=c.y-a.y;
double c1=(a1*a1+b1*b1)/2;
double c2=(a2*a2+b2*b2)/2;
double d=a1*b2-a2*b1;
cp.x=a.x+(c1*b2-c2*b1)/d;
cp.y=a.y+(a1*c2-a2*c1)/d;
return cp;
}
//三角形垂心
Point TOrtho(Point a,Point b,Point c){
return TCore(a,b,c)*3.0-TCircum(a,b,c)*2.0;
}
//三角形内心
Point TInner(Point a,Point b,Point c){
Point cp;
double la=distPP(b,c),lb=distPP(c,a),lc=distPP(a,b);
cp.x=(la*a.x+lb*b.x+lc*c.x)/(la+lb+lc);
cp.y=(la*a.y+lb*b.y+lc*c.y)/(la+lb+lc);
return cp;
}
//求三角形面?
double TArea(Point a,Point b,Point c){
return fabs(cross(a,b,c))/2;
}
/*-----------------------?相?-------------------------*/
struct Circle{
Point o; double r;
Circle(Point o,double r):o(o),r(r){}
Circle(){}
void Read(){ o.Read(); scanf("%lf",&r); }
double area(){ return PI*r*r; }
};
//求??面?交
double getAreaCC(Circle a,Circle b){
double d=(a.o.x-b.o.x)*(a.o.x-b.o.x)+(a.o.y-b.o.y)*(a.o.y-b.o.y);
if(d<=(a.r-b.r)*(a.r-b.r)){
return min(a.r,b.r)*min(a.r,b.r)*PI;
}else if(d>(a.r-b.r)*(a.r-b.r)&&d<(a.r+b.r)*(a.r+b.r)){
double m1=(a.r*a.r+d-b.r*b.r)/(2*a.r*sqrt(d));
double m2=(b.r*b.r+d-a.r*a.r)/(2*b.r*sqrt(d));
double s1=acos(m1)*a.r*a.r;
double s2=acos(m2)*b.r*b.r;
double s3=sqrt(d)*a.r*sin(acos(m1));
return s1+s2-s3;
}
return 0.0;
}
//求??交点,先判断是否有交点
Point rotatePCS(Point p,double c,double s){
return Point(p.x*c-p.y*s,p.x*s+p.y*c);
}
pair<Point,Point> getcrossCC(Circle a,Circle b){
double d=length(a.o-b.o);
double cost=(a.r*a.r+d*d-b.r*b.r)/(2*a.r*d);
double sint=sqrt(1.0-cost*cost);
Point v=(b.o-a.o)/d*a.r;
return mp(a.o+rotatePCS(v,cost,-sint),a.o+rotatePCS(v,cost,sint));
}
int getCrossCL(Circle c,Line l,Point *cl){
int fg=dcmp(distPL(c.o,l)-c.r);
int cnt=0;
if(!fg) cl[cnt++]=root(c.o,l);
else if(fg==-1){
Point rt=root(c.o,l);
double r=sqrt(c.r*c.r-(c.o-rt)*(c.o-rt));
cl[cnt++]=rt+r*unit(l.b-l.a);
cl[cnt++]=rt-r*unit(l.b-l.a);
}
return cnt;
}
double rad(Point a,Point b,Point p){
return fabs(atan2(fabs(cross(a-p,b-p)),(a-p)*(b-p)));
}
Point lineprog(Line l,Point p){
return l.a+(((l.b-l.a)*((l.b-l.a)*(p-l.a)))/((l.b-l.a)*(l.b-l.a)));
}
int relation(Point b,Circle c){
double d=distPP(b,c.o);
if(dcmp(d-c.r)<0) return 2;
if(!dcmp(d-c.r)) return 1;
return 0;
}
int getCrossCL(Circle c,Line l,Point &p1,Point &p2){
double dx=distPL(c.o,l);
if(dcmp(dx-c.r)>0) return 0;
Point a=lineprog(l,c.o);
double d=distPL(c.o,l);
d=sqrt(c.r*c.r-d*d);
if(!dcmp(d)){
p1=p2=a;
return 1;
}
Point s=unit(l.b-l.a);
p1=a+s*d;
p2=a-s*d;
return 2;
}
double getAreaTC(Point a,Point b,Circle c){
Point q[5];
int len=0;
q[len++]=a;
Line l(a,b);
Point p1,p2;
if(getCrossCL(c,l,q[1],q[2])==2){
if(dcmp((a-q[1])*(b-q[1]))<0) q[len++]=q[1];
if(dcmp((a-q[2])*(b-q[2]))<0) q[len++]=q[2];
}
q[len++]=b;
if(len==4&&dcmp((q[0]-q[1])*(q[2]-q[1]))>0) swap(q[1],q[2]);
double res=0.0;
for(int i=0;i<len-1;i++){
if(!relation(q[i],c)||!relation(q[i+1],c)){
double arg=rad(q[i],q[i+1],c.o);
res+=c.r*c.r*arg/2.0;
}else res+=fabs(cross(q[i]-c.o,q[i+1]-c.o))/2.0;
}
return res;
}
double getAreaPC(Point *Pts,int n,Circle c){
double apc=0.0;
for(int i=0;i<n;i++){
int s=dcmp(cross(Pts[i]-c.o,Pts[i+1]-c.o));
if(!!s) apc+=getAreaTC(Pts[i],Pts[i+1],c)*s;
}
return fabs(apc);
}
/*----------------------三?点、?基本函数-----------------------------*/
struct Point3{
double x,y,z;
Point3(double x,double y,double z):x(x),y(y),z(z){}
Point3(){}
void Read(){ scanf("%lf%lf%lf",&x,&y,&z); }
};
struct Line3{
Point3 a,b;
Line3(Point3 a,Point3 b):a(a),b(b){}
Line3(){}
void Read(){ a.Read(); b.Read(); }
};
Point3 operator +(Point3 a,Point3 b){ return Point3(a.x+b.x,a.y+b.y,a.z+b.z); }
Point3 operator -(Point3 a,Point3 b){ return Point3(a.x-b.x,a.y-b.y,a.z-b.z); }
double operator *(Point3 a,Point3 b){ return a.x*b.x+a.y*b.y+a.z*b.z; }
Point3 operator *(Point3 a,double k){ return Point3(a.x*k,a.y*k,a.z*k); }
Point3 operator *(double k,Point3 a){ return Point3(a.x*k,a.y*k,a.z*k); }
Point3 operator /(Point3 a,double k){ return Point3(a.x/k,a.y/k,a.z/k); }
double length(Point3 a){ return sqrt(a.x*a.x+a.y*a.y+a.z*a.z); }
Point3 unit(Point3 a){ return a/length(a); }
double dot(Point3 a,Point3 b){ return a.x*b.x+a.y*b.y+a.z*b.z; }
Point3 cross(Point3 a,Point3 b){
return Point3(a.y*b.z-a.z*b.y,a.z*b.x-a.x*b.z,a.x*b.y-a.y*b.x);
}
//混合?
double Mix(Point3 a,Point3 b,Point3 c){ return dot(a,cross(b,c)); }
//?点距?
double dist(const Point3 &a,const Point3 &b){ return length(a-b); }
/*---------------------------------体?-------------------------------------*/
//四面体体?
double volume(double l,double n,double a,double m,double b,double c){
double x,y;
x=4*a*a*b*b*c*c-a*a*(b*b+c*c-m*m)*(b*b+c*c-m*m)-b*b*(c*c+a*a-n*n)*(c*c+a*a-n*n);
y=c*c*(a*a+b*b-l*l)*(a*a+b*b-l*l)-(a*a+b*b-l*l)*(b*b+c*c-m*m)*(c*c+a*a-n*n);
return sqrt(x-y)/12;
}
double volume(Point3 a,Point3 b,Point3 c,Point3 d){ return fabs(Mix(b-a,c-a,d-a)/6); }
#define MAXN 15
Point Pts[MAXN];
int n;
double R,minx,miny,maxx,maxy;
double sanfeny(double x){
double l=maxy,r=miny;
Line s=Line(Point(x,0),Point(x,1));
for(int i=0;i<n;i++){
Point st=getCrossLL(s,Line(Pts[i],Pts[i+1]));
if(PointOnS(st,Line(Pts[i],Pts[i+1]))){
l=min(l,st.y);
r=max(r,st.y);
}
}
double m1,m2;
for(int i=0;i<100;i++){
m1=(l+l+r)/3;
m2=(l+r+r)/3;
if(getAreaPC(Pts,n,Circle(Point(x,m1),R))<getAreaPC(Pts,n,Circle(Point(x,m2),R))){
l=m1;
}else{
r=m2;
}
}
return getAreaPC(Pts,n,Circle(Point(x,l),R));
}
double sanfenx(){
double l=minx,r=maxx;
double m1,m2;
for(int i=0;i<100;i++){
m1=(l+l+r)/3;
m2=(l+r+r)/3;
if(sanfeny(m1)<sanfeny(m2)){
l=m1;
}else{
r=m2;
}
}
return sanfeny(l);
}
int main(){ios_base::sync_with_stdio(0);//cin.tie(0);
minx=miny=1000;
maxx=maxy=0;
cin>>n>>R;
for(int i=1;i<=n;i++){
cin>>Pts[n-i].x>>Pts[n-i].y;
minx=min(minx,Pts[n+1-i].x);
miny=min(miny,Pts[n+1-i].y);
maxx=max(maxx,Pts[n+1-i].x);
maxy=max(maxy,Pts[n+1-i].y);
}
Pts[n]=Pts[0];
double maans=sanfenx();
cout.setf(ios::fixed);
cout<<fixed<<setprecision(10)<<maans<<endl;
return 0;
}
//cout.setf(ios::fixed);
//cout<<fixed<<setprecision(10)<<s<<endl; |
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
template<class T> using V = vector<T>;
using D = double;
const D PI = acos(D(-1)), EPS = 1e-10;
int sgn(D a) { return (abs(a) <= EPS) ? 0 : (a < 0 ? -1 : 1); }
int sgn(D a, D b) { return sgn(a-b); }
//relative sign
// int rsgn(D a, D f) {
// if (abs(a) <= f*EPS) return 0;
// return (a < 0) ? -1 : 1;
// }
struct Pt2 {
D x, y;
Pt2(D _x = D(), D _y = D()) : x(_x), y(_y) {}
Pt2 operator+(const Pt2 &r) const { return Pt2(x+r.x, y+r.y); }
Pt2 operator-(const Pt2 &r) const { return Pt2(x-r.x, y-r.y); }
Pt2 operator*(const Pt2 &r) const { return Pt2(x*r.x-y*r.y, x*r.y+y*r.x); }
Pt2 operator*(const D &r) const { return Pt2(x*r, y*r); }
Pt2 operator/(const D &r) const { return Pt2(x/r, y/r); }
Pt2& operator+=(const Pt2 &r) { return *this=*this+r; }
Pt2& operator-=(const Pt2 &r) { return *this=*this-r; }
Pt2& operator*=(const Pt2 &r) { return *this=*this*r; }
Pt2& operator*=(const D &r) { return *this=*this*r; }
Pt2& operator/=(const D &r) { return *this=*this/r; }
Pt2 operator-() const { return Pt2(-x, -y); }
bool operator<(const Pt2 &r) const { return 2*sgn(x, r.x)+sgn(y, r.y)<0; }
bool operator==(const Pt2 &r) const { return sgn((*this-r).rabs()) == 0; }
D norm() const { return x*x + y*y; }
D abs() const { return sqrt(norm()); }
D rabs() const { return max(std::abs(x), std::abs(y)); } // robust abs
D arg() const { return atan2(y, x); }
pair<D, D> to_pair() const { return make_pair(x, y); }
static Pt2 polar(D le, D th) { return Pt2(le*cos(th), le*sin(th)); }
};
ostream& operator<<(ostream& os, const Pt2 &p) {
return os << "P(" << p.x << ", " << p.y << ")";
}
using P = Pt2;
struct L {
P s, t;
L(P _s = P(), P _t = P()) : s(_s), t(_t) {}
P vec() const { return t-s; }
D abs() const { return vec().abs(); }
D arg() const { return vec().arg(); }
};
ostream& operator<<(ostream& os, const L &l) {
return os << "L(" << l.s << ", " << l.t << ")";
}
D cross(P a, P b) { return a.x*b.y - a.y*b.x; }
D dot(P a, P b) { return a.x*b.x + a.y*b.y; }
// cross(a, b) is too small?
int sgncrs(P a, P b) {
D cr = cross(a, b);
if (abs(cr) <= (a.rabs() + b.rabs()) * EPS) return 0;
return (cr < 0) ? -1 : 1;
}
// -2, -1, 0, 1, 2 : front, clock, on, cclock, back
int ccw(P b, P c) {
int s = sgncrs(b, c);
if (s) return s;
if (!sgn(c.rabs()) || !sgn((c-b).rabs())) return 0;
if (dot(b, c) < 0) return 2;
if (dot(-b, c-b) < 0) return -2;
return 0;
}
int ccw(P a, P b, P c) { return ccw(b-a, c-a); }
int ccw(L l, P p) { return ccw(l.s, l.t, p); }
P project(const L &l, const P &p) {
P v = l.vec();
return l.s + v * (dot(v, p-l.s) / v.norm());
}
bool insSL(const L &s, const L &l) {
int a = ccw(l, s.s), b = ccw(l, s.t);
return (a%2 == 0 || b%2 == 0 || a != b);
}
bool insSS(const L &s, const L &t) {
int a = ccw(s, t.s), b = ccw(s, t.t);
int c = ccw(t, s.s), d = ccw(t, s.t);
if (a*b <= 0 && c*d <= 0) return true;
return false;
}
D distLP(const L &l, const P &p) {
return abs(cross(l.vec(), p-l.s)) / l.abs();
}
D distSP(const L &s, const P &p) {
P q = project(s, p);
if (ccw(s, q) == 0) return (p - q).abs();
else return min((s.s - p).abs(), (s.t - p).abs());
}
int crossLL(const L &l, const L &m, P &r) {
D cr1 = cross(l.vec(), m.vec()), cr2 = cross(l.vec(), l.t - m.s);
if (sgncrs(l.vec(), m.vec()) == 0) {
r = l.s;
if (sgncrs(l.vec(), l.t - m.s)) return 0;
return -1;
}
r = m.s + m.vec() * (cr2 / cr1);
return 1;
}
using Pol = V<P>;
struct C {
P p; D r;
C(P _p = P(), D _r = D()) : p(_p), r(_r) {}
};
//need Intersect/distLP, r.sはよりl.sに近い
int crossCL(const C &c, const L &l, L &r) {
D u = distLP(l, c.p);
int si = sgn(u, c.r);
if (si == 1) return 0;
P v = project(l, c.p);
P di = (si == 0) ? P(0, 0) : l.vec() * (sqrt(c.r*c.r - u*u) / l.abs());
r = L(v-di, v+di);
if (si == 0) return 1;
return 2;
}
// C(P(0, 0), r)とTri((0, 0), a, b)の共有面積
D area2CT(const C &c, const P &_a, const P &_b) {
P a = _a - c.p, b = _b - c.p; D r = c.r;
if (a == b) return 0;
auto single = [&](P x, P y, bool tri) {
if (tri) return cross(x, y);
else return r * r * ((y * P(x.x, -x.y)).arg());
};
bool ia = sgn(a.abs(), r) != 1, ib = sgn(b.abs(), r) != 1;
if (ia && ib) return single(a, b, true);
D r2 = distSP(L(a, b), P(0, 0));
if (sgn(r, r2) != 1) return single(a, b, false);
L l;
assert(crossCL(C(P(0, 0), r), L(a, b), l) == 2);
if (ia) l.s = l.t;
else if (ib) l.t = l.s;
assert(ccw(a, b, l.s) == 0); assert(ccw(a, b, l.t) == 0);
return single(a, l.s, ia) + single(l.s, l.t, true) + single(l.t, b, ib);
}
// p, cの共有面積
D area2CPol(const C &c, const Pol &po) {
D sm = 0;
P a, b = po.back();
for (auto p: po) {
a = b; b = p;
sm += area2CT(c, a, b);
}
return sm;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << setprecision(20);
int n; D r;
cin >> n >> r;
Pol pol;
D ymi = 1e100, yma = -1e100;
for (int i = 0; i < n; i++) {
D x, y;
cin >> x >> y;
pol.push_back(P(x, y));
ymi = min(ymi, y);
yma = max(yma, y);
}
auto calc = [&](D y) {
D xmi = 1e100, xma = -1e100;
P a, b = pol.back();
for (int i = 0; i < n; i++) {
a = b; b = pol[i];
P p;
if (crossLL(L(a, b), L(P(0, y), P(1, y)), p) == 0) continue;
if (ccw(a, b, p) != 0) continue;
xmi = min(xmi, p.x); xma = max(xma, p.x);
}
D lw = xmi, up = xma;
for (int ph = 0; ph < 30; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
D z1 = area2CPol(C(P(md1, y), r), pol) / 2;
D z2 = area2CPol(C(P(md2, y), r), pol) / 2;
if (z1 < z2) {
lw = md1;
} else {
up = md2;
}
}
return area2CPol(C(P(lw, y), r), pol) / 2;
};
D lw = ymi, up = yma;
for (int ph = 0; ph < 30; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
if (calc(md1) < calc(md2)) {
lw = md1;
} else {
up = md2;
}
}
cout << calc(lw) << endl;
return 0;
}
|
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
struct P {
double x, y;
P() {
}
P(double _x, double _y) :
x(_x), y(_y) {
}
P operator+(const P&p) const {
return P(x + p.x, y + p.y);
}
P operator-(const P&p) const {
return P(x - p.x, y - p.y);
}
P operator*(double d) const {
return P(x * d, y * d);
}
P operator/(double d) const {
return P(x / d, y / d);
}
double det(const P&p) const {
return x * p.y - y * p.x;
}
double dot(const P&p) const {
return x * p.x + y * p.y;
}
double alpha() const {
return atan2(y, x);
}
P rot90() const {
return P(-y, x);
}
void read() {
scanf("%lf%lf", &x, &y);
}
void write() const {
printf("(%lf,%lf)", x, y);
}
double abs() {
return sqrt(abs2());
}
double abs2() {
return x * x + y * y;
}
P unit() {
return *this / abs();
}
};
#define cross(p1,p2,p3) ((p2.x-p1.x)*(p3.y-p1.y)-(p3.x-p1.x)*(p2.y-p1.y))
const double EPS = 1e-8; //you should change it according to problem, nevertheless, it mustn't be a constant value some times.
inline int sign(double a) {
return a < -EPS ? -1 : a > EPS;
}
#define crossOp(p1,p2,p3) (sign(cross(p1,p2,p3)))
P isSS(P p1, P p2, P q1, P q2) {
double a1 = cross(q1,q2,p1), a2 = -cross(q1,q2,p2);
return (p1 * a2 + p2 * a1) / (a1 + a2);
}
int n;
double x[12],y[12],r;
bool onLine(P p, P q, P x){
return (x-p).dot(x-q) <= EPS;
}
vector<P> isCS(P c,double r,P p, P q){
double d = cross(q,p,c) / (p-q).abs();
vector<P> ret;
if(d>=r+EPS)
return ret;
P dir = (q-p).rot90();
P pq = (p-q);
pq = pq/pq.abs();
dir = dir / dir.abs();
P mid = c + dir * d;
double h = sqrt(max(r*r-d*d,0.0));
if(onLine(p,q,mid + pq*h))
ret.push_back(mid + pq*h);
if(onLine(p,q,mid - pq*h))
ret.push_back(mid - pq*h);
return ret;
}
double rad(P p,P q){
return atan2(p.det(q),p.dot(q));
}
double calc(P p, P q){
bool inp = p.abs2() <= r*r;
bool inq = q.abs2() <= r*r;
if(inp && inq){
return p.det(q)/2;
}
if(inp && !inq){
return -calc(q,p);
}
vector<P> is = isCS(P(0,0),r,p,q);
if(!inp && inq){
P m = is[0];
return r*r*rad(p,m)/2 + m.det(q)/2;
}
if(!inp && !inq){
if(is.empty())
return r*r*rad(p,q)/2;
return r*r*(rad(p,is[0]) + rad(is[1],q))/2 + is[0].det(is[1])/2;
}
}
double calcArea(double cx,double cy){
P ps[12];
rep(i,n) ps[i].x=x[i]-cx,ps[i].y=y[i]-cy;
ps[n] = ps[0];
double area = 0;
rep(i,n){
P p=ps[i],q=ps[i+1];
area += calc(p,q);
}
//cout<<area<<endl;
return area;
}
double ffy(double x){
double l = 1e100,r=-1e100;
P ps[12];
rep(i,n) ps[i].x=::x[i], ps[i].y=y[i];
ps[n] = ps[0];
rep(i,n){
P p = ps[i], q = ps[i+1];
if(p.x > q.x)
swap(p,q);
if(p.x<=x+EPS && x<=q.x+EPS){
double iy;
if(p.y==q.y)
iy = p.y;
else
iy = p.y + (q.y - p.y) * (x-p.x) / (q.x-p.x);
l = min(l,iy);
r = max(r,iy);
}
}
rep(it,100){
double ll=(l*2+r)/3,rr=(l+r*2)/3;
if(calcArea(x,ll)>calcArea(x,rr))
r=rr;
else
l=ll;
}
return calcArea(x,l);
}
double ffx(){
double l=*min_element(x,x+n),r=*max_element(x,x+n);
rep(it,100){
double ll=(l*2+r)/3,rr=(l+r*2)/3;
if(ffy(ll)>ffy(rr))
r=rr;
else
l=ll;
}
return ffy(l);
}
int main(){
cin>>n>>r;
rep(i,n) cin>>x[i]>>y[i];
printf("%0.10lf\n",ffx());
} |
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
template<class T> using V = vector<T>;
using D = double;
const D PI = acos(D(-1)), EPS = 1e-10;
int sgn(D a) { return (abs(a) <= EPS) ? 0 : (a < 0 ? -1 : 1); }
int sgn(D a, D b) { return sgn(a-b); }
//relative sign
// int rsgn(D a, D f) {
// if (abs(a) <= f*EPS) return 0;
// return (a < 0) ? -1 : 1;
// }
struct Pt2 {
D x, y;
Pt2(D _x = D(), D _y = D()) : x(_x), y(_y) {}
Pt2 operator+(const Pt2 &r) const { return Pt2(x+r.x, y+r.y); }
Pt2 operator-(const Pt2 &r) const { return Pt2(x-r.x, y-r.y); }
Pt2 operator*(const Pt2 &r) const { return Pt2(x*r.x-y*r.y, x*r.y+y*r.x); }
Pt2 operator*(const D &r) const { return Pt2(x*r, y*r); }
Pt2 operator/(const D &r) const { return Pt2(x/r, y/r); }
Pt2& operator+=(const Pt2 &r) { return *this=*this+r; }
Pt2& operator-=(const Pt2 &r) { return *this=*this-r; }
Pt2& operator*=(const Pt2 &r) { return *this=*this*r; }
Pt2& operator*=(const D &r) { return *this=*this*r; }
Pt2& operator/=(const D &r) { return *this=*this/r; }
Pt2 operator-() const { return Pt2(-x, -y); }
bool operator<(const Pt2 &r) const { return 2*sgn(x, r.x)+sgn(y, r.y)<0; }
bool operator==(const Pt2 &r) const { return sgn((*this-r).rabs()) == 0; }
D norm() const { return x*x + y*y; }
D abs() const { return sqrt(norm()); }
D rabs() const { return max(std::abs(x), std::abs(y)); } // robust abs
D arg() const { return atan2(y, x); }
pair<D, D> to_pair() const { return make_pair(x, y); }
static Pt2 polar(D le, D th) { return Pt2(le*cos(th), le*sin(th)); }
};
ostream& operator<<(ostream& os, const Pt2 &p) {
return os << "P(" << p.x << ", " << p.y << ")";
}
using P = Pt2;
struct L {
P s, t;
L(P _s = P(), P _t = P()) : s(_s), t(_t) {}
P vec() const { return t-s; }
D abs() const { return vec().abs(); }
D arg() const { return vec().arg(); }
};
ostream& operator<<(ostream& os, const L &l) {
return os << "L(" << l.s << ", " << l.t << ")";
}
D cross(P a, P b) { return a.x*b.y - a.y*b.x; }
D dot(P a, P b) { return a.x*b.x + a.y*b.y; }
// cross(a, b) is too small?
int sgncrs(P a, P b) {
D cr = cross(a, b);
if (abs(cr) <= (a.rabs() + b.rabs()) * EPS) return 0;
return (cr < 0) ? -1 : 1;
}
// -2, -1, 0, 1, 2 : front, clock, on, cclock, back
int ccw(P b, P c) {
int s = sgncrs(b, c);
if (s) return s;
if (!sgn(c.rabs()) || !sgn((c-b).rabs())) return 0;
if (dot(b, c) < 0) return 2;
if (dot(-b, c-b) < 0) return -2;
return 0;
}
int ccw(P a, P b, P c) { return ccw(b-a, c-a); }
int ccw(L l, P p) { return ccw(l.s, l.t, p); }
P project(const L &l, const P &p) {
P v = l.vec();
return l.s + v * (dot(v, p-l.s) / v.norm());
}
bool insSL(const L &s, const L &l) {
int a = ccw(l, s.s), b = ccw(l, s.t);
return (a%2 == 0 || b%2 == 0 || a != b);
}
bool insSS(const L &s, const L &t) {
int a = ccw(s, t.s), b = ccw(s, t.t);
int c = ccw(t, s.s), d = ccw(t, s.t);
if (a*b <= 0 && c*d <= 0) return true;
return false;
}
D distLP(const L &l, const P &p) {
return abs(cross(l.vec(), p-l.s)) / l.abs();
}
D distSP(const L &s, const P &p) {
P q = project(s, p);
if (ccw(s, q) == 0) return (p - q).abs();
else return min((s.s - p).abs(), (s.t - p).abs());
}
int crossLL(const L &l, const L &m, P &r) {
D cr1 = cross(l.vec(), m.vec()), cr2 = cross(l.vec(), l.t - m.s);
if (sgncrs(l.vec(), m.vec()) == 0) {
r = l.s;
if (sgncrs(l.vec(), l.t - m.s)) return 0;
return -1;
}
r = m.s + m.vec() * (cr2 / cr1);
return 1;
}
using Pol = V<P>;
struct C {
P p; D r;
C(P _p = P(), D _r = D()) : p(_p), r(_r) {}
};
//need Intersect/distLP, r.sはよりl.sに近い
int crossCL(const C &c, const L &l, L &r) {
D u = distLP(l, c.p);
int si = sgn(u, c.r);
if (si == 1) return 0;
P v = project(l, c.p);
P di = (si == 0) ? P(0, 0) : l.vec() * (sqrt(c.r*c.r - u*u) / l.abs());
r = L(v-di, v+di);
if (si == 0) return 1;
return 2;
}
// C(P(0, 0), r)とTri((0, 0), a, b)の共有面積
D area2CT(const C &c, const P &_a, const P &_b) {
P a = _a - c.p, b = _b - c.p; D r = c.r;
if (a == b) return 0;
auto single = [&](P x, P y, bool tri) {
if (tri) return cross(x, y);
else return r * r * ((y * P(x.x, -x.y)).arg());
};
bool ia = sgn(a.abs(), r) != 1, ib = sgn(b.abs(), r) != 1;
if (ia && ib) return single(a, b, true);
D r2 = distSP(L(a, b), P(0, 0));
if (sgn(r, r2) != 1) return single(a, b, false);
L l;
assert(crossCL(C(P(0, 0), r), L(a, b), l) == 2);
if (ia) l.s = l.t;
else if (ib) l.t = l.s;
assert(ccw(a, b, l.s) == 0); assert(ccw(a, b, l.t) == 0);
return single(a, l.s, ia) + single(l.s, l.t, true) + single(l.t, b, ib);
}
// p, cの共有面積
D area2CPol(const C &c, const Pol &po) {
D sm = 0;
P a, b = po.back();
for (auto p: po) {
a = b; b = p;
sm += area2CT(c, a, b);
}
return sm;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << setprecision(20);
int n; D r;
cin >> n >> r;
Pol pol;
D ymi = 1e100, yma = -1e100;
for (int i = 0; i < n; i++) {
D x, y;
cin >> x >> y;
pol.push_back(P(x, y));
ymi = min(ymi, y);
yma = max(yma, y);
}
auto calc = [&](D y) {
D xmi = 1e100, xma = -1e100;
for (int i = 0; i < n; i++) {
P p;
if (crossLL(L(pol[i], pol[(i+1)%n]), L(P(0, y), P(1, y)), p) == 0) continue;
if (ccw(pol[i], pol[(i+1)%n], p) != 0) continue;
xmi = min(xmi, p.x); xma = max(xma, p.x);
}
D lw = xmi, up = xma;
for (int ph = 0; ph < 50; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
D z1 = area2CPol(C(P(md1, y), r), pol) / 2;
D z2 = area2CPol(C(P(md2, y), r), pol) / 2;
if (z1 < z2) {
lw = md1;
} else {
up = md2;
}
}
return area2CPol(C(P(lw, y), r), pol) / 2;
};
D lw = ymi, up = yma;
for (int ph = 0; ph < 50; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
if (calc(md1) < calc(md2)) {
lw = md1;
} else {
up = md2;
}
}
cout << calc(lw) << endl;
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
typedef complex<double> P;
typedef vector< P > vecp;
struct S{
P p,q;
S(P p,P q) : p(p),q(q) {}
};
struct C{
P p; double r;
C(P p,double r):p(p),r(r){}
C(double x,double y,double rr){
p=P(x,y);
r=rr;
}
};
double eps=1e-8, PI=acos(-1), PI2=PI*2.0;
bool eq(double a,double b){return (b-a<eps&&a-b<eps);}
bool eq(P a,P b){return (abs(a-b)<eps);}
double Sqrt(double x){ return ( x<0 ? 0.0 : sqrt(x) ); }
double dot(P a,P b){return real(b*conj(a));}
double cross(P a,P b){return imag(b*conj(a));}
double dist(P a,P b,P c){
if(dot(b-a,c-a)<0)return abs(c-a);
if(dot(a-b,c-b)<0)return abs(c-b);
return abs(cross(b-a,c-a))/abs(b-a);
}
P project(P a,P b,P c){ b-=a; c-=a; return a+b*real(c/b); }
double getTime(P a,P b){
assert( eq(cross(a,b),0) );
return ( dot(a,b) < 0 ? -1.0 : 1.0 ) * abs(b);
}
bool onSegment(P a,P b,P p){
return eq( abs(a-b) , abs(a-p)+abs(b-p) );
}
P getCrossPoint(P a,P b,P c,P d){
a-=d;b-=d;c-=d;
return d+a+(b-a)*imag(a/c)/imag(a/c-b/c);
}
double getArg(P a,P b){ return arg(b*conj(a)); }
vecp getCrossPoint(C c,P a,P b){
vecp res;
P base=b-a, target=project(a,b,c.p);
double length=abs(base), h=abs(c.p-target);
if(c.r+eps<h)return res;
double w=Sqrt(c.r*c.r-h*h);
double L=getTime(base,target-a)-w, R=L+w*2.0;
base/=length;
if( -eps<L && L<length+eps )res.push_back(a+base*L);
if( eq(L,R) )return res;
if( -eps<R && R<length+eps )res.push_back(a+base*R);
return res;
}
vecp getCrossPoint(C a,S b, bool debug=false){
vecp res;
P base=b.q-b.p, target=project(b.p,b.q,a.p);
double length=abs(base), h=abs(a.p-target);
if(a.r+eps<h)return res;
double w=Sqrt(a.r*a.r-h*h);
double L=getTime(base,target-b.p)-w, R=L+w*2.0;
base/=length;
if( -eps<L && L< length+eps )res.push_back(b.p+base*L);
if( eq(L,R) )return res;
if( -eps<R && R< length+eps )res.push_back(b.p+base*R);
return res;
}
double getArea(C c,P a,P b){
P va=c.p-a, vb=c.p-b;
double A=abs(va), B=abs(vb);
double f=cross(va,vb), d=dist(a,b,c.p), res=0;
if( eq(0, f ) )return 0;
if(A<c.r+eps&&B<c.r+eps)return f*0.5;
if(d>c.r-eps)return c.r*c.r*PI*getArg(va,vb)/PI2;
vecp u=getCrossPoint(c, S(a,b) );
assert( !u.empty() );
u.insert(u.begin(), a), u.push_back(b);
for(int i=0;i+1<(int)u.size();i++) res+=getArea(c,u[i],u[i+1]);
return res;
}
double getArea(vecp t,C c){
int n=t.size();
if(n<3)return 0;
double res=0;
for(int i=0;i<n;i++){
P a=t[i], b=t[(i+1)%n];
res+=getArea(c,a,b);
}
return res;
}
int n;
double cr;
vecp t;
double calc(double gx){
double left=1e9, right=-1e9;
for(int i=0;i<(int)t.size();i++){
P a=t[i];
P b=t[ (i+1)%n ];
P k=getCrossPoint( a,b, P(gx,0), P(gx,1) );
if( onSegment(a,b,k) == false )continue;
left=min(left,k.imag());
right=max(right,k.imag());
}
for(int i=0;i<100;i++){
double dist=(right-left)/3.0;
double ml=left+dist;
double mr=right-dist;
if( getArea(t,C(P(gx,ml),cr)) > getArea(t,C(P(gx,mr),cr))){
right=mr;
}else{
left=ml;
}
}
return getArea(t,C(P(gx,left),cr));
}
int main(){
cin>>n>>cr;
double left=1e9, right=-1e9;
for(int i=0;i<n;i++){
double x,y;
cin>>x>>y;
t.push_back(P(x,y));
left=min(left,x);
right=max(right,x);
}
for(int i=0;i<100;i++){
double dist=(right-left)/3.0;
double ml=left+dist,mr=right-dist;
if( calc(ml) > calc(mr) )right=mr;
else left=ml;
}
printf("%.10f\n", calc(left) );
return 0;
} |
#include<bits/stdc++.h>
#define inf 400
#define linf 1e18
#define eps (1e-9)
#define mod 1000000007
#define pi M_PI
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(),(a).end()
#define pd(a) printf("%.10f\n",(double)(a))
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define RFOR(i,a,b) for(int i=(a)-1;(b)<=i;i--)
#define equals(a,b) (fabs((a)-(b))<eps)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<double,int> pdi;
typedef vector<int> vi;
typedef vector<pii> vpi;
class Point{
public:
double x,y;
Point(double x=0,double y=0):x(x),y(y){}
Point operator+(Point p){ return Point(x+p.x,y+p.y);}
Point operator-(Point p){ return Point(x-p.x,y-p.y);}
Point operator*(double k){ return Point(x*k,y*k);}
Point operator/(double k){ return Point(x/k,y/k);}
bool operator<(Point p)const{ return (x!=p.x ? x<p.x : y<p.y);}
bool operator==(Point p)const{ return fabs(x-p.x)<eps && fabs(y-p.y)<eps;}
double abs(){ return sqrt(norm());}
double norm(){ return (x*x+y*y);}
};
typedef Point Vector;
typedef vector<Point> Polygon;
class Segment{
public:
Point p1,p2;
Segment(Point p1=Point(),Point p2=Point()):p1(p1),p2(p2){}
};
typedef Segment Line;
class Circle{
public:
Point c;
double r;
Circle(Point c=Point(),double r=0.0):c(c),r(r){}
};
double norm(Vector a){ return (a.x*a.x+a.y*a.y);}
double abs(Vector a){ return sqrt(norm(a));}
double dot(Vector a,Vector b){ return (a.x*b.x+a.y*b.y);}
double cross(Vector a,Vector b){ return (a.x*b.y-a.y*b.x);}
bool in(Circle c,Point p){
if(abs(c.c-p)-c.r<-eps)return true;
return false;
}
Point project(Segment s,Point p){
Vector base=(s.p2-s.p1);
double r=(dot(p-s.p1,base)/base.norm());
return (s.p1+base*r);
}
int ccw(Point p0,Point p1,Point p2){
Vector a=p1-p0;
Vector b=p2-p0;
if(cross(a,b)>eps)return 1;
if(cross(a,b)<-eps)return -1;
if(dot(a,b)<-eps)return 2;
if(a.norm()<b.norm())return -2;
return 0;
}
double getDistanceLP(Line l,Point p){
return abs(cross(l.p2-l.p1,p-l.p1)/abs(l.p2-l.p1));
}
double getDistanceSP(Segment s,Point p){
if(dot(s.p2-s.p1,p-s.p1)<0.0)return abs(p-s.p1);
if(dot(s.p1-s.p2,p-s.p2)<0.0)return abs(p-s.p2);
return getDistanceLP(s,p);
}
bool intersect(Circle c,Segment s){
if(getDistanceSP(s,c.c)-c.r<-eps)return true;
return false;
}
double getAngle(Vector a,Vector b){
double tmp=dot(a,b)/(abs(a)*abs(b));
if(tmp<-1.0)tmp=-1.0;
if(1.0<tmp)tmp=1.0;
return acos(tmp)*180.0/pi;
}
pair<Point,Point> getCrossPoints(Circle c,Line l){
Vector pr=project(l,c.c);
Vector e=(l.p2-l.p1)/abs(l.p2-l.p1);
double base=sqrt(c.r*c.r-norm(pr-c.c));
return mp(pr+e*base,pr-e*base);
}
Point getCrossPointSC(Circle c,Segment s){
Point res;
pair<Point,Point> pp=getCrossPoints(c,s);
if(ccw(s.p1,s.p2,pp.f)==0){
res=pp.f;
if(ccw(s.p1,s.p2,pp.s)==0 && abs(s.p1-pp.s)<abs(s.p1-pp.f))res=pp.s;
}
else res=pp.s;
return res;
}
double getCommonAreaTC(Point a,Point b,Circle c){
double res=abs(cross(a-c.c,b-c.c)/2.0);
if(equals(0.0,res))return 0.0;
if(in(c,a) && !in(c,b)){
Point p1=getCrossPointSC(c,Segment(b,a));
Point p2=getCrossPointSC(c,Segment(b,c.c));
res+=(c.r*c.r*pi)*(getAngle(p1-c.c,p2-c.c)/360.0);
res-=abs(cross(p1-c.c,p2-c.c)/2.0);
res-=abs(cross(p2-b,p1-b)/2.0);
}
else if(!in(c,a) && in(c,b)){
Point p1=getCrossPointSC(c,Segment(a,c.c));
Point p2=getCrossPointSC(c,Segment(a,b));
res+=(c.r*c.r*pi)*(getAngle(p1-c.c,p2-c.c)/360.0);
res-=abs(cross(p1-c.c,p2-c.c)/2.0);
res-=abs(cross(p2-a,p1-a)/2.0);
}
else if(!in(c,a) && !in(c,b)){
if(intersect(c,Segment(a,b))){
pair<Point,Point> pp=getCrossPoints(c,Segment(a,b));
Point m=pp.f+(pp.s-pp.f)/2.0;
res=abs(getCommonAreaTC(a,m,c))+abs(getCommonAreaTC(m,b,c));
}
else res=(c.r*c.r*pi)*(getAngle(a-c.c,b-c.c)/360.0);
}
if(cross(a-c.c,b-c.c)<0.0)res=-res;
return res;
}
double getCommonAreaPC(Polygon p,Circle c){
double res=0.0;
int n=p.size();
FOR(i,0,n)res+=getCommonAreaTC(p[i],p[(i+1)%n],c);
return abs(res);
}
int n,r;
Polygon p;
Point g(0,0);
double check(Point a){
Vector v=(g-a);
v=v/abs(v);
double R=0.0,L=inf;
FOR(k,0,50){
double m1=(L*2.0+R)/3.0;
double m2=(L+R*2.0)/3.0;
double res1=getCommonAreaPC(p,Circle(a+v*m1,r));
double res2=getCommonAreaPC(p,Circle(a+v*m2,r));
if(res2-res1<-eps)R=m2;
else L=m1;
}
return getCommonAreaPC(p,Circle(a+v*R,r));
}
int main()
{
cin>>n>>r;
FOR(i,0,n){
int x,y;
cin>>x>>y;
p.pb(Point(x,y));
}
FOR(i,0,n)g=g+p[i];
g=g/n;
double ans=0.0;
FOR(i,0,n){
Point a=p[i],b=p[(i+1)%n];
Vector v=b-a;
v=v/abs(v);
double R=0.0,L=inf*2;
FOR(k,0,50){
double m1=(L*2.0+R)/3.0;
double m2=(L+R*2.0)/3.0;
double res1=check(a+v*(m1-inf));
double res2=check(a+v*(m2-inf));
if(res2-res1<-eps)R=m2;
else L=m1;
}
ans=max(ans,check(a+v*(R-inf)));
}
pd(ans);
return 0;
} |
#include <iostream>
#include <iomanip>
#include <complex>
#include <vector>
#include <algorithm>
#include <cmath>
#include <array>
using namespace std;
const double EPS = 1e-10;
const double INF = 1e12;
const double PI = acos(-1);
#define EQ(n,m) (abs((n)-(m)) < EPS)
#define X real()
#define Y imag()
typedef complex<double> P;
typedef vector<P> VP;
struct L : array<P, 2>{
L(const P& a, const P& b){ at(0)=a; at(1)=b; }
L(){}
};
struct C{
P p;
double r;
C(const P& p, const double& r) : p(p), r(r) {}
C(){}
};
namespace std{
bool operator < (const P& a, const P& b){
return (a.X!=b.X) ? a.X<b.X : a.Y<b.Y;
}
bool operator == (const P& a, const P& b){
return abs(a-b) < EPS;
}
}
double dot(P a, P b){
return (conj(a)*b).X;
}
double cross(P a, P b){
return (conj(a)*b).Y;
}
int ccw(P a, P b, P c){
b -= a;
c -= a;
if(cross(b,c) > EPS) return +1; //ccw
if(cross(b,c) < -EPS) return -1; //cw
if(dot(b,c) < -EPS) return +2; //c-a-b
if(abs(c)-abs(b) > EPS) return -2; //a-b-c
return 0; //a-c-b
}
P unit(const P &p){
return p/abs(p);
}
P rotate(const P &p, double rad){
return p *P(cos(rad), sin(rad));
}
bool intersectSP(const L& s, const P &p){
return abs(cross(s[0]-p, s[1]-p))<EPS && dot(s[0]-p, s[1]-p)<EPS;
}
bool intersectSS(const L& a, const L& b){
return ( ccw(a[0],a[1],b[0]) *ccw(a[0],a[1],b[1]) <= 0 ) &&
( ccw(b[0],b[1],a[0]) *ccw(b[0],b[1],a[1]) <= 0 );
}
P projection(const L& l, const P& p) {
double t = dot(p-l[0], l[0]-l[1]) / norm(l[0]-l[1]);
return l[0] + t*(l[0]-l[1]);
}
double distanceLP(const L &l, const P &p) {
return abs(p - projection(l, p));
}
double distanceSP(const L &s, const P &p) {
const P r = projection(s, p);
if (intersectSP(s, r)) return abs(r - p);
return min(abs(s[0]-p), abs(s[1]-p));
}
bool isParallel(const P &a, const P &b){
return abs(cross(a,b)) < EPS;
}
bool isParallel(const L &a, const L &b){
return isParallel(a[1]-a[0], b[1]-b[0]);
}
P crosspointLL(const L &l, const L &m) {
double A = cross(l[1]-l[0], m[1]-m[0]);
double B = cross(l[1]-l[0], l[1]-m[0]);
return m[0] + B/A *(m[1]-m[0]);
}
VP crosspointCL(const C &c, const L &l){
VP ret;
P mid = projection(l, c.p);
double d = distanceLP(l, c.p);
if(EQ(d, c.r)){
ret.push_back(mid);
}else if(d < c.r){
double len = sqrt(c.r*c.r -d*d);
ret.push_back(mid +len*unit(l[1]-l[0]));
ret.push_back(mid -len*unit(l[1]-l[0]));
}
return ret;
}
VP crosspointCS(const C &c, const L &s){
VP ret;
VP cp = crosspointCL(c,s);
for(int i=0; i<(int)cp.size(); i++){
if(intersectSP(s, cp[i])){
ret.push_back(cp[i]);
}
}
return ret;
}
int in_poly(const P &p, const VP &poly){
int n = poly.size();
int ret = -1;
for(int i=0; i<n; i++){
P a = poly[i]-p;
P b = poly[(i+1)%n]-p;
if(a.Y > b.Y) swap(a,b);
if(intersectSP(L(a,b), P(0,0))) return 0;
if(a.Y<=0 && b.Y>0 && cross(a,b)<0) ret = -ret;
}
return ret;
}
VP convex(VP v){
VP ret;
int n = v.size();
sort(v.begin(), v.end());
for(int i=0; i<n; i++){
while((int)ret.size()>1 && cross(ret.back()-ret[ret.size()-2], v[i]-ret.back()) < EPS){
ret.pop_back();
}
ret.push_back(v[i]);
}
int t = ret.size();
for(int i=n-2; i>=0; i--){
while((int)ret.size()>t && cross(ret.back()-ret[ret.size()-2], v[i]-ret.back()) < EPS){
ret.pop_back();
}
ret.push_back(v[i]);
}
if((int)ret.size() > 1) ret.pop_back();
return ret;
}
double commonarea_circle_convex(C c, VP poly){
int n = poly.size();
for(int i=0; i<n; i++) poly[i] -= c.p;
c.p = P(0, 0);
VP cp;
for(int i=0; i<n; i++){
L edge(poly[i], poly[(i+1)%n]);
VP ret = crosspointCS(c, edge);
cp.insert(cp.begin(), ret.begin(), ret.end());
if(abs(poly[i]) < c.r) cp.push_back(poly[i]);
}
sort(cp.begin(), cp.end());
cp.erase(unique(cp.begin(), cp.end()), cp.end());
double res = 0;
VP v = convex(cp);
int m = v.size();
for(int i=0; i<m; i++){
P curr = v[i];
P next = v[(i+1)%m];
if(EQ(abs(curr), c.r) && EQ(abs(next), c.r)
&& in_poly(c.r *unit(next -curr)*P(0,-1), poly) > 0){
double theta = arg(next /curr);
if(theta < 0) theta += 2*PI;
res += c.r*c.r *theta /2;
}else{
res += cross(curr, next) /2;
}
}
return res;
}
int main(){
int n,r;
cin >> n >> r;
VP poly(n);
int xmax=0, xmin=100;
for(int i=0; i<n; i++){
int x,y;
cin >> x >> y;
poly[i] = P(x, y);
xmax = max(xmax, x);
xmin = min(xmin, x);
}
double ans = 0;
double lb=xmin, ub=xmax;
for(int rep=0; rep<50; rep++){
double mid[2] = {(2*lb +ub)/3, (lb +2*ub)/3};
double area[2];
for(int i=0; i<2; i++){
vector<double> bound;
double x = mid[i];
L div(P(x, -INF), P(x, INF));
for(int j=0; j<n; j++){
L edge(poly[j], poly[(j+1)%n]);
if(!isParallel(div, edge) && intersectSS(div, edge)){
bound.push_back(crosspointLL(div, edge).Y);
}
}
sort(bound.begin(), bound.end());
double lb = bound[0], ub = bound.back();
for(int rep=0; rep<50; rep++){
double mid[2] = {(2*lb +ub)/3, (lb +2*ub)/3};
double area[2];
for(int i=0; i<2; i++){
area[i] = commonarea_circle_convex(C(P(x, mid[i]), r), poly);
}
if(area[0] > area[1]){
ub = mid[1];
}else{
lb = mid[0];
}
}
area[i] = commonarea_circle_convex(C(P(x, lb), r), poly);
ans = max(ans, area[i]);
}
if(area[0] > area[1]){
ub = mid[1];
}else{
lb = mid[0];
}
}
cout << fixed;
cout << setprecision(10);
cout << ans << endl;
return 0;
}
|
#include<bits/stdc++.h>
#define inf 400
#define linf 1e18
#define eps (1e-9)
#define mod 1000000007
#define pi M_PI
#define phi (1.0+sqrt(5))/2.0
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(),(a).end()
#define pd(a) printf("%.10f\n",(double)(a))
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define RFOR(i,a,b) for(int i=(a)-1;(b)<=i;i--)
#define equals(a,b) (fabs((a)-(b))<eps)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<double,int> pdi;
typedef vector<int> vi;
typedef vector<pii> vpi;
class Point{
public:
double x,y;
Point(double x=0,double y=0):x(x),y(y){}
Point operator+(Point p){ return Point(x+p.x,y+p.y);}
Point operator-(Point p){ return Point(x-p.x,y-p.y);}
Point operator*(double k){ return Point(x*k,y*k);}
Point operator/(double k){ return Point(x/k,y/k);}
bool operator<(Point p)const{ return (x!=p.x ? x<p.x : y<p.y);}
bool operator==(Point p)const{ return fabs(x-p.x)<eps && fabs(y-p.y)<eps;}
double abs(){ return sqrt(norm());}
double norm(){ return (x*x+y*y);}
};
typedef Point Vector;
typedef vector<Point> Polygon;
class Segment{
public:
Point p1,p2;
Segment(Point p1=Point(),Point p2=Point()):p1(p1),p2(p2){}
};
typedef Segment Line;
class Circle{
public:
Point c;
double r;
Circle(Point c=Point(),double r=0.0):c(c),r(r){}
};
double norm(Vector a){ return (a.x*a.x+a.y*a.y);}
double abs(Vector a){ return sqrt(norm(a));}
double dot(Vector a,Vector b){ return (a.x*b.x+a.y*b.y);}
double cross(Vector a,Vector b){ return (a.x*b.y-a.y*b.x);}
bool in(Circle c,Point p){
if(abs(c.c-p)-c.r<-eps)return true;
return false;
}
Point project(Segment s,Point p){
Vector base=(s.p2-s.p1);
double r=(dot(p-s.p1,base)/base.norm());
return (s.p1+base*r);
}
int ccw(Point p0,Point p1,Point p2){
Vector a=p1-p0;
Vector b=p2-p0;
if(cross(a,b)>eps)return 1;
if(cross(a,b)<-eps)return -1;
if(dot(a,b)<-eps)return 2;
if(a.norm()<b.norm())return -2;
return 0;
}
double getDistanceLP(Line l,Point p){
return abs(cross(l.p2-l.p1,p-l.p1)/abs(l.p2-l.p1));
}
double getDistanceSP(Segment s,Point p){
if(dot(s.p2-s.p1,p-s.p1)<0.0)return abs(p-s.p1);
if(dot(s.p1-s.p2,p-s.p2)<0.0)return abs(p-s.p2);
return getDistanceLP(s,p);
}
bool intersect(Circle c,Segment s){
if(getDistanceSP(s,c.c)-c.r<-eps)return true;
return false;
}
double getAngle(Vector a,Vector b){
double tmp=dot(a,b)/(abs(a)*abs(b));
if(tmp<-1.0)tmp=-1.0;
if(1.0<tmp)tmp=1.0;
return acos(tmp)*180.0/pi;
}
pair<Point,Point> getCrossPoints(Circle c,Line l){
Vector pr=project(l,c.c);
Vector e=(l.p2-l.p1)/abs(l.p2-l.p1);
double base=sqrt(c.r*c.r-norm(pr-c.c));
return mp(pr+e*base,pr-e*base);
}
Point getCrossPointSC(Circle c,Segment s){
Point res;
pair<Point,Point> pp=getCrossPoints(c,s);
if(ccw(s.p1,s.p2,pp.f)==0){
res=pp.f;
if(ccw(s.p1,s.p2,pp.s)==0 && abs(s.p1-pp.s)<abs(s.p1-pp.f))res=pp.s;
}
else res=pp.s;
return res;
}
double getCommonAreaTC(Point a,Point b,Circle c){
double res=abs(cross(a-c.c,b-c.c)/2.0);
if(equals(0.0,res))return 0.0;
if(in(c,a) && !in(c,b)){
Point p1=getCrossPointSC(c,Segment(b,a));
Point p2=getCrossPointSC(c,Segment(b,c.c));
res+=(c.r*c.r*pi)*(getAngle(p1-c.c,p2-c.c)/360.0);
res-=abs(cross(p1-c.c,p2-c.c)/2.0);
res-=abs(cross(p2-b,p1-b)/2.0);
}
else if(!in(c,a) && in(c,b)){
Point p1=getCrossPointSC(c,Segment(a,c.c));
Point p2=getCrossPointSC(c,Segment(a,b));
res+=(c.r*c.r*pi)*(getAngle(p1-c.c,p2-c.c)/360.0);
res-=abs(cross(p1-c.c,p2-c.c)/2.0);
res-=abs(cross(p2-a,p1-a)/2.0);
}
else if(!in(c,a) && !in(c,b)){
if(intersect(c,Segment(a,b))){
pair<Point,Point> pp=getCrossPoints(c,Segment(a,b));
Point m=pp.f+(pp.s-pp.f)/2.0;
res=abs(getCommonAreaTC(a,m,c))+abs(getCommonAreaTC(m,b,c));
}
else res=(c.r*c.r*pi)*(getAngle(a-c.c,b-c.c)/360.0);
}
if(cross(a-c.c,b-c.c)<0.0)res=-res;
return res;
}
double getCommonAreaPC(Polygon p,Circle c){
double res=0.0;
int n=p.size();
FOR(i,0,n)res+=getCommonAreaTC(p[i],p[(i+1)%n],c);
return abs(res);
}
int n,r;
Polygon p;
Point g(0,0);
double check(Point a){
Vector v=(g-a);
v=v/abs(v);
double R=0.0,L=inf;
FOR(k,0,40){
double m1=(L*phi+R)/(1.0+phi);
double m2=(L+R*phi)/(1.0+phi);
double res1=getCommonAreaPC(p,Circle(a+v*m1,r));
double res2=getCommonAreaPC(p,Circle(a+v*m2,r));
if(res2-res1<-eps)R=m2;
else L=m1;
}
return getCommonAreaPC(p,Circle(a+v*R,r));
}
double solve(){
FOR(i,0,n)g=g+p[i];
g=g/n;
double res=0.0;
FOR(i,0,n){
Point a=p[i],b=p[(i+1)%n];
Vector v=b-a;
v=v/abs(v);
double R=0.0,L=inf*2;
FOR(k,0,40){
double m1=(L*phi+R)/(1.0+phi);
double m2=(L+R*phi)/(1.0+phi);
double res1=check(a+v*(m1-inf));
double res2=check(a+v*(m2-inf));
if(res2-res1<-eps)R=m2;
else L=m1;
}
res=max(res,check(a+v*(R-inf)));
}
return res;
}
int main()
{
cin>>n>>r;
FOR(i,0,n){
int x,y;
cin>>x>>y;
p.pb(Point(x,y));
}
pd(solve());
return 0;
} |
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
using ll = long long;
using ull = unsigned long long;
constexpr ll TEN(int n) { return (n==0) ? 1 : 10*TEN(n-1); }
template<class T> using V = vector<T>;
template<class T> using VV = V<V<T>>;
using D = double;
const D PI = acos(D(-1)), EPS = 1e-10;
struct Pt2 {
D x, y;
Pt2() {}
Pt2(D _x, D _y) : x(_x), y(_y) {}
Pt2 operator+(const Pt2 &r) const { return Pt2(x+r.x, y+r.y); }
Pt2 operator-(const Pt2 &r) const { return Pt2(x-r.x, y-r.y); }
Pt2 operator*(const Pt2 &r) const { return Pt2(x*r.x-y*r.y, x*r.y+y*r.x); }
Pt2 operator*(const D &r) const { return Pt2(x*r, y*r); }
Pt2 operator/(const D &r) const { return Pt2(x/r, y/r); }
Pt2& operator+=(const Pt2 &r) { return *this=*this+r; }
Pt2& operator-=(const Pt2 &r) { return *this=*this-r; }
Pt2& operator*=(const Pt2 &r) { return *this=*this*r; }
Pt2 operator-() const { return Pt2(-x, -y); }
D abs() const { return sqrt(x*x + y*y); }
D rabs() const { return max(::abs(x), ::abs(y)); } // robust abs
D arg() const { return atan2(y, x); }
pair<D, D> to_pair() const { return make_pair(x, y); }
static Pt2 polar(D le, D th) { return Pt2(le*cos(th), le*sin(th)); }
};
ostream& operator<<(ostream& os, const Pt2 &p) {
os << "(" << p.x << ", " << p.y << ")";
return os;
}
using P = Pt2;
struct L {
P s, t;
L() {}
L(P _s, P _t) : s(_s), t(_t) {}
P vec() const { return t-s; }
D abs() const { return vec().abs(); }
D arg() const { return vec().arg(); }
};
int sgn(D a) {
if (abs(a) <= EPS) return 0;
return (a < 0) ? -1 : 1;
}
int sgn(D a, D b) { return sgn(a-b); }
//relative sign
int rsgn(D a, D f) {
if (abs(a) <= f*EPS) return 0;
return (a < 0) ? -1 : 1;
}
bool near(P a, P b) { return !sgn((a-b).abs()); }
D cross(P a, P b) { return a.x*b.y - a.y*b.x; }
D dot(P a, P b) { return a.x*b.x + a.y*b.y; }
// -2, -1, 0, 1, 2 : front, clock, on, cclock, back
int ccw(P b, P c) {
int s = rsgn(cross(b, c), b.rabs());
if (s) return s;
if (!sgn(c.rabs()) || !sgn((c-b).rabs())) return 0;
if (dot(b, c) < 0) return 2;
if (dot(-b, c-b) < 0) return -2;
return 0;
}
int ccw(P a, P b, P c) { return ccw(b-a, c-a); }
int ccw(L l, P p) { return ccw(l.s, l.t, p); }
D distLP(const L &l, const P &p) {
return abs(cross(l.vec(), p-l.s)) / l.abs();
}
D distSP(const L &s, const P &p) {
P s2 = s.vec() * P(0, 1);
if (ccw(s.s, s.s+s2, p) == 1) return (s.s-p).abs();
if (ccw(s.t, s.t+s2, p) == -1) return (s.t-p).abs();
return distLP(s, p);
}
int crossLL(const L &l, const L &m, P &r) {
if (sgn(cross(l.vec(), m.vec())) == 0) {
r = l.s;
if (ccw(l.s, l.t, m.s) % 2 == 0) return -1;
return 0;
}
D t = cross(l.vec(), l.t - m.s) / cross(l.vec(), m.vec());
r = m.s + m.vec() * t;
return 1;
}
using Pol = V<P>;
struct C {
P p; D r;
C() {}
C(P p, D r) : p(p), r(r) {}
};
D insAreaTC(const P &a, const P &b, const D &r) {
if (near(a, b)) return 0;
D r2 = distSP(L(a, b), P(0, 0));
// cout << "Z " << a << " " << b << " " << c.p << " " << c.r << endl;
if (sgn(max(a.abs(), b.abs()), r) != 1) return cross(a, b) / 2;
if (sgn(r, r2) != 1) {
D ar = b.arg() - a.arg();
ar = fmod(fmod(ar, 2*PI) + 2*PI, 2*PI);
if (!sgn(ar - 2*PI)) ar = 0;
if (ar >= PI) ar -= 2*PI;
return r * r * ar / 2;
}
return insAreaTC(a, (a+b)/2, r) + insAreaTC((a+b)/2, b, r);
}
const P& c_at(const Pol &p, int idx) {
int n = int(p.size());
return p[idx < n ? idx : idx-n];
}
D insAreaPolC(const Pol &p, const C &c) {
int n = int(p.size());
D sm = 0;
for (int i = 0; i < n; i++) {
sm += insAreaTC(p[i] - c.p, c_at(p, i+1) - c.p, c.r);
}
return sm;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << setprecision(20);
int n; D r;
cin >> n >> r;
Pol pol;
D ymi = 1e100, yma = -1e100;
for (int i = 0; i < n; i++) {
D x, y;
cin >> x >> y;
pol.push_back(P(x, y));
ymi = min(ymi, y);
yma = max(yma, y);
}
auto calc = [&](D y) {
D xmi = 1e100, xma = -1e100;
for (int i = 0; i < n; i++) {
P p;
if (crossLL(L(pol[i], c_at(pol, i+1)), L(P(0, y), P(1, y)), p) == 0) continue;
if (ccw(pol[i], c_at(pol, i+1), p) != 0) continue;
xmi = min(xmi, p.x); xma = max(xma, p.x);
}
D lw = xmi, up = xma;
for (int ph = 0; ph < 50; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
D z1 = insAreaPolC(pol, C(P(md1, y), r));
D z2 = insAreaPolC(pol, C(P(md2, y), r));
if (z1 < z2) {
lw = md1;
} else {
up = md2;
}
}
return insAreaPolC(pol, C(P(lw, y), r));
};
D lw = ymi, up = yma;
for (int ph = 0; ph < 50; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
if (calc(md1) < calc(md2)) {
lw = md1;
} else {
up = md2;
}
}
cout << calc(lw) << endl;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-8;
const double PI = acos(-1.0);
struct point
{
double x,y;
point() {}
point(double a,double b) : x(a),y(b) {}
friend point operator + (const point &a,const point &b)
{
return point(a.x+b.x,a.y+b.y);
}
friend point operator - (const point &a,const point &b)
{
return point(a.x-b.x,a.y-b.y);
}
friend point operator * (const point &a,const double &b)
{
return point(a.x*b,a.y*b);
}
friend point operator * (const double &a,const point &b)
{
return point(a*b.x,a*b.y);
}
friend point operator / (const point &a,const double &b)
{
return point(a.x/b,a.y/b);
}
};
point res[15],temp[15];
double r;
int n;
int dcmp(double k)
{
return k < -EPS ? -1 : k > EPS ? 1 : 0;
}
double dot(const point &a,const point &b)
{
return a.x*b.x + a.y*b.y;
}
double cross(const point &a,const point &b)
{
return a.x*b.y - a.y*b.x;
}
double abs(const point &o)
{
return sqrt(dot(o,o));
}
point crosspt(const point &a,const point &b,const point &p,const point &q)
{
double a1 = cross(b - a,p - a);
double a2 = cross(b - a,q - a);
return (p*a2 - q*a1)/(a2 - a1);
}
double mysqrt(double n)
{
return sqrt(max(0.0,n));
}
double sector_area(const point &a,const point &b)
{
double theta = atan2(a.y,a.x) - atan2(b.y,b.x);
while(theta <= 0) theta += 2*PI;
while(theta > 2*PI) theta -= 2*PI;
theta = min(theta,2*PI - theta);
return r * r * theta / 2;
}
void circle_cross_line(point a,point b,point o,double r,point ret[],int &num)
{
double x0 = o.x,y0 = o.y;
double x1 = a.x,y1 = a.y;
double x2 = b.x,y2 = b.y;
double dx = x2 -x1,dy = y2 - y1;
double A = dx*dx + dy*dy;
double B = 2*dx*(x1 - x0) + 2*dy*(y1 - y0);
double C = (x1 -x0)*(x1 - x0) + (y1 - y0)*(y1 - y0) - r*r;
double delta = B*B - 4*A*C;
num = 0;
if(dcmp(delta) >= 0)
{
double t1 = (-B - mysqrt(delta))/(2*A);
double t2 = (-B + mysqrt(delta))/(2*A);
if(dcmp(t1-1) <= 0 && dcmp(t1) >= 0)
{
ret[num++] = point(x1 + t1*dx,y1 + t1*dy);
}
if(dcmp(t2-1) <= 0 && dcmp(t2) >= 0)
{
ret[num++] = point(x1 + t2*dx,y1 + t2*dy);
}
}
}
double cacl(const point &a,const point &b)
{
point p[2];
int num = 0;
int ina = dcmp(abs(a) - r) < 0;
int inb = dcmp(abs(b) - r) < 0;
if(ina)
{
if(inb) return fabs(cross(a,b))/2.0;
else
{
circle_cross_line(a,b,point(0,0),r,p,num);
return sector_area(b,p[0]) + fabs(cross(a,p[0]))/2.0;
}
}
else
{
if(inb)
{
circle_cross_line(a,b,point(0,0),r,p,num);
return sector_area(p[0],a) + fabs(cross(p[0],b)) / 2.0;
}
else
{
circle_cross_line(a,b,point(0,0),r,p,num);
if(num == 2)
{
return sector_area(a,p[0]) + sector_area(p[1],b) + fabs(cross(p[0],p[1])) / 2.0;
}
else return sector_area(a,b);
}
}
}
double area()
{
double ret = 0;
for(int i = 0;i < n;i++)
{
int sgn = dcmp(cross(res[i],res[i+1]));
if(sgn != 0) ret += sgn*cacl(res[i],res[i+1]);
}
return ret;
}
double pol_area()
{
double tarea = 0;
for (int i = 1; i < n; i++)
tarea += fabs(cross(temp[i] - temp[0], temp[i + 1] - temp[0]));
return tarea / 2;
}
point MassCenter()
{
point ans = point(0,0);
double tarea = pol_area();
if (dcmp(tarea) == 0) return ans;
for (int i = 0; i < n; i++) ans = ans + (temp[i] + temp[i + 1]) * cross(temp[i], temp[i + 1]);
return ans / tarea / 6;
}
double get_ymin(double x)
{
double y = 500;
for (int i = 0; i < n; i++)
{
if (dcmp((temp[i].x - x) * (temp[i + 1].x - x)) <= 0)
{
if (dcmp(temp[i].x - temp[i + 1].x) == 0) {
y = min(y, min(temp[i].y, temp[i + 1].y));
} else {
double rat = (x - temp[i].x) / (temp[i + 1].x - temp[i].x);
y = min(y, rat * (temp[i + 1].y - temp[i].y) + temp[i].y);
}
}
}
return y;
}
double get_ymax(double x)
{
double y = -100;
for (int i = 0; i < n; i++)
{
if (dcmp((temp[i].x - x) * (temp[i + 1].x - x)) <= 0)
{
if (dcmp(temp[i].x - temp[i + 1].x) == 0) {
y = max(y, max(temp[i].y, temp[i + 1].y));
} else {
double rat = (x - temp[i].x) / (temp[i + 1].x - temp[i].x);
y = max(y, rat * (temp[i + 1].y - temp[i].y) + temp[i].y);
}
}
}
return y;
}
double check2(double x,double y)
{
for (int i = 0; i <= n; i++)
{
res[i] = temp[i] - point(x, y);
}
return area();
}
double check(double x)
{
double l2 = get_ymin(x),r2 = get_ymax(x);
while(abs(r2-l2) > EPS)
{
double mid1 = (2*l2+r2)/3,mid2 = (2*r2+l2)/3;
if(check2(x,mid1) > check2(x,mid2)) r2 = mid2;
else l2 = mid1;
}
return check2(x,l2);
}
int main()
{
double Mi1 = 10000,Ma1 = -10000,Mi2 = 10000,Ma2 = -10000;
cin.sync_with_stdio(false);
cin>>n>>r;
for(int i = 1;i <= n;i++)
{
cin>>temp[i].x>>temp[i].y;
Mi1 = min(Mi1,temp[i].x);
Ma1 = max(Ma1,temp[i].x);
Mi2 = min(Mi2,temp[i].y);
Ma2 = max(Ma2,temp[i].y);
}
temp[0] = temp[n];
point center = MassCenter();
for (int i = 0; i <= n; i++)
res[i] = temp[i] - center;
/* double ans = area();
cerr << center.x << ' ' << center.y << endl;
printf("%.8f\n", ans);*/
double l1 = Mi1,r1 = Ma1;
while(abs(r1 - l1) > EPS)
{
double mid1 = (2*l1+r1)/3,mid2 = (2*r1+l1) / 3;
if(check(mid1) > check(mid2)) r1 = mid2;
else l1 = mid1;
}
printf("%.8lf\n", check(l1));
} |
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<climits>
#include<algorithm>
#include<vector>
#include<complex>
#include<cassert>
#define REP(i,s,n) for(int i=s;i<n;++i)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-9)
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
using namespace std;
// BEGIN - Library
bool LT(double a,double b) { return !equals(a,b) && a < b; }
bool LTE(double a,double b) { return equals(a,b) || a < b; }
class Point{
public:
double x,y;
Point(double x = 0,double y = 0): x(x),y(y){}
Point operator + (Point p){return Point(x+p.x,y+p.y);}
Point operator - (Point p){return Point(x-p.x,y-p.y);}
Point operator * (double a){return Point(a*x,a*y);}
Point operator / (double a){return Point(x/a,y/a);}
Point operator * (Point a){ return Point(x * a.x - y * a.y, x * a.y + y * a.x); }
bool operator < (const Point& p) const{ return !equals(x,p.x)?x<p.x:(!equals(y,p.y)&&y<p.y); }
bool operator == (const Point& p)const{ return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS; }
};
struct Segment{
Point p1,p2;
Segment(Point p1 = Point(),Point p2 = Point()):p1(p1),p2(p2){}
bool operator < (const Segment& s) const { return ( p2 == s.p2 ) ? p1 < s.p1 : p2 < s.p2; }
bool operator == (const Segment& s) const { return ( s.p1 == p1 && s.p2 == p2 ) || ( s.p1 == p2 && s.p2 == p1 ); }
};
typedef Point Vector;
typedef Segment Line;
typedef vector<Point> Polygon;
ostream& operator << (ostream& os,const Point& a){ return os << "(" << a.x << "," << a.y << ")"; }
ostream& operator << (ostream& os,const Segment& a){ return os << "( " << a.p1 << " , " << a.p2 << " )"; }
double dot(Point a,Point b){ return a.x*b.x + a.y*b.y; }
double cross(Point a,Point b){ return a.x*b.y - a.y*b.x; }
double norm(Point a){ return a.x*a.x+a.y*a.y; }
double abs(Point a){ return sqrt(norm(a)); }
//rad ????§???????????????¢?????§?????????????????¨
Point rotate(Point a,double rad){ return Point(cos(rad)*a.x - sin(rad)*a.y,sin(rad)*a.x + cos(rad)*a.y); }
// ??????????????¢????????????
double toRad(double agl){ return agl*M_PI/180.0; }
// a => prev, b => cur, c=> next
// prev ?????? cur ????????£??? next ????????????????§????????±???????
double getArg(Point a,Point b,Point c){
double arg1 = atan2(b.y-a.y,b.x-a.x);
double arg2 = atan2(c.y-b.y,c.x-b.x);
double arg = fabs( arg1 - arg2 );
while( arg > M_PI ) arg -= 2.0 * M_PI;
return fabs(arg);
}
int ccw(Point p0,Point p1,Point p2){
Point a = p1-p0;
Point b = p2-p0;
if(cross(a,b) > EPS)return COUNTER_CLOCKWISE;
if(cross(a,b) < -EPS)return CLOCKWISE;
if(dot(a,b) < -EPS)return ONLINE_BACK;
if(norm(a) < norm(b))return ONLINE_FRONT;
return ON_SEGMENT;
}
bool intersectLL(Line l, Line m) {
return abs(cross(l.p2-l.p1, m.p2-m.p1)) > EPS || // non-parallel
abs(cross(l.p2-l.p1, m.p1-l.p1)) < EPS; // same line
}
bool intersectLS(Line l, Line s) {
return cross(l.p2-l.p1, s.p1-l.p1)* // s[0] is left of l
cross(l.p2-l.p1, s.p2-l.p1) < EPS; // s[1] is right of l
}
bool intersectLP(Line l,Point p) {
return abs(cross(l.p2-p, l.p1-p)) < EPS;
}
bool intersectSS(Line s, Line t) {
return ccw(s.p1,s.p2,t.p1)*ccw(s.p1,s.p2,t.p2) <= 0 &&
ccw(t.p1,t.p2,s.p1)*ccw(t.p1,t.p2,s.p2) <= 0;
}
bool intersectSP(Line s, Point p) {
return abs(s.p1-p)+abs(s.p2-p)-abs(s.p2-s.p1) < EPS; // triangle inequality
}
Point projection(Line l,Point p) {
double t = dot(p-l.p1, l.p1-l.p2) / norm(l.p1-l.p2);
return l.p1 + (l.p1-l.p2)*t;
}
Point reflection(Line l,Point p) {
return p + (projection(l, p) - p) * 2;
}
double distanceLP(Line l, Point p) {
return abs(p - projection(l, p));
}
double distanceLL(Line l, Line m) {
return intersectLL(l, m) ? 0 : distanceLP(l, m.p1);
}
double distanceLS(Line l, Line s) {
if (intersectLS(l, s)) return 0;
return min(distanceLP(l, s.p1), distanceLP(l, s.p2));
}
double distanceSP(Line s, Point p) {
Point r = projection(s, p);
if (intersectSP(s, r)) return abs(r - p);
return min(abs(s.p1 - p), abs(s.p2 - p));
}
double distanceSS(Line s, Line t) {
if (intersectSS(s, t)) return 0;
return min(min(distanceSP(s, t.p1), distanceSP(s, t.p2)),
min(distanceSP(t, s.p1), distanceSP(t, s.p2)));
}
Point crosspoint(Line l,Line m){
double A = cross(l.p2-l.p1,m.p2-m.p1);
double B = cross(l.p2-l.p1,l.p2-m.p1);
if(abs(A) < EPS && abs(B) < EPS){
vector<Point> vec;
vec.push_back(l.p1),vec.push_back(l.p2),vec.push_back(m.p1),vec.push_back(m.p2);
sort(vec.begin(),vec.end());
assert(vec[1] == vec[2]); //???????????°??????????????????
return vec[1];
//return m.p1;
}
if(abs(A) < EPS)assert(false);
return m.p1 + (m.p2-m.p1)*(B/A);
}
//cross product of pq and pr
double cross3p(Point p,Point q,Point r) { return (r.x-q.x) * (p.y -q.y) - (r.y - q.y) * (p.x - q.x); }
//returns true if point r is on the same line as the line pq
bool collinear(Point p,Point q,Point r) { return fabs(cross3p(p,q,r)) < EPS; }
//returns true if point t is on the left side of line pq
bool ccwtest(Point p,Point q,Point r){
return cross3p(p,q,r) > 0; //can be modified to accept collinear points
}
bool onSegment(Point p,Point q,Point r){
return collinear(p,q,r) && equals(sqrt(pow(p.x-r.x,2)+pow(p.y-r.y,2)) + sqrt(pow(r.x-q.x,2) + pow(r.y-q.y,2) ),sqrt(pow(p.x-q.x,2)+pow(p.y-q.y,2)) ) ;
}
double getArea(vector<Point>& vec) {
double sum = 0;
for(int i=0;i<vec.size();i++)
sum += cross(vec[i],vec[(i+1)%vec.size()]);
return fabs(sum)/2.0;
}
typedef pair<double,double> dd;
const double DINF = 1e20;
#define pow2(a) ((a)*(a))
dd calc(double x1,double y1,double vx1,double vy1,
double x2,double y2,double vx2,double vy2,double r){
double VX = (vx1-vx2), X = (x1-x2), VY = (vy1-vy2), Y = (y1-y2);
double a = pow2(VX) + pow2(VY), b = 2*(X*VX+Y*VY), c = pow2(X) + pow2(Y) - pow2(r);
dd ret = dd(DINF,DINF);
double D = b*b - 4 * a * c;
if( LT(D,0.0) ) return ret;
if( equals(a,0.0) ) {
if( equals(b,0.0) ) return ret;
if( LT(-c/b,0.0) ) return ret;
ret.first = - c / b;
return ret;
}
if( equals(D,0.0) ) D = 0;
ret.first = ( -b - sqrt( D ) ) / ( 2 * a );
ret.second = ( -b + sqrt( D ) ) / ( 2 * a );
if( !equals(ret.first,ret.second) && ret.first > ret.second ) swap(ret.first,ret.second);
return ret;
}
const Point ZERO = Point(0,0);
//??????AB??¨?????????cp,??????r????????¨?????±?????¨????????¢???????±???????
inline double calculator_TypeA(Point A,Point B,Point cp,double r){
A = A - cp, B = B - cp;
if( A == ZERO || B == ZERO ) return 0;
double cross_value = cross(A,B);
if( equals(cross_value,0.0) ) return 0;
double sig = LT(cross_value,0.0) ? -1 : 1;
Segment AB = Segment(A,B);
double nearest_distance = distanceLP(AB,ZERO);
double distance_OA = abs(A);
double distance_OB = abs(B);
if( LTE(0.0,r-distance_OA) && LTE(0.0,r-distance_OB) && LTE(0.0,r-nearest_distance) ) {
return sig * fabs( cross_value / 2.0 );
} else if( LTE(0.0,distance_OA-r) && LTE(0.0,distance_OB-r) && LTE(0.0,nearest_distance-r) ) {
return sig * ( r * r * (M_PI-getArg(A,ZERO,B)) ) / 2.0;
} else if( LTE(0.0,distance_OA-r) && LTE(0.0,distance_OB-r) && LT(0.0,r-nearest_distance) ) {
Point proj_p = projection(AB,ZERO);
if( onSegment(AB.p1,AB.p2,proj_p) ) {
Vector e = ( A - B ) / abs( A - B );
dd tmp = calc(A.x,A.y,e.x,e.y,0,0,0,0,r);
Point r_p1 = A + e * tmp.first;
Point r_p2 = A + e * tmp.second;
double ret = r * r * (M_PI-getArg(B,ZERO,A)) / 2.0;
double subtract = r * r * (M_PI-getArg(r_p1,ZERO,r_p2)) / 2.0 - fabs(cross(r_p1,r_p2))/2.0 ;
return sig * ( ret - subtract );
} else {
return sig * ( r * r * (M_PI-getArg(B,ZERO,A)) ) / 2.0;
}
} else {
if( LT(distance_OB-r,0.0) ) swap(A,B);
Vector e = ( A - B ) / abs( A - B );
dd tmp = calc(A.x,A.y,e.x,e.y,0,0,0,0,r);
Point r_p1 = A + e * tmp.first;
Point r_p2 = A + e * tmp.second;
if( onSegment(A,B,r_p2) ) r_p1 = r_p2;
double ret = fabs(cross(r_p1,A)) * 0.5;
ret += r * r * (M_PI-getArg(r_p1,ZERO,B)) * 0.5;
return sig * ret;
}
assert(false);
}
double getCommonAreaPolygonCircle(const Polygon &poly,Point cp,double r){
double sum = 0;
rep(i,(int)poly.size()){
sum += calculator_TypeA(poly[i],poly[(i+1)%(int)poly.size()],cp,r);
}
return fabs(sum);
}
Polygon andrewScan(Polygon s) {
Polygon u,l;
if(s.size() < 3)return s;
sort(s.begin(),s.end());
u.push_back(s[0]);
u.push_back(s[1]);
l.push_back(s[s.size()-1]);
l.push_back(s[s.size()-2]);
for(int i=2;i<(int)s.size();i++)
{
for(int n=u.size();n >= 2 && ccw(u[n-2],u[n-1],s[i]) != CLOCKWISE; n--)
u.pop_back();
u.push_back(s[i]);
}
for(int i=s.size()-3; i>=0 ; i--)
{
for(int n=l.size(); n >= 2 && ccw(l[n-2],l[n-1],s[i]) != CLOCKWISE; n--)
l.pop_back();
l.push_back(s[i]);
}
reverse(l.begin(),l.end());
for(int i = u.size()-2; i >= 1; i--) l.push_back(u[i]);
return l;
}
Point calc_ps(Polygon poly) {
poly = andrewScan(poly);
Point mp = poly[0];
double rate = 1; // 0.5???????????¨???
int max_pos;
double eps = 1e-10; // 1e-20???????????¨???
while( rate > eps ) {
rep(_,60){ // 70???????????¨???
max_pos = 0;
REP(j,1,(int)poly.size()) {
double dist1 = abs(mp-poly[max_pos]);
double dist2 = abs(mp-poly[j]);
if( LT(dist1,dist2) ) max_pos = j;
}
mp.x += ( poly[max_pos].x - mp.x ) * rate;
mp.y += ( poly[max_pos].y - mp.y ) * rate;
}
rate *= 0.5;
}
return mp;
}
Point getCentroidOfConvex(Polygon& poly){
double area = getArea(poly);
int V = poly.size();
assert( !equals(area,0.0) );
double x = 0, y = 0;
rep(i,(int)poly.size()) {
x += ( poly[i].x + poly[(i+1)%V].x ) * ( poly[i].x*poly[(i+1)%V].y - poly[(i+1)%V].x*poly[i].y );
y += ( poly[i].y + poly[(i+1)%V].y ) * ( poly[i].x*poly[(i+1)%V].y - poly[(i+1)%V].x*poly[i].y );
}
return Point(x/(6.0*area),y/(6.0*area));
}
// END - Library
int n,r;
Polygon poly;
void compute() {
double maxi;
Point mp = calc_ps(poly);
maxi = getCommonAreaPolygonCircle(poly,mp,r);
double rate = 1.0;
double eps = 1e-10;
while( LT(eps,rate) ) {
rep(_,70) {
double max_area = -1;
Point np;
rep(i,n) {
Point tp = mp;
tp.x += ( poly[i].x - mp.x ) * rate;
tp.y += ( poly[i].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,tp,r);
if( LT(max_area,area) ) {
max_area = area;
np = tp;
}
}
assert( !equals(max_area,-1) );
mp = np;
if( LT(maxi,max_area) ) maxi = max_area;
}
rate *= 0.5;
}
rep(__,n+1) {
Point mp = calc_ps(poly);
if( __ ) mp = poly[__-1];
double rate = 1.0;
double eps = 1e-10;
while( LT(eps,rate) ) {
rep(_,70) {
double max_area = -1;
Point np;
rep(i,n) {
Point tp = mp;
tp.x += ( poly[i].x - mp.x ) * rate;
tp.y += ( poly[i].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,tp,r);
if( LT(max_area,area) ) {
max_area = area;
np = tp;
}
}
if( rand() % 50 == 0 ) {
int v = rand() % n;
np.x = ( poly[v].x - mp.x ) * rate;
np.y = ( poly[v].y - mp.y ) * rate;
double area = getCommonAreaPolygonCircle(poly,np,r);
if( LT(max_area,area) ) {
max_area = area;
}
}
assert( !equals(max_area,-1) );
mp = np;
if( LT(maxi,max_area) ) maxi = max_area;
}
rate *= 0.5;
}
}
printf("%.10f\n",maxi);
}
int main() {
srand((unsigned int)time(NULL));
cin >> n >> r;
poly.resize(n);
rep(i,n) cin >> poly[i].x >> poly[i].y;
//cout << getArea(poly) << endl;
compute();
return 0;
} |
#include <bits/stdc++.h>
#define cout if (1) cout
// XXX without explanation marks untested functions
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> pii;
#define pb push_back
// NOT STANDART FROM HERE
// area de calota 2.pi.R.h (h altura)
// volume de calota pi.h/6 * (3r^2 + h^2)
typedef double cood;
cood eps = 1e-8;
// tests for double were made with eps = 1e-8
double eps_d = 1e-8; // necessary even in integer geometry, should be eps otherwise
const double pi = acos(-1.);
inline ll sq (ll x)
{ return x*x; }
inline double sq (double x)
{ return x*x; }
struct vec { // vector
// === BASIC ===
cood x, y;
vec () : x(0), y(0) {}
vec (cood a, cood b) : x(a), y(b) {}
friend ostream& operator<<(ostream& os, vec o);
vec operator - (vec o)
{ return vec(x - o.x, y - o.y); }
vec operator + (vec o)
{ return vec(x + o.x, y + o.y); }
vec operator * (cood o)
{ return vec(x * o, y * o); }
vec operator / (cood o)
{ return vec(x / o, y / o); }
cood operator ^ (vec o)
{ return x * o.y - y * o.x; }
cood operator * (vec o)
{ return x * o.x + y * o.y; }
// positive is (*this)b is clockwise from (*this)a
double angle (vec a, vec b)
{ return atan2((a-(*this))^(b-(*this)), (a-(*this))*(b-(*this))); }
cood sq (vec o = vec())
{ return ((*this)-o)*((*this)-o); }
double nr (vec o = vec())
{ return sqrt(sq(o)); }
cood cross (vec a, vec b) // ccw signed area (positive if this is to the left of ab)
{ return (b - a) ^ ((*this) - a); }
int ccw (vec a, vec b) // which side is this from ab? (1 left, 0 over, -1 right)
{ cood o = cross(a, b); return (eps < o) - (o < -eps); }
int dir (vec a, vec b) // direction of (this)a relative to (this)b (-1 opposite, 0 none, 1 same)
{ cood o = ((*this) - a)*((*this) - b); return (eps < o) - (o < -eps); }
cood inner (vec s, vec t) // (p-s)*(t-s) where p = this projected on st
{ return ((*this) - s) * (t - s); }
vec proj (vec s, vec t) // projection of this point over line st
{ return s + (t - s)*(inner(s,t) / t.sq(s)); }
vec rotate (double a) // rotate ccw by a (fails with ll)
{ return vec(cos(a) * x - sin(a) * y, sin(a) * x + cos(a) * y); }
vec rot90 () // rotate pi/2 ccw
{ return vec(-y, x); }
// === ADVANCED ===
// ordering that defines the compare method
// used only there, change it accordingly
// sorts increasing on y and, then increasing on x
bool operator < (const vec & o) const {
if (y != o.y)
return y < o.y;
return x < o.x;
}
// full ordering (ccw angle from this+(1,0), distance to this)
// is a < b?
// PRECISION : ok with double if norm in [-1e9,5e3]
bool compare (vec a, vec b) {
if (((*this) < a) != ((*this) < b))
return (*this) < a;
int o = ccw(a,b);
if (o) return o > 0;
return a.dir((*this),b) < 0;
}
// is this inside segment st? (tip of segment included, change for dr < 0 otherwise)
bool in_seg (vec s, vec t)
{ return (ccw(s,t) == 0) && (dir(s,t) <= 0); }
// squared distance from this to line defined by st
double dist2_lin (vec s, vec t)
{ return double(::sq(cross(s,t))) / t.sq(s); }
// squared distance from this to segment st
double dist2_seg (vec s, vec t)
{ return s.dir((*this),t) == t.dir((*this),s) ? dist2_lin(s,t) : min(sq(s),sq(t)); }
// is this inside (borders included) the convex polygon v of size n?
// if yes, prec is the vec that this on acw order from v[0] or 0 if there is no such
// if not, prec is the predecessor of this when added to poly and succ is the sucessor
// p should be a vector with [0..n-1]
// n should be >= 2
bool in_conv_poly (vec v[], int n, const vector<int> & p, int & prec, int & succ) {
if (nr(v[0]) <= eps) {
prec = 0;
return 1;
}
if (n == 2) {
if (in_seg(v[0],v[1]))
return (prec = 1);
if (ccw(v[0],v[1]) > 0) {
prec = 1;
succ = 0;
} else if (ccw(v[0],v[1]) < 0) {
prec = 0;
succ = 1;
} else {
prec = succ = (v[0].dir((*this),v[1]) < 0);
}
return 0;
}
if (ccw(v[0],v[1]) > 0 || ccw(v[0],v[n-1]) < 0) {
// case where v[0] is not removed
// last diagonal before or over this
int di = lower_bound(p.begin() + 1, p.end(), -1, [this,v] (int i, int j) {
assert(j == -1);
return ccw(v[0],v[i]) >= 0;
}) - p.begin() - 1;
// is this inside the polygon?
prec = di;
if (di == n-1) {
// last segment
if (ccw(v[0],v[n-1]) == 0 && ccw(v[n-2],v[n-1]) >= 0)
return 1;
} else {
// inside otherwise
if (ccw(v[di],v[di+1]) >= 0)
return 1;
}
// last that stays before (or eq to) di
prec = lower_bound(p.begin() + 1, p.begin() + di + 1, -1, [this,v] (int i, int j) {
assert(j == -1);
return ccw(v[i-1],v[i]) > 0;
}) - p.begin() - 1;
// first that stays after di
succ = lower_bound(p.begin() + di + 1, p.end(), -1, [this,v,n] (int i, int j) {
assert(j == -1);
return ccw(v[(i+1)%n],v[i]) >= 0;
}) - p.begin();
if (succ == n) succ = 0;
} else {
// case where v[0] is removed
// first diagonal before of over this
// di is certainly not removed
int di = lower_bound(p.begin() + 1, p.end() - 1, -1, [this,v] (int i, int j) {
assert(j == -1);
return ccw(v[0],v[i]) < 0;
}) - p.begin();
// first that stays (<= di)
succ = lower_bound(p.begin(), p.begin() + di, -1, [this,v] (int i, int j) {
assert(j == -1);
return ccw(v[i+1],v[i]) >= 0;
}) - p.begin();
// last that stays (>= di)
prec = lower_bound(p.begin() + di + 1, p.end(), -1, [this,v] (int i, int j) {
assert(j == -1);
return ccw(v[i-1],v[i]) > 0;
}) - p.begin() - 1;
}
return 0;
}
};
ostream& operator<<(ostream& os, vec o)
{ return os << '(' << o.x << ", " << o.y << ')'; }
struct lin { // line
cood a, b, c; // a*x + b*y = c
lin () {}
lin (cood x, cood y, cood z) : a(x), b(y), c(z) {}
lin (vec s, vec t) : a(t.y - s.y), b(s.x - t.x), c(a * s.x + b * s.y) {}
lin parll (vec p) // parallel to this through p
{ return lin(a, b, a * p.x + b * p.y); }
lin perp ()
{ return lin(-b, a, c); }
vec inter (lin o) {
cood d = a * o.b - o.a * b;
if (d < eps && -eps < d) throw 0; // parallel
return vec((o.b * c - b * o.c) / d, (a * o.c - o.a * c) / d);
}
};
struct cir { // circle
vec c; cood r;
// borders included
bool contains (vec w)
{ return c.sq(w) <= sq(r) + eps; }
bool has_inter (cir o)
{ return c.sq(o.c) <= sq(r + o.r) + eps; }
bool has_inter_lin (vec s, vec t)
{ return c.dist2_lin(s,t) <= sq(r) + eps_d; }
bool has_inter_seg (vec s, vec t)
{ return c.dist2_seg(s,t) <= sq(r) + eps_d; }
// borders not included
bool contains (cir o)
{ return (o.r < r - eps && c.sq(o.c) < sq(r - o.r) - eps); }
// ccw area of arc from ca to cb
double arc_area (vec a, vec b) {
double ang = c.angle(a,b);
return r*r*ang*.5;
}
// double only
pair<vec,vec> inter_pts (cir o) {
assert(has_inter(o) && !contains(o)); // fully contained case
double d = c.nr(o.c);
double a = (r*r + d*d - o.r*o.r) / (2.*d); // r*cos(ans,v,c.v)
double h = sqrt(r*r - a*a);
if (h != h) h = 0;
vec p = o.c - c;
return pair<vec,vec>(c + p*(a/d) + (p.rot90()*(h/d)), c + p*(a/d) - (p.rot90()*(h/d)));
}
// double only XXX careful precision
pair<vec,vec> inter_pts (vec s, vec t) {
assert(has_inter_lin(s,t));
double h2 = c.dist2_lin(s,t);
double d = sqrt(c.sq(t) - h2);
if (d != d) d = 0;
vec p = (s-t);
vec m = t + p*(d/p.nr());
vec m_b = t - p*(d/p.nr());
if (m_b.sq(c) < m.sq(c))
m = m_b;
d = sqrt(r*r - h2);
if (d != d) d = 0;
return pair<vec,vec>(m + p*(d/p.nr()), m - p*(d/p.nr()));
}
// double only XXX not tested
// signed area of intersection of this with triangle (this.c,a,b)
double inter (vec a, vec b) {
double res = 0.; bool inv = 0;
if (contains(b)) {
swap(a,b);
inv = 1;
}
if (contains(b)) {
res = c.cross(a,b)*.5;
} else if (contains(a)) {
pair<vec,vec> rt = inter_pts(a,b);
vec q = rt.first;
if (!q.in_seg(a,b) || (a.sq(q) <= eps && rt.second.in_seg(a,b)))
q = rt.second;
res += c.cross(a,q)*.5;
res += arc_area(q,b);
} else if (has_inter_seg(a,b)) {
pair<vec,vec> rt = inter_pts(a,b);
if (a.sq(rt.second) < a.sq(rt.first))
swap(rt.first,rt.second);
res += arc_area(a,rt.first);
res += c.cross(rt.first,rt.second)*.5;
res += arc_area(rt.second,b);
} else {
res += arc_area(a,b);
}
if (inv) return -res;
return res;
}
// double only XXX not tested
// signed area of intersection of this with polygon
double inter (vector<vec> & p) {
double res = 0;
for (int i = 0; i < p.size(); i++)
res += inter(p[i],p[(i+1)%p.size()]);
return res;
}
};
// do the segments ab and cd intersect? (borders included) XXX
bool inter_seg (vec a, vec b, vec c, vec d) {
if (a.in_seg(c, d) || b.in_seg(c, d) || c.in_seg(a, b) || d.in_seg(a, b))
return true;
return (c.ccw(a, b) * d.ccw(a, b) == -1 && a.ccw(c, d) * b.ccw(c, d) == -1);
}
// squared distance from segments ab and cd XXX
double dist2_seg (vec a, vec b, vec c, vec d)
{ return inter_seg(a,b,c,d) ? 0. : min({ a.dist2_seg(c,d), b.dist2_seg(c,d), c.dist2_seg(a,b), d.dist2_seg(a,b) }); }
// brd = do points on the border belong to convex?
// computes convex hull of given vector (inplace)
// returns size of convex hull
int graham (vec v[], int n, int brd) {
for (int i = 1; i < n; i++) {
if (v[i].x < v[0].x || (v[i].x == v[0].x && v[i].y < v[0].y))
swap(v[0], v[i]);
}
sort(v+1, v+n, [v] (vec a, vec b) {
int o = b.ccw(v[0], a);
if (o) return (o == 1);
return v[0].sq(a) < v[0].sq(b);
});
if (brd) {
int s = n-1;
while (s > 1 && v[s].ccw(v[s-1],v[0]) == 0)
s--;
for (int i = s; i < n - 1 - (i - s); i++)
swap(v[i], v[n-1-(i-s)]);
}
int s = 0;
for (int i = 0; i < n; i++) {
if (s && v[s-1].x == v[i].x && v[s-1].y == v[i].y) continue;
while (s >= 2 && v[s-1].ccw(v[s-2],v[i]) >= brd)
s--;
v[s++] = v[i];
}
return s;
}
const int N = 1e2+7;
int n;
double r;
vector<vec> v;
double x[2], y[2];
double solve (double x) {
double lo = 200, hi = -100.;
for (int i = 0; i < n; i++) {
int j = (i+1)%n;
lin ln(v[i],v[j]);
vec it(x, (ln.c - ln.a*x)/ln.b);
if (it.in_seg(v[i],v[j]) && it.y == it.y && abs(it.y) < 200) {
lo = min(lo, it.y);
hi = max(hi, it.y);
}
if (abs(v[i].x - x) <= eps_d) {
lo = min(lo, v[i].y);
hi = max(hi, v[i].y);
}
}
hi = min(hi, 200.); lo = max(lo, -100.);
int ts = 60;
while (ts--) {
double q1 = (lo+lo+hi)/3;
double q2 = (lo+hi+hi)/3;
double r1 = abs(cir({ vec(x,q1), r }).inter(v));
double r2 = abs(cir({ vec(x,q2), r }).inter(v));
if (r1 < r2)
lo = q1;
else
hi = q2;
}
return abs(cir({ vec(x,lo), r }).inter(v));
}
int main () {
while (scanf("%d %lf", &n, &r) != EOF) {
v = vector<vec>(n);
x[0] = 200;
x[1] = -100;
for (int i = 0; i < n; i++) {
scanf("%lf %lf", &v[i].x, &v[i].y);
x[0] = min(x[0],v[i].x);
x[1] = max(x[1],v[i].x);
}
double lo = x[0], hi = x[1];
//int ts = 60;
int ts = 50;
while (ts--) {
double q1 = (lo+lo+hi)/3;
double q2 = (lo+hi+hi)/3;
if (solve(q1) < solve(q2))
lo = q1;
else
hi = q2;
}
double res = solve(lo);
for (int i = 0; i < n; i++)
res = max(res, abs(cir({ v[i], r }).inter(v)));
printf("%.20f\n", res);
}
} |
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
template<class T> using V = vector<T>;
using D = double;
const D PI = acos(D(-1)), EPS = 1e-10;
int sgn(D a) { return (abs(a) <= EPS) ? 0 : (a < 0 ? -1 : 1); }
int sgn(D a, D b) { return sgn(a-b); }
//relative sign
// int rsgn(D a, D f) {
// if (abs(a) <= f*EPS) return 0;
// return (a < 0) ? -1 : 1;
// }
struct Pt2 {
D x, y;
Pt2(D _x = D(), D _y = D()) : x(_x), y(_y) {}
Pt2 operator+(const Pt2 &r) const { return Pt2(x+r.x, y+r.y); }
Pt2 operator-(const Pt2 &r) const { return Pt2(x-r.x, y-r.y); }
Pt2 operator*(const Pt2 &r) const { return Pt2(x*r.x-y*r.y, x*r.y+y*r.x); }
Pt2 operator*(const D &r) const { return Pt2(x*r, y*r); }
Pt2 operator/(const D &r) const { return Pt2(x/r, y/r); }
Pt2& operator+=(const Pt2 &r) { return *this=*this+r; }
Pt2& operator-=(const Pt2 &r) { return *this=*this-r; }
Pt2& operator*=(const Pt2 &r) { return *this=*this*r; }
Pt2& operator*=(const D &r) { return *this=*this*r; }
Pt2& operator/=(const D &r) { return *this=*this/r; }
Pt2 operator-() const { return Pt2(-x, -y); }
bool operator<(const Pt2 &r) const { return 2*sgn(x, r.x)+sgn(y, r.y)<0; }
bool operator==(const Pt2 &r) const { return sgn((*this-r).rabs()) == 0; }
D norm() const { return x*x + y*y; }
D abs() const { return sqrt(norm()); }
D rabs() const { return max(std::abs(x), std::abs(y)); } // robust abs
D arg() const { return atan2(y, x); }
pair<D, D> to_pair() const { return make_pair(x, y); }
static Pt2 polar(D le, D th) { return Pt2(le*cos(th), le*sin(th)); }
};
ostream& operator<<(ostream& os, const Pt2 &p) {
return os << "P(" << p.x << ", " << p.y << ")";
}
using P = Pt2;
struct L {
P s, t;
L(P _s = P(), P _t = P()) : s(_s), t(_t) {}
P vec() const { return t-s; }
D abs() const { return vec().abs(); }
D arg() const { return vec().arg(); }
};
ostream& operator<<(ostream& os, const L &l) {
return os << "L(" << l.s << ", " << l.t << ")";
}
D cross(P a, P b) { return a.x*b.y - a.y*b.x; }
D dot(P a, P b) { return a.x*b.x + a.y*b.y; }
// cross(a, b) is too small?
int sgncrs(P a, P b) {
D cr = cross(a, b);
if (abs(cr) <= (a.rabs() + b.rabs()) * EPS) return 0;
return (cr < 0) ? -1 : 1;
}
// -2, -1, 0, 1, 2 : front, clock, on, cclock, back
int ccw(P b, P c) {
int s = sgncrs(b, c);
if (s) return s;
if (!sgn(c.rabs()) || !sgn((c-b).rabs())) return 0;
if (dot(b, c) < 0) return 2;
if (dot(-b, c-b) < 0) return -2;
return 0;
}
int ccw(P a, P b, P c) { return ccw(b-a, c-a); }
int ccw(L l, P p) { return ccw(l.s, l.t, p); }
P project(const L &l, const P &p) {
P v = l.vec();
return l.s + v * (dot(v, p-l.s) / v.norm());
}
bool insSL(const L &s, const L &l) {
int a = ccw(l, s.s), b = ccw(l, s.t);
return (a%2 == 0 || b%2 == 0 || a != b);
}
bool insSS(const L &s, const L &t) {
int a = ccw(s, t.s), b = ccw(s, t.t);
int c = ccw(t, s.s), d = ccw(t, s.t);
if (a*b <= 0 && c*d <= 0) return true;
return false;
}
D distLP(const L &l, const P &p) {
return abs(cross(l.vec(), p-l.s)) / l.abs();
}
D distSP(const L &s, const P &p) {
P q = project(s, p);
if (ccw(s, q) == 0) return (p - q).abs();
else return min((s.s - p).abs(), (s.t - p).abs());
}
int crossLL(const L &l, const L &m, P &r) {
D cr1 = cross(l.vec(), m.vec()), cr2 = cross(l.vec(), l.t - m.s);
if (sgncrs(l.vec(), m.vec()) == 0) {
r = l.s;
if (sgncrs(l.vec(), l.t - m.s)) return 0;
return -1;
}
r = m.s + m.vec() * (cr2 / cr1);
return 1;
}
using Pol = V<P>;
struct C {
P p; D r;
C(P _p = P(), D _r = D()) : p(_p), r(_r) {}
};
//need Intersect/distLP, r.sはよりl.sに近い
int crossCL(const C &c, const L &l, L &r) {
D u = distLP(l, c.p);
int si = sgn(u, c.r);
if (si == 1) return 0;
P v = project(l, c.p);
P di = (si == 0) ? P(0, 0) : l.vec() * (sqrt(c.r*c.r - u*u) / l.abs());
r = L(v-di, v+di);
if (si == 0) return 1;
return 2;
}
// C(P(0, 0), r)とTri((0, 0), a, b)の共有面積
D area2CT(const C &c, const P &_a, const P &_b) {
P a = _a - c.p, b = _b - c.p; D r = c.r;
if (a == b) return 0;
auto single = [&](P x, P y, bool tri) {
if (tri) return cross(x, y);
else return r * r * ((y * P(x.x, -x.y)).arg());
};
bool ia = sgn(a.abs(), r) != 1, ib = sgn(b.abs(), r) != 1;
if (ia && ib) return single(a, b, true);
D r2 = distSP(L(a, b), P(0, 0));
if (sgn(r, r2) != 1) return single(a, b, false);
L l;
assert(crossCL(C(P(0, 0), r), L(a, b), l) == 2);
if (ia) l.s = l.t;
else if (ib) l.t = l.s;
assert(ccw(a, b, l.s) == 0); assert(ccw(a, b, l.t) == 0);
return single(a, l.s, ia) + single(l.s, l.t, true) + single(l.t, b, ib);
}
// p, cの共有面積
D area2CPol(const C &c, const Pol &po) {
D sm = 0;
P a, b = po.back();
for (auto p: po) {
a = b; b = p;
sm += area2CT(c, a, b);
}
return sm;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << setprecision(20);
int n; D r;
cin >> n >> r;
Pol pol;
D ymi = 1e100, yma = -1e100;
for (int i = 0; i < n; i++) {
D x, y;
cin >> x >> y;
pol.push_back(P(x, y));
ymi = min(ymi, y);
yma = max(yma, y);
}
auto calc = [&](D y) {
D xmi = 1e100, xma = -1e100;
P a, b = pol.back();
for (int i = 0; i < n; i++) {
a = b; b = pol[i];
P p;
if (crossLL(L(a, b), L(P(0, y), P(1, y)), p) == 0) continue;
if (ccw(a, b, p) != 0) continue;
xmi = min(xmi, p.x); xma = max(xma, p.x);
}
D lw = xmi, up = xma;
for (int ph = 0; ph < 50; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
D z1 = area2CPol(C(P(md1, y), r), pol) / 2;
D z2 = area2CPol(C(P(md2, y), r), pol) / 2;
if (z1 < z2) {
lw = md1;
} else {
up = md2;
}
}
return area2CPol(C(P(lw, y), r), pol) / 2;
};
D lw = ymi, up = yma;
for (int ph = 0; ph < 50; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
if (calc(md1) < calc(md2)) {
lw = md1;
} else {
up = md2;
}
}
cout << calc(lw) << endl;
return 0;
}
|
#include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;
struct Point{
Point(double arg_x,double arg_y){
x = arg_x;
y = arg_y;
}
Point(){
x = y = 0.0;
}
Point operator + (Point p){ return Point(x+p.x,y+p.y); }
Point operator - (Point p){ return Point(x-p.x,y-p.y);}
Point operator * (double a){ return Point(a*x,a*y); }
Point operator / (double a){ return Point(x/a,y/a); }
double abs(){ return sqrt(norm()); }
double norm(){ return x*x + y*y; }
bool operator<(const Point &p) const{
return x != p.x? x < p.x: y < p.y;
}
bool operator == (const Point &p) const{
return fabs(x-p.x) < EPS && fabs(y-p.y) < EPS;
}
double x,y;
};
typedef Point Vector;
typedef vector<Point> Polygon;
struct Circle{
Point center;
double r;
};
struct Line{
Point p[2];
Line(Point p1,Point p2){
p[0] = p1;
p[1] = p2;
}
Line(){
}
};
int N;
double r;
double min_x,max_x,min_y,max_y;
bool is_out[15];
Polygon POLYGON;
double norm(Vector a){
return a.x*a.x+a.y*a.y;
}
double abs(Vector a){
return sqrt(norm(a));
}
double cross(Vector a,Vector b){
return a.x*b.y-a.y*b.x;
}
double dot(Vector a,Vector b){
return a.x*b.x + a.y*b.y;
}
Point project(Line l,Point p){
Vector base = l.p[1]-l.p[0];
double r = dot(p-l.p[0],base)/norm(base);
return l.p[0]+base*r;
}
//円と直線の交点を求める関数
vector<Point> getCrossPoints(Circle c,Line l){
vector<Point> ret;
Vector pr = project(l,c.center);
Vector e = (l.p[1]-l.p[0])/abs(l.p[1]-l.p[0]);
double base;
if(fabs(c.r*c.r-norm(pr-c.center)) < EPS){
base = 0;
}else{
base = sqrt(c.r*c.r-norm(pr-c.center));
}
ret.push_back(Point(pr+e*base));
ret.push_back(Point(pr-e*base));
return ret;
}
Point calc_minus(Point a,Point b){
Point ret;
ret.x = a.x-b.x;
ret.y = a.y-b.y;
return ret;
}
double calc_len(Vector a){
return sqrt(a.x*a.x+a.y*a.y);
}
double calc_slope(Line A){
if(fabs(A.p[0].x-A.p[1].x) < EPS){
return DBL_MAX;
}else if(fabs(A.p[0].y-A.p[1].y) < EPS){
return 0;
}else{
return (A.p[0].y-A.p[1].y)/(A.p[0].x-A.p[1].x);
}
}
//★★線分ではなく直線と点の距離★★
double getDistanceLP(Line l,Point p){
return fabs(cross(calc_minus(l.p[1],l.p[0]),calc_minus(p,l.p[0]))/calc_len(calc_minus(l.p[1],l.p[0])));
}
//★★点と線分の距離★★
double getDistanceSP(Line l,Point p){
if(dot(calc_minus(l.p[1],l.p[0]),calc_minus(p,l.p[0])) < 0.0)return calc_len(calc_minus(p,l.p[0]));
if(dot(calc_minus(l.p[0],l.p[1]),calc_minus(p,l.p[1])) < 0.0)return calc_len(calc_minus(p,l.p[1]));
return getDistanceLP(l,p);
}
double calc_S(Polygon g){
int N = g.size();
double ret = 0;
for(int i = 0; i < g.size(); i++){
ret += cross(g[i],g[(i+1)%N]);
}
return ret/2.0;
}
double calc_dist(Point A,Point B){
return sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
}
//交点を求める関数
Point calc_Cross_Point(double x1,double x2,double x3,double x4,double y1,double y2,double y3,double y4){
Point ret;
ret.x = ((x2-x1)*(y3*(x4-x3)+x3*(y3-y4))-(x4-x3)*(y1*(x2-x1)+x1*(y1-y2)))/((y2-y1)*(x4-x3)-(y4-y3)*(x2-x1));
if(x1 != x2){
ret.y = ((y2-y1)*ret.x+y1*(x2-x1)+x1*(y1-y2))/(x2-x1);
}else{
ret.y = ((y4-y3)*ret.x+y3*(x4-x3)+x3*(y3-y4))/(x4-x3);
}
return ret;
}
//インタフェース関数
Point calc_Cross_Point(Point a,Point b,Point c,Point d){
return calc_Cross_Point(a.x,b.x,c.x,d.x,a.y,b.y,c.y,d.y);
}
Point calc_Cross_Point(Line A,Line B){
if(getDistanceSP(B,A.p[0]) < EPS){
return A.p[0];
}else if(getDistanceSP(B,A.p[1]) < EPS){
return A.p[1];
}else if(getDistanceSP(A,B.p[0]) < EPS){
return B.p[0];
}else if(getDistanceSP(A,B.p[1]) < EPS){
return B.p[1];
}
return calc_Cross_Point(A.p[0],A.p[1],B.p[0],B.p[1]);
}
//円とポリゴンの共通面積を求める
double calc_common_S(Circle circle,Polygon polygon){
//それぞれの頂点が、円の内部にあるか否かを調べる
for(int i = 0; i < N; i++){
double tmp_dist = calc_dist(polygon[i],circle.center);
if(tmp_dist <= circle.r){
is_out[i] = false; //中
}else{
is_out[i] = true; //外
}
}
double ret = 0;
for(int i = 0; i < N; i++){
Point left = polygon[i];
Point right = polygon[(i+1)%N];
Line tmp_line = Line(left,right);
double tmp_dist = getDistanceSP(tmp_line,circle.center);
if(is_out[i] == false && is_out[(i+1)%N] == false){ //両方中
Polygon tmp;
tmp.push_back(circle.center);
tmp.push_back(right);
tmp.push_back(left);
ret += calc_S(tmp);
}else if(is_out[i] == true && is_out[(i+1)%N] == true){ //両方外
//printf("点%dと点%dは両方外\n",i,(i+1)%N);
if(tmp_dist > circle.r){ //両方外かつ交点なし:扇形
Vector vec1 = left-circle.center;
Vector vec2 = right-circle.center;
double theta = acos(dot(vec1,vec2)/(abs(vec1)*abs(vec2)));
ret += (r*r*theta)/2;
}else{ //交点あり
vector<Point> cross_points = getCrossPoints(circle,Line(left,right));
if(calc_dist(left,cross_points[1]) < calc_dist(left,cross_points[0])){
swap(cross_points[0],cross_points[1]);
}
//左側扇形
Vector vec1 = left-circle.center;
Vector vec2 = cross_points[0]-circle.center;
double theta = acos(dot(vec1,vec2)/(abs(vec1)*abs(vec2)));
ret += (r*r*theta)/2;
//三角形
Polygon tmp;
tmp.push_back(circle.center);
tmp.push_back(cross_points[1]);
tmp.push_back(cross_points[0]);
ret += calc_S(tmp);
//右側扇形
Vector vec3 = cross_points[1]-circle.center;
Vector vec4 = right-circle.center;
double theta2 = acos(dot(vec3,vec4)/(abs(vec3)*abs(vec4)));
ret += (r*r*theta2)/2;
}
}else{
if(is_out[i] == true){ //leftが外
vector<Point> cross_points = getCrossPoints(circle,Line(left,right));
//leftに近い方が交点
Point cross_point;
if(calc_dist(left,cross_points[0]) < calc_dist(left,cross_points[1])){
cross_point = cross_points[0];
}else{
cross_point = cross_points[1];
}
//左扇
Vector vec1 = left-circle.center;
Vector vec2 = cross_point-circle.center;
double theta = acos(dot(vec1,vec2)/(abs(vec1)*abs(vec2)));
ret += (r*r*theta)/2;
//三角形
Polygon tmp;
tmp.push_back(circle.center);
tmp.push_back(right);
tmp.push_back(cross_point);
ret += calc_S(tmp);
}else{ //rightが外
vector<Point> cross_points = getCrossPoints(circle,Line(left,right));
//rightに近い方が交点
Point cross_point;
if(calc_dist(right,cross_points[0]) < calc_dist(right,cross_points[1])){
cross_point = cross_points[0];
}else{
cross_point = cross_points[1];
}
//三角形
Polygon tmp;
tmp.push_back(circle.center);
tmp.push_back(cross_point);
tmp.push_back(left);
ret += calc_S(tmp);
//右扇
Vector vec1 = cross_point-circle.center;
Vector vec2 = right-circle.center;
double theta = acos(dot(vec1,vec2)/(abs(vec1)*abs(vec2)));
ret += (r*r*theta)/2;
}
}
}
return ret;
}
int func(double x1,double y1,double x2, double y2, double xp, double yp){
double naiseki,norm1,norm2,gaiseki;
norm1 = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
norm2 = sqrt((xp-x1)*(xp-x1)+(yp-y1)*(yp-y1));
naiseki = (xp-x1)*(x2-x1)+(yp-y1)*(y2-y1);
gaiseki = (x2-x1)*(yp-y1)-(xp-x1)*(y2-y1);
if(gaiseki > EPS){
return 1;
}else if(gaiseki < -EPS){
return -1;
}
if(naiseki < -EPS){
return 2;
}
if(norm1 < norm2){
return -2;
}
return 0;
}
bool is_Cross(Line a,Line b){
if(func(a.p[0].x,a.p[0].y,a.p[1].x,a.p[1].y,b.p[0].x,b.p[0].y)*
func(a.p[0].x,a.p[0].y,a.p[1].x,a.p[1].y,b.p[1].x,b.p[1].y) <= 0 &&
func(b.p[0].x,b.p[0].y,b.p[1].x,b.p[1].y,a.p[0].x,a.p[0].y)*
func(b.p[0].x,b.p[0].y,b.p[1].x,b.p[1].y,a.p[1].x,a.p[1].y) <= 0){
return true;
}
return false;
}
double thirds_searchY(double X){
double L = max_y,R = min_y;
//交点を持つy座標の範囲を求める
Line line = Line(Point(X,-1000),Point(X,1000));
bool FLG = false;
for(int i = 0; i < N; i++){
Line tmp = Line(POLYGON[i],POLYGON[(i+1)%N]);
if(is_Cross(line,tmp)){
Point p = calc_Cross_Point(tmp,line);
L = min(L,p.y);
R = max(R,p.y);
FLG = true;
}
}
if(!FLG)return 0;
for(int loop = 0; loop < 100; loop++){
double mid1 = (2.0*L+R)/3.0;
double mid2 = (1.0*L+2.0*R)/3.0;
Circle circle1,circle2;
circle1.center.x = X;
circle1.center.y = mid1;
circle1.r = r;
circle2.center.x = X;
circle2.center.y = mid2;
circle2.r = r;
if(calc_common_S(circle1,POLYGON) > calc_common_S(circle2,POLYGON)){
R = mid2;
}else{
L = mid1;
}
}
Circle circle;
circle.center.x = X;
circle.center.y = (L+R)/2;
circle.r = r;
return calc_common_S(circle,POLYGON);
}
double thirds_searchX(){
double L = min_x,R = max_x;
for(int loop = 0; loop < 100; loop++){
double mid1 = (2.0*L+R)/3.0;
double mid2 = (1.0*L+2.0*R)/3.0;
if(thirds_searchY(mid1) > thirds_searchY(mid2)){
R = mid2;
}else{
L = mid1;
}
}
return thirds_searchY((L+R)/2);
}
int main(){
scanf("%d %lf",&N,&r);
min_x = BIG_NUM;
min_y = BIG_NUM;
max_x = -BIG_NUM;
max_y = -BIG_NUM;
for(int i = 0; i < N; i++){
double x,y;
scanf("%lf %lf",&x,&y);
min_x = min(min_x,x);
min_y = min(min_y,y);
max_x = max(max_x,x);
max_y = max(max_y,y);
POLYGON.push_back(Point(x,y));
}
reverse(POLYGON.begin(),POLYGON.end());
printf("%.10lf\n",thirds_searchX());
return 0;
}
|
#include <iostream>
#include <complex>
#include <vector>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <map>
using namespace std;
#define x1 jkflwjjkfjekjfe
#define x2 fwekwfefekfje
int iter = log(100 * 100 * 10000) / log(3) + 20;
typedef complex<double> P;
struct L{
P a,b;
};
vector<double> ax,ay;
vector<L> ls;
double R,cx,cy;
bool eq(double a,double b){
return fabs(a-b) < 1e-7;
}
bool eq2(double a,double b){
return fabs(a-b) < 1e-8;
}
pair<double,double> seg(double y){
double x1 = +1e5;
double x2 = -1e5;
for( auto &&l : ls){
if( eq(l.a.imag(),y) ){
x1 = min(x1,l.a.real());
x2 = max(x2,l.a.real());
}
if( eq(l.b.imag(),y) ){
x1 = min(x1,l.b.real());
x2 = max(x2,l.b.real());
}
if( l.a.imag() + 1e-7 < y and y < l.b.imag() - 1e-7 ){
P v = (l.b - l.a);
P p = l.a + v * (y-l.a.imag()) / v.imag();
x1 = min(x1,p.real());
x2 = max(x2,p.real());
}
}
return {x1,x2};
}
double len(pair<double,double> p){
if( p.first < p.second ) return p.second - p.first;
return 0;
}
pair<double,double> merge(const pair<double,double> &a,const pair<double,double> &b){
return {max(a.first,b.first),min(a.second,b.second)};
}
double g(double y){
if( R - abs(y-cy) < 1e-7 ) return 0;
// for given y, compute the overlapped length of the circle and the polygon.
double t = sqrt(R*R-(cy-y)*(cy-y));
pair<double,double> circle_seg = {cx-t,cx+t};
return len(merge(circle_seg,seg(y)));
}
double simpson(double l,double r){
return (r-l)/6*(g(l)+4*g((l+r)/2)+g(r));
}
double integral(double l,double r,int k=5){
if( l >= r ) return 0;
double m = (l+r) / 2;
double A = simpson(l,m) + simpson(m,r);
double B = simpson(l,r);
if( k<=0 and eq2(A,B) ) return A;
else return integral(l,m,k-1) + integral(m,r,k-1);
}
double f(double x,double y){
cx = x;
cy = y;
double ans = 0;
for(int i = 0 ; i+1 < ay.size() ; i++){
ans += integral(max(cy-R,ay[i]),min(cy+R,ay[i+1]));
}
return ans;
}
double search2(double y){
double ans = 0;
double l,r;
tie(l,r) = seg(y);
for(int i = 0 ; i < iter ; i++){
double a = (2*l+r) / 3;
double b = (l+2*r) / 3;
if( f(a,y) < f(b,y) ){
l = a;
}else{
r = b;
}
}
return f(l,y);
}
double search1(){
double ans = 0;
double l = ay.front(), r = ay.back();
for(int i = 0 ; i < iter ; i++){
double a = (2*l+r) / 3;
double b = (l+2*r) / 3;
if( search2(a) < search2(b) ){
l = a;
}else{
r = b;
}
}
return search2(l);
}
int main(){
int n;
cin >> n >> R;
vector<P> g(n+1);
for(int i = 0 ; i < n ; i++){
double x,y;
cin >> x >> y;
g[i] = P(x,y);
ax.push_back(x);
ay.push_back(y);
}
g[n] = g[0];
for(int i = 0 ; i < n ; i++){
ls.push_back({g[i],g[i+1]});
if( ls.back().a.imag() > ls.back().b.imag() ) swap(ls.back().a,ls.back().b);
}
sort(ax.begin(),ax.end());
sort(ay.begin(),ay.end());
ax.erase(unique(ax.begin(),ax.end()),ax.end());
ay.erase(unique(ay.begin(),ay.end()),ay.end());
//printf("%.10lf\n",f(0,0));
//return 0;
printf("%.10lf\n",search1());
} |
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
template<class T> using V = vector<T>;
using D = double;
const D PI = acos(D(-1)), EPS = 1e-10;
int sgn(D a) { return (abs(a) <= EPS) ? 0 : (a < 0 ? -1 : 1); }
int sgn(D a, D b) { return sgn(a-b); }
//relative sign
// int rsgn(D a, D f) {
// if (abs(a) <= f*EPS) return 0;
// return (a < 0) ? -1 : 1;
// }
struct Pt2 {
D x, y;
Pt2(D _x = D(), D _y = D()) : x(_x), y(_y) {}
Pt2 operator+(const Pt2 &r) const { return Pt2(x+r.x, y+r.y); }
Pt2 operator-(const Pt2 &r) const { return Pt2(x-r.x, y-r.y); }
Pt2 operator*(const Pt2 &r) const { return Pt2(x*r.x-y*r.y, x*r.y+y*r.x); }
Pt2 operator*(const D &r) const { return Pt2(x*r, y*r); }
Pt2 operator/(const D &r) const { return Pt2(x/r, y/r); }
Pt2& operator+=(const Pt2 &r) { return *this=*this+r; }
Pt2& operator-=(const Pt2 &r) { return *this=*this-r; }
Pt2& operator*=(const Pt2 &r) { return *this=*this*r; }
Pt2& operator*=(const D &r) { return *this=*this*r; }
Pt2& operator/=(const D &r) { return *this=*this/r; }
Pt2 operator-() const { return Pt2(-x, -y); }
bool operator<(const Pt2 &r) const { return 2*sgn(x, r.x)+sgn(y, r.y)<0; }
bool operator==(const Pt2 &r) const { return sgn((*this-r).rabs()) == 0; }
D norm() const { return x*x + y*y; }
D abs() const { return sqrt(norm()); }
D rabs() const { return max(std::abs(x), std::abs(y)); } // robust abs
D arg() const { return atan2(y, x); }
pair<D, D> to_pair() const { return make_pair(x, y); }
static Pt2 polar(D le, D th) { return Pt2(le*cos(th), le*sin(th)); }
};
ostream& operator<<(ostream& os, const Pt2 &p) {
return os << "P(" << p.x << ", " << p.y << ")";
}
using P = Pt2;
struct L {
P s, t;
L(P _s = P(), P _t = P()) : s(_s), t(_t) {}
P vec() const { return t-s; }
D abs() const { return vec().abs(); }
D arg() const { return vec().arg(); }
};
ostream& operator<<(ostream& os, const L &l) {
return os << "L(" << l.s << ", " << l.t << ")";
}
D cross(P a, P b) { return a.x*b.y - a.y*b.x; }
D dot(P a, P b) { return a.x*b.x + a.y*b.y; }
// cross(a, b) is too small?
int sgncrs(P a, P b) {
D cr = cross(a, b);
if (abs(cr) <= (a.rabs() + b.rabs()) * EPS) return 0;
return (cr < 0) ? -1 : 1;
}
// -2, -1, 0, 1, 2 : front, clock, on, cclock, back
int ccw(P b, P c) {
int s = sgncrs(b, c);
if (s) return s;
if (!sgn(c.rabs()) || !sgn((c-b).rabs())) return 0;
if (dot(b, c) < 0) return 2;
if (dot(-b, c-b) < 0) return -2;
return 0;
}
int ccw(P a, P b, P c) { return ccw(b-a, c-a); }
int ccw(L l, P p) { return ccw(l.s, l.t, p); }
P project(const L &l, const P &p) {
P v = l.vec();
return l.s + v * (dot(v, p-l.s) / v.norm());
}
bool insSL(const L &s, const L &l) {
int a = ccw(l, s.s), b = ccw(l, s.t);
return (a%2 == 0 || b%2 == 0 || a != b);
}
bool insSS(const L &s, const L &t) {
int a = ccw(s, t.s), b = ccw(s, t.t);
int c = ccw(t, s.s), d = ccw(t, s.t);
if (a*b <= 0 && c*d <= 0) return true;
return false;
}
D distLP(const L &l, const P &p) {
return abs(cross(l.vec(), p-l.s)) / l.abs();
}
D distSP(const L &s, const P &p) {
P q = project(s, p);
if (ccw(s, q) == 0) return (p - q).abs();
else return min((s.s - p).abs(), (s.t - p).abs());
}
int crossLL(const L &l, const L &m, P &r) {
D cr1 = cross(l.vec(), m.vec()), cr2 = cross(l.vec(), l.t - m.s);
if (sgncrs(l.vec(), m.vec()) == 0) {
r = l.s;
if (sgncrs(l.vec(), l.t - m.s)) return 0;
return -1;
}
r = m.s + m.vec() * (cr2 / cr1);
return 1;
}
using Pol = V<P>;
struct C {
P p; D r;
C(P _p = P(), D _r = D()) : p(_p), r(_r) {}
};
//need Intersect/distLP, r.sはよりl.sに近い
int crossCL(const C &c, const L &l, L &r) {
D u = distLP(l, c.p);
int si = sgn(u, c.r);
if (si == 1) return 0;
P v = project(l, c.p);
P di = (si == 0) ? P(0, 0) : l.vec() * (sqrt(c.r*c.r - u*u) / l.abs());
r = L(v-di, v+di);
if (si == 0) return 1;
return 2;
}
//need Intersect/distLP, r.sはよりl.sに近い
int crossCS(const C &c, const L &s, L &l) {
if (!crossCL(c, s, l)) return 0;
bool f1 = ccw(s, l.s) == 0, f2 = ccw(s, l.t) == 0;
if (f1 && f2) return 2;
if (!f1 && !f2) return 0;
if (f1) l.t = l.s;
else l.s = l.t;
return 1;
}
// C(P(0, 0), r)とTri((0, 0), a, b)の共有面積
D area2CT(const C &c, const P &_a, const P &_b) {
P a = _a - c.p, b = _b - c.p; D r = c.r;
if (a == b) return 0;
auto single = [&](P x, P y, bool tri) {
if (tri) return cross(x, y);
else return r * r * ((y * P(x.x, -x.y)).arg());
};
bool ia = sgn(a.abs(), r) != 1, ib = sgn(b.abs(), r) != 1;
if (ia && ib) return single(a, b, true);
L l;
if (!crossCS(C(P(0, 0), r), L(a, b), l)) return single(a, b, false);
return single(a, l.s, ia) + single(l.s, l.t, true) + single(l.t, b, ib);
}
// p, cの共有面積
D area2CPol(const C &c, const Pol &po) {
D sm = 0;
P a, b = po.back();
for (auto p: po) {
a = b; b = p;
sm += area2CT(c, a, b);
}
return sm;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << setprecision(20);
int n; D r;
cin >> n >> r;
Pol pol;
D ymi = 1e100, yma = -1e100;
for (int i = 0; i < n; i++) {
D x, y;
cin >> x >> y;
pol.push_back(P(x, y));
ymi = min(ymi, y);
yma = max(yma, y);
}
auto calc = [&](D y) {
D xmi = 1e100, xma = -1e100;
P a, b = pol.back();
for (int i = 0; i < n; i++) {
a = b; b = pol[i];
P p;
if (crossLL(L(a, b), L(P(0, y), P(1, y)), p) == 0) continue;
if (ccw(a, b, p) != 0) continue;
xmi = min(xmi, p.x); xma = max(xma, p.x);
}
D lw = xmi, up = xma;
for (int ph = 0; ph < 30; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
D z1 = area2CPol(C(P(md1, y), r), pol) / 2;
D z2 = area2CPol(C(P(md2, y), r), pol) / 2;
if (z1 < z2) {
lw = md1;
} else {
up = md2;
}
}
return area2CPol(C(P(lw, y), r), pol) / 2;
};
D lw = ymi, up = yma;
for (int ph = 0; ph < 30; ph++) {
D md1 = (lw+lw+up) / 3;
D md2 = (lw+up+up) / 3;
if (calc(md1) < calc(md2)) {
lw = md1;
} else {
up = md2;
}
}
cout << calc(lw) << endl;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
using Real = double;
using Point = complex< Real >;
const Real EPS = 1e-8, PI = acos(-1);
inline bool eq(Real a, Real b) { return fabs(b - a) < EPS; }
Point operator*(const Point &p, const Real &d) {
return Point(real(p) * d, imag(p) * d);
}
istream &operator>>(istream &is, Point &p) {
Real a, b;
is >> a >> b;
p = Point(a, b);
return is;
}
ostream &operator<<(ostream &os, Point &p) {
os << fixed << setprecision(10) << p.real() << " " << p.imag();
}
Point rotate(Real theta, const Point &p) {
return Point(cos(theta) * p.real() - sin(theta) * p.imag(), sin(theta) * p.real() + cos(theta) * p.imag());
}
Real radian_to_degree(Real r) {
return (r * 180.0 / PI);
}
Real degree_to_radian(Real d) {
return (d * PI / 180.0);
}
Real get_angle(const Point &a, const Point &b, const Point &c) {
const Point v(b - a), w(c - b);
Real alpha = atan2(v.imag(), v.real()), beta = atan2(w.imag(), w.real());
if(alpha > beta) swap(alpha, beta);
Real theta = (beta - alpha);
return min(theta, 2 * acos(-1) - theta);
}
namespace std {
bool operator<(const Point &a, const Point &b) {
return a.real() != b.real() ? a.real() < b.real() : a.imag() < b.imag();
}
}
struct Line {
Point a, b;
Line() = default;
Line(Point a, Point b) : a(a), b(b) {}
Line(Real A, Real B, Real C) // Ax + By = C
{
if(eq(A, 0)) a = Point(0, C / B), b = Point(1, C / B);
else if(eq(B, 0)) b = Point(C / A, 0), b = Point(C / A, 1);
else a = Point(0, C / B), b = Point(C / A, 0);
}
friend ostream &operator<<(ostream &os, Line &p) {
return os << p.a << " to " << p.b;
}
friend istream &operator>>(istream &is, Line &a) {
return is >> a.a >> a.b;
}
};
struct Segment : Line {
Segment() = default;
Segment(Point a, Point b) : Line(a, b) {}
};
struct Circle {
Point p;
Real r;
Circle() = default;
Circle(Point p, Real r) : p(p), r(r) {}
};
using Points = vector< Point >;
using Polygon = vector< Point >;
using Segments = vector< Segment >;
using Lines = vector< Line >;
using Circles = vector< Circle >;
Real cross(const Point &a, const Point &b) {
return real(a) * imag(b) - imag(a) * real(b);
}
Real dot(const Point &a, const Point &b) {
return real(a) * real(b) + imag(a) * imag(b);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C
int ccw(const Point &a, Point b, Point c) {
b = b - a, c = c - a;
if(cross(b, c) > EPS) return +1; // "COUNTER_CLOCKWISE"
if(cross(b, c) < -EPS) return -1; // "CLOCKWISE"
if(dot(b, c) < 0) return +2; // "ONLINE_BACK"
if(norm(b) < norm(c)) return -2; // "ONLINE_FRONT"
return 0; // "ON_SEGMENT"
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A
bool parallel(const Line &a, const Line &b) {
return eq(cross(a.b - a.a, b.b - b.a), 0.0);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A
bool orthogonal(const Line &a, const Line &b) {
return eq(dot(a.a - a.b, b.a - b.b), 0.0);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A
Point projection(const Line &l, const Point &p) {
double t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);
return l.a + (l.a - l.b) * t;
}
Point projection(const Segment &l, const Point &p) {
double t = dot(p - l.a, l.a - l.b) / norm(l.a - l.b);
return l.a + (l.a - l.b) * t;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B
Point reflection(const Line &l, const Point &p) {
return p + (projection(l, p) - p) * 2.0;
}
bool intersect(const Line &l, const Point &p) {
return abs(ccw(l.a, l.b, p)) != 1;
}
bool intersect(const Line &l, const Line &m) {
return abs(cross(l.b - l.a, m.b - m.a)) > EPS || abs(cross(l.b - l.a, m.b - l.a)) < EPS;
}
bool intersect(const Segment &s, const Point &p) {
return ccw(s.a, s.b, p) == 0;
}
bool intersect(const Line &l, const Segment &s) {
return cross(l.b - l.a, s.a - l.a) * cross(l.b - l.a, s.b - l.a) < EPS;
}
Real distance(const Line &l, const Point &p);
bool intersect(const Circle &c, const Line &l) {
return distance(l, c.p) <= c.r + EPS;
}
bool intersect(const Circle &c, const Point &p) {
return abs(abs(p - c.p) - c.r) < EPS;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B
bool intersect(const Segment &s, const Segment &t) {
return ccw(s.a, s.b, t.a) * ccw(s.a, s.b, t.b) <= 0 && ccw(t.a, t.b, s.a) * ccw(t.a, t.b, s.b) <= 0;
}
int intersect(const Circle &c, const Segment &l) {
if(norm(projection(l, c.p) - c.p) - c.r * c.r > EPS) return 0;
auto d1 = abs(c.p - l.a), d2 = abs(c.p - l.b);
if(d1 < c.r + EPS && d2 < c.r + EPS) return 0;
if(d1 < c.r - EPS && d2 > c.r + EPS || d1 > c.r + EPS && d2 < c.r - EPS) return 1;
const Point h = projection(l, c.p);
if(dot(l.a - h, l.b - h) < 0) return 2;
return 0;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_A&lang=jp
int intersect(Circle c1, Circle c2) {
if(c1.r < c2.r) swap(c1, c2);
Real d = abs(c1.p - c2.p);
if(c1.r + c2.r < d) return 4;
if(eq(c1.r + c2.r, d)) return 3;
if(c1.r - c2.r < d) return 2;
if(eq(c1.r - c2.r, d)) return 1;
return 0;
}
Real distance(const Point &a, const Point &b) {
return abs(a - b);
}
Real distance(const Line &l, const Point &p) {
return abs(p - projection(l, p));
}
Real distance(const Line &l, const Line &m) {
return intersect(l, m) ? 0 : distance(l, m.a);
}
Real distance(const Segment &s, const Point &p) {
Point r = projection(s, p);
if(intersect(s, r)) return abs(r - p);
return min(abs(s.a - p), abs(s.b - p));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D
Real distance(const Segment &a, const Segment &b) {
if(intersect(a, b)) return 0;
return min({distance(a, b.a), distance(a, b.b), distance(b, a.a), distance(b, a.b)});
}
Real distance(const Line &l, const Segment &s) {
if(intersect(l, s)) return 0;
return min(distance(l, s.a), distance(l, s.b));
}
Point crosspoint(const Line &l, const Line &m) {
Real A = cross(l.b - l.a, m.b - m.a);
Real B = cross(l.b - l.a, l.b - m.a);
if(eq(abs(A), 0.0) && eq(abs(B), 0.0)) return m.a;
return m.a + (m.b - m.a) * B / A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C
Point crosspoint(const Segment &l, const Segment &m) {
return crosspoint(Line(l), Line(m));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_D
pair< Point, Point > crosspoint(const Circle &c, const Line l) {
Point pr = projection(l, c.p);
Point e = (l.b - l.a) / abs(l.b - l.a);
if(eq(distance(l, c.p), c.r)) return {pr, pr};
double base = sqrt(c.r * c.r - norm(pr - c.p));
return {pr - e * base, pr + e * base};
}
pair< Point, Point > crosspoint(const Circle &c, const Segment &l) {
Line aa = Line(l.a, l.b);
if(intersect(c, l) == 2) return crosspoint(c, aa);
auto ret = crosspoint(c, aa);
if(dot(l.a - ret.first, l.b - ret.first) < 0) ret.second = ret.first;
else ret.first = ret.second;
return ret;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_E
pair< Point, Point > crosspoint(const Circle &c1, const Circle &c2) {
Real d = abs(c1.p - c2.p);
Real a = acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d));
Real t = atan2(c2.p.imag() - c1.p.imag(), c2.p.real() - c1.p.real());
Point p1 = c1.p + Point(cos(t + a) * c1.r, sin(t + a) * c1.r);
Point p2 = c1.p + Point(cos(t - a) * c1.r, sin(t - a) * c1.r);
return {p1, p2};
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_F
pair< Point, Point > tangent(const Circle &c1, const Point &p2) {
return crosspoint(c1, Circle(p2, sqrt(norm(c1.p - p2) - c1.r * c1.r)));
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_G
Lines tangent(Circle c1, Circle c2) {
Lines ret;
if(c1.r < c2.r) swap(c1, c2);
Real g = norm(c1.p - c2.p);
if(eq(g, 0)) return ret;
Point u = (c2.p - c1.p) / sqrt(g);
Point v = rotate(PI * 0.5, u);
for(int s : {-1, 1}) {
Real h = (c1.r + s * c2.r) / sqrt(g);
if(eq(1 - h * h, 0)) {
ret.emplace_back(c1.p + u * c1.r, c1.p + (u + v) * c1.r);
} else if(1 - h * h > 0) {
Point uu = u * h, vv = v * sqrt(1 - h * h);
ret.emplace_back(c1.p + (uu + vv) * c1.r, c2.p - (uu + vv) * c2.r * s);
ret.emplace_back(c1.p + (uu - vv) * c1.r, c2.p - (uu - vv) * c2.r * s);
}
}
return ret;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B
bool is_convex(const Polygon &p) {
int n = (int) p.size();
for(int i = 0; i < n; i++) {
if(ccw(p[(i + n - 1) % n], p[i], p[(i + 1) % n]) == -1) return false;
}
return true;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A
Polygon convex_hull(Polygon &p) {
int n = (int) p.size(), k = 0;
if(n <= 2) return p;
sort(p.begin(), p.end());
vector< Point > ch(2 * n);
for(int i = 0; i < n; ch[k++] = p[i++]) {
while(k >= 2 && cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1]) < 0) --k;
}
for(int i = n - 2, t = k + 1; i >= 0; ch[k++] = p[i--]) {
while(k >= t && cross(ch[k - 1] - ch[k - 2], p[i] - ch[k - 1]) < 0) --k;
}
ch.resize(k - 1);
return ch;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C
enum {
OUT, ON, IN
};
int contains(const Polygon &Q, const Point &p) {
bool in = false;
for(int i = 0; i < Q.size(); i++) {
Point a = Q[i] - p, b = Q[(i + 1) % Q.size()] - p;
if(a.imag() > b.imag()) swap(a, b);
if(a.imag() <= 0 && 0 < b.imag() && cross(a, b) < 0) in = !in;
if(cross(a, b) == 0 && dot(a, b) <= 0) return ON;
}
return in ? IN : OUT;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1033
void merge_segments(vector< Segment > &segs) {
auto merge_if_able = [](Segment &s1, const Segment &s2) {
if(abs(cross(s1.b - s1.a, s2.b - s2.a)) > EPS) return false;
if(ccw(s1.a, s2.a, s1.b) == 1 || ccw(s1.a, s2.a, s1.b) == -1) return false;
if(ccw(s1.a, s1.b, s2.a) == -2 || ccw(s2.a, s2.b, s1.a) == -2) return false;
s1 = Segment(min(s1.a, s2.a), max(s1.b, s2.b));
return true;
};
for(int i = 0; i < segs.size(); i++) {
if(segs[i].b < segs[i].a) swap(segs[i].a, segs[i].b);
}
for(int i = 0; i < segs.size(); i++) {
for(int j = i + 1; j < segs.size(); j++) {
if(merge_if_able(segs[i], segs[j])) {
segs[j--] = segs.back(), segs.pop_back();
}
}
}
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1033
vector< vector< int > > segment_arrangement(vector< Segment > &segs, vector< Point > &ps) {
vector< vector< int > > g;
int N = (int) segs.size();
for(int i = 0; i < N; i++) {
ps.emplace_back(segs[i].a);
ps.emplace_back(segs[i].b);
for(int j = i + 1; j < N; j++) {
const Point p1 = segs[i].b - segs[i].a;
const Point p2 = segs[j].b - segs[j].a;
if(cross(p1, p2) == 0) continue;
if(intersect(segs[i], segs[j])) {
ps.emplace_back(crosspoint(segs[i], segs[j]));
}
}
}
sort(begin(ps), end(ps));
ps.erase(unique(begin(ps), end(ps)), end(ps));
int M = (int) ps.size();
g.resize(M);
for(int i = 0; i < N; i++) {
vector< int > vec;
for(int j = 0; j < M; j++) {
if(intersect(segs[i], ps[j])) {
vec.emplace_back(j);
}
}
for(int j = 1; j < vec.size(); j++) {
g[vec[j - 1]].push_back(vec[j]);
g[vec[j]].push_back(vec[j - 1]);
}
}
return (g);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C
Polygon convex_cut(const Polygon &U, Line l) {
Polygon ret;
for(int i = 0; i < U.size(); i++) {
Point now = U[i], nxt = U[(i + 1) % U.size()];
if(ccw(l.a, l.b, now) != -1) ret.push_back(now);
if(ccw(l.a, l.b, now) * ccw(l.a, l.b, nxt) < 0) {
ret.push_back(crosspoint(Line(now, nxt), l));
}
}
return (ret);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A
Real area2(const Polygon &p) {
Real A = 0;
for(int i = 0; i < p.size(); ++i) {
A += cross(p[i], p[(i + 1) % p.size()]);
}
return A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_H
Real area2(const Polygon &p, const Circle &c) {
if(p.size() < 3) return 0.0;
function< Real(Circle, Point, Point) > cross_area = [&](const Circle &c, const Point &a, const Point &b) {
Point va = c.p - a, vb = c.p - b;
Real f = cross(va, vb), ret = 0.0;
if(eq(f, 0.0)) return ret;
if(max(abs(va), abs(vb)) < c.r + EPS) return f;
if(distance(Segment(a, b), c.p) > c.r - EPS) return c.r * c.r * arg(vb * conj(va));
auto u = crosspoint(c, Segment(a, b));
vector< Point > tot{a, u.first, u.second, b};
for(int i = 0; i + 1 < tot.size(); i++) {
ret += cross_area(c, tot[i], tot[i + 1]);
}
return ret;
};
Real A = 0;
for(int i = 0; i < p.size(); i++) {
A += cross_area(c, p[i], p[(i + 1) % p.size()]);
}
return A;
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B
Real convex_diameter(const Polygon &p) {
int N = (int) p.size();
int is = 0, js = 0;
for(int i = 1; i < N; i++) {
if(p[i].imag() > p[is].imag()) is = i;
if(p[i].imag() < p[js].imag()) js = i;
}
Real maxdis = norm(p[is] - p[js]);
int maxi, maxj, i, j;
i = maxi = is;
j = maxj = js;
do {
if(cross(p[(i + 1) % N] - p[i], p[(j + 1) % N] - p[j]) >= 0) {
j = (j + 1) % N;
} else {
i = (i + 1) % N;
}
if(norm(p[i] - p[j]) > maxdis) {
maxdis = norm(p[i] - p[j]);
maxi = i;
maxj = j;
}
} while(i != is || j != js);
return sqrt(maxdis);
}
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A
Real closest_pair(Points ps) {
if(ps.size() <= 1) throw (0);
sort(begin(ps), end(ps));
auto compare_y = [&](const Point &a, const Point &b) {
return imag(a) < imag(b);
};
vector< Point > beet(ps.size());
const Real INF = 1e18;
function< Real(int, int) > rec = [&](int left, int right) {
if(right - left <= 1) return INF;
int mid = (left + right) >> 1;
auto x = real(ps[mid]);
auto ret = min(rec(left, mid), rec(mid, right));
inplace_merge(begin(ps) + left, begin(ps) + mid, begin(ps) + right, compare_y);
int ptr = 0;
for(int i = left; i < right; i++) {
if(abs(real(ps[i]) - x) >= ret) continue;
for(int j = 0; j < ptr; j++) {
auto luz = ps[i] - beet[ptr - j - 1];
if(imag(luz) >= ret) break;
ret = min(ret, abs(luz));
}
beet[ptr++] = ps[i];
}
return ret;
};
return rec(0, (int) ps.size());
}
int main() {
int N, R;
cin >> N >> R;
Polygon ps(N);
double ret = 0.0;
auto check = [&](double x) {
double vv = 0.0;
double low = 1e9, high = -1e9;
Line l = Line(Point(x, 0), Point(x, 1));
for(int i = 0; i < N; i++) {
if(intersect(l, Segment(ps[i], ps[(i + 1) % N]))) {
auto point = crosspoint(l, Segment(ps[i], ps[(i + 1) % N]));
low = min(low, imag(point));
high = max(high, imag(point));
}
}
for(int i = 0; i < 100; i++) {
double left = (low * 2 + high) / 3;
double right = (low + high * 2) / 3;
auto A = area2(ps, Circle(Point(x, left), R));
auto B = area2(ps, Circle(Point(x, right), R));
vv = max(vv, max(A, B));
if(A < B) low = left;
else high = right;
}
ret = max(ret, vv);
return (vv);
};
double low = 1e9, high = -1e9;
for(int i = 0; i < N; i++) {
cin >> ps[i];
low = min(low, real(ps[i]));
high = max(high, real(ps[i]));
}
for(int i = 0; i < 100; i++) {
double left = (low * 2 + high) / 3;
double right = (low + high * 2) / 3;
if(check(left) < check(right)) low = left;
else high = right;
}
cout << fixed << setprecision(10) << ret * 0.5 << endl;
}
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<int, int>;
using vi = vector<int>;
using vvi = vector<vector<int>>;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
const ld eps = 1e-9;
const ll MOD = 1000000007;
const int INF = 1000000000;
const ll LINF = 1ll<<50;
template<typename T>
void printv(const vector<T>& s) {
for(int i=0;i<(int)(s.size());++i) {
cout << s[i];
if(i == (int)(s.size())-1) cout << endl;
else cout << " ";
}
}
template<typename T1, typename T2>
ostream& operator<<(ostream &os, const pair<T1, T2> p) {
os << p.first << ":" << p.second;
return os;
}
const bool comp (const P &p1, const P &p2) {
if(p1.first == p2.first) {
return p1.second < p2.second;
} else {
return p1.first > p2.first;
}
}
P min(const P &p1, const P &p2) {
if(comp(p1, p2)) return p1;
else return p2;
}
void solve(int n) {
vi p(n);
int ma = 0;
for(int i=0;i<n;++i) {
cin >> p[i];
ma = max(ma, p[i]);
}
ma = 1000;
vector<P> d(n*ma+1, {-INF, INF});
d[0] = {0, 0};
for(int i=0;i<n;++i) {
int mod = p[i] % 1000;
vector<P> dnxt(n*ma+1, {-INF, INF});
for(int j=0;j<=n*ma;++j) {
if(d[j] == make_pair(-INF, INF)) continue;
if(1 <= mod && mod <= 500) {
dnxt[j+500-mod] = min(dnxt[j+500-mod], {d[j].first + 1, d[j].second + p[i]});
} else {
dnxt[j] = min(dnxt[j], d[j]);
if(mod == 0 && j >= 500) dnxt[j-500] = min(dnxt[j-500], {d[j].first + 1, d[j].second + p[i]});
if(mod != 0 && j >= mod - 500) dnxt[j-(mod - 500)] = min(dnxt[j - (mod - 500)], {d[j].first + 1, d[j].second + p[i]});
if(mod != 0) dnxt[j+1000-mod] = min(dnxt[j+1000-mod], {d[j].first, d[j].second + p[i]});
}
}
d = dnxt;
}
P ans = {-INF, INF};
for(int i=0;i<=n*ma;++i) {
ans = min(ans, d[i]);
}
cout << ans.first << " " << ans.second << endl;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout << fixed << setprecision(10);
while(1) {
int n; cin >> n;
if(n == 0) break;
solve(n);
}
}
|
#include <bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<map>
#include<cstring>
#include<string>
#include <math.h>
#include<algorithm>
// #include <boost/multiprecision/cpp_int.hpp>
#include<functional>
// #define int long long
#define inf 1000000007
#define pa pair<int,int>
#define ll long long
#define pal pair<double,int>
#define ppa pair<pa,int>
#define ppap pair<int,pa>
#define ssa pair<string,int>
#define mp make_pair
#define pb push_back
#define EPS (1e-10)
#define equals(a,b) (fabs((a)-(b))<EPS)
using namespace std;
//priority_queue<int, vector<int>, greater<int> > que;
class Point{
public:
double x,y;
Point(double x=0,double y=0):x(x),y(y) {}
Point operator + (Point p) {return Point(x+p.x,y+p.y);}
Point operator - (Point p) {return Point(x-p.x,y-p.y);}
Point operator * (double a) {return Point(x*a,y*a);}
Point operator / (double a) {return Point(x/a,y/a);}
double absv() {return sqrt(norm());}
double norm() {return x*x+y*y;}
bool operator < (const Point &p) const{
return x != p.x ? x<p.x: y<p.y;
}
bool operator == (const Point &p) const{
return fabs(x-p.x)<EPS && fabs(y-p.y)<EPS;
}
};
typedef Point Vector;
struct Segment{
Point p1,p2;
};
double hen(Vector a){
if(fabs(a.x)<EPS && a.y>0) return acos(0);
else if(fabs(a.x)<EPS && a.y<0) return 3*acos(0);
else if(fabs(a.y)<EPS && a.x<0) return 2*acos(0);
else if(fabs(a.y)<EPS && a.x>0) return 0.0;
else if(a.y>0) return acos(a.x/a.absv());
else return 2*acos(0)+acos(-a.x/a.absv());
}
string itos( int i ) {
ostringstream s ;
s << i ;
return s.str() ;
}
int gcd(int v,int b){
if(v>b) return gcd(b,v);
if(v==b) return b;
if(b%v==0) return v;
return gcd(v,b%v);
}
double dot(Vector a,Vector b){
return a.x*b.x+a.y*b.y;
}
double cross(Vector a,Vector b){
return a.x*b.y-a.y*b.x;
}
double distans(double x1,double y1,double x2,double y2){
double rr=(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);
return sqrt(rr);
}
/*}
int pr[100010];
//int inv[100010];
int beki(int wa,int rr){
if(rr==0) return 1ll;
if(rr==1) return wa;
if(rr%2==1) return (beki(wa,rr-1)*wa)%inf;
int zx=beki(wa,rr/2);
return (zx*zx)%inf;
}
void gya(){
pr[0]=1;
for(int i=1;i<100010;i++){
pr[i]=(pr[i-1]*i)%inf;
}
for(int i=0;i<100010;i++) inv[i]=beki(pr[i],inf-2);
}
*/
//----------------kokomade tenpure------------
int n;
int dp[101][540005];
//bool me[101][540005]={0};
signed main(){
int u=10000000;
while(1){
cin>>n;
if(n==0) break;
int zx=-9000000;
for(int i=0;i<=100;i++)for(int j=0;j<540005;j++){
dp[i][j]=zx;
}
dp[0][0]=0;
for(int i=1;i<=n;i++){
int p,pq;
cin>>p;
pq=p;
p%=1000;
if(p==0) p+=1000;
for(int j=0;j<540005;j++){
if(dp[i-1][j]==zx) continue;
if(dp[i][j]<dp[i-1][j]) dp[i][j]=dp[i-1][j];
if(p>500){
// me[i][j+(1000-p)]=1;
if(dp[i][j+(1000-p)]<dp[i-1][j]-pq) dp[i][j+(1000-p)]=dp[i-1][j]-pq;
}
else{
// me[i][j+(1000-p-500)]=1;
if(dp[i][j+(500-p)]<dp[i-1][j]+u-pq) dp[i][j+(500-p)]=dp[i-1][j]+u-pq;
}
if(p>500){
if(j>=p+500-1000){
// me[i][j-(p-500)]=1;
if(dp[i][j-(p-500)]<dp[i-1][j]+u-pq) dp[i][j-(p-500)]=dp[i-1][j]+u-pq;
}
}
else{
if(j>=p+500){
// me[i][j-(p+500)]=1;
if(dp[i][j-(p+500)]<dp[i-1][j]+u-pq) dp[i][j-(p+500)]=dp[i-1][j]+u-pq;
}
}
}
}
int ans=zx;
for(int j=0;j<540005;j++){
if(dp[n][j]==zx) continue;
if(dp[n][j]>ans)ans=dp[n][j];
}
if(ans%u!=0){
cout<<ans/u +1<<" "<<u-ans%u<<endl;
}
else{
cout<<ans/u<<" 0"<<endl;
}
}
return 0;
} |
#include "bits/stdc++.h"
using namespace std;
typedef pair<int,int> P;
P comp(P lhs,P rhs)
{
if(lhs.first>rhs.first)
return lhs;
else if(lhs.first==rhs.first && lhs.second<rhs.second)
return lhs;
else
return rhs;
}
P dp[101][50001]; //i番目まで端数でj円持っているときの500の数と金額
int m[100]; //価格
P pay1000[100]; //1000円オンリーで払ったときにもらえる500ともらえる端数
P adjust[100]; //端数を調整したときに500を1もらうために必要な端数
int main()
{
while(1)
{
int n;
cin>>n;
if(n==0)
break;
for(int i=0;i<n;i++)
{
cin>>m[i];
int p=(7000-m[i])%1000;
if(p>=500)
pay1000[i]=P(1,p-500);
else
pay1000[i]=P(0,p);
p=(m[i]+1000)%1000;
if(p!=0)
adjust[i]=P(1,(p+500)%1000);
else
adjust[i]=P(1,500);
}
//ここからdp
fill(dp[0],dp[101],P(-1,-1));
dp[0][0]=P(0,0);
for(int i=1;i<n+1;i++)
{
//cerr<<pay1000[i-1].first<<" "<<pay1000[i-1].second<<endl;
//cerr<<adjust[i-1].first<<" "<<adjust[i-1].second<<endl;
for(int j=0;j<50001;j++)
{
if(dp[i-1][j]!=P(-1,-1))
{
dp[i][j]=comp(dp[i][j],dp[i-1][j]);
//端数調整して買う場合
if(j>=adjust[i-1].second)
{
dp[i][j-adjust[i-1].second]=comp(dp[i][j-adjust[i-1].second],
P(dp[i-1][j].first+adjust[i-1].first, dp[i-1][j].second+m[i-1]));
}
//1000円だけで買う場合
dp[i][j+pay1000[i-1].second]=comp(dp[i][j+pay1000[i-1].second],
P(dp[i-1][j].first+pay1000[i-1].first, dp[i-1][j].second+m[i-1]));
}
}
}
P ans=P(0,0);
for(int i=0;i<50001;i++)
ans=comp(dp[n][i],ans);
cout<<ans.first<<" "<<ans.second<<endl;
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
#define _for(i,j,N) for(int i = (j);i < (N);i++)
#define _rep(i,j,N) for(int i = (j);i <= (N);i++)
#define ALL(x) x.begin(),x.end()
#define PB push_back
#define LL long long
const int maxzeni = 10000;
int dp[102][10001];
int pp[102];
int reals[102];
int money[102][10001];
void update2(int &a,int b,int &c,int d){
if(a < b){
a = b;
c = d;
}
else if(a == b){
if(c > d || c < 0) c = d;
}
}
void update(int i,int zeni,int c,int real){
int val = dp[i][zeni];
//cout << "i:"<<i << "zeni:"<<zeni << "reals:"<< real <<endl;
update2(dp[i+1][zeni],val,money[i+1][zeni],money[i][zeni]);
if(zeni - c >= 500){
update2(dp[i+1][zeni - c - 500],val+1,money[i+1][zeni - c - 500],money[i][zeni]+real);
}
if(1000 - c >= 500 && (1000 - c - 500+ zeni) <= maxzeni){
update2(dp[i+1][1000 - c - 500 + zeni],val+1,money[i+1][1000 - c - 500+zeni],money[i][zeni]+real);
}
else{
if(1000 + zeni - c >= 500 && 1000 + zeni - c <= maxzeni){
update2(dp[i+1][1000 + zeni - c - 500],val+1,money[i+1][1000 + zeni - c - 500],money[i][zeni]+real);
}
else{
update2(dp[i+1][1000 + zeni - c],val,money[i+1][1000 + zeni - c],money[i][zeni]+real);
}
}
}
int main()
{
int p;
while(scanf("%d",&p)&&p){
memset(dp,-1,sizeof(dp));
memset(money,-1,sizeof(money));
_for(i,0,p) {
scanf("%d",&pp[i]);
reals[i] = pp[i];
pp[i] %= 1000;
if(pp[i] == 0) pp[i] = 1000;
}
dp[0][0] = 0;
money[0][0] = 0;
_for(i,0,p){
_for(j,0,maxzeni){
if(dp[i][j] >= 0){
update(i,j,pp[i],reals[i]);
}
}
}
int maxcoin = 0;
int min_cost = 0;
_for(j,0,maxzeni){
if(dp[p][j] >= maxcoin){
//cout << j <<" "<< money[p][j] <<endl;
if(dp[p][j] > maxcoin){
maxcoin = dp[p][j];
min_cost = money[p][j];
}
else{
min_cost = min(min_cost,money[p][j]);
}
}
}
cout << maxcoin <<" "<<min_cost << endl;
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;
typedef pair<ll ,P> P3;
typedef pair<P ,P> PP;
const ll MOD = ll(1e9+7);
const int IINF = INT_MAX;
const ll LLINF = LLONG_MAX;
const int MAX_N = int(1e5 + 5);
const double EPS = 1e-6;
const int di[] = {0, 1, 0, -1}, dj[] = {1, 0, -1, 0};
#define REP(i, n) for (int i = 0; i < n; i++)
#define REPR(i, n) for (int i = n; i >= 0; i--)
#define SORT(v) sort((v).begin(), (v).end())
#define SORTR(v) sort((v).rbegin(), (v).rend())
#define ALL(v) (v).begin(), (v).end()
int n, p[105], dp[2][105][500*60];
void solve(){
REP(i,2)REP(j,n+1) fill(dp[i][j],dp[i][j]+500*60,IINF);
dp[0][0][0] = 0;
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
for(int k=0;k<=500*55;k++){
if(dp[i%2][j][k]==IINF)continue;
int chg = (1000-p[i]%1000)%1000;
if(chg < 500){
dp[(i+1)%2][j][k+chg] = min(dp[(i+1)%2][j][k+chg],dp[i%2][j][k]+p[i]);
if(500-chg <= k){
dp[(i+1)%2][j+1][k+chg-500] = min(dp[(i+1)%2][j+1][k+chg-500],dp[i%2][j][k]+p[i]);
}
}
else{
dp[(i+1)%2][j+1][min(k+chg-500,500*55)] = min(dp[(i+1)%2][j+1][min(k+chg-500,500*55)],dp[i%2][j][k]+p[i]);
}
dp[(i+1)%2][j][k] = min(dp[(i+1)%2][j][k],dp[i%2][j][k]);
}
}
}
int ma = 0, ans = 0;
for(int i=1;i<=n;i++){
for(int j=0;j<=500*55;j++){
if(dp[n%2][i][j] < IINF){
if(i > ma){
ma = i;
ans = dp[n%2][i][j];
}
else if (i==ma){
ans = min(ans, dp[n%2][i][j]);
}
}
}
}
cout << ma << " " << ans << endl;
}
int main() {
while(cin >> n, n){
REP(i,n){
cin >> p[i];
}
solve();
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
int dp[101][501][501];
int roundup(int v){
return (v + 999) / 1000 * 1000;
}
bool solve(){
int INF = 5000 * 1000;
int n;
cin >> n;
if (n == 0)
return true;
vector<int> P(n);
for (auto &p: P) cin >> p;
for (auto &i: dp){
for (auto &j: i){
for (auto &k: j){
k = -INF;
}
}
}
int max_500 = 0;
dp[0][0][0] = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < 501; j++){
for (int k = 0; k < 501; k++){
if (dp[i][j][k] < 0) continue;
dp[i + 1][j][k] = max(dp[i + 1][j][k], dp[i][j][k]);
int change = min(dp[i][j][k], 999 - (roundup(P[i]) - P[i]));
int pay = roundup(P[i]) + change;
int next = dp[i][j][k] + roundup(P[i]) - P[i];
if (pay - P[i] >= 500){
dp[i + 1][j + roundup(P[i]) / 1000][k + 1] = max(dp[i + 1][j + roundup(P[i]) / 1000][k + 1], next - 500);
max_500 = max(max_500, k + 1);
}
else
dp[i + 1][j + roundup(P[i]) / 1000][k] = max(dp[i + 1][j + roundup(P[i]) / 1000][k] , next);
}
}
}
int ans = INF;
for (int i = 0; i < 501; i++)
ans = min(ans, i * 1000 - dp[n][i][max_500] - 500 * max_500);
cout << max_500 << " " << ans << endl;;
return false;
}
int main(){
while (true){
if (solve())
break;
}
}
|
#include <bits/stdc++.h>
using namespace std;
template<class T> T &chmax(T &a,const T &b){ return a = max(a,b); }
int n,a[110];
using P = pair<int,int>;
P dp[110][50010];
P operator+(const P &p1,const P &p2){
return P(p1.first + p2.first,p1.second + p2.second);
}
void solve(){
const int INF = 1e+9;
for(int i = 0;i < n;i++) cin >> a[i];
for(int i = 0;i <= n;i++){
for(int j = 0;j <= n * 500;j++) dp[i][j] = P(-INF,-INF);
}
dp[0][0] = P(0,0);
for(int i = 0;i < n;i++){
int b = (a[i] % 1000 ? a[i] % 1000 : 1000);
for(int j = 0;j <= n * 500;j++){
chmax(dp[i + 1][j],dp[i][j]);
if(j + 500 - b >= 0 && j + 500 - b <= n * 500) chmax(dp[i + 1][j + 500 - b],dp[i][j] + P(1,-a[i]));
if(b > 500 && j + 1000 - b <= n * 500) chmax(dp[i + 1][j + 1000 - b],dp[i][j] + P(0,-a[i]));
}
}
P ans(-INF,-INF);
for(int i = 0;i <= n * 500;i++){
chmax(ans,dp[n][i]);
}
cout << ans.first << " " << -ans.second << endl;
}
signed main(){
while(cin >> n,n) solve();
}
|
#include<cstdio>
#include<algorithm>
using namespace std;
typedef pair<int, int> PP;
int N;
int P[100];
PP dp[100][50000];
PP max(PP a, PP b){
if(a.first == b.first){
if(a.second > b.second){
return b;
}else{
return a;
}
}else if(a.first >= b.first){
return a;
}else{
return b;
}
}
PP recur(int idx, int kozeni){
if(idx == N){
return make_pair(0, 0);
}
if(dp[idx][kozeni].first != -1){
return dp[idx][kozeni];
}
PP ans = recur(idx + 1, kozeni);
int nk = (1000 - P[idx] % 1000) % 1000;
if(nk >= 500){
PP ans2 = recur(idx + 1, kozeni + nk - 500);
ans = max(ans, make_pair(ans2.first + 1, ans2.second + P[idx]));
}else{
PP ans2 = recur(idx + 1, kozeni + nk);
ans = max(ans, make_pair(ans2.first, ans2.second + P[idx]));
if(kozeni + nk >= 500){
ans2 = recur(idx + 1, kozeni + nk - 500);
ans = max(ans, make_pair(ans2.first + 1, ans2.second + P[idx]));
}
}
return dp[idx][kozeni] = ans;
}
int main(){
while(1){
scanf("%d", &N);
if(!N) break;
for(int i = 0; i < N; i++){
for(int j = 0; j < 50000; j++){
dp[i][j] = make_pair(-1, -1);
}
}
for(int i = 0; i < N; i++){
scanf("%d", &P[i]);
}
PP ans = recur(0, 0);
printf("%d %d\n", ans.first, ans.second);
}
} |
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
pii max(pii a, pii b){
if(a.first > b.first){
return a;
}else if(a.first < b.first){
return b;
}else{
if(a.second > b.second){
return b;
}else{
return a;
}
}
}
pii dp[111][50000];
int main(){
int n;
while(std::cin >> n, n){
vector<int> shop(n);
for (int i = 0; i < n; i++) std::cin >> shop[i];
for (int i = 0; i <= n; i++) {
for (int j = 0; j < 50000; j++) {
dp[i][j] = pii(-1e9, 0);
}
}
dp[0][0] = pii(0, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < 50000; j++) {
dp[i + 1][j] = max(dp[i + 1][j], dp[i][j]);
int tf = dp[i][j].first;
int tc = dp[i][j].second;
int five_hundred;
int diff = (5000 - shop[i])%1000;
if(j + diff >= 500)
dp[i + 1][j + diff - 500] = max(dp[i + 1][j + diff - 500], pii(tf + 1, tc + shop[i]));
else
dp[i + 1][j + diff] = max(dp[i + 1][j + diff],
pii(tf, tc + shop[i]));
}
}
pii ans = pii(0, 0);
for (int i = 0; i < 50000; i++) {
ans = max(ans, dp[n][i]);
}
std::cout << ans.first << " " << ans.second << std::endl;
}
return 0;
} |
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
const ll INF = (1ll << 50);
ll dp[101][502][101];
ll n;
ll p[101];
int main(){
while(cin >> n){
if(n == 0) return 0;
for(ll i = 0;i < n;i++) cin >> p[i];
for(ll i = 0;i <= 100;i++){
for(ll j = 0;j <= 501;j++){
for(ll k = 0;k <= 100;k++){
dp[i][j][k] = INF;
}
}
}
dp[0][0][0] = 0;
for(ll i = 0;i < n;i++){
for(ll j = 0;j <= 500;j++){
for(ll k = 0;k <= 100;k++){
dp[i+1][j][k] = min(dp[i+1][j][k],dp[i][j][k]);
if(p[i]%1000 <= 500 && p[i]%1000 > 0){
dp[i+1][j+(p[i]/1000)+1][k+1] = min(dp[i+1][j+(p[i]/1000)+1][k+1], dp[i][j][k]+p[i]);
}else if(p[i]%1000 > 500){
ll nokori = (p[i]%1000) - 500;
ll kozeni = j*1000-dp[i][j][k]-500*k;
if(kozeni >= nokori){
dp[i+1][j+(p[i]/1000)+1][k+1] = min(dp[i+1][j+(p[i]/1000)+1][k+1], dp[i][j][k]+p[i]);
}else{
dp[i+1][j+(p[i]/1000)+1][k] = min(dp[i+1][j+(p[i]/1000)+1][k], dp[i][j][k]+p[i]);
}
}else{
ll kozeni = j*1000-dp[i][j][k]-500*k;
if(kozeni >= 500){
dp[i+1][j+(p[i]/1000)][k+1] = min(dp[i+1][j+(p[i]/1000)][k+1], dp[i][j][k]+p[i]);
}else{
// dp[i+1][j+(p[i]/1000)][k] = min(dp[i+1][j+(p[i]/1000)][k], dp[i][j][k]);
}
}
}
}
}
// for(ll i = 0;i <= n;i++){
// for(ll j = 0;j <= 5;j++){
// for(ll k = 0;k <= 5;k++){
// cerr << dp[i][j][k] << " ";
// }
// cerr << endl;
// }
// cerr << endl;
// }
ll ans = 0;
ll cost = INF;
ll i = n;
for(ll j = 0;j <= 500;j++){
for(ll k = 0;k <= 100;k++){
if(dp[i][j][k] != INF){
if(ans < k){
ans = k;
cost = dp[i][j][k];
// cerr << j << " " << k << endl;
}else if(ans == k){
cost = min(cost, dp[i][j][k]);
}
}
}
}
cout << ans << " " << cost << endl;
}
}
|
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
P dp[105][50005];
int p[100],n;
void Max(P &a,P b){a=max(a,b);}
int main(){
while(cin>>n&&n){
memset(dp,-1,sizeof(dp));
for(int i=0;i<n;i++)cin>>p[i];
dp[0][0] = P(0,0);
for(int i=0;i<n;i++){
for(int j=0;j<500*n;j++){
if(dp[i][j]==P(-1,-1)) continue;
int nf=dp[i][j].first,ns=dp[i][j].second-p[i];
Max(dp[i+1][j],dp[i][j]);
if(p[i]%1000==0) {if(j>=500)Max(dp[i+1][j-500],P(nf+1,ns));}
else if(p[i]%1000<500) Max(dp[i+1][j+500-p[i]%500],P(nf+1,ns));
else if(p[i]%500<=j) Max(dp[i+1][j-p[i]%500],P(nf+1,ns));
else Max(dp[i+1][j+500-p[i]%500],P(nf,ns));
}
}
P ans(0,0);
for(int i=0;i<500*n;i++) Max(ans,dp[n][i]);
cout<<ans.first<<" "<<-ans.second<<endl;
}
return 0;
} |
#include <bits/stdc++.h>
using namespace std;
#define DUMP(x) cerr << #x << "=" << x << endl
#define DUMP2(x, y) cerr<<"("<<#x<<", "<<#y<<") = ("<<x<<", "<<y<<")"<< endl
#define BINARY(x) static_cast<bitset<16> >(x)
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define REP(i,m,n) for (int i=m;i<(int)(n);i++)
#define in_range(x, y, w, h) (0<=(int)(x) && (int)(x)<(int)(w) && 0<=(int)(y) && (int)(y)<(int)(h))
#define ALL(a) (a).begin(),(a).end()
typedef long long ll;
const int INF = 1e9;
typedef pair<int, int> PII;
int dx[4]={0, -1, 1, 0}, dy[4]={-1, 0, 0, 1};
int N;
vector<int> P;
PII dp[100][50000];
bool cmp (const PII &l, const PII &r)
{
if (l.first == r.first) return l.second > r.second;
return l.first < r.first;
}
PII solve(int n, int x, int sum, int num)
{
if (n == N) return PII(0, 0);
if (dp[n][x].first != -1) return dp[n][x];
PII res = PII(0, INF);
// ????????????
res = max(res, solve(n+1, x, sum, num), cmp);
// ?°????????????£?????????
{
int kozeni = (P[n] + 500) % 1000;
if (kozeni <= x) {
PII tmp = solve(n+1, x-kozeni, sum+P[n], num+1);
tmp.first++;
tmp.second += P[n];
res = max(res, tmp, cmp);
}
}
// ?????????????????£?????????
{
int kozeni = (1000 - P[n]%1000)%1000;
int get = 0;
if (kozeni >= 500) {
get = 1;
kozeni -= 500;
}
PII tmp = solve(n+1, x+kozeni, sum+P[n], num+get);
tmp.first += get;
tmp.second += P[n];
res = max(res, tmp, cmp);
}
return dp[n][x] = res;
}
int main()
{
while (cin >> N, N) {
fill(dp[0], dp[0]+100*50000, PII(-1, -1));
P.resize(N);
rep(i, N) cin >> P[i];
PII ans = solve(0, 0, 0, 0);
cout << ans.first << " " << ans.second << endl;
}
} |
#include <iostream>
#include <string>
#include <vector>
#include <tuple>
#include <cassert>
#define REP(i, n) for (int i = 0; i < (n); i ++)
using namespace std;
void chmax(int& x, int y) { if (x < y) x = y; }
void chmin(int& x, int y) { if (x > y) x = y; }
int main() {
while(true) {
int n; cin >> n;
if (n == 0) break;
vector<int> p(n);
REP(i, n) cin >> p[i];
// dp[store][500][spend1000]
vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(n + 1, vector<int>(601, -1)));
dp[0][0][0] = 0;
int maxcoin = 0;
REP(pi, n) {
int price = p[pi];
int oturi = 1000 - (price % 1000);
int us = (price - 1) / 1000 + 1;
if (oturi == 1000) oturi = 0;
//cout << "pi: " << pi << " price: "<< price << " Use: " << us << " Oturi:" << oturi << endl;
REP(i5, n) {
REP(s, 600) {
int hav = dp[pi][i5][s];
if (hav == -1) continue;
//cout << "i5: " << i5 << " s: " << s << " hav : " << hav << endl;
chmax(dp[pi + 1][i5][s], hav); // 買わない
if (oturi >= 500) {
//cout <<"MUST" << endl;
chmax(dp[pi + 1][i5 + 1][s + us], hav + oturi - 500);
chmax(maxcoin, i5 + 1);
}else{
chmax(dp[pi + 1][i5][s + us], hav + oturi); //買う
if (500 - oturi <= hav) {
//cout <<"MORE BUY" << endl;
chmax(dp[pi + 1][i5 + 1][s + us], hav - (500 - oturi)); //余計に出して買う
chmax(maxcoin, i5 + 1);
}
}
}
}
}
int used = 100000000;
cout << maxcoin << " ";
REP(i, 601) {
int hav = dp[n][maxcoin][i];
if (hav != -1) {
//cout << "S: " << i << " - " << hav << endl;
chmin(used, 1000 * i - hav - maxcoin * 500);
}
}
cout << used << endl;
}
}
|
#pragma GCC optimize("Ofast", "unroll-loops")
#include <bits/stdc++.h>
using namespace std;
int n;
vector<int> p(101);
bool input() {
cin >> n;
if (n == 0) return false;
for (int i = 1; i <= n; ++i)
cin >> p[i];
return true;
}
using pii = pair<int, int>;
const int MAX_CHANGE = 100000;
void update(pii& a, pii b) {
if (a.first > b.first) return;
if (a.first < b.first) a = b;
else if (a.second > b.second) a = b;
}
void solve() {
static vector<vector<pii>>
dp(101, vector<pii>(MAX_CHANGE));
for (int j = 1; j < MAX_CHANGE; ++j)
dp[0][j] = make_pair(-1000, 0);
dp[0][0] = make_pair(0, 0);
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < MAX_CHANGE; ++j) {
dp[i][j] = dp[i - 1][j];
if (p[i] % 1000 > 500) {
// p[i] に?000円支払う
int change = 1000 - (p[i] % 1000);
if (j >= change) {
pii tmp = dp[i - 1][j - change];
tmp.second += p[i];
update(dp[i][j], tmp);
}
// p[i] に?000 + p[i] % 500円支払う
int use = p[i] % 500;
if (j + use < MAX_CHANGE) {
pii tmp = dp[i - 1][j + use];
++tmp.first; tmp.second += p[i];
update(dp[i][j], tmp);
}
}
else {
// p[i] に?000円支払う
if (p[i] % 1000) {
int change = 500 - (p[i] % 1000);
if (j >= change) {
pii tmp = dp[i - 1][j - change];
++tmp.first; tmp.second += p[i];
update(dp[i][j], tmp);
}
}
// p[i] に?000円 + おつりを用いる
int use = (p[i] % 1000) + 500;
if (j + use < MAX_CHANGE) {
pii tmp = dp[i - 1][j + use];
++tmp.first; tmp.second += p[i];
update(dp[i][j], tmp);
}
}
}
}
pii res = { 0, 0 };
for (int j = 0; j < MAX_CHANGE; ++j)
update(res, dp[n][j]);
cout << res.first << " " << res.second << endl;
}
int main() {
while (input()) solve();
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
P dp[101][50001];
void Max(P &a,P b){a=max(a,b);}
int main(){
int n,p[101];
while(cin>>n,n){
for(int i=0;i<n;i++)cin>>p[i];
memset(dp,-1,sizeof(dp));
dp[0][0]=P(0,0);
for(int i=0;i<n;i++)
for(int j=0;j<50000;j++){
if(dp[i][j]==P(-1,-1))continue;
int coin=dp[i][j].first;
int ncost=dp[i][j].second-p[i];
Max(dp[i+1][j],dp[i][j]);
if(p[i]%1000<=500&&p[i]%1000)Max(dp[i+1][j+(1000-p[i]%1000)%500],P(coin+1,ncost));
if(p[i]%1000==0&&j>=500) Max(dp[i+1][j-500],P(coin+1,ncost));
if(p[i]%1000>500) {
if(j>=p[i]%500)Max(dp[i+1][j-p[i]%500],P(coin+1,ncost));
else Max(dp[i+1][j+(500-p[i]%500)],P(coin,ncost));
}
}
P ans=P(0,0);
for(int i=0;i<50000;i++)Max(ans,dp[n][i]);
cout <<ans.first<<" "<<-ans.second<<endl;
}
return 0;
} |
#include<bits/stdc++.h>
#define fi first
#define se second
typedef long long ll;
using namespace std;
pair<int,int> dp[2][200001];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
while(cin>>n,n){
int a[201];
fill(a,a+201,0);
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=0;i<=200000;i++)dp[0][i]=make_pair(-1,0);
dp[0][0]=make_pair(0,0);
for(int i=0;i<n;i++){
for(int j=0;j<=200000;j++)dp[(i+1)&1][j]=make_pair(-1,0);
for(int j=0;j<=200000;j++){
if(dp[i&1][j].fi==-1)continue;
int tmp=a[i]%1000;
if(tmp<=500 && tmp>=1){
if(dp[(i+1)&1][j+500-tmp]<make_pair(dp[i&1][j].fi+1,dp[i&1][j].se-a[i])){
dp[(i+1)&1][j+500-tmp]=make_pair(dp[i&1][j].fi+1,dp[i&1][j].se-a[i]);
}
}else{
int pay=(tmp+500)%1000;
dp[(i+1)&1][j]=max(dp[(i+1)&1][j],dp[i&1][j]);
if(pay<=j){
if(dp[(i+1)&1][j-pay]<make_pair(dp[i&1][j].fi+1,dp[i&1][j].se-a[i])){
dp[(i+1)&1][j-pay]=make_pair(dp[i&1][j].fi+1,dp[i&1][j].se-a[i]);
}
}
int pay2=(1000-tmp)%1000;
if(dp[(i+1)&1][j+pay2]<make_pair(dp[i&1][j].fi,dp[i&1][j].se-a[i])){
dp[(i+1)&1][j+pay2]=make_pair(dp[i&1][j].fi,dp[i&1][j].se-a[i]);
}
}
}
}
pair<int,int> ans=make_pair(0,0);
for(int i=0;i<=200000;i++){
if(dp[n&1][i]>ans){
ans=make_pair(dp[n&1][i].fi,dp[n&1][i].se);
}
}
cout<<ans.fi<<" "<<-ans.se<<endl;
}
return 0;
}
|
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#include <limits>
#include <cfloat>
#include <climits>
#include <ctime>
#include <cassert>
#include <numeric>
#include <functional>
using namespace std;
#define rep(i,a,n) for(int (i)=(a); (i)<(n); (i)++)
#define repq(i,a,n) for(int (i)=(a); (i)<=(n); (i)++)
#define repr(i,a,n) for(int (i)=(a); (i)>=(n); (i)--)
#define int long long int
template<typename T> void chmax(T &a, T b) {a = max(a, b);}
template<typename T> void chmin(T &a, T b) {a = min(a, b);}
template<typename T> void chadd(T &a, T b) {a = a + b;}
typedef pair<int, int> pii;
typedef long long ll;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
constexpr ll INF = 1001001001001001LL;
constexpr ll MOD = 1000000007LL;
int N, P[110];
// dp[i][j] := i ???????????§???????????£???????°???? j ????????????????????¨??????
// 500 ??????????????§?????¨?????????????¶?????????????????°????
pii dp[110][50000];
signed main() {
while(cin >> N, N) {
rep(i,0,N) cin >> P[i];
rep(i,0,110) rep(j,0,50000) dp[i][j] = pii(-1, INF);
dp[0][0] = pii(0, 0);
rep(i,0,N) rep(j,0,50000) {
if(dp[i][j].first == -1) continue;
chmax(dp[i+1][j], dp[i][j]);
int change = (1000 - (P[i] % 1000)) % 1000;
int getcoin = (j + change >= 500);
int next_money = j + change - 500 * getcoin;
chmax(dp[i+1][next_money], pii(dp[i][j].first + getcoin, dp[i][j].second - P[i]));
}
pii ans(-1, INF);
rep(i,0,50000) chmax(ans, dp[N][i]);
printf("%lld %lld\n", ans.first, -ans.second);
}
return 0;
} |
#include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "iomanip"
#include "cmath"
using namespace std;
const long long int MOD = 1000000007;
long long int N, M, K, H, W, L, R;
class weight {
public:
int coin;
int pay;
weight() {
coin = -1;
pay = -1;
}
bool operator < (const weight& w)const {
if (coin < w.coin)return true;
if (coin==w.coin&&pay > w.pay)return true;
return false;
}
bool operator > (const weight& w)const {
if (coin > w.coin)return true;
if (coin==w.coin&&pay < w.pay)return true;
return false;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> N;
while (N) {
weight ans;
vector<vector<weight>>dp(N + 1, vector<weight>(N * 999 + 1));
dp[0][0].coin = 0;
dp[0][0].pay = 0;
for (int i = 1; i <= N; i++) {
cin >> M;
for (int j = 0; j <= (i - 1) * 999; j++) {
if (dp[i - 1][j].coin == -1) {
continue;
}
weight box(dp[i - 1][j]);
dp[i][j] = max(dp[i][j], box);
box.coin++;
box.pay += M;
K = M % 1000;
if (K&&K <= 500) {
dp[i][j + 500 - K] = max(dp[i][j + 500 - K], box);
if (j >= 500+K) {
dp[i][j - 500 - K] = max(dp[i][j - 500 - K], box);
}
}
else if (K) {
if (j >= K - 500) {
dp[i][j - K + 500] = max(dp[i][j - K + 500], box);
}
box.coin--;
dp[i][j + 1000 - K] = max(dp[i][j + 1000 - K], box);
}
else {
if (j >= 500) {
dp[i][j - 500] = max(dp[i][j - 500], box);
}
}
}
}
for (auto i : dp[N]) {
if (i.coin != -1) {
ans = max(ans, i);
}
}
cout << ans.coin << " " << ans.pay << endl;
cin >> N;
}
return 0;
} |
/*
* D.cpp
*
* Created on: 2017/07/01
* Author: LitMc
*/
//#define MYDEBUG
#include <bits/stdc++.h>
#ifdef MYDEBUG
#define dbp(x) cout<<#x<<": "<<x<<endl
#define dbp2(x,y) cout<<#x<<","<<#y<<": "<<x<<","<<y<<endl
#define dbp3(x,y,z) cout<<#x<<","<<#y<<","<<#z<<": "<<x<<","<<y<<","<<z<<endl
#define dbp4(w,x,y,z) cout<<#w<<","<<#x<<","<<#y<<","<<#z<<": "<<w<<","<<x<<","<<y<<","<<z<<endl
#define ifcin(x) std::ifstream cin(x)
#else
#define dbp(x)
#define dbp2(x,y)
#define dbp3(x,y,z)
#define dbp4(w,x,y,z)
#define ifcin(x)
#endif
#define ll long long
#define ull unsigned long long
#define all(x) x.begin(), x.end()
#define rep(i, from, to) for(int i=from; i<to; ++i)
#define REP(i, from, to) for(int i=from; i<=to; ++i)
#define EPS = 1e-14;
using std::vector;
using std::cout;
using std::cin;
using std::endl;
using std::max;
using std::min;
using std::swap;
using std::string;
using std::fill;
using std::pair;
using std::sort;
using std::reverse;
using std::pair;
using std::greater;
using std::priority_queue;
using std::ostream;
template<typename T>
ostream& operator<<(ostream& out, const vector<vector<T> >& v) {
for (size_t i = 0; i < v.size(); ++i) {
out << v[i] << endl;
}
return out;
}
template<typename T>
ostream& operator<<(ostream& out, const vector<T>& v) {
out << "[";
size_t last = v.size() - 1;
for (size_t i = 0; i < v.size(); ++i) {
out << v[i];
if (i != last) {
out << ",";
}
}
out << "]";
return out;
}
typedef pair<int, int> P;
bool cmp(const P &p1, const P &p2) {
if (p1.first == p2.first) {
return p1.second > p2.second;
} else {
return p1.first < p2.first;
}
}
static const int MAX_N = 102;
static const int MAX_E = 1000 * MAX_N; //10^5
int n;
int p[MAX_N];
P dp[MAX_N][MAX_E];
//P ch[MAX_N][MAX_E]; //??????????????¨
//dp[i][k]: k????°?????????????????????¶?????§???i????????\????????????????????£?????????????????????????????§???
//dp[1][0]: ?¬??????????
//dp[n+1][*]: ?????????(0???, 0???)
void init() {
rep(i,0,MAX_N)
{
p[i] = 0;
rep(j,0,MAX_E)
{
dp[i][j] = P(0, 0);
}
}
}
//ex: 900
//p: 400
//1900?????????
//1000 = (400+1000-1)/1000
//900: ex
//1900 - 400 = 1500
//%1000????????¨500, 1???get
//??????
//base: (p + 1000 - 1) / 1000 : 1000???????????§??????????????????
//?????????????????£????????¨?????????: ex
//????????????: base + ex
//????????????: ret = (base+ex) - p
//????????????500??????????????°: ret%1000
//?????????????????????: p
//500????????????????????????????????£???: ret - ((ret%1000) / 500) * 500
//100?????????????????????, ?°????700???
//1000 + 700 - 100 = 1600
//1600%1000 = 600
//600/500 = 1
//?????£???: 1600 - 1*500 = 1100
//1700????????£???+1100???(600???????????????)
//????±???????????????£????????????p???????????????????????????????????£????????????????????£?????????
//??????price??????1000???????????§???????????????????????????
int only1000(int &price) {
return ((price + 1000 - 1) / 1000) * 1000;
}
void doDP() {
rep(k,0,MAX_E)
{
dp[n + 1][k] = P(0, 0);
}
for (int i = n; i >= 1; --i) {
int base = only1000(p[i]);
int pay, ret, get; //get: 500??????????????????????????°(0???1)
rep(ex,0, MAX_E-1000) //1??????1000?????\???????°???????????????\???????????¨?????????
{
P nobuy, buy1000, try500; //???????????§??????????????¢????????§??????3???(????????????, ?°??????????, 500????????????)w
//????????????
nobuy = dp[i + 1][ex];
//??????
// ?°?????????£???????????????
pay = base;
ret = pay - p[i];
get = ret / 500;
ret -= get * 500; //500??????????????????????????????????¶??????????
buy1000 = dp[i + 1][ret + ex]; //?°?????????????????????£????????§???????¶????
buy1000.first += get;
buy1000.second += p[i];
// int ret1000 = ret;
// 500?????????????????????
int usedEx = 0;
pay = base;
ret = pay - p[i];
if (ret >= 500) { //500??????????°?????????¢???????????????
usedEx = 0;
get = ret / 500;
ret -= get * 500;
} else if (ret + ex >= 500) { //?°???????????????°500?????????????????§??????
usedEx = 500 - ret;
pay += usedEx;
ret = pay - p[i]; //??????500??????????????????
get = ret / 500;
ret -= get * 500;
} else {
//1000???????????§?????£???????°????????????£??????500??????????????§?????????
usedEx = 0;
}
try500 = dp[i + 1][ret + ex - usedEx];
try500.first += get;
try500.second += p[i];
P best = max(buy1000, try500, cmp);
best = max(best, nobuy, cmp);
// if (best == nobuy) {
// ch[i][ex] = P(i + 1, ex);
// } else if (best == buy1000) {
// ch[i][ex] = P(i + 1, ret1000);
// } else if (best == try500) {
// ch[i][ex] = P(i + 1, ret);
// }
dp[i][ex] = best;
}
}
}
//void trace() { //???????????????????????°??¨
// int i = 1;
// int ex = 0;
// REP(t,1,4)
// {
// dbp4(i, ex, dp[i][ex].first, dp[i][ex].second);
// P next = ch[i][ex];
// i = next.first;
// ex = next.second;
// }
//}
void solve() {
while (cin >> n, n) {
init();
REP(i,1,n)
{
cin >> p[i];
}
doDP();
cout << dp[1][0].first << " " << dp[1][0].second << endl;
}
}
int main() {
solve();
} |
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define fi first
#define sc second
#define mp make_pair
pair<int,int> dp[105][50005];
int n,p[105];
void chh(pair<int,int> &a,pair<int,int> &b){
if(a.fi < b.fi) a = b;
else if(a.fi == b.fi) a.sc = min(a.sc,b.sc);
}
int main(){
while(1){
cin>>n; if(!n) return 0;
for(int i=1;i<=n;i++) cin>>p[i];
for(int i=0;i<105;i++) for(int j=0;j<50005;j++) dp[i][j] = mp(-10000,100000000);
dp[0][0] = mp(0,0);
for(int i=0;i<n;i++){
for(int j=0;j<50005;j++){
if(dp[i][j].fi < 0) continue; //cout <<i << " " <<j<< endl;
if(dp[i+1][j].fi < dp[i][j].fi) dp[i+1][j] = dp[i][j];
else if(dp[i+1][j].fi == dp[i][j].fi) dp[i+1][j].sc = min(dp[i+1][j].sc,dp[i][j].sc);
if(p[i+1]%1000 == 0){
if(j>=500){
pair<int,int> Q=mp(dp[i][j].fi+1,dp[i][j].sc+p[i+1]) ;
chh(dp[i+1][j-500],Q);
}
}
else if(p[i+1]%1000 <= 500){
pair<int,int> Q=mp(dp[i][j].fi+1,dp[i][j].sc+p[i+1]) ;
chh(dp[i+1][j+500-(p[i+1]%1000)],Q);
}
else{
if(j+500-(p[i+1]%1000)>=0){
pair<int,int> Q=mp(dp[i][j].fi+1,dp[i][j].sc+p[i+1]) ;
chh(dp[i+1][j+500-(p[i+1]%1000)],Q);
}
pair<int,int> Q=mp(dp[i][j].fi,dp[i][j].sc+p[i+1]) ;
chh(dp[i+1][j+1000-(p[i+1]%1000)],Q);
}
}
}
pair<int,int> ans = mp(-10000,100000000);
for(int i=0;i<=n;i++){
for(int j=0;j<50005;j++){
if(ans.fi < dp[i][j].fi) ans = dp[i][j];
else if(ans.fi == dp[i][j].fi) ans.sc = min(ans.sc,dp[i][j].sc);
}}
cout <<ans.fi<<" " << ans.sc << endl;
}
} |
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
P dp[101][50001];
void Max(P &a,P b){a=max(a,b);}
int main(){
int n,p[101];
while(cin>>n,n){
for(int i=0;i<n;i++)cin>>p[i];
memset(dp,-1,sizeof(dp));
dp[0][0]=P(0,0);
for(int i=0;i<n;i++)
for(int j=0;j<50000;j++){
if(dp[i][j]==P(-1,-1))continue;
int coin=dp[i][j].first, ncost=dp[i][j].second-p[i];
Max(dp[i+1][j],dp[i][j]);
if(p[i]%1000<500&&p[i]%1000)Max(dp[i+1][j+(500-p[i]%500)],P(coin+1,ncost));
if(p[i]%1000==0&&j>=500) Max(dp[i+1][j-500],P(coin+1,ncost));
if(p[i]%1000>=500) {
if(j>=p[i]%500)Max(dp[i+1][j-p[i]%500],P(coin+1,ncost));
else Max(dp[i+1][j+(500-p[i]%500)],P(coin,ncost));
}
}
P ans=P(0,0);
for(int i=0;i<50000;i++)Max(ans,dp[n][i]);
cout <<ans.first<<" "<<-ans.second<<endl;
}
return 0;
} |
#include<bits/stdc++.h>
using namespace std;
const int INF = 1 << 30;
bool cmp(pair< int, int > a, pair< int, int > b)
{
if(a.first != b.first) return(a.first > b.first);
return(a.second < b.second);
}
int main()
{
int N, p[100];
while(scanf("%d", &N), N) {
for(int i = 0; i < N; i++) {
scanf("%d", &p[i]);
}
pair< int, int > dp[2][50001];
fill_n(*dp, 2 * 50001, make_pair(-INF, INF));
pair< int, int > *now = dp[0], *nxt = dp[1];
now[0] = {0, 0};
int reach = 0;
for(int i = 0; i < N; i++) {
int mod = p[i] % 1000;
if(1 <= mod && mod <= 500) {
int rev = 1000 - mod - 500;
reach += rev;
for(int j = reach; j >= rev; j--) {
nxt[j] = min(nxt[j], {now[j - rev].first + 1, now[j - rev].second + p[i]}, cmp);
}
} else {
int rev = (1000 - mod) % 1000;
int need = (mod + 500) % 1000;
reach += max(rev, need);
for(int j = reach; j >= 0; j--) {
nxt[j] = min(nxt[j], now[j], cmp);
}
for(int j = reach; j >= rev; j--) {
nxt[j] = min(nxt[j], {now[j - rev].first, now[j - rev].second + p[i]}, cmp);
}
for(int j = need; j <= reach; j++) {
nxt[j - need] = min(nxt[j - need], {now[j].first + 1, now[j].second + p[i]}, cmp);
}
}
swap(now, nxt);
}
auto p = *min_element(now, now + 50000, cmp);
printf("%d %d\n", p.first, p.second);
}
} |
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <string>
#include <deque>
#include <utility>
#include <set>
#include <queue>
#include <functional>
#define REP(i, n) FOR(i, 0, n)
#define FOR(i, a, b) for(int i = int(a); i < int(b); ++i)
#define RREP(i, n) RFOR(i, 0, n)
#define RFOR(i, a, b) for(int i = int(b) - 1; i >= int(a); --i)
#define CHMAX(a, b) a = (a < b ? b : a)
constexpr double EPS = 1e-7;
using PAIR = std::pair<int, int>;
PAIR dp[102][49901];
// dp[i][j] = i番目まで見て小銭をj円持ってる時の(最大500円枚数, そのときの最小消費金額)
signed main() {
while (true) {
int n;
std::cin >> n;
if (n == 0) break;
std::vector<int> p(n);
REP(i, n) std::cin >> p[i];
REP(i, n + 1) REP(j, 49901) dp[i][j] = PAIR(-1, 0);
dp[0][0] = PAIR(0, 0);
REP(i, n) REP(j, 49901) {
if (dp[i][j].first == -1) continue;
CHMAX(dp[i + 1][j], dp[i][j]);
if (p[i] % 1000 > 500) {
CHMAX(dp[i + 1][j + 1000 - p[i] % 1000], PAIR(dp[i][j].first, dp[i][j].second - p[i]));
if (p[i] % 1000 - 500 <= j) {
CHMAX(dp[i + 1][j - (p[i] % 1000 - 500)], PAIR(dp[i][j].first + 1, dp[i][j].second - p[i]));
}
}
else if (p[i] % 1000 == 0) {
if (j >= 500) {
CHMAX(dp[i + 1][j - 500], PAIR(dp[i][j].first + 1, dp[i][j].second - p[i]));
}
}
else {
CHMAX(dp[i + 1][j + 500 - p[i] % 1000], PAIR(dp[i][j].first + 1, dp[i][j].second - p[i]));
}
}
PAIR ans(-1, 0);
REP(j, 49901) CHMAX(ans, dp[n][j]);
std::cout << ans.first << " " << -ans.second << "\n";
}
return 0;
}
|
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
#define INF 100000000
#define OTU 5000
int d[101][OTU][2],oturi,otusum;
bool otu(int p){
int j=0;
while(p>=10000)p-=10000;
while(p>=1000)p-=1000;
while(p>=500){
p-=500;
j++;
}
oturi=500-p;
if(!p)return j%2+1;
return j%2;
}
int main()
{
while(1){
int n,p[102];
cin>>n;
if(!n)return 0;
for(int i=0;i<n;i++){
cin>>p[i+1];
}
otusum=1;
for(int sum=0;sum<101;sum++)
for(int j=0;j<OTU;j++){
d[sum][j][0]=INF;
d[sum][j][1]=INF;
}
d[0][0][0]=0;
for(int i=1;i<=n;i++){
otusum+=500;
otusum=min(otusum,OTU);
if(p[i]%1000==0){
for(int j=0;j<otusum-500;j++){
d[0][j][i%2]=d[0][j][(i-1)%2];
for(int sum=1;sum<=i;sum++)
d[sum][j][i%2]=min(d[sum][j][(i-1)%2],d[sum-1][j+500][(i-1)%2]+p[i]);
}
for(int j=otusum-500;j<otusum;j++)
for(int sum=0;sum<=i;sum++)d[sum][j][i%2]=d[sum][j][(i-1)%2];
continue;
}
if(otu(p[i])){
for(int j=0;j<oturi;j++){
d[0][j][i%2]=d[0][j][(i-1)%2];
for(int sum=1;sum<=i;sum++)
d[sum][j][i%2]=min(d[sum-1][j+500-oturi][(i-1)%2]+p[i],d[sum][j][(i-1)%2]);
}
for(int j=oturi;j<otusum-500+oturi;j++){
d[0][j][i%2]=min(d[0][j][(i-1)%2],d[0][j-oturi][(i-1)%2]+p[i]);
for(int sum=1;sum<=i;sum++)
d[sum][j][i%2]=min(d[sum][j-oturi][(i-1)%2]+p[i],min(d[sum-1][j+500-oturi][(i-1)%2]+p[i],d[sum][j][(i-1)%2]));
}
for(int j=otusum-500+oturi;j<otusum;j++){
d[0][j][i%2]=min(d[0][j][(i-1)%2],d[0][j-oturi][(i-1)%2]+p[i]);
for(int sum=1;sum<=i;sum++)
d[sum][j][i%2]=min(d[sum][j-oturi][(i-1)%2]+p[i],d[sum][j][(i-1)%2]);
}
}
else{
for(int j=0;j<oturi;j++){
d[0][j][i%2]=d[0][j][(i-1)%2];
for(int sum=1;sum<=i;sum++)
d[sum][j][i%2]=d[sum][j][(i-1)%2];
}
for(int j=oturi;j<otusum;j++){
d[0][j][i%2]=d[0][j][(i-1)%2];
for(int sum=1;sum<=i;sum++)
d[sum][j][i%2]=min(d[sum-1][j-oturi][(i-1)%2]+p[i],d[sum-1][j][(i-1)%2]+p[i]);
}
}
// int ans=INF;
//for(int sum=100;sum>=0;sum--){
// for(int j=0;j<1000;j++){
// ans=min(d[sum][j][i%2],ans);
// if(d[sum][j][i%2]<INF)
//cout<<"i "<<i<<" sum "<<sum<<" ans "<<ans<<" oturi "<<j<<endl;
//}
//if(ans<INF){
// cout<<"I "<<i<<" sum "<<sum<<" ans "<<ans<<endl;
//break;
// }
//}
}
int ans=INF;
for(int sum=100;sum>=0;sum--){
for(int j=0;j<OTU;j++){
ans=min(d[sum][j][n%2],ans);
}
if(ans<INF){
cout<<sum<<" "<<ans<<endl;
break;
}
}
}
}
|
#include <bits/stdc++.h>
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,n) FOR(i,0,n)
using namespace std;
const int INF = 1e7;
typedef pair<int,int> P;
int main(){
int n;
while(cin >> n, n){
vector<vector<P>> dp(n+1,vector<P>(55000,P(0,-INF)));
dp[0][0]=P(0,0);
for(int i=0;i<n;i++){
int p;
cin >> p;
for(int j=0;j<=50000;j++){
if(dp[i][j].second<=-INF)
continue;
dp[i+1][j]=max(dp[i+1][j], dp[i][j]);
int fee=(p+999)/1000*1000;
int back=fee-p;
int get= back+j>=500 ? 1 : 0;
int rest=(back+j)-get*500;
//cout << fee << " " << back << " " << get << " " << rest << endl;
dp[i+1][rest]=max(dp[i+1][rest], P(dp[i][j].first+get,dp[i][j].second-p));
}
}
P ans=P(0,-INF);
for(int i=0;i<50000;i++)
ans=max(ans,dp[n][i]);
cout << ans.first << " " << -ans.second << endl;
}
return 0;
} |
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
while (cin >> N, N) {
vector<vector<pair<int, int>>>dp(N + 1, vector<pair<int,int>>(101000, make_pair(INT_MIN / 6, INT_MAX / 6)));
dp[0][0] = make_pair(0, 0);
for (int i = 0; i < N; i++) {
int p;
cin >> p;
int q = p;
int num1000 = p / 1000;
p %= 1000;
// 500???????????°???????????´???
for (int j = 0; j < 100000 - p; j++) {
if (dp[i + 1][j + (1000 - p) % 1000].first < dp[i][j].first || (dp[i + 1][j + (1000 - p) % 1000].first == dp[i][j].first && dp[i + 1][j + (1000 - p) % 1000].second > dp[i][j].second + q) ) {
dp[i + 1][j + (1000 - p) % 1000].first = dp[i][j].first;
dp[i + 1][j + (1000 - p) % 1000].second = dp[i][j].second + q;
}
}
// 500????????????????????´???
if (p == 0) {
for (int j = 500 ; j < 100000; j++) {
if (dp[i + 1][j - 500].first < dp[i][j].first + 1 || (dp[i + 1][j - 500].first == dp[i][j].first + 1 && dp[i + 1][j - 500].second > dp[i][j].second + q)) {
dp[i + 1][j - 500].first = dp[i][j].first + 1;
dp[i + 1][j - 500].second = dp[i][j].second + q;
}
}
} else if (p >= 500) {
for (int j = p - 500 ; j < 100000; j++) {
if (dp[i + 1][j + 500 - p].first < dp[i][j].first + 1 || (dp[i + 1][j + 500 - p].first == dp[i][j].first + 1 && dp[i + 1][j + 500 - p].second > dp[i][j].second + q)) {
dp[i + 1][j + 500 - p].first = dp[i][j].first + 1;
dp[i + 1][j + 500 - p].second = dp[i][j].second + q;
}
}
} else {
for (int j = 0; j < 100000; j++) {
if (dp[i + 1][j + 500 - p].first < dp[i][j].first + 1 || (dp[i + 1][j + 500 - p].first == dp[i][j].first + 1 && dp[i + 1][j + 500 - p].second > dp[i][j].second + q)) {
dp[i + 1][j + 500 - p].first = dp[i][j].first + 1;
dp[i + 1][j + 500 - p].second = dp[i][j].second + q;
}
}
}
// ????????????????????´???
for (int j = 0; j < 100000; j++) {
if (dp[i + 1][j].first < dp[i][j].first || (dp[i + 1][j].first == dp[i][j].first && dp[i + 1][j].second > dp[i][j].second)) {
dp[i + 1][j] = dp[i][j];
}
}
}
pair<int,int>ans = make_pair(INT_MIN, INT_MAX / 6);
for (int j = 0; j < 101000; j++) {
if (ans.first < dp[N][j].first || (ans.first == dp[N][j].first && ans.second > dp[N][j].second)) {
ans = dp[N][j];
}
}
cout<<ans.first<<" "<<ans.second<<endl;
}
} |
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
//INSERT ABOVE HERE
signed main(){
int n;
while(cin>>n,n){
vector<int> ps(n);
for(int i=0;i<n;i++) cin>>ps[i];
const int MAX = 600;
const int INF = 1e9;
vector< vector<int> > dp(n+1,vector<int>(MAX,INF));
dp[0][0]=0;
for(int p:ps){
int q=p%1000;
for(int i=n-1;i>=0;i--){
for(int j=MAX-1;j>=0;j--){
if(dp[i][j]==INF) continue;
int coin=j*1000-dp[i][j]-i*500;
assert(coin>=0);
int k=(p+999)/1000;
// get 500 yen
if((q==0&&500<=coin)||(0<q&&q<=500)||(500<q&&q%500<=coin))
chmin(dp[i+1][j+k],dp[i][j]+p);
// no 500 yen
chmin(dp[i][j+k],dp[i][j]+p);
}
}
}
for(int i=n;i>=0;i--){
int res=INF;
for(int j=0;j<MAX;j++)
chmin(res,dp[i][j]);
if(res==INF) continue;
cout<<i<<" "<<res<<endl;
break;
}
}
return 0;
}
|
#include<bits/stdc++.h>
#define fi first
#define se second
typedef long long ll;
using namespace std;
pair<int,int> dp[2][200001];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
while(cin>>n,n){
int a[201];
fill(a,a+201,0);
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=0;i<=200000;i++)dp[0][i]=make_pair(-1,0);
dp[0][0]=make_pair(0,0);
for(int i=0;i<n;i++){
for(int j=0;j<=200000;j++)dp[(i+1)&1][j]=make_pair(-1,0);
for(int j=0;j<=200000;j++){
if(dp[i&1][j].fi==-1)continue;
int tmp=a[i]%1000;
if(tmp<=500 && tmp>=1)
dp[(i+1)&1][j+500-tmp]=max(make_pair(dp[i&1][j].fi+1,dp[i&1][j].se-a[i]),dp[(i+1)&1][j+500-tmp]);
else{
int pay=(tmp+500)%1000;
dp[(i+1)&1][j]=max(dp[(i+1)&1][j],dp[i&1][j]);
if(pay<=j)
dp[(i+1)&1][j-pay]=max(make_pair(dp[i&1][j].fi+1,dp[i&1][j].se-a[i]),dp[(i+1)&1][j-pay]);
int pay2=(1000-tmp)%1000;
dp[(i+1)&1][j+pay2]=max(make_pair(dp[i&1][j].fi,dp[i&1][j].se-a[i]),dp[(i+1)&1][j+pay2]);
}
}
}
pair<int,int> ans=make_pair(0,0);
for(int i=0;i<=200000;i++){
if(dp[n&1][i]>ans){
ans=make_pair(dp[n&1][i].fi,dp[n&1][i].se);
}
}
cout<<ans.fi<<" "<<-ans.se<<endl;
}
return 0;
}
|
// Ryo Kamoi
// #define DEBUG
#include<iostream>
#include<math.h>
#include<vector>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
using namespace std;
#define REP(i, n) for(int i=0; i<n; i++)
typedef pair<int, int> pii;
typedef long long ll;
typedef pair<ll, ll> pll;
int INF = 1000000000;
int n;
int p[101];
int res_[101];
int rt_[101];
pii dp[500*100+1];
pii prevdp[500*100+1];
int main(){
while(1) {
cin >> n;
if (n==0) break;
p[0] = INF; // not used
REP(i, n) {
cin >> p[i+1];
}
REP(k, 500*n+1) {
prevdp[k] = pii(0, INF);
dp[k] = pii(0, INF);
}
prevdp[0] = pii(0, 0);
for(int i=1; i<=n; i++) {
REP(k, 500*n+1) {
int res = p[i] % 1000;
int rt = 1000 - res;
if (rt == 1000) {
res = 1000;
rt = 0;
}
dp[k] = prevdp[k];
if (rt >= 500) {
if (k>=(rt-500)) {
pii prev = prevdp[k-(rt-500)];
if (prev.second >= INF) continue;
if (dp[k].first == prev.first+1) {
dp[k] = pii(prev.first+1, min(dp[k].second, prev.second+p[i]));
} else if (dp[k].first < prev.first+1) {
dp[k] = pii(prev.first+1, prev.second+p[i]);
}
}
} else {
if (k<=500*n-(res-500)) {
pii prev = prevdp[k+(res-500)];
if (prev.second < INF) {
if (dp[k].first < prev.first + 1) {
dp[k].first = prev.first+1;
dp[k].second = prev.second + p[i];
} else if (dp[k].first == prev.first + 1) {
dp[k].second = min(dp[k].second, prev.second+p[i]);
}
}
}
if (k>=rt) {
pii prev = prevdp[k-rt];
if (prev.second < INF) {
if (dp[k].first == prev.first) {
dp[k].second = min(dp[k].second, prev.second + p[i]);
} else if (dp[k].first < prev.first) {
dp[k].first = prev.first;
dp[k].second = prev.second + p[i];
}
}
}
}
}
REP(k, 500*n+1) {
prevdp[k] = dp[k];
}
}
int maxnum = 0;
int price;
REP(k, 500*n+1) {
if (dp[k].second >= INF) {
continue;
}
if (dp[k].first > maxnum) {
maxnum = dp[k].first;
price = dp[k].second;
} else if (dp[k].first == maxnum) {
price = min(price, dp[k].second);
}
}
cout << maxnum << " " << price << endl;
}
}
|
//#pragma GCC optimize("Ofast,unroll-loops")
//#pragma GCC target("avx")
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
typedef pair<int, int> i_i;
vector<i_i> Prev(100001), Next(100001);
int main() {
while(true) {
int n;
cin >> n;
if(n == 0) break;
for(int i = 0; i <= 100000; i++) {
Prev[i] = {-INF,0};
Next[i] = {-INF,0};
}
Prev[0] = {0, 0};
for(int i = 1; i <= n; i++) {
int p;
cin >> p;
int nowchange = 1000 - ((p + 999) % 1000 + 1);
//cerr << "P:" << p << endl;
for(int change = 0; change <= 100000; change++) {
/*
for(int num = 0; num <= i; num++) {
Next[change][num] = Prev[change][num];
if(nowchange >= 500) {
if(change - nowchange + 500 >= 0 && num - 1 >= 0) {
Next[change][num] = min(Next[change][num], Prev[change - nowchange + 500][num-1] + p);
}
} else {
if(change - nowchange >= 0) {
Next[change][num] = min(Next[change][num], Prev[change - nowchange][num] + p);
}
if(change + 500 - nowchange <= 1000 * i && num - 1 >= 0) {
Next[change][num] = min(Next[change][num], Prev[change + 500 - nowchange][num-1] + p);
}
}
}
}
*/
Next[change] = Prev[change];
if(nowchange >= 500) {
if(change - nowchange + 500 >= 0) {
i_i tmp = Prev[change-nowchange+500];
tmp.second -= p;
tmp.first++;
Next[change] = max(Next[change], tmp);
}
} else {
if(change - nowchange >= 0) {
i_i tmp = Prev[change-nowchange];
tmp.second -= p;
Next[change] = max(Next[change], tmp);
}
if(change + 500 - nowchange <= 100000) {
i_i tmp = Prev[change + 500 - nowchange];
tmp.second -= p;
tmp.first++;
Next[change] = max(Next[change], tmp);
}
}
}
swap(Next, Prev);
}
/*
int ansnum = 0;
int ansval = 0;
for(int change = 0; change <= 100000; change++) {
for(int num = 0; num <= 100; num++) {
if(Prev[change][num] < INF) {
if(num > ansnum) {
ansval = Prev[change][num];
ansnum = num;
} else if(num == ansnum && ansval > Prev[change][num]) {
ansval = Prev[change][num];
}
}
}
}
*/
i_i ans = {0, 0};
for(int change = 0; change <= 100000; change++) {
ans = max(ans, Prev[change]);
}
cout << ans.first << " " << -ans.second << endl;
}
}
|
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <map>
#include <set>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <bitset>
#include <climits>
#define REP(i,n) for (int i=0;i<(n);i++)
#define FOR(i,a,b) for (int i=(a);i<(b);i++)
#define RREP(i,n) for (int i=(n)-1;i>=0;i--)
#define RFOR(i,a,b) for (int i=(a)-1;i>=(b);i--)
#define ll long long
#define ull unsigned long long
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
const int INF = 1e9;
const int MOD = 1e9 + 7;
using namespace std;
const int MAXN = 500003;
pair<int,int> maxa(pair<int,int> a, int f,int s,pair<int,int> b){
if(f)a.first++;
a.second+=s;
if(a.first > b.first)return a;
else if(a.first == b.first){
if(a.second < b.second)return a;
else return b;
}else return b;
}
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
int n;
while(cin>>n,n){
vector<int> p(n);
REP(i,n)cin>>p[i];
pair<int,int> dp[2][MAXN + 503];
fill(dp[0],dp[2],make_pair(0,INF));// num of 500 and imamade ni tukatta okane
dp[1][0] = make_pair(0,0);
REP(i,n){
fill(dp[i&1],dp[i&1] + MAXN,make_pair(0,INF));// num of 500 and imamade ni tukatta okane
for(int j = MAXN;j >= 0;j--){
if(p[i] % 1000 <= 500 && p[i] % 1000 > 0 && (dp[(i+1)&1][j].second != INF || j==0) ){
dp[i&1][j + (5000-p[i])%500] = maxa(dp[(i+1)&1][j],1,p[i],dp[i&1][j + (5000-p[i])%500]);
//toriaezu 1000(+500)
}else{
if(p[i] %1000 > 0 && dp[(i+1)&1][j + p[i]%500].second != INF){
dp[i&1][j] = maxa(dp[(i+1)&1][j + p[i]%500],1,p[i],dp[i&1][j]);
}//1000n + iikanjino
if(p[i] %1000 == 0 && dp[(i+1)&1][j + 500].second != INF){
dp[i&1][j] = maxa(dp[(i+1)&1][j + 500],1,p[i],dp[i&1][j]);
}// 1000n + 500
if(dp[(i+1)&1][j].second != INF || j==0)//toriaezu 1000(not +500)
dp[i&1][j + (5000-p[i])%500] = maxa(dp[(i+1)&1][j],0,p[i],dp[i&1][j + (5000-p[i])%500]);
}
dp[i&1][j] = maxa(dp[i&1][j],0,0,dp[(i+1)&1][j]);
}
}
pair<int,int> ans = make_pair(0,0);
for(int j = MAXN + 500;j >= 0;j--){
ans = maxa(dp[(n-1)&1][j],0,0,ans);
}
cout << ans.first << ' ' << ans.second << endl;
}
return 0;
} |
#include<bits/stdc++.h>
using namespace std;
const int INF = 1 << 30;
bool cmp(pair< int, int > a, pair< int, int > b)
{
if(a.first != b.first) return(a.first > b.first);
return(a.second < b.second);
}
int main()
{
int N, p[100];
while(scanf("%d", &N), N) {
for(int i = 0; i < N; i++) {
scanf("%d", &p[i]);
}
pair< int, int > dp[2][50001];
fill_n(*dp, 2 * 50001, make_pair(-INF, INF));
pair< int, int > *now = dp[0], *nxt = dp[1];
now[0] = {0, 0};
int reach = 0;
for(int i = 0; i < N; i++) {
int mod = p[i] % 1000;
if(1 <= mod && mod <= 500) {
int rev = 1000 - mod - 500;
reach += rev;
for(int j = reach; j >= rev; j--) {
nxt[j] = min(nxt[j], {now[j - rev].first + 1, now[j - rev].second + p[i]}, cmp);
}
} else {
int rev = (1000 - mod) % 1000;
int need = (mod + 500) % 1000;
reach += max(rev, need);
for(int j = reach; j >= 0; j--) {
nxt[j] = min(nxt[j], now[j], cmp);
}
for(int j = reach; j >= rev; j--) {
nxt[j] = min(nxt[j], {now[j - rev].first, now[j - rev].second + p[i]}, cmp);
}
for(int j = need; j <= reach; j++) {
nxt[j - need] = min(nxt[j - need], {now[j].first + 1, now[j].second + p[i]}, cmp);
}
}
swap(now, nxt);
for(int j = 0; j <= reach; j++) nxt[j] = {-INF, INF};
}
auto p = *min_element(now, now + 50000, cmp);
printf("%d %d\n", p.first, p.second);
}
} |
#include <bits/stdc++.h>
// dp[i][500yen][num_1000yen] := remain ([i] is deleted)
int dp[128][512];
int n;
int P[128];
void init() {
for(int j = 0; j < 128; ++j) {
for(int k = 0; k < 512; ++k) {
dp[j][k] = -1;
}
}
}
int main() {
for(;;) {
init();
scanf("%d", &n);
if( n == 0 ) break;
for(int i = 0; i < n; ++i) {
scanf("%d", &P[i]);
}
dp[0][0] = 0;
for(int i = 0; i < n; ++i) {
for(int j = n-1; j >= 0; --j) {
for(int k = 512 - 1; k >= 0; --k) {
if( dp[j][k] == -1 ) continue;
int n1kyen = (P[i] + 999) / 1000;
int rem = dp[j][k] + n1kyen * 1000 - P[i];
int next_num500yen = j + (rem >= 500 ? 1 : 0);
int next_num1kyen = k + n1kyen;
int next_rem = rem >= 500 ? rem - 500 : rem;
int& next = dp[next_num500yen][next_num1kyen];
next = std::max(next, next_rem);
}
}
}
int res = (1 << 28);
int max = -1;
for(int j = n; j >= 0; --j) {
for(int k = 0; k < 512; ++k) {
if( dp[j][k] == -1 ) continue;
int cost = k * 1000 - 500 * j - dp[j][k];
res = std::min(res, cost);
}
if( res != (1 << 28) ) {
max = j;
break;
}
}
printf("%d %d\n", max, res);
}
return 0;
} |
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
int N;
void solve() {
vector<int> shop(N);
for (auto& i : shop) cin >> i;
vector<int> diff(N);
for (int i = 0; i < N; i++) {
int d = shop[i] % 1000;
if (d == 0) diff[i] = 500;
else if (d < 500) diff[i] = 0;
else diff[i] = d - 500;
}
vector<vector<P> > dp(N + 1, vector<P>(500 * N + 1, P(-1, 0)));
dp[0][0] = P(0, 0);
for (int i = 0; i < N; i++) {
for (int j = 0; j <= 500 * i; j++) {
auto coin = dp[i][j];
if (coin.first == - 1) continue;
dp[i+1][j] = max(dp[i+1][j], coin);
if (diff[i] == 0) {
P ncoin = P(coin.first + 1, coin.second - shop[i]);
int f = j + 500 - (shop[i] % 1000);
dp[i+1][f] = max(dp[i+1][f], ncoin);
} else {
if (diff[i] <= j) {
P ncoin = P(coin.first + 1, coin.second - shop[i]);
int f = j - diff[i];
dp[i+1][f] = max(dp[i+1][f], ncoin);
}
P pcoin = P(coin.first, coin.second - shop[i]);
int f_ = j + (shop[i] % 1000 ? 1000 - shop[i] % 1000 : 0);
dp[i+1][f_] = max(dp[i+1][f_], pcoin);
}
}
}
P ans(0, 0);
for (auto p : dp[N]) {
ans = max(ans, p);
}
cout << ans.first << " " << -ans.second << endl;
}
int main() {
while (cin >> N, N) solve();
return 0;
} |
#include <bits/stdc++.h>
using namespace std;
const int MAX = 500;
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
int n;
while (cin >> n, n) {
vector<vector<int>> dp(MAX + 1, vector<int>(n + 1, -1));
dp[0][0] = 0;
for (int i = 0; i < n; i++) {
int p;
cin >> p;
for (int j = MAX; j >= 0; j--) {
for (int k = n; k >= 0; k--) if (dp[j][k] != -1) {
int val = (p + 999) / 1000;
if (p % 1000 != 0 && p % 1000 <= 500) {
dp[j + val][k + 1] = max(dp[j + val][k + 1], dp[j][k] + val * 1000 - p - 500);
}
else {
dp[j + val][k] = max(dp[j + val][k], dp[j][k] + val * 1000 - p);
if (val * 1000 - p + dp[j][k] >= 500) {
dp[j + val][k + 1] = max(dp[j + val][k + 1], dp[j][k] + val * 1000 - p - 500);
}
}
}
}
}
int cnt = 0, sum = 0;
for (int i = 0; i <= MAX; i++) {
for (int j = 0; j <= n; j++) if (dp[i][j] != -1) {
if (j > cnt) {
cnt = j;
sum = i * 1000 - j * 500 - dp[i][j];
}
else if (j == cnt) {
sum = min(sum, i * 1000 - j * 500 - dp[i][j]);
}
}
}
cout << cnt << ' ' << sum << endl;
}
return 0;
}
|
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const double EPS = 1e-12;
const int INF = numeric_limits<int>::max()/2;
const int MOD = 1e9+7;
struct State{
int count,price;
State(int count, int price): count(count),price(price){}
};
bool operator < (const State &e, const State &f){
return e.count!=f.count ? e.count < f.count : e.price>f.price;
}
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
int n;
while(cin>>n,n){
vector<int> p(n+1);
for(int i=1;i<=n;i++) cin>>p[i];
vector<vector<State>> dp(n+1,vector<State>(66666,State(-1,0)));
dp[0][0]=State(0,0);
for(int i=0;i<n;i++){
for(int j=0;j<=50000;j++){
int cnt=dp[i][j].count,pri=dp[i][j].price;
if(cnt<0) continue;
dp[i+1][j]=max(dp[i+1][j],dp[i][j]);
int r=(1000-p[i+1]%1000)%1000;
dp[i+1][j+r]=max(dp[i+1][j+r],State(cnt,pri+p[i+1]));
if(j+r>=500) dp[i+1][(j+r)-500]=max(dp[i+1][(j+r)-500],State(cnt+1,pri+p[i+1]));
}
}
State res=dp[n][0];
for(int i=1;i<=50000;i++) res=max(res,dp[n][i]);
cout<<res.count<<" "<<res.price<<endl;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.