CF883G Orientation of Edges(贪心+dfs)
作者:互联网
思路:
首先,从起点通过有向边连接的点是一定可以到达的,我们只需要最大化&&最小化通过无向边连接的点。
其次,贪心的考虑这个问题,如果是最大化的话,从起点连出去的无向边是向外扩展的,也就是说假设起点为\(u\),边为\(u-v\),那么方向为\(u->v\)的比较优的;对于最小化也同理,向内扩展是最优的。
\(dfs\)跑一下就好了,每个点最多会经过一次,时间复杂度\(O(n+m)\)
代码:
// Problem: CF883G Orientation of Edges
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/CF883G
// Memory Limit: 250 MB
// Time Limit: 3000 ms
// Author:Cutele
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read()
{
ll x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9')
{
if(ch == '-')f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9')
{
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
inline void out(ll x){
if (x < 0) x = ~x + 1, putchar('-');
if (x > 9) out(x / 10);
putchar(x % 10 + '0');
}
inline void write(ll x){
if (x < 0) x = ~x + 1, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)
ll ksm(ll a, ll b,ll p)
{
ll res = 1;
while(b)
{
if(b & 1)res = res * a%p;
a = a * a %p;
b >>= 1;
}
return res;
}
const int maxn=3e5+100;
vector<PII>g[maxn];
int op[maxn],vis[maxn],ans[maxn],sum=0,n,m,s;
PII pos[maxn];
void dfs1(int u){
if(vis[u]) return ;
vis[u]=1;sum++;
// cout<<u<<endl;
for(int i=0;i<g[u].size();i++){
PII t=g[u][i];
int nex=t.first,id=t.second;
if(op[id]==1) dfs1(nex);
else if(!ans[id]){
if(nex==pos[id].second) ans[id]=1;
else ans[id]=2;
dfs1(nex);
}
}
}
void dfs2(int u){
if(vis[u]) return ;
vis[u]=1;sum++;
for(int i=0;i<g[u].size();i++){
PII t=g[u][i];
int nex=t.first,id=t.second;
if(op[id]==1) dfs2(nex);
else if(op[id]==2&&!ans[id]){
if(nex==pos[id].second) ans[id]=2;
else ans[id]=1;
}
}
}
int main(){
n=read,m=read,s=read;
rep(i,1,m){
op[i]=read;
int u=read,v=read;
pos[i]={u,v};
g[u].push_back({v,i});
if(op[i]==2) g[v].push_back({u,i});
}
dfs1(s);
printf("%d\n",sum);
rep(i,1,m){
if(op[i]==2){
if(ans[i]==1) cout<<"+";
else cout<<"-";
}
ans[i]=0;
}
puts("");
sum=0;
rep(i,1,n) vis[i]=0;
dfs2(s);
printf("%d\n",sum);
rep(i,1,m){
if(op[i]==2){
if(ans[i]==1) cout<<"+";
else cout<<"-";
}
ans[i]=0;
}
puts("");
return 0;
}
标签:typedef,ch,Orientation,int,ll,Edges,maxn,CF883G,define 来源: https://www.cnblogs.com/OvOq/p/15108965.html