luogu P2765 魔术球问题 (最小路径覆盖)
大意:给定n根柱子, 依次放入1,2,3,...的球, 同一根柱子相邻两个球和为完全平方数, 求最多放多少个球.
对和为平方数的点连边, 就相当于求DAG上最小路径覆盖.
#include <iostream> #include <sstream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #include <bitset> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl '\n' #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;}) using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, P2 = 998244353, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;} //head const int N = 1e6+10; int n, clk, deg[N], nxt[N]; int c[N], fa[N], vis[N]; vector<int> g[N]; int dfs(int x) { for (int y:g[x]) if (vis[y]!=clk) { vis[y] = clk; if (!fa[y]||dfs(fa[y])) return fa[y]=x; } return 0; } int chk(int x) { REP(i,1,2*x) g[i].clear(),fa[i]=0; REP(i,1,x) REP(j,i+1,x) if (c[i+j]) { g[i].pb(j+x),g[j+x].pb(i); } int ans = 0; REP(i,1,x) ++clk, ans+=!!dfs(i); return x-ans<=n; } int main() { REP(i,1,1000) c[i*i]=1; scanf("%d", &n); int ans = 1; while (chk(ans)) ++ans; chk(--ans); printf("%d\n", ans); REP(i,1,ans) if (fa[i]) nxt[i]=fa[i]-ans,deg[fa[i]-ans]=1; REP(i,ans+1,2*ans) if (fa[i]) nxt[fa[i]]=i-ans,deg[i-ans]=1; REP(i,1,ans) if (!deg[i]) { int x = i; do printf("%d ",x),x=nxt[x]; while (x); hr; } }