void test_case() { int n = rand() % (MAXN - 2) + 3; int MaxEdges = min(n*(n-1)/2, MAXM); int m = rand() % (MaxEdges + 1); if (m < n - 1) m = n - 1; printf("\n%d %d\n", n, m); IV ls; IIS s; for (int i = 0; i < n; ++i) ls.push_back(i); random_shuffle(ls.begin(), ls.end()); printf("%d %d\n", ls[0], ls[1]); --m; int u = ls[0], v = ls[1]; if (u > v) swap(u, v); s.insert(II(u, v)); for (int i = 2; i < n; ++i) { u = ls[rand() % i], v = ls[i]; printf("%d %d\n", u, v); --m; if (u > v) swap(u, v); s.insert(II(u, v)); } while (m--) { int u, v; do { u = rand() % n; v = rand() % n; if (u > v) swap(u, v); } while (u == v || s.find(II(u, v)) != s.end()); s.insert(II(u, v)); if (rand() % 2 == 0) swap(u, v); printf("%d %d\n", u, v); } }
void dijkstra(int src, IV &dis) { IIS q; dis = IV(n, INF); BV flg(n); dis[src] = 0; q.insert(II(0, src)); while (! q.empty()) { int v = q.begin()->second; q.erase(q.begin()); if (flg[v]) continue; flg[v] = true; cFor (EL, e, adj[v]) { int d = dis[v] + e->w; if (!flg[e->v] && d < dis[e->v]) { if (dis[e->v] != INF) q.erase(II(dis[e->v], e->v)); dis[e->v] = d; q.insert(II(dis[e->v], e->v)); } } }
void prim_min(ELV &g, int src) { IIS q; IV dis(n, INF); BV flg(n); dis[src] = 0; q.insert(II(0, src)); while (! q.empty()) { int d = q.begin()->first; int v = q.begin()->second; q.erase(q.begin()); if (flg[v]) continue; flg[v] = true; cFor (EL, e, g[v]) if (!flg[e->v] && e->w < dis[e->v]) { if (dis[e->v] != INF) q.erase(II(dis[e->v], e->v)); dis[e->v] = e->w; q.insert(II(dis[e->v], e->v)); } } }
int prim_mst(int src) { IIS q; IV dis(n, INF); BV flg(n); dis[src] = 0; q.insert(II(0, src)); int mst = 0; while (! q.empty()) { int d = q.begin()->first; int v = q.begin()->second; q.erase(q.begin()); if (flg[v]) continue; flg[v] = true; mst += d; For (EL, e, adj[v]) if (!flg[e->v] && e->w < dis[e->v]) { dis[e->v] = e->w; q.insert(II(dis[e->v], e->v)); } } return mst; }