CSU1574: Amanda Lounges,csu1574lounges
Description
Input
Output
Sample Input
4 41 2 22 3 13 4 14 1 2
Sample Output
3
HINT
Source
NCPC 2014
題意:有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 longconst double pi = acos(-1.0);#define Len 200005#define mod 19999997const int INF = 0x3f3f3f3f;#define exp 1e-6typedef 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;}