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

题目链接

B. Leha and another game about graph

分析

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

ac code

#include
#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 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;
}

你可能感兴趣的:(算法刷题)