假设有 n n n 根柱子,现要按下述规则在这 n n n 根柱子中依次放入编号为 1,2,3,4,⋯ 1, 2, 3, 4, \cdots 1,2,3,4,⋯ 的球。
每次只能在某根柱子的最上面放球。
在同一根柱子中,任何 2 2 2 个相邻球的编号之和为完全平方数。
试设计一个算法,计算出在 n n n 根柱子上最多能放多少个球。
输入格式
文件第 1 1 1 行有 1 1 1 个正整数 n n n,表示柱子数。
输出格式
第一行是球数。接下来的 n n n 行,每行是一根柱子上的球的编号。
样例
样例输入
4
样例输出
11
1 8
2 7 9
3 6 10
4 5 11
数据范围与提示
每次只能在某根柱子的最上面放球。
在同一根柱子中,任何 2 2 2 个相邻球的编号之和为完全平方数。
试设计一个算法,计算出在 n n n 根柱子上最多能放多少个球。
输入格式
文件第 1 1 1 行有 1 1 1 个正整数 n n n,表示柱子数。
输出格式
第一行是球数。接下来的 n n n 行,每行是一根柱子上的球的编号。
样例
样例输入
4
样例输出
11
1 8
2 7 9
3 6 10
4 5 11
数据范围与提示
1≤n≤55 1 \leq n \leq 55 1≤n≤55
分析:建立有向图后,就是跑最小路径覆盖。
#include <iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<vector>
const int maxn = 20000;
const int Mid = 10000;
typedef long long ll;
using namespace std;
int n,m;
vector<int>G[maxn+5];
int match[maxn+5];
bool used[maxn+5];
void Addedge(int fr,int to)
{
G[fr].push_back(to);
}
bool dfs(int v)
{
used[v] = true;
for(int i=0,l=G[v].size(); i<l; i++)
{
int u = G[v][i], w = match[u];
if(w<0||(!used[w]&&dfs(w)))
{
match[v] = u, match[u] = v;
return true;
}
}
return false;
}
void DFS(int x)
{
if(match[x+Mid]!=-1) DFS(match[x+Mid]);
printf("%d ",x);
}
void solve()
{
int ans,ret=0;
memset(match,-1,sizeof(match));
for(n=1;;n++)
{
for(int i=1;i<n;i++)
{
int x = sqrt(i+n);
if(x*x!=i+n) continue;
Addedge(n,i+Mid);
}
if(dfs(n)) ret++;// 因为以前加入的点不可能会没有边连到 n+MId 所以 可以在原来的网络上 dfs。
if(n-ret>m) break;// n-ret变大 这里说明刚刚加入的n没有匹配到, 所以可以用原来的匹配情况来输出路径。
ans = n;
}
printf("%d\n",ans);
for(int i=1;i<=ans;i++)
{
if(match[i]!=-1) continue;
DFS(i);
printf("\n");
}
}
int main()
{
while(~scanf("%d",&m))
{
solve();
}
return 0;
}