Description
Assuming that there are $n$ pillars, it is now necessary to place the ball in the $n$ column numbered $1,2,3,... $ in accordance with the following rules.
$1.$ can only place the ball at the top of a column at a time.
$2.$ in the same pillar, the sum of the numbers of any $2$ adjacent balls is the total square number.
Ask for the maximum number of balls to be placed on the $n$ pole.
Input
Line $1$ has a $1$ positive integer $n$, which indicates the number of pillars.
Output
The first line is the number of balls.
The next $n$ line, each row is the number of a ball on a pillar.
Sample Input
4
Sample Output
11
1 8
2 7 9
3 6 10
4 5 11
HINT
$n \;\leq\;100$
Solution
Enumerates the answer $ans$, establishing the node $1,2,..., ans$ in the diagram. If for $i,j,\;i<j$ and $i+j$ is a complete square number, build an edge $ (i,j) $. The graph is a direction-free graph, and the minimum path overlay is obtained. Find the maximum $ans$ so that the minimum path coverage number $=n$. (Enumerate $ans$)
#include <cmath>#include<ctime>#include<queue>#include<stack>#include<cstdio>#include<vector>#include<cstring>#include<cstdlib>#include<iostream>#include<algorithm>#defineN 5005#defineM 200001using namespacestd;structgraph{intnxt,to,f;} E[M];inta[n<<1],g[n<<1],dep[n<<1],l,m,s,t,fl,ans,cnt=1;BOOLV[n];queue<int>q; inlineBOOLSqintx) { intk=sqrt (x); returnk*k==x;} InlinevoidAddedge (intXintYintf) {e[++cnt].nxt=g[x];g[x]=cnt;e[cnt].to=y;e[cnt].f=F;} InlinevoidAdde (intXintYintf) {Addedge (x,y,f); Addedge (Y,x,0);} InlineBOOLBFsintu) {memset (DEP,0,sizeof(DEP)); Q.push (U);d Ep[u]=1; while(!Q.empty ()) {u=Q.front (); Q.pop (); for(intI=g[u];i;i=e[i].nxt)if(e[i].f>0&&!Dep[e[i].to]) {Q.push (e[i].to); Dep[e[i].to]=dep[u]+1; } } returndep[t];} InlineintDfsintUintf) { intret=0; if(u==t)returnF; for(intI=g[u],d;i&&f;i=e[i].nxt)if(e[i].f>0&&dep[e[i].to]>Dep[u]) {D=Dfs (E[i].to,min (e[i].f,f)); E[I].F-=d;e[i^1].f+=d;f-=d;ret+=D; } returnret;} InlinevoidDinic () { while(true){ if(!bfs (s))return; FL+=DFS (S,N); }}inlineBOOLChkintx) {dinic (); returnx-fl<=m;} InlinevoidFindintu) {a[++l]=u; for(intI=g[u];i;i=e[i].nxt)if(e[i].to!=s&&!v[e[i].to-n]&&!e[i].f) {v[e[i].to-n]=true; Find (e[i].to-N); }}inlinevoidAireen () {scanf ("%d", &m); ans=m; S=n-1; T= (n<<1)-1; for(intj=1; j<=ans;++j) {Adde (s,j,1); Adde (J+n,t,1); for(intI=1; i<j;++i)if(Sq (i+j)) Adde (I,j+n,1); } Do{ ++ans; Adde (S,ans,1); Adde (Ans+n,t,1); for(intI=1; i<ans;++i)if(Sq (I+ans)) Adde (I,ans+n,1); } while(chk (ans)); printf ("%d\n", ans-1); V[ans]=0; for(intI=1; i<ans;++i)if(!V[i]) {L=0; v[i]=true; find (i); for(intj=1; j<=l;++j) printf ("%d", A[j]); printf ("\ n"); }}intMain () {Freopen ("ball.in","R", stdin); Freopen ("Ball.out","W", stdout); Aireen (); Fclose (stdin); Fclose (stdout); return 0;}
[Network Flow 24 questions] Magic ball problem