題意:ios
給定一張邊權爲 1 的有向圖,求四個不一樣點 A, B, C, D
使得 dis(A, B) + dis(B, C) + dis(C, D) 取最大值,dis表示最短路距離 1 ≤ n ≤ 3000, 1 ≤ m ≤ 5000c++
我又寫了假作法嗚嗚嗚spa
首先固然\(O(nm)\)預處理兩點之間最短路code
而後預處理出從每一個點開始前3個dis最大的點ci
貪心,枚舉A,貪心選擇dis較大的BCD,就是3*3*3搜索選出B、C、Dget
貪心不成立,由於前面會影響後面,能夠先差,再優、優string
再預處理到達每一個點的前3個dis最大的點it
枚舉B、C,再3*3選出A、D,選A、D不會像以前那樣互相干擾了io
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int N = 1e4+5, inf = 1e9; int n, m; struct edge {int v, ne;} e[N]; int cnt, h[N], d[N][N]; inline void ins(int u, int v) { e[++cnt] = (edge) {v, h[u]}; h[u] = cnt; } int q[N], head, tail, vis[N]; #define fir first #define sec second pair<int, int> a[N], f[N][5], g[N][5]; void bfs(int s) { memset(vis, 0, sizeof(vis)); head = tail = 1; q[tail++] = s; vis[s] = 1; memset(d[s], 0x3f, sizeof(d[s])); int *dis = d[s]; dis[s] = 0; while(head != tail) { int u = q[head++]; for(int i=h[u]; i; i=e[i].ne) { int v = e[i].v; if(vis[v]) continue; dis[v] = dis[u] + 1; vis[v] = 1; q[tail++] = v; } } } void solve(int s) { int cnt = 0; for(int i=1; i<=n; i++) if(i!=s && d[s][i] < inf) a[++cnt] = make_pair(d[s][i], i); for(int i=cnt+1; i<=3; i++) a[i] = make_pair(0, 0); sort(a+1, a+cnt+1, greater<pair<int, int> >()); f[s][1] = a[1], f[s][2] = a[2], f[s][3] = a[3]; cnt = 0; for(int i=1; i<=n; i++) if(i!=s && d[i][s] < inf) a[++cnt] = make_pair(d[i][s], i); for(int i=cnt+1; i<=3; i++) a[i] = make_pair(0, 0); sort(a+1, a+cnt+1, greater<pair<int, int> >()); g[s][1] = a[1], g[s][2] = a[2], g[s][3] = a[3]; //if(s == 1) printf("hi %d %d %d\n", a[1].sec, a[2].sec, a[3].sec); //printf("sssssssssssssssssssssssssssss %d\n", s); //for(int i=1; i<=3; i++) printf("f %d %d %d\n", i, f[s][i].fir, f[s][i].sec); } int ans, li[10]; int main() { //freopen("in", "r", stdin); ios::sync_with_stdio(false); cin.tie(); cout.tie(); cin >> n >> m; for(int i=1; i<=m; i++) { int u, v; cin >> u >> v; if(u != v && !d[u][v]) ins(u, v), d[u][v] = 1; } for(int i=1; i<=n; i++) bfs(i); for(int i=1; i<=n; i++) solve(i); for(int b=1; b<=n; b++) for(int c=1; c<=n; c++) if(d[b][c] < inf && c != b) { int now = d[b][c]; for(int i=1; i<=3; i++) { pair<int, int> &ra = g[b][i]; int a = ra.sec; if(a == b || a == c || !ra.fir) continue; now += ra.fir; for(int j=1; j<=3; j++) { pair<int, int> &rd = f[c][j]; int d = rd.sec; if(d ==a || d == b || d == c || !rd.fir) continue; now += rd.fir; if(now > ans) { ans = now; li[1] = a; li[2] = b; li[3] = c; li[4] = d; } now -= rd.fir; } now -= ra.fir; } } for(int i=1; i<=4; i++) cout << li[i] << ' '; }