魔术球问题

P2765 魔术球问题

关键

1.问题的转换
2.路径的记录
3.枚举的区间

代码

#include <bits/stdc++.h>
using namespace std;
const int N=10005,M=1e6+5;
const int inf=1e9;
 
int h[N],ne[M],e[M],w[M],tot=1;
void add(int from,int to,int wi) {
    e[++tot]=to;  w[tot]=wi;  ne[tot]=h[from];  h[from]=tot;
    e[++tot]=from;w[tot]=0;  ne[tot]=h[to];    h[to]=tot;
}
 
int S=N-2,T=N-1;
int cur[N],dep[N];
bool bfs() {
    memcpy(cur,h,sizeof(h));
    memset(dep,0,sizeof(dep));
    queue<int>q;
    q.push(S);
    dep[S]=1;
    while(!q.empty()) {
        int now=q.front();
        q.pop();
        for(int i=h[now];i;i=ne[i]) {
            int to=e[i];
            if(dep[to]==0&&w[i]>0)
                dep[to]=dep[now]+1,q.push(to);
        }
    }
    return dep[T];
}

int a[M],b[M];
int dfs(int now,int sum) {
    if(now==T)return sum;
    int ans=0;
    for(int i=cur[now];i&&sum;i=ne[i]) {
        cur[now]=i;
        int to=e[i];
        if(dep[to]==dep[now]+1&&w[i]>0) {
            int k=dfs(to,min(sum,w[i]));
            if(k==0)dep[to]=0;
            else b[now>>1]=to>>1; 
            w[i]-=k;
            w[i^1]+=k;
            sum-=k;
            ans+=k;
        }
    }
    return ans;
}
 
int dinic() {
    int ans=0;
    while(bfs())ans+=dfs(S,inf);
    return ans;
}

int main() {
    int cnt=0,num=0;
    int n;cin>>n;
    while(cnt<=n) {
        num++;
        add(S,num<<1,1);
        add(num<<1|1,T,1);
        for(int i=sqrt(num)+1;i*i<2*num;i++)
            add((i*i-num)<<1,num<<1|1,1);
        int k=dinic();
        if(k==0)a[++cnt]=num;//记录的第一个
    }
    cout<<num-1<<endl;
    for(int i=1;i<=n;i++) {
        while(a[i]&&a[i]<num)cout<<a[i]<<' ',a[i]=b[a[i]];
        cout<<endl;
    }
    return 0;
}
posted @ 2023-01-05 21:38  basicecho  阅读(33)  评论(0)    收藏  举报