
Go Deeper
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 3184 Accepted Submission(s): 1035
Problem Description
go(int dep, int n, int m)
begin
output the value of dep.
if dep < m and x[a[dep]] + x[b[dep]] != c[dep] then go(dep + 1, n, m)
end
In this code n is an integer. a, b, c and x are 4 arrays of integers. The index of array always starts from 0. Array a and b consist of non-negative integers smaller than n. Array x consists of only 0 and 1. Array c consists of only 0, 1 and 2. The lengths of array a, b and c are m while the length of array x is n. Given the elements of array a, b, and c, when we call the procedure go(0, n, m) what is the maximal possible value the procedure may output?
Input
Output
Sample Input
2 1
0 1 0
2 1
0 0 0
2 2
0 1 0
1 1 2
Sample Output
1
2
Author
Source
//2017-08-27
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cmath> using namespace std; const int N = ;
const int M = N*N;
const double EPS = 1e-;
int head[N], rhead[N], tot, rtot;
struct Edge{
int to, next;
}edge[M], redge[M]; void init(){
tot = ;
rtot = ;
memset(head, -, sizeof(head));
memset(rhead, -, sizeof(rhead));
} void add_edge(int u, int v){
edge[tot].to = v;
edge[tot].next = head[u];
head[u] = tot++; redge[rtot].to = u;
redge[rtot].next = rhead[v];
rhead[v] = rtot++;
} vector<int> vs;//后序遍历顺序的顶点列表
bool vis[N];
int cmp[N];//所属强连通分量的拓扑序 //input: u 顶点
//output: vs 后序遍历顺序的顶点列表
void dfs(int u){
vis[u] = true;
for(int i = head[u]; i != -; i = edge[i].next){
int v = edge[i].to;
if(!vis[v])
dfs(v);
}
vs.push_back(u);
} //input: u 顶点编号; k 拓扑序号
//output: cmp[] 强连通分量拓扑序
void rdfs(int u, int k){
vis[u] = true;
cmp[u] = k;
for(int i = rhead[u]; i != -; i = redge[i].next){
int v = redge[i].to;
if(!vis[v])
rdfs(v, k);
}
} //Strongly Connected Component 强连通分量
//input: n 顶点个数
//output: k 强连通分量数;
int scc(int n){
memset(vis, , sizeof(vis));
vs.clear();
for(int u = ; u < n; u++)
if(!vis[u])
dfs(u);
int k = ;
memset(vis, , sizeof(vis));
for(int i = vs.size()-; i >= ; i--)
if(!vis[vs[i]])
rdfs(vs[i], k++);
return k;
} int n, m;
int a[], b[], c[]; bool check(int len){
init();
for(int i = ; i < len; i++){
if(c[i] == ){
add_edge(a[i]+n, b[i]);
add_edge(b[i]+n, a[i]);
}else if(c[i] == ){
add_edge(a[i], b[i]);
add_edge(a[i]+n, b[i]+n);
add_edge(b[i], a[i]);
add_edge(b[i]+n, a[i]+n);
}else if(c[i] == ){
add_edge(a[i], b[i]+n);
add_edge(b[i], a[i]+n);
}
}
scc(n<<);
for(int i = ; i < n; i++)
if(cmp[i] == cmp[i+n])
return false;
return true;
} int main()
{
std::ios::sync_with_stdio(false);
//freopen("inputD.txt", "r", stdin);
int T;
cin>>T;
while(T--){
cin>>n>>m;
for(int i = ; i < m; i++)
cin>>a[i]>>b[i]>>c[i];
int l = , r = m, mid, ans;
while(l <= r){
mid = (l+r)/;
if(check(mid)){
ans = mid;
l = mid+;
}else
r = mid-;
}
cout<<ans<<endl;
} return ;
}