C. Not Assigning
题意:给出n个节点,n-1条路经,给每条路径赋上初值(这里的值必须为素数),使得每两条路径权值之和为素数,且对于每条路径,每个节点只能访问一次(即判断是否为线性结构)。
分析:找头节点,依次赋值,根据路径输出答案。
#include <bits/stdc++.h>
//dfs 大法师
#define ll long long
using namespace std;
const int mod=20100403;
const int Inf=0x3f3f3f3f;
inline int read()
{
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;
}
int m1[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int m2[]={0,31,29,31,30,31,30,31,31,30,31,30,31};
void Get_Time()
{
time_t timep;
time(&timep); //获取从1970至今过了多少秒,存入time_t类型的timep
printf("%s", ctime(&timep));//用ctime将秒数转化成字符串格式,输出:Thu Feb 28 14:14:17 2019
}
vector<pair<int,int> >v[200005];
int ans[200005];
int d;
void dfs(int i,int j,int k)
{
for(int a=0;a<v[i].size();a++)
{
if(v[i][a].first!=j)
{
ans[v[i][a].second]=k;
if(k==2)dfs(v[i][a].first,i,k+1);
else if(k==3)dfs(v[i][a].first,i,k-1);
}
}
}
void solve()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int i,j;
memset(ans,0,sizeof(ans));
d=0;
for(int a=1;a<n+1;a++)v[a].clear();
for(int a=1;a<=n-1;a++)
{
cin>>i>>j;
v[i].push_back(make_pair(j,a));
v[j].push_back(make_pair(i,a));
}
int flag=0;
int k;
for(int a=1;a<=n;a++)if(v[a].size()>2)flag=1;else if(v[a].size()==1)k=a;
if(flag==1)cout<<-1<<endl;
else
{
dfs(k,0,2);
for(int a=1;a<=n-1;a++)cout<<ans[a]<<" ";
cout<<endl;
}
}
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
//clock_t st,en;
//st=clock();
//Get_Time();
solve();
//en=clock();
//cout<<(double)(en-st)/CLOCKS_PER_SEC<<endl;
return 0;
}