1. 程式人生 > >Leha and another game about graph CodeForces - 840B (dfs)

Leha and another game about graph CodeForces - 840B (dfs)

get game force ces 給定 light void back problems

鏈接

大意: 給定無向連通圖, 每個點有權值$d_i$($-1\leq d_i \leq 1$), 求選擇一個邊的集合, 使得刪除邊集外的所有邊後, $d_i$不為-1的點的度數模2等於權值

首先要註意到該題只需要考慮dfs樹即可, 因為反向邊一定不會產生貢獻

存在權值為-1的點, 則直接以權值為-1的點為根dfs

若無權值為-1的點, 則答案不一定存在, 任選一個點為根dfs即可

#include <iostream>
#include <algorithm>
#include <math.h>
#include <cstdio>
#include <vector>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define x first
#define y second
#define pb push_back 
using namespace std;
typedef pair<int,int> pii;

const int N = 4e5+10, INF = 0x3f3f3f3f;
int a[N], b[N], c[N], vis[N], f[N], n, m, k, t;
vector<pii> g[N];

void dfs(int x) {
	if (vis[x]) return;
	vis[x]=1;
	for (auto e:g[x]) {
		dfs(e.x);
		if (a[e.x]==1) a[e.x]=0,f[e.y]^=1,a[x]^=1;
	}
}

int main() {
	scanf("%d%d", &n, &m);
	int rt = 1;
	REP(i,1,n) scanf("%d", a+i),a[i]==-1?rt=i:0;
	REP(i,1,m) {
		int u, v;
		scanf("%d%d",&u,&v);
		g[u].pb({v,i}),g[v].pb({u,i});
	}
	dfs(rt);
	if (a[rt]==1) return puts("-1"),0;
	int cnt = 0;
	REP(i,1,m) cnt += f[i];
	printf("%d\n", cnt);
	REP(i,1,m) if (f[i]) printf("%d ",i);
	puts("");
}

Leha and another game about graph CodeForces - 840B (dfs)