其他分享
首页 > 其他分享> > 2022江苏 B. Prime Ring Plus

2022江苏 B. Prime Ring Plus

作者:互联网

2022江苏 B. Prime Ring Plus

分析

网络流,直接说建图了。

确定方案

一点碎碎念,其实这题最难的是想到,只要有合法方案,那我们一定可以将其合成一个环

AC_code

#include<bits/stdc++.h>

using namespace std;

const int N = 1e4 + 10,M = 2e7,INF = 0x3f3f3f3f;

int h[N],ne[M],e[M],f[M],idx;
int cur[N],d[N],q[N];
bool st[N<<1];
int primes[N<<1],cnt;
int n,S,T;

void init(int x)
{
    st[x] = 1;
    for(int i=2;i<x;i++)
    {
        if(!st[i]) primes[cnt++] = i;
        for(int j=0;primes[j]*i<x;j++)
        {
            st[primes[j]*i] = 1;
            if(i%primes[j]==0) break;
        }
    }
}

void add(int a,int b,int c)
{
    e[idx] = b,ne[idx] = h[a],f[idx] = c,h[a] = idx++;
    e[idx] = a,ne[idx] = h[b],f[idx] = 0,h[b] = idx++;
} 

bool bfs()
{
    int hh = 0,tt = -1;
    memset(d,0x3f,sizeof d);
    q[++tt] = S,d[S] = 1,cur[S] = h[S];
    while(hh<=tt)
    {
        int t = q[hh++];
        for(int i=h[t];~i;i=ne[i])
        {
            int j = e[i];
            if(d[j]==INF&&f[i])
            {
                d[j] = d[t] + 1;
                cur[j] = h[j];
                if(j==T) return 1;
                q[++tt] = j;
            }
        }
    }
    return 0;
}

int find(int u,int limit)
{
    if(u==T) return limit;
    int flow = 0;
    for(int i=cur[u];~i&&flow<limit;i=ne[i])
    {
        int j = e[i];
        cur[u] = i;
        if(d[j]==d[u]+1&&f[i])
        {
            int t = find(j,min(limit-flow,f[i]));
            if(!t) d[j] = -1;
            f[i] -= t,f[i^1] += t,flow += t;
        }
    }
    return flow;
}

int dinic()
{
    int r = 0,flow;
    while(bfs()) if(flow = find(S,INF)) r += flow;
    return r;
}

int main()
{
    init(N<<1);
    scanf("%d",&n);
    memset(h,-1,sizeof h);
    S = 0,T = n + 1;
    for(int i=1;i<=n;i+=2) add(S,i,2);
    for(int i=1;i<=n;i+=2)
        for(int j=2;j<=n;j+=2)
            if(!st[i+j])
                add(i,j,1);
    for(int i=2;i<=n;i+=2) add(i,T,2);
    if(dinic()!=n) cout<<"-1\n";
    else 
    {
        cout<<"1\n"<<n<<" ";
        memset(st,0,sizeof st);
        int t = 1;
        while(1)
        {
            cout<<t;
            st[t] = 1;
            bool F = 0;
            for(int i=h[t];~i;i=ne[i])
            {
                int j = e[i];
                if(j==T||j==S) continue;
                if(st[j]) continue;
                F = 1;
                t = j;
                break;
            }
            if(!F) break;
            else cout<<" ";
        }
    }
    return 0;
}

标签:Prime,匹配,int,奇点,建图,Plus,偶点,Ring
来源: https://www.cnblogs.com/aitejiu/p/16528129.html