CF1635E Cars
在一个数轴上有 n n n 个点,并给定 m m m 个限制。表示 u , v u,v u,v 会相遇或者不会相遇。其中的相遇指的是无论 u , v u,v u,v 的初始速度是什么都会或者不会相遇。输出是否可以满足所有的限制,如果可以输出方案即每辆车的位置与方向。
1.如果 u , v u,v u,v 方向相同那么是无法确定, u , v u,v u,v 是相遇还是不相遇的。所有有限制点的朝向不同,由于只有两个方向故考虑使用二分图。
2.建图判断是否为二分图,如果不是二分图显然无解,是二分图的情况下我们把其中一边的点看作方向朝左,另一些看作朝右。
3.那么如果一个左点不会遇到一个右点显然,左点的位置在左边,,如果是左点会遇到右点则左点在右边。反之亦然。
4.显然这是一种偏序关系,我们称在左边的位置是小于在右边,即如果 u < v u < v u<v 有边 u − > v u -> v u−>v 然后用拓扑排序即可。
5.如果有拓扑序说明有解,按拓扑序输出即可,否则无解。
#include<bits/stdc++.h>
//#pragma GCC optimize(2)
#define endl "\n"
#define int long long
#define pii pair<int,int>
#define pll pair<long long,long long>
#define fi first
#define sc second
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf32 = 0x3f3f3f3f;
const ll inf64 = 0x3f3f3f3f3f3f3f3f;
const double pi = acos(-1),eps = 1e-7;
mt19937 rnd(time(0));
const int maxn = 2*1e5+10,maxm = 1e6+10,mod = 1e9+7;
int n,m,d[maxn],ans[maxn];
vector<int> g[maxn],e[maxn];
struct node{
int u,v,type;
};
vector<node> a;
int color[maxn];
bool dfs(int u,int c){
color[u] = c;
for(int v : g[u]){
if(color[v]){
if(color[v] == color[u]) return false;
}else if (!dfs(v,3-c)) return false;
}
return true;
}
bool check(){
memset(color,0,sizeof(color));
for(int i = 1;i <= n;i++){
if(!color[i]){
if(!dfs(i,1)) return false;
}
}
return true;
}
vector<int> top;
void topsort(){
queue<int> q;
for(int i = 1;i <= n;i++){
if(!d[i]) q.push(i);
}
while(q.size()){
int u = q.front();
q.pop();
top.push_back(u);
for(int v : e[u]){
d[v]--;
if(!d[v]){
q.push(v);
}
}
}
}
signed main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
//freopen("in.in","r",stdin);
//freopen("out.out","w",stdout);
cin>>n>>m;
while(m--){
int u,v,type;
cin>>type>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
a.push_back({u,v,type});
}
if(!check()){
cout<<"NO"<<endl;
return 0;
}
for(int i = 0;i < a.size();i++){
int u,v,type;
u = a[i].u,v = a[i].v,type = a[i].type;
if(color[u] == 1){
if(type == 1) e[u].push_back(v),d[v]++;
else e[v].push_back(u),d[u]++;
}else{
if(type == 1) e[v].push_back(u),d[u]++;
else e[u].push_back(v),d[v]++;
}
}
topsort();
if(top.size() == n){
int t = 0;
for(int u : top){
ans[u] = t++;
}
cout<<"YES"<<endl;
for(int i = 1;i <= n;i++){
if(color[i] == 1) cout<<"L"<<" "<<ans[i]<<endl;
else cout<<"R"<<" "<<ans[i]<<endl;
}
}else{
cout<<"NO"<<endl;
}
return 0;
}