結果

問題 No.5007 Steiner Space Travel
ユーザー komori3komori3
提出日時 2022-07-30 16:49:52
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 952 ms / 1,000 ms
コード長 13,805 bytes
コンパイル時間 4,589 ms
実行使用メモリ 6,952 KB
スコア 8,473,954
最終ジャッジ日時 2022-07-30 16:50:28
合計ジャッジ時間 35,837 ms
ジャッジサーバーID
(参考情報)
judge11 / judge10
純コード判定しない問題か言語
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 952 ms
4,900 KB
testcase_01 AC 952 ms
6,948 KB
testcase_02 AC 951 ms
4,900 KB
testcase_03 AC 952 ms
4,904 KB
testcase_04 AC 952 ms
4,900 KB
testcase_05 AC 951 ms
4,900 KB
testcase_06 AC 952 ms
4,904 KB
testcase_07 AC 952 ms
6,948 KB
testcase_08 AC 952 ms
4,900 KB
testcase_09 AC 952 ms
4,900 KB
testcase_10 AC 952 ms
4,904 KB
testcase_11 AC 952 ms
4,904 KB
testcase_12 AC 952 ms
6,948 KB
testcase_13 AC 952 ms
6,952 KB
testcase_14 AC 952 ms
6,952 KB
testcase_15 AC 952 ms
6,952 KB
testcase_16 AC 952 ms
4,904 KB
testcase_17 AC 951 ms
6,952 KB
testcase_18 AC 952 ms
4,900 KB
testcase_19 AC 952 ms
4,900 KB
testcase_20 AC 952 ms
4,904 KB
testcase_21 AC 952 ms
4,900 KB
testcase_22 AC 952 ms
4,900 KB
testcase_23 AC 952 ms
4,900 KB
testcase_24 AC 952 ms
4,900 KB
testcase_25 AC 951 ms
6,948 KB
testcase_26 AC 952 ms
6,948 KB
testcase_27 AC 952 ms
6,948 KB
testcase_28 AC 952 ms
6,952 KB
testcase_29 AC 951 ms
4,904 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#define _CRT_NONSTDC_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
#include <random>
#include <unordered_set>
#include <atcoder/all>
//#include <boost/rational.hpp>
//#include <boost/multiprecision/cpp_int.hpp>
//#include <boost/multiprecision/cpp_bin_float.hpp>
#ifdef _MSC_VER
#include <conio.h>
#include <ppl.h>
#include <filesystem>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <intrin.h>
int __builtin_clz(unsigned int n)
{
    unsigned long index;
    _BitScanReverse(&index, n);
    return 31 - index;
}
int __builtin_ctz(unsigned int n)
{
    unsigned long index;
    _BitScanForward(&index, n);
    return index;
}
namespace std {
    inline int __lg(int __n) { return sizeof(int) * 8 - 1 - __builtin_clz(__n); }
}
#else
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#endif

/** compro_io **/

/* tuple */
// out
namespace aux {
    template<typename T, unsigned N, unsigned L>
    struct tp {
        static void output(std::ostream& os, const T& v) {
            os << std::get<N>(v) << ", ";
            tp<T, N + 1, L>::output(os, v);
        }
    };
    template<typename T, unsigned N>
    struct tp<T, N, N> {
        static void output(std::ostream& os, const T& v) { os << std::get<N>(v); }
    };
}
template<typename... Ts>
std::ostream& operator<<(std::ostream& os, const std::tuple<Ts...>& t) {
    os << '[';
    aux::tp<std::tuple<Ts...>, 0, sizeof...(Ts) - 1>::output(os, t);
    return os << ']';
}

template<class Ch, class Tr, class Container>
std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& os, const Container& x);

/* pair */
// out
template<class S, class T>
std::ostream& operator<<(std::ostream& os, const std::pair<S, T>& p) {
    return os << "[" << p.first << ", " << p.second << "]";
}
// in
template<class S, class T>
std::istream& operator>>(std::istream& is, std::pair<S, T>& p) {
    return is >> p.first >> p.second;
}

/* container */
// out
template<class Ch, class Tr, class Container>
std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& os, const Container& x) {
    bool f = true;
    os << "[";
    for (auto& y : x) {
        os << (f ? "" : ", ") << y;
        f = false;
    }
    return os << "]";
}
// in
template <
    class T,
    class = decltype(std::begin(std::declval<T&>())),
    class = typename std::enable_if<!std::is_same<T, std::string>::value>::type
