# P2765 魔术球问题【最小路径覆盖】

«问题描述：

（1）每次只能在某根柱子的最上面放球。
（2）在同一根柱子中，任何2个相邻球的编号之和为完全平方数。

«编程任务：

4

11
1 8
2 7 9
3 6 10
4 5 11

4<=n<=55

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
typedef long long LL;
using namespace std;

const int MAXN = 3200 + 50;
const int INF = 0x3f3f3f3f;
int cur[MAXN], in[MAXN << 1];
int n, m, pre[MAXN << 1];
int top = 0;

struct Edge {
int to, cap, flow, next;
}edge[MAXN * 20];

void init() {
top = 0;
memset(pre, -1, sizeof(pre));
memset(in, 0, sizeof(in));
memset(vis, 0, sizeof(vis));
}

void addedge(int a, int b, int c) {
Edge E1 = {b, c, 0, head[a]};
edge[top] = E1;
Edge E2 = {a, 0, 0, head[b]};
edge[top] = E2;
}

bool BFS(int st, int ed) {
memset(dist, -1, sizeof(dist));
memset(vis, 0, sizeof(vis));
queue<int> que;
que.push(st);
vis[st] = 1;
dist[st] = 0;
while(!que.empty()) {
int u = que.front();
que.pop();
for(int i = head[u]; i != -1; i = edge[i].next) {
Edge E = edge[i];
if(!vis[E.to] && E.cap > E.flow) {
dist[E.to] = dist[u] + 1;
vis[E.to] = 1;
if(E.to == ed) return true;
que.push(E.to);
}
}
}
return false;
}

int DFS(int x, int a, int ed) {
if(x == ed || a == 0) return a;
int flow = 0, f;
for(int& i = cur[x]; i != -1; i = edge[i].next) {
Edge& E = edge[i];
if(dist[E.to] == dist[x] + 1 && (f = DFS(E.to, min(a, E.cap - E.flow), ed)) > 0) {
E.flow += f;
edge[i^1].flow -= f;
flow += f;
a -= f;
if(a == 0) break;
}
}
return flow;
}

int Maxflow(int st, int ed) {
int flow = 0;
while(BFS(st, ed)) {
flow += DFS(st, INF, ed);
}
return flow;
}

int main()
{
init();
scanf("%d", &n);
m = (n + 1) * n / 2 + (n - 1) / 2; //关键得一步
for(int i = 1; i <= m; ++i) {
addedge(i + m, m + m + 1, 1);
}
for(int i = 1; i <= m; ++i) {
for(int j = i + 1; j <= m; ++j) {
int cnt = (int)ceil(sqrt(i + j)) * (int)ceil(sqrt(i + j));
if(cnt == i + j) addedge(i, j + m, 1);
}
}
int ans = Maxflow(0, m + m + 1);
for(int i = 1; i <= m; ++i) {
for(int j = head[i]; ~j; j = edge[j].next) {
if(edge[j].flow && edge[j].to) {
pre[edge[j].to - m] = i;
in[i] = edge[j].to - m;
//printf("#  %d %d\n", i, edge[j].to);
}
}
}
printf("%d\n", m);
for(int i = 1; i <= m; ++i) {
if(pre[i] < 0) {
int x = i;
printf("%d", x);
while(in[x]) {
printf(" %d", in[x]);
x = in[x];
}
puts("");
}
}
return 0;
}