1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| #include <cstdio> #include <vector> #include <algorithm> using namespace std; template <class Type> void read (Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 1) + (x << 3) + c - '0'; flag && (x = ~x + 1); } template <class Type> void write (Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar('0' + x % 10); } template <class Type> void chkmin (Type &x, Type k) { k < x && (x = k); } typedef long long LL; const int N = 2e5 + 10, inf = 2e9; LL s[N]; int n, m, p[N]; int fa (int x) { return p[x] == x ? x : p[x] = fa(p[x]); } struct Edge { int u, v; LL w; bool operator < (const Edge &_) const { return w < _.w; } }; vector <Edge> e; int main () { read(n), read(m); for (int i = 0; i < n; i++) s[i] = inf; for (int a, b, c; m; m--) { read(a), read(b), read(c); chkmin(s[a], c + 1ll), chkmin(s[b], c + 2ll); e.push_back((Edge){a, b, c}); } LL t = s[0]; for (int i = 0; i < n << 1; i++, t += 2) chkmin(t, s[i % n]), chkmin(s[i % n], t); for (int i = 0; i < n; i++) e.push_back((Edge){i, (i + 1) % n, s[i]}); sort(e.begin(), e.end()); for (int i = 0; i < n; i++) p[i] = i; LL res = 0; for (Edge i : e) if (fa(i.u) ^ fa(i.v)) { res += i.w; p[p[i.u]] = p[i.v]; } write(res); return 0; }
|