>
std::istream& operator>>(std::istream& is, T& a) {
    for (auto& x : a) is >> x;
    return is;
}

std::ostream& operator<<(std::ostream& os, const std::vector<bool>& v) {
    std::string s(v.size(), ' ');
    for (int i = 0; i < v.size(); i++) s[i] = v[i] + '0';
    os << s;
    return os;
}

std::ostream& operator<<(std::ostream& os, const std::vector<std::vector<bool>>& m) {
    for (const auto& v : m) os << v << '\n';
    return os;
}

/* struct */
template<typename T>
auto operator<<(std::ostream& out, const T& t) -> decltype(out << t.stringify()) {
    out << t.stringify();
    return out;
}

/* setup */
struct IOSetup {
    IOSetup(bool f) {
        if (f) { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); }
        std::cout << std::fixed << std::setprecision(15);
    }
} iosetup(true);

/** string formatter **/
template<typename... Ts>
std::string format(const std::string& f, Ts... t) {
    size_t l = std::snprintf(nullptr, 0, f.c_str(), t...);
    std::vector<char> b(l + 1);
    std::snprintf(&b[0], l + 1, f.c_str(), t...);
    return std::string(&b[0], &b[0] + l);
}

template<typename T>
std::string stringify(const T& x) {
    std::ostringstream oss;
    oss << x;
    return oss.str();
}

/* dump */
#define DUMPOUT std::cerr
std::ostringstream DUMPBUF;
#define dump(...) do{DUMPBUF<<"  ";DUMPBUF<<#__VA_ARGS__<<" :[DUMP - "<<__LINE__<<":"<<__FUNCTION__<<"]"<<std::endl;DUMPBUF<<"    ";dump_func(__VA_ARGS__);DUMPOUT<<DUMPBUF.str();DUMPBUF.str("");DUMPBUF.clear();}while(0);
void dump_func() { DUMPBUF << std::endl; }
template <class Head, class... Tail> void dump_func(Head&& head, Tail&&... tail) { DUMPBUF << head; if (sizeof...(Tail) == 0) { DUMPBUF << " "; } else { DUMPBUF << ", "; } dump_func(std::move(tail)...); }

/* timer */
class Timer {
    double t = 0, paused = 0, tmp;
public:
    Timer() { reset(); }
    static double time() {
#ifdef _MSC_VER
        return __rdtsc() / 2.3e9;
#else
        unsigned long long a, d;
        __asm__ volatile("rdtsc"
            : "=a"(a), "=d"(d));
        return (d << 32 | a) / 2.3e9;
#endif
    }
    void reset() { t = time(); }
    void pause() { tmp = time(); }
    void restart() { paused += time() - tmp; }
    double elapsed_ms() const { return (time() - t - paused) * 1000.0; }
} timer;

/* rand */
struct Xorshift {
    uint64_t x = 88172645463325252LL;
    void set_seed(unsigned seed, int rep = 100) { x = uint64_t((seed + 1) * 10007); for (int i = 0; i < rep; i++) next_int(); }
    unsigned next_int() { x = x ^ (x << 7); return x = x ^ (x >> 9); }
    unsigned next_int(unsigned mod) { x = x ^ (x << 7); x = x ^ (x >> 9); return x % mod; }
    unsigned next_int(unsigned l, unsigned r) { x = x ^ (x << 7); x = x ^ (x >> 9); return x % (r - l + 1) + l; } // inclusive
    double next_double() { return double(next_int()) / UINT_MAX; }
} rnd;

/* shuffle */
template<typename T>
void shuffle_vector(std::vector<T>& v, Xorshift& rnd) {
    int n = v.size();
    for (int i = n - 1; i >= 1; i--) {
        int r = rnd.next_int(i);
        std::swap(v[i], v[r]);
    }
}

/* split */
std::vector<std::string> split(std::string str, const std::string& delim) {
    for (char& c : str) if (delim.find(c) != std::string::npos) c = ' ';
    std::istringstream iss(str);
    std::vector<std::string> parsed;
    std::string buf;
    while (iss >> buf) parsed.push_back(buf);
    return parsed;
}

template<typename A, size_t N, typename T> inline void Fill(A(&array)[N], const T& val) {
    std::fill((T*)array, (T*)(array + N), val);
}

