题意:给一棵n个点的无根树和q条有向路径,请构造出任意合法有向树使得所有点的出度不大于1.保证输入合法。
- 首先对任意一个点建一棵树维护祖先关系;
- 对于任意一颗子树R:
- 若子树中存在某一起点S的终点在子树外那么,R的与父节点的路径指向父节点。
- 若子树中存在某一起点T的起点在子树外那么,R的与父节点的路径指向父节点。
- 由于题目保证了数据合法,那么我们可以简单的维护一个(S++T--)的树上查分。快速的查询子树中的起终点的关系建边;
- 对于子树R的查分等于0有
- R的出度为零,直接由R指向父节点。贪心的维护父节点的最小出度;
- R的出度不为零,那么只能由父节点指向R了。
#include<algorithm>
#include<vector>
#include<iostream>
#include<math.h>
#include<cstring>
#include<string>
#include<stack>
#include<map>
#include<set>
#include<unordered_map>
#include<queue>
#define qcin; ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define pb push_back
#define clr(x) memset(x,0,sizeof x)
#define fmax(x) memset(x,0x3f,sizeof x)
#define finit(x) memset(x,-1,sizeof x)
#define dis(l,r) r-l+1
#define gstr(str) scanf("%s",str)
#define glen(str) strlen(str)
using namespace std;
typedef long long ll;
namespace Input{
const int BUF = 65536;
char buf[BUF + 1];
char *head = buf, *tail = buf;
}
inline char inputchar(){
using namespace Input;
if(head == tail)
*(tail = (head = buf) + fread(buf, 1, BUF, stdin)) = 0;
return *head++;
}
inline void io(int &ret){
char ch = inputchar();
while(ch < '0' || ch > '9')
ch = inputchar();
ret = ch - '0';
ch = inputchar();
while(ch >= '0' && ch <= '9'){
ret = ret * 10 + ch - '0';
ch = inputchar();
}
}
inline void sio(int &ret){
ret = 0;
char ch = inputchar();
while((ch < '0' || ch > '9') && ch != '-')
ch = inputchar();
bool neg = false;
if(ch == '-')
neg = true, ch = inputchar();
while(ch >= '0' && ch <= '9'){
ret = ret * 10 + ch - '0';
ch = inputchar();
}
if(neg)
ret = -ret;
}
typedef pair<ll,ll>pll;
const int maxn = 2e6+10;
typedef int arr[maxn];
typedef char str[maxn];
void file(int x){if(x&&fopen("in.txt","r")){freopen("in.txt","r",stdin);}}
struct node{
int to,next;
}E[maxn];
int n,m,x,L,u,v,R[maxn],q,len,t,tot;
arr sum,cnt,head,res,dep,out;
const double pi=acos(-1);
void addedge(int u,int v){
E[tot].to=v;
E[tot].next=head[u];
head[u]=tot++;
}
void dfs(int u,int pre,int d){
dep[u]=d;
for(int i=head[u];~i;i=E[i].next){
int v=E[i].to;
if(v!=pre){
dfs(v,u,d+1);
sum[u]+=sum[v];
}
}
if(sum[u]>0)res[u]=1;
else if(sum[u]<0){
res[u]=0;
out[pre]++;
}else if(sum[u]==0){
if(out[u]){
res[u]=0;
out[pre]++;
}
else res[u]=1;
}
}
int e[maxn][2];
char s[2]={'C','D'};
int main(){
file(1);
for(io(t);t--;){
tot=0;
io(n),io(q);
memset(sum,0,(n+5)*sizeof(int));
memset(out,0,(n+5)*sizeof(int));
memset(res,-1,(n+5)*sizeof(int));
memset(head,-1,(n+5)*sizeof(int));
for(int i=1;i<n;i++){
io(e[i][0]),io(e[i][1]);
addedge(e[i][0],e[i][1]);
addedge(e[i][1],e[i][0]);
}
while(q--){
io(u),io(v);
sum[u]++;sum[v]--;
}
dfs(1,0,0);
for(int i=1;i<n;i++){
int tmp=0,son;
if(dep[e[i][0]]>dep[e[i][1]]){
son=e[i][0];
}else{
tmp=1;
son=e[i][1];
}
putchar(s[res[son]^tmp]);
//cout<<s[res[son]^tmp];
}
puts("");
}
return 0;
}