nowcoder网络流Birthday 思维建图
Posted kaka0010
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nowcoder网络流Birthday 思维建图相关的知识,希望对你有一定的参考价值。
原题链接:https://ac.nowcoder.com/acm/problem/19802
题意
分析
题目唯一的难点是x^2该如何去表示
我们写出来看一下1, 4, 9, 16, 25…
我们再观察一下差1, 3, 5, 7, 9…
惊奇发现居然是等差数列,那么我们在给点加边的时候可以一次性加入n条边,分别代表第i次加入的费用。
Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const ll INF = 1e9;
const int N = 500 + 10;
const int M = 3e6 + 10;
const int MOD = 1e9 + 7;
int st, ed;
struct node {
int maxflow, mincost, cnt;
int vis[N], dis[N], pre[N], last[N], h[N], flow[N];
struct edge {
int to, next, cap, cos;
} e[M << 1];
void add(int u, int v, int cap, int cos) {
e[cnt].to = v;
e[cnt].cap = cap;
e[cnt].cos = cos;
e[cnt].next = h[u];
h[u] = cnt++;
e[cnt].to = u;
e[cnt].cap = 0;
e[cnt].cos = -cos;
e[cnt].next = h[v];
h[v] = cnt++;
}
void init() {
memset(h, -1, sizeof h);
cnt = 0;
mincost = maxflow = 0;
}
bool spfa() {
queue<int> q;
for (int i = 0; i <= ed; i++) dis[i] = INF, vis[i] = 0;
vis[st] = 1, dis[st] = 0, flow[st] = INF;
q.push(st);
while (q.size()) {
int u = q.front();
q.pop(); vis[u] = 0;
for (int i = h[u]; ~i; i = e[i].next) {
int v = e[i].to;
if (e[i].cap && dis[v] > dis[u] + e[i].cos) {
dis[v] = e[i].cos + dis[u];
flow[v] = min(flow[u], e[i].cap);
pre[v] = u;
last[v] = i;
if (!vis[v]) {
vis[v] = 1;
q.push(v);
}
}
}
}
if (dis[ed] != INF) return true;
else return false;
}
void MCMF() {
while (spfa()) {
int now = ed;
maxflow += flow[ed];
mincost += flow[ed] * dis[ed];
while (st != now) {
e[last[now]].cap -= flow[ed];
e[last[now] ^ 1].cap += flow[ed];
now = pre[now];
}
}
}
}mcmf;
void solve() {
int n, m; cin >> n >> m;
mcmf.init();
st = n + m + 1, ed = n + m + 2;
for (int i = 1; i <= n; i++) {
int a, b; cin >> a >> b;
mcmf.add(i, a + n, 1, 0);
mcmf.add(i, b + n, 1, 0);
}
for (int i = 1; i <= n; i++) {
mcmf.add(st, i, 1, 0);
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
mcmf.add(i + n, ed, 1, j * 2 - 1);
}
}
mcmf.MCMF();
cout << mcmf.mincost << endl;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifdef ACM_LOCAL
freopen("input", "r", stdin);
freopen("output", "w", stdout);
signed test_index_for_debug = 1;
char acm_local_for_debug = 0;
do {
if (acm_local_for_debug == '$') exit(0);
if (test_index_for_debug > 20)
throw runtime_error("Check the stdin!!!");
auto start_clock_for_debug = clock();
solve();
auto end_clock_for_debug = clock();
cout << "Test " << test_index_for_debug << " successful" << endl;
cerr << "Test " << test_index_for_debug++ << " Run Time: "
<< double(end_clock_for_debug - start_clock_for_debug) / CLOCKS_PER_SEC << "s" << endl;
cout << "--------------------------------------------------" << endl;
} while (cin >> acm_local_for_debug && cin.putback(acm_local_for_debug));
#else
solve();
#endif
return 0;
}
以上是关于nowcoder网络流Birthday 思维建图的主要内容,如果未能解决你的问题,请参考以下文章