template<typename T, typename ...Args> auto make_vector(T x, int arg, Args ...args) { if constexpr (sizeof...(args) == 0)return std::vector<T>(arg, x); else return std::vector(arg, make_vector<T>(x, args...)); }
template<typename T> bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } return false; }
template<typename T> bool chmin(T& a, const T& b) { if (a > b) { a = b; return true; } return false; }

using ll = long long;
using ull = unsigned long long;
using ld = double;
//using ld = boost::multiprecision::cpp_bin_float_quad;
using pii = std::pair<int, int>;
using pll = std::pair<ll, ll>;
using namespace std;



template<typename T>
void print_vector(const std::vector<T>& v) {
    for (int i = 0; i < v.size(); i++) {
        std::cout << (i ? " " : "") << v[i];
    }
    std::cout << '\n';
}

double lrnd[1 << 16];

void init() {
    Xorshift rnd;
    for (int i = 0; i < 100; i++) rnd.next_int();
    for (int i = 0; i < (1 << 16); i++) lrnd[i] = log(rnd.next_double());
}

constexpr int N = 100;
constexpr int M = 8;
constexpr int alpha = 5;
constexpr int alpha2 = alpha * alpha;
int xs[N], ys[N];
int ds[N][N];

inline int dist2(int x1, int y1, int x2, int y2) {
    return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}

struct TSP {

    Xorshift& rnd;

    int score;
    vector<int> p;

    TSP(Xorshift& rnd) : rnd(rnd) {
        score = 0;
        p.resize(N);
        for (int i = 0; i < N; i++) {
            score += ds[i][(i + 1) % N];
            p[i] = i;
        }
    }

    inline int dist(int i1, int i2) {
        return ds[i1][i2];
    }

    double calc_2opt_diff(int idx1, int idx2) {
        int p1 = p[idx1], p2 = p[(idx1 + 1) % N], p3 = p[idx2], p4 = p[(idx2 + 1) % N];
        return dist(p1, p3) + dist(p2, p4) - dist(p1, p2) - dist(p3, p4);
    }

    void solve_2opt_climbing() {
        while (true) {
            bool update = false;
            for (int i1 = 0; i1 < N - 1; i1++) {
                for (int i2 = i1 + 1; i2 < N; i2++) {
                    int diff = calc_2opt_diff(i1, i2);
                    if (diff < 0) {
                        reverse(p.begin() + i1 + 1, p.begin() + i2 + 1);
                        score += diff;
                        update = true;
                    }
                }
            }
            if (!update) break;
        }
    }

    double get_temp(double startTemp, double endTemp, int t, int T) {
        return endTemp + (startTemp - endTemp) * (T - t) / T;
    }

    void solve_2opt_annealing(int numLoop) {
        double bestScore = DBL_MAX;
        vector<int> bp;
        for (int n = 0; n < numLoop; n++) {
            int i1 = rnd.next_int() % N;
            int i2 = rnd.next_int() % (N - 1);
            if (i2 >= i1) i2++;
            if (i1 > i2) swap(i1, i2);

            double diff = calc_2opt_diff(i1, i2);

            double temp = get_temp(10000.0, 1.0, n, numLoop);
            double x = -diff / temp;

            if (-diff > temp * lrnd[n & 0xFFFF]) {
                reverse(p.begin() + i1 + 1, p.begin() + i2 + 1);
                score += diff;
                if (score < bestScore) {
                    bestScore = score;
                    bp = p;
                }
            }

            if (!(n & 0x3FFFFF)) {
                //dump(n, score);
            }
        }
        score = bestScore;
        //dump(score);
        p = bp;
    }

};

struct KMeansRetVal {
    int cxs[M];
    int cys[M];
    int cluster[N];
};

