这道题真的,我哭死QWQ
自己想的这段代码没有过去,只过去了14个样例(共19),
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int n, m, e[N], ne[N], h[N], idx, color[N];
queue<int> q;
void add(int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
bool dfs(int x)
{
for (int i = h[x]; i != -1; i = ne[i])
{
int j = e[i];
if (!color[j])
color[j] = 3 - color[x], q.push(j);
else
{
if (color[j] == color[x])
return false;
else
continue;
}
return true;
}
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
while (m--)
{
int v, p;
cin >> v >> p;
add(v, p);
add(p, v);
}
q.push(1);
color[1] = 1;
while (q.size())
{
auto t = q.front();
q.pop();
if (dfs(t))
continue;
else
{
cout << "No" << endl;
return 0;
}
}
cout << "Yes" << endl;
return 0;
}
然后我去学了y总的
我想了一下,这是在数据过10000+时发生的答案错误,在插入一个数要对那个数造成的影响负责(dfs()),不能仅仅赋值(color[j] = 3-c;)
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10,M = 1e6 + 10;
int n, m,color[N],ne[M],e[M],h[N],idx;
void add(int a,int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
bool dfs(int u,int c)
{
color[u] = c;
for (int i = h[u]; ~i ; i=ne[i]) {
int j = e[i];
if(!color[j]) {
if(!dfs(j,3-c)) return false;//有谁跟我一样这里一开始写的是 color[j]=3-c;QWQ
}
else if(color[j]==color[u])
return false;
}
return true;
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int v, p;cin >> v >> p;
add(v, p);
add(p, v);
}
for (int i = 1; i <= n; i++) {
if (!color[i]) {
if(!dfs(i,1)) {
cout << "No";
return 0;
}
}
}
cout << "Yes";
return 0;
}