LA3713 Astronauts

来源:互联网 发布:openwrt usb网络共享 编辑:程序博客网 时间:2024/05/20 01:36

分组问题。年龄<=平均值的宇航员可选择A和C组,年龄>平均值的可选择B和C组,每两个有矛盾的宇航员不能分在一组,求一组可能的分组情况

关键词:分组问题:2sat

做法:每个宇航员选择A/B,对应于true,选择C,对应于false,

2sat问题:将每个元素的两个选择对应于true和false;将条件对应于子句xi:true/false or xj:true/false

本题中同组矛盾对应两个子句:(xi==1||xj==1)&&(xi==0||xj==0);不同组矛盾对应一个句子:(xi==1||xj==1) 

#include<iostream>#include<stdio.h>#include<string.h>#include<algorithm>#include<math.h>#include<vector>#include<stack>#define ll long long#define INF 0x3f3f3f3f#define maxn 100010#define maxm 100010#define mem(a,b) memset(a,b,sizeof(a))using namespace std;int n,m;int kind[maxn];int age[maxn],sum;int mark[maxn<<2],S[maxn<<2],c;struct Edge{    int to,next;}edge[maxm<<4];int head[maxn<<3],tot;void add(int u,int v){    edge[tot].to=v,edge[tot].next=head[u],head[u]=tot++;}void add_clause(int x,int xval,int y,int yval){    x=x*2+xval,y=y*2+yval;    add(x^1,y),add(y^1,x);}void build(){//2*i+1:A/B 2*i:C    mem(head,-1),tot=0    for(int i=1;i<=m;i++){        int a,b;        scanf("%d%d",&a,&b);a--,b--;        if(kind[a]==kind[b]){            add_clause(a,1,b,1),add_clause(a,0,b,0);        }        else add_clause(a,1,b,1);    }}bool dfs(int u){    if(mark[u]) return true;    if(mark[u^1]) return false;    mark[u]=true;S[c++]=u;    for(int i=head[u];i!=-1;i=edge[i].next){        if(!dfs(edge[i].to)) return false;    }    return true;}bool judge_2sat(){    mem(mark,0);    for(int i=0;i<2*n;i+=2){        if(!mark[i]&&!mark[i+1]){            c=0;            if(!dfs(i)){                while(c>0) mark[S[--c]]=false;                if(!dfs(i+1)) return false;            }        }    }    return true;}void print_2sat(){    if(judge_2sat()){        for(int i=1;i<2*n;i+=2){            if(mark[i]){                if(kind[i/2]==1) printf("A\n");                else printf("B\n");            }            else printf("C\n");        }    }    else printf("No solution.\n");}int main(){    //freopen("a.txt","r",stdin);    while(scanf("%d%d",&n,&m)!=EOF){        if(!n&&!m) break;        sum=0,mem(kind,0);        for(int i=0;i<n;i++){            scanf("%d",&age[i]);            sum+=age[i];        }        for(int i=0;i<n;i++)            if(n*age[i]>=sum) kind[i]=1;            else kind[i]=2;        build();        print_2sat();    }    return 0;}


0 0
原创粉丝点击