KMeansRetVal kmeans() {

    int cxs[M] = {};
    int cys[M] = {};
    int nc = 0;
    double prob[N]; Fill(prob, 1.0 / N);

    double cumu[N];
    auto sampling = [&]() {
        memset(cumu, 0, sizeof(double) * N);
        for (int i = 1; i < N; i++) cumu[i] = cumu[i - 1] + prob[i - 1];
        double d = rnd.next_double() * cumu[N - 1];
        int idx = distance(cumu, upper_bound(cumu, cumu + N, d)) - 1;
        return idx;
    };

    auto nearest_centroid = [&](int x, int y) {
        int mindist = INT_MAX;
        int minidx = -1;
        for (int i = 0; i < nc; i++) {
            int dist = dist2(x, y, cxs[i], cys[i]);
            if (chmin(mindist, dist)) {
                minidx = i;
            }
        }
        return minidx;
    };

    for (int i = 0; i < M; i++) {
        int idx = sampling();
        cxs[i] = xs[idx];
        cys[i] = ys[idx];
        nc++;
        // update prob
        int sum = 0;
        for (int j = 0; j < N; j++) {
            int nearest = nearest_centroid(xs[j], ys[j]);
            int weight = dist2(xs[j], ys[j], cxs[nearest], cys[nearest]);
            prob[j] = weight;
            sum += weight;
        }
        for (int j = 0; j < N; j++) prob[j] /= sum;
    }

    int cluster[N];
    for (int i = 0; i < N; i++) cluster[i] = nearest_centroid(xs[i], ys[i]);

    while (true) {
        int xmean[M] = {}, ymean[M] = {};
        int ctr[M] = {};
        for (int i = 0; i < N; i++) {
            int c = cluster[i];
            xmean[c] += xs[i];
            ymean[c] += ys[i];
            ctr[c]++;
        }
        for (int c = 0; c < M; c++) {
            if (!ctr[c]) continue;
            cxs[c] = xmean[c] / ctr[c];
            cys[c] = ymean[c] / ctr[c];
        }
        bool update = false;
        for (int i = 0; i < N; i++) {
            int idx = nearest_centroid(xs[i], ys[i]);
            if (cluster[i] != idx) update = true;
            cluster[i] = idx;
        }
        if (!update) break;
    }

    KMeansRetVal res;
    memcpy(res.cxs, cxs, sizeof(int) * M);
    memcpy(res.cys, cys, sizeof(int) * M);
    memcpy(res.cluster, cluster, sizeof(int) * N);

    return std::move(res);
}

int main() {

    //ifstream ifs(R"(C:\Users\komori3\OneDrive\dev\compro\atcoder\env\misc\steiner-space-travel\input\0002.txt)");
    //istream& cin = ifs;

    Timer timer;

    init();

    { int buf; cin >> buf >> buf; }
    for (int i = 0; i < N; i++) cin >> xs[i] >> ys[i];
    for (int i = 1; i < N; i++) {
        for (int j = 0; j < i; j++) {
            ds[i][j] = ds[j][i] = dist2(xs[i], ys[i], xs[j], ys[j]);
        }
    }

    TSP tsp(rnd);
    tsp.solve_2opt_annealing(30000000);

    vector<pii> best_ans;
    KMeansRetVal best_k;
    int best_score = INT_MAX;
    
    int loop = 0;
    while (timer.elapsed_ms() < 950) {
        auto kres = kmeans();
        auto [cxs, cys, cluster] = kres;

        vector<pii> ans;
        int score = 0;
        for (int i = 0; i < N; i++) {
            // p[i], p[i+1] のクラスタが等しく c のとき、p[i] -> c -> p[i+1] としたときスコアが下がるなら採用
            int u = tsp.p[i], v = tsp.p[(i + 1) % N];
            int cu = cluster[u], cv = cluster[v];
            ans.emplace_back(1, u + 1);

            pii p(-1, -1);
            int cost = ds[u][v] * alpha2;
            int cost2 = (dist2(xs[u], ys[u], cxs[cu], cys[cu]) + dist2(cxs[cu], cys[cu], xs[v], ys[v])) * alpha;
            if (chmin(cost, cost2)) {
                p = { 2, cu + 1 };
            }
            int cost3 = (dist2(xs[u], ys[u], cxs[cv], cys[cv]) + dist2(cxs[cv], cys[cv], xs[v], ys[v])) * alpha;
            if (chmin(cost, cost3)) {
                p = { 2, cv + 1 };
            }
            if (p.first != -1) ans.push_back(p);
            score += cost;
        }
        ans.emplace_back(1, tsp.p[0] + 1);
        if (chmin(best_score, score)) {
            best_ans = ans;
            best_k = kres;
            //dump(score);
        }
        loop++;
    }
    dump(loop);

    auto [cxs, cys, cluster] = best_k;
    const auto& ans = best_ans;

    for (int i = 0; i < M; i++) {
        cout << format("%d %d\n", cxs[i], cys[i]);
    }
    cout << ans.size() << '\n';
    for (const auto [t, r] : ans) {
        cout << t << ' ' << r << '\n';
    }

    return 0;
}
0