考试的时候只做出了 T1,没想到 T2 是区间 DP。
题意
给你一个有 个点与 条边的无向图,而每个点都有两个度,给它染色,问至少需多少种颜色。
有多组测试数据。
分析
关于“每个点都有两个度”的理解
想一想,它等价于每个点都只有两条边与之相连,那必然是一或几个环。
证明
答案的求解
明显,图可能不联通,所以要按联通块的方式处理。
对每个环考虑,我们称环里编号最小的节点名叫搜索起点。从搜索起点开始,与下一个节点绑定,若绑定过则不操作。让每个绑定里的第一个节点附 ,第二个附 ,明显,有以下两种情况:
1.环的大小为偶数。
(加重颜色的是附 的点。)
没有矛盾。
2.环的大小为奇数。
(标红的是附 的,标黄的是矛盾点。)
(原图给删了,用平板弄了个新的。)
此时,就有矛盾了:
是搜索起点,附 。
但它又与 绑定在一块,所以附 。
为了让他与世无争,给 附 。
这下很简单了:
若环的大小为偶数,输出 ;
若环的大小为奇数,输出 。
AC Code
代码
//警示后人:十年OI一场空,不开long long见祖宗
#include <bits/stdc++.h>
using namespace std;
#define int long long
using ll=long long;
using pll=pair<int,int>;
template<typename T>
inline void readinVector(vector<T>& vec,int l,int r){
for(int i=l;i<=r;i++)cin>>vec[i];
}
template<typename T>
class matvec{
public:
vector<vector<T> >mat;
matvec(){}
matvec(int n){
mat.resize(n+1);
}
void rs(int n){
mat.resize(n+1);
}
matvec(int n,int m){
mat.resize(n+1,vector<T>(m+1));
}
matvec(int n,int m,T v){
mat.resize(n+1,vector<T>(m+1,v));
}
vector<T>& operator[](int i){
return mat[i];
}
void p_b(const vector<T>&vec){
mat.push_back(vec);
}
};
int n;
vector<vector<int> >g;
vector<int>vis;
int got=0;
int cnt=0;
void dfs(int u,int fa){
vis[u]=1;
for(int v:g[u]){
if(v==fa)continue;
if(vis[v]){
got=1;
cnt=1;
return ;
}
dfs(v,u);
if(got){
cnt++;
return;
}
}
}
int T=1;
void solve(){
g.clear();
vis.clear();
int n;
cin>>n;
g.resize(n+1);
vis.resize(n+1);
for(int i=1;i<=n;i++){
int f,t;
cin>>f>>t;
g[f].push_back(t);
g[t].push_back(f);
}
int ans=2;
for(int i=1;i<=n;i++){
if(!vis[i]){
dfs(i,0);
if(cnt%2){
ans=3;
break;
}
}
cnt=0;
got=0;
}
cout<<ans<<endl;
}
signed main(){
// freopen("xxx.in","r",stdin);
// freopen("xxx.out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin>>T;
while(T--)solve();
return 0;
}
代码的解释
WARNING
多测不清空,考完两行泪。
但我清空了,即使在考场上被硬控了几分钟
还有, DFS 函数中的判断 是否等于一,要写在循环内,因为在搜索起点时,他会进行两次递归。为防止这点,要在这里让它止步。
时间复杂度分析
差点忘写了。
dfs 的时间复杂度
看似 ,因为 solve 里有一个 的循环,而 DFS 的最坏复杂度为 。但实际上,solve 的循环是寻找下一个联通块,所以他贡献的是联通块的数量。而每一次 DFS 搜索的复杂度为联通块的大小,合起来为 。
合起来:。


