Add variations on PDP26 A task (juniors, graphs)

parent 18eafc36
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
enum state { UNVISITED, SEEN, VISITED };
int main ()
{
int N, M;
scanf("%d %d", &N, &M);
vector<int> neighbors[N+1];
for (int i=0; i<M; i++) {
int u, v;
scanf("%d %d", &u, &v);
neighbors[u].push_back(v);
neighbors[v].push_back(u);
}
// BFS scanning from 1
queue<int> Q;
vector<int> p(N+1);
vector<state> m(N+1);
Q.push(1);
m[1] = SEEN;
while (!Q.empty()) {
int u = Q.front();
Q.pop();
m[u] = VISITED;
#if 0
for (vector<int>::iterator i = neighbors[u].begin();
i != neighbors[u].end(); i++)
if (m[*i] == UNVISITED) {
Q.push(*i);
m[*i] = SEEN;
p[*i] = u;
}
#else
for (int k=0; k < neighbors[u].size(); k++) {
int v = neighbors[u][k];
if (m[v] == UNVISITED) {
Q.push(v);
m[v] = SEEN;
p[v] = u;
}
}
#endif
}
for (int i=1; i<=N; i++)
printf("parent of %d is %d\n", i, p[i]);
return 0;
}
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
vector< vector<int> > neighbors;
vector<int> p;
enum state { UNVISITED, SEEN, VISITED };
vector<state> m;
void dfs (int u)
{
m[u] = SEEN;
for (vector<int>::iterator i = neighbors[u].begin();
i != neighbors[u].end(); i++)
if (m[*i] == UNVISITED) {
p[*i] = u;
dfs(*i);
}
m[u] = VISITED;
}
int main ()
{
int N, M;
scanf("%d %d", &N, &M);
neighbors.resize(N+1);
for (int i=0; i<M; i++) {
int u, v;
scanf("%d %d", &u, &v);
neighbors[u].push_back(v);
neighbors[v].push_back(u);
}
// DFS scanning from all possible starts
p.resize(N+1);
m.resize(N+1);
for (int i=1; i<=N; i++)
if (m[i] == UNVISITED)
dfs(i);
for (int i=1; i<=N; i++)
printf("parent of %d is %d\n", i, p[i]);
return 0;
}
#include <stdio.h>
#include <vector>
using namespace std;
int main ()
{
int N, M;
scanf("%d %d", &N, &M);
// you don't really need an adjacency list for
// this problem!!!
vector<int> neighbors[N];
for (int i=0; i<M; i++) {
int u, v;
scanf("%d %d", &u, &v);
u--; v--;
neighbors[u].push_back(v);
neighbors[v].push_back(u);
}
int count = 0;
for (int i=0; i<N; i++)
if (neighbors[i].size() < 2) count++;
printf("%d\n", count);
return 0;
}
#include <stdio.h>
#include <vector>
using namespace std;
int main ()
{
int N, M;
scanf("%d %d", &N, &M);
// we should not really be using an adjacency
// matrix for this problem!!!
vector<bool> A[N];
for (int i=0; i<N; i++)
A[i].resize(N);
for (int i=0; i<M; i++) {
int u, v;
scanf("%d %d", &u, &v);
u--; v--;
A[u][v] = A[v][u] = true;
}
int count = 0;
for (int i=0; i<N; i++) {
int degree_i = 0;
for (int j=0; j<N; j++)
if (A[i][j]) degree_i++;
if (degree_i < 2) count++;
}
printf("%d\n", count);
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment