Ring Road 2

Ring Road 2

题目链接

思路:先考虑什么情况下会相交,对于两条道路 \((x_1,y_1)\)\((x_2,y_2)\) 。这里默认 \(x < y\) ,显然

当 $x2 < x1<y2 $ 并且 \(y1<x2\) || \(y1>y2\) 时(\(x1\)\(y1\) 互换也可以,即一个点在范围内,一个点在范围外),

那么两条道路就会产生交点。

因此对于产生交点的两条道路,如果一条在环内,那么另外一条必须在环外。反之同理。那么直接 \(2-SAT\) 建边即可。

tips:以往的题目都是通过转化成或关系然后转蕴含关系再建边,此类题目可以根据选了谁必须选谁就可以更加方便的建边了。

注意不要少建了两条边即可。

代码

#include<bits/stdc++.h>

using namespace std;

#define ff first
#define ss second
#define pb push_back
#define all(u) u.begin(), u.end()
#define endl '\n'
#define debug(x) cout<<#x<<":"<<x<<endl;

typedef pair<int, int> PII;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int N = 1e5 + 10, M = 105;
const int mod = 1e9 + 7;
const int cases = 0;

vector<int> e[N];
stack<int> stk;
int dfn[N],low[N],tot;
int instk[N],scc[N],siz[N],cnt;
int n,m,st[N];

void tarjan(int u){
  dfn[u]=low[u]=++tot;
  stk.push(u);instk[u]=1;
  for(auto v:e[u]){
    if(!dfn[v]){
      tarjan(v);
      low[u]=min(low[u],low[v]);
    }else if(instk[v]) low[u]=min(low[u],dfn[v]);
  }
  if(dfn[u]==low[u]){
    int v;cnt++;
    do{
      v=stk.top();
      stk.pop();
      instk[v]=0;
      scc[v]=cnt;
      siz[cnt]++;
    }while(v!=u);
  }  
}

void Showball(){
  cin>>n>>m;
  vector<PII> a(m); 
  for(int i=0;i<m;i++){
    int u,v;
    cin>>u>>v;
    if(u>v) swap(u,v);
    a[i]={u,v};
  }
  
  auto check=[&](int x,int y,int st,int ed){
     return (st<x&&x<ed&&(y<st||y>ed))||(st<y&&y<ed&&(x<st||x>ed));
  };
  
  for(int i=0;i<m;i++){
    auto [st,ed]=a[i];
    for(int j=i+1;j<m;j++){
      auto [u,v]=a[j];
      if(check(u,v,st,ed)){
        e[i<<1].pb(j<<1|1);
        e[j<<1].pb(i<<1|1);
        e[i<<1|1].pb(j<<1);
        e[j<<1|1].pb(i<<1);
      }
    }
  }
  for(int i=0;i<2*m;i++){
    if(!dfn[i]) tarjan(i);
  }

  string ans="";
  for(int i=0;i<m;i++){
     if(scc[i<<1]==scc[i<<1|1]) return cout<<"Impossible\n",void();
     ans+=(scc[i<<1]<scc[i<<1|1]?"i":"o");   
  }
  cout<<ans<<endl;

}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int T=1;
    if(cases) cin>>T;
    while(T--)
    Showball();
    return 0;
}
posted @ 2024-05-20 11:42  Showball  阅读(2)  评论(0编辑  收藏  举报