既然是二选一,考虑两个问题有什么联系。题面没有说无解怎么办,所以如果不存在经过k条边的简单路径,一定存在k染色方案。考虑怎么证明这个东西,我们造一棵dfs树。于是可以发现如果树深>k(根节点深度为1),显然能找到一条经过k条边的简单路径;否则对于dfs树每一层染一种颜色,因为dfs树上不存在同层之间的边,这种k染色方案显然是合法的。那么这个题也就做完了。注意图不一定连通。
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define N 1010 #define M 10010 char getc(){char c=getchar();while ((c<'A'||c>'Z')&&(c<'a'||c>'z')&&(c<'0'||c>'9')) c=getchar();return c;} int gcd(int n,int m){return m==0?n:gcd(m,n%m);} int read() { int x=0,f=1;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } int T,n,m,s,p[N],fa[N],deep[N],t; struct data{int to,nxt; }edge[M<<1]; void addedge(int x,int y){t++;edge[t].to=y,edge[t].nxt=p[x],p[x]=t;} void print(int k) { printf("path "); while (k) printf("%d ",k),k=fa[k]; } bool dfs(int k) { if (deep[k]>s) return print(k),1; for (int i=p[k];i;i=edge[i].nxt) if (!deep[edge[i].to]) { deep[edge[i].to]=deep[k]+1; fa[edge[i].to]=k; if (dfs(edge[i].to)) return 1; } return 0; } int main() { #ifndef ONLINE_JUDGE freopen("bzoj4878.in","r",stdin); freopen("bzoj4878.out","w",stdout); const char LL[]="%I64d "; #else const char LL[]="%lld "; #endif T=read(); while (T--) { n=read(),m=read(),s=read(); for (int i=1;i<=n;i++) p[i]=deep[i]=fa[i]=0;t=0; for (int i=1;i<=m;i++) { int x=read(),y=read(); addedge(x,y),addedge(y,x); } bool flag=0; for (int i=1;i<=n;i++) if (!deep[i]) {deep[i]=1,flag|=dfs(i);if (flag) break;} if (!flag) { printf("color "); for (int i=1;i<=n;i++) printf("%d ",deep[i]); } printf(" "); } return 0; }