codeforces 840B. Leha and another game about graph(构造,dfs)

本文介绍了一个关于图论的游戏问题,并提供了一种有效的解决思路和代码实现。通过深度优先搜索(DFS)确定图中边的操作顺序,使得每个节点的状态满足题目要求。文章包含完整的ACM代码和关键算法步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

B. Leha and another game about graph

分析

思维题,仔细分析题意其实一点也不难。详情见官方文档

ac code

#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define PI acos(-1)
#define fi first
#define se second
#define INF 0x3f3f3f3f
#define INF64 0x3f3f3f3f3f3f3f3f
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define ms(x,v) memset((x),(v),sizeof(x))
#define scint(x) scanf("%d",&x );
#define scf(x) scanf("%lf",&x );
#define eps 1e-10
#define dcmp(x) (fabs(x) < eps? 0:((x) <0?-1:1))
#define lc o<<1
#define rc o<<1|1
using namespace std;
typedef long long LL;
typedef long double DB;
typedef pair<int,int> Pair;
const int maxn = 3e5+10;
const int MAX_V= 500+10;
const int MOD = 1e9+7;
int d[maxn];
std::vector<Pair> G[maxn];
std::vector<int> ans;
bool vis[maxn];
bool dfs(int u){
   vis[u] = 1;
   for(auto e : G[u]){
      if(vis[e.fi])continue;
      if(dfs(e.fi)){
         ans.pb(e.se);
         d[e.fi] ^=1;
         d[u] ^=1;
      }
   }
   return d[u];
}


int main()
{
    ios_base::sync_with_stdio(0);
    cout.tie(0);
    cin.tie(0);
    int n,m;
    cin>>n>>m;
    int ok = 0;
    int root = -1;
    for(int i=1  ; i<=n ; ++i){
      cin>>d[i];
      if(d[i] == -1)root = i;
      else ok ^=d[i];
   }
   for(int i=1 ; i<=m ; ++i){
      int u,v;cin>>u>>v;
      G[u].pb(mp(v,i));
      G[v].pb(mp(u,i));
   }
   if(ok && root == -1){
      std::cout << "-1" << '\n';return 0;
   }
   if(ok)d[root] = 1;
   else root =1;
   for(int i=1 ; i<=n ; ++i){
      if(d[i]==-1)d[i]=0;
   }
   ms(vis,0);
   dfs(root);
   std::cout << ans.size() << '\n';
   for(auto id: ans){
      std::cout << id << '\n';
   }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值