【UVALive

题意:

  有n个宇航员,按照年龄划分,年龄低于平均年龄的是年轻宇航员,而年龄大于等于平均年龄的是老练的宇航员。

  现在要分配他们去A,B,C三个空间站,其中A站只有老练的宇航员才能去,而B站是只有年轻的才能去,C站都可以去。

  有m对宇航员相互讨厌,不能让他们在同一个空间站工作。

  输出每个宇航员应分配到哪个空间站,如果没有则输出No solution.

分析:

  对于每个宇航员,有两种选择,(A,B)或C。第一个选择中取A还是取B取决于年龄。

  构图,2-SAT找满足题意的方案再输出即可。

代码如下:

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<cstring>
 4 #define Maxn 100010
 5 #define Maxm 100010
 6 
 7 int n,m;
 8 int age[Maxn],first[2*Maxn],mark[2*Maxn],s[2*Maxn];
 9 int c,v;
10 
11 struct node
12 {
13     int x,y,next;
14 }t[4*Maxm];int len;
15 
16 void ins(int x,int y)
17 {
18     t[++len].x=x;t[len].y=y;
19     t[len].next=first[x];first[x]=len;
20 }
21 
22 bool dfs(int x)
23 {
24     if(mark[x^1]) return 0;
25     if(mark[x]) return 1;
26     mark[x]=1;
27     s[++c]=x;
28     for(int i=first[x];i;i=t[i].next)
29      if(!dfs(t[i].y)) return 0;
30     return 1;
31 }
32 
33 bool solve()
34 {
35     memset(mark,0,sizeof(mark));
36     for(int i=0;i<n;i++)
37      if(!mark[2*i]&&!mark[2*i+1])
38      {
39          c=0;
40          if(!dfs(2*i))
41          {
42              while(c>0) mark[s[c--]]=0;
43              if(!dfs(2*i+1)) return 0;
44         }
45       }
46       return 1;
47 }
48 
49 void output()
50 {
51     for(int i=0;i<n;i++)
52      if(mark[i*2+1]) printf("C
");
53      else if(age[i]*n>=v) printf("A
");
54      else printf("B
");
55 }
56 
57 int main()
58 {
59     while(1)
60     {
61         
62         scanf("%d%d",&n,&m);
63         len=0;v=0;
64         if(n==0&&m==0) break;
65         memset(first,0,sizeof(first));
66         for(int i=0;i<n;i++) scanf("%d",&age[i]),v+=age[i];
67         for(int i=1;i<=m;i++)
68         {
69             int x,y;
70             scanf("%d%d",&x,&y);x--;y--;
71             ins(x*2+1,y*2);ins(y*2+1,x*2);
72             if(!((age[x]*n>=v)^(age[y]*n>=v))) ins(x*2,y*2+1),ins(y*2,x*2+1);
73         }
74         if(!solve()) printf("No solution.
");
75         else output();
76     }
77     return 0;
78 }
[LA3713]

2016-03-18 13:19:17

原文地址:https://www.cnblogs.com/Konjakmoyu/p/5291662.html