题意:
给定n个点m条边的无向图(开始每个点都是白色)
下面m行给出边和边权,边权表示这条边所连接的2个点中被染成黑色的点数。
0表示染,1表示其中一个点染,2表示都染。
问:最少染多少个点可以满足上述的边权。若不存在输出impossible
思路:
首先处理所有边权为0和2的情况,这样处理后图中就只剩下边权为1的子图,任意染一个点,然后bfs一下把子图染掉即可。很多细节需要考虑,值得反复做!!!
#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=400005;
const double eps=1e-8;
const double PI = acos(-1.0);
#define lowbit(x) (x&(-x))
struct edge
{
int from,to,col,next;
} e[maxn];
int head[maxn],tot,c[maxn],ans,n,m;
vector<pair<int,int> > G;
void init()
{
tot=0;
memset(head,-1,sizeof(head));
}
void addedge(int a,int b,int c)
{
e[tot].from=a;
e[tot].to=b;
e[tot].next=head[a];
e[tot].col=c;
head[a]=tot++;
}
int bfs(int a)
{
int siz=1,sum=1;
c[a]=1;
queue<int> q;
q.push(a);
while(!q.empty())
{
int u=q.front();
q.pop();
for(int i=head[u]; ~i; i=e[i].next)
{
int v=e[i].to;
if(c[v]!=-1)
{
if(1!=c[u]+c[v])
return -1;
}
else
{
siz++;
c[v]=1^c[u];
sum+=c[v];
q.push(v);
}
}
}
return min(sum,siz-sum);
}
bool solve()
{
//先处理0和2
int u,v;
queue<int> q;
for(int i=0; i<tot; i+=2)
{
u=e[i].from;
v=e[i].to;
if(e[i].col==0)
{
if(c[u]==1||c[v]==1) return false;
if(c[u]==-1) q.push(u),c[u]=0;
if(c[v]==-1) q.push(v),c[v]=0;
}
else if(e[i].col==2)
{
if(c[u]==0||c[v]==0) return false;
if(c[u]==-1) q.push(u),c[u]=1;
if(c[v]==-1) q.push(v),c[v]=1;
}
}
while(!q.empty())
{
u=q.front();
q.pop();
for(int i=head[u]; ~i; i=e[i].next)
{
v=e[i].to;
if(c[v]!=-1)
{
if(e[i].col!=c[u]+c[v])
return false;
}
else
{
c[v]=c[u]^1;
q.push(v);
}
}
}
for(int i=1; i<=n; i++)
{
ans+= c[i]==1;
}
G.clear();
for(int i=0; i<tot; i+=2)
{
u=e[i].from,v=e[i].to;
if(e[i].col!=1)
continue;
if(c[u]==-1&&c[v]==-1)
G.push_back(pair<int,int> (u,v));
}
init();
for(int i=0; i<G.size(); i++)
{
u=G[i].first,v=G[i].second;
addedge(u,v,1);
addedge(v,u,1);
}
int temp;
for(int i=1; i<=n; i++)
{
if(c[i]==-1)
{
temp=bfs(i);
if(temp==-1)
return false;
ans+=temp;
}
}
return true;
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
while(cin>>n>>m)
{
init();
memset(c,-1,sizeof(c));
ans=0;
int a,b,c;
for(int i=0; i<m; i++)
{
cin>>a>>b>>c;
addedge(a,b,c);
addedge(b,a,c);
}
if(false==solve())
{
cout<<"impossible"<<endl;
}
else
{
cout<<ans<<endl;
}
}
return 0;
}