Description
Input
Output
Sample Input
4 4
1 2 2
2 3 1
3 4 1
4 1 2
Sample Output
3
HINT
Source
题意:有n个点,每个点最多一个加油站,然后m个条件,输入a,b,c代表a,b两个点有c个加油站,问能满足所有条件的情况下,加油站最少是几个
思路:由于有5秒,可以试着搜索
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
#define ls 2*i
#define rs 2*i+1
#define up(i,x,y) for(i=x;i<=y;i++)
#define down(i,x,y) for(i=x;i>=y;i--)
#define mem(a,x) memset(a,x,sizeof(a))
#define w(a) while(a)
#define LL long long
const double pi = acos(-1.0);
#define Len 200005
#define mod 19999997
const int INF = 0x3f3f3f3f;
#define exp 1e-6
typedef pair<int,int> PII;
vector<int> mat[Len];
int n,m,col[Len],flag = 1;
void dfs1(int u,int father,int c)
{
if(!col[u]) col[u]=c;
else if(col[u]==-c)
{
flag = 0;
return;
}
int i,len = mat[u].size();
for(i = 0; i<len; i++)
{
int v = mat[u][i];
if(v == father) continue;
if(col[v] == -c) continue;
dfs1(v,u,-c);
}
}
PII dfs2(int u,int father,int c)
{
PII ret = make_pair(0,0);
if(!col[u]) col[u]=c;
else if(col[u]==-c)
{
flag = 0;
return ret;
}
if(c==1) ret.first++;
else ret.second++;
int len = mat[u].size();
for(int i=0; i<len; i++)
{
int v=mat[u][i];
if(v==father) continue;
if(col[v]==-c) continue;
PII tem=dfs2(v,u,-c);
ret.first+=tem.first;
ret.second+=tem.second;
}
return ret;
}
int main()
{
int i,j,k,a,b,c;
mem(col,0);
scanf("%d%d",&n,&m);
w(m--)
{
scanf("%d%d%d",&a,&b,&c);
c--;
if(c == 0)
{
mat[a].push_back(b);
mat[b].push_back(a);
}
else//确定能染色的,1为染,-1为不染
{
if(col[a]==0) col[a] = c;
else if(col[a]==-c) flag = 0;//染色情况相悖
if(col[b]==0) col[b] = c;
else if(col[b]==-c) flag = 0;
}
}
if(!flag)
{
printf("impossible\n");
return 0;
}
else
{
up(i,1,n)//更新
{
if(col[i])
dfs1(i,i,col[i]);
if(!flag)
{
printf("impossible\n");
return 0;
}
}
int bb=0,ww=0;
up(i,1,n)//计算所有确定的染色情况
{
if(!col[i]) continue;
if(col[i]==1) bb++;
else ww++;
}
int tt = 0;
up(i,1,n)//不确定的,进行搜索
{
if(col[i])continue;
PII tem = dfs2(i,i,1);
tt+=min(tem.first,tem.second);
}
if(!flag)
{
printf("impossible\n");
return 0;
}
printf("%d\n",bb+tt);
}
return 0;
}