博客
关于我
【题解】魔术球问题
阅读量:83 次
发布时间:2019-02-26

本文共 2821 字,大约阅读时间需要 9 分钟。

题意

思路

一看标签:网络流24题。

我们考虑建图,把每个点拆开,若两个数和为平方数,那么就从编号小的向编号大的连权值为1的有向边。那么就把这个问题转换成了匹配问题。

然后我们考虑对于一个新的球,如果能找到原来在的一个球能够匹配,那么可以直接匹配,否则就需要新开一根柱子。所以我们从小到大枚举放的球数,每次加入一个球,直到柱子个数超过给定的上限,那么上一次就是能放的最多球数。

对于方案,我们为了方便,在新增一根柱子的时候记录这个需要新柱子的球的编号,其余路径就按网络流跑二分图匹配的路径记录搞一搞即可。

代码

#include 
#define MAXN 20005#define MAXM 100005#define INF 0x3f3f3f3fusing namespace std;template
void write(T n) { if(n<0) putchar('-'), n = -n; if(n>9) write(n/10); putchar(n%10+'0');}int num, cnt = 1, s, t;int head[MAXN], Next[MAXM], vet[MAXM], cost[MAXM];void add(int x, int y, int w) { cnt++; Next[cnt] = head[x]; head[x] = cnt; vet[cnt] = y; cost[cnt] = w;}int vis[MAXN], dep[MAXN], cur[MAXN], to[MAXN], hd[MAXN];bool bfs() { for(int i = 0; i <= t; i++) { vis[i] = 0, dep[i] = INF; cur[i] = head[i]; } queue
q; q.push(s); vis[s] = 1; dep[s] = 1; while(!q.empty()) { int x = q.front(); q.pop(); vis[x] = 0; for(int i = head[x]; i; i = Next[i]) { int v = vet[i]; if(cost[i] && dep[v] > dep[x]+1) { dep[v] = dep[x]+1; if(!vis[v]) { vis[v] = true; q.push(v); } } } } return dep[t] != INF;}int ans, tot;int dfs(int x, int flow) { if(x == t) { ans += flow; return flow; } int used = 0; for(int &i = cur[x]; i; i = Next[i]) { int v = vet[i]; if(cost[i] && dep[v] == dep[x]+1) { int m = dfs(v, min(flow-used, cost[i])); if(m) { cost[i] -= m; cost[i^1] += m; used += m; to[x] = v; if(used == flow) break; } } } return used;}bool chk(int x) { return (int)sqrt(x*1.0)*(int)sqrt(x*1.0) == x;}bool solve(int n) { s = 0, t = 10001; ans = 0; add(s, n*2, 1); add(n*2, s, 0); add(n*2+1, t, 1); add(t, n*2+1, 0); for(int i = 1; i < n; i++) { if(chk(i+n)) { add(i*2, n*2+1, 1); add(n*2+1, i*2, 0); } } while(bfs()) { dfs(s, INF); } if(!ans) tot++, hd[tot] = n*2; //新增柱子的时候记录编号 return tot <= num;}int main() { cin >> num; int i; for(i = 1; ; i++) { if(!solve(i)) { break; } } i--; write(i); putchar('\n'); int now; for(int j = 1; j <= num; j++) { now = hd[j]; write(now/2); putchar(' '); now = to[now]; to[now] = 0; while(now && now != t) { now = now/2*2; write(now/2), putchar(' '); int t = to[now]; to[now] = 0; now = t; } putchar('\n'); } return 0;}

转载地址:http://pxwu.baihongyu.com/

你可能感兴趣的文章
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>
Multisim中555定时器使用技巧
查看>>
MySQL CRUD 数据表基础操作实战
查看>>
multisim变压器反馈式_穿过隔离栅供电:认识隔离式直流/ 直流偏置电源
查看>>
mysql csv import meets charset
查看>>
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>
multi_index_container
查看>>
MySQL DBA 进阶知识详解
查看>>