Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Questions_bank_for_Final_exam_on_SSD5 (2).docx
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
72.52 Кб
Скачать

Int main ()

{

int tmp, i, j = 0, save = 1, qsave = 0;

cin » N;

save = 1;

if (N == 2)

{

bool ok = true, first = true;

cin » k;

if (k)

{

cin » tmp;

i = 1;

while (tmp == 1 && i < k)

{

cin » tmp;

++i;

}

j = tmp == 2;

while (i < k)

{

cin » tmp;

if (tmp == 1) ok = false;

++j;

++i;

}

}

cin » k;

if (k)

{

cin » tmp;

i = 1;

while (tmp == 2 && i < k)

{

cin » tmp;

++i;

}

if (j && tmp == 1) ok = false;

else if (tmp == 1) first = false;

j += tmp == 1;

while (i < k)

{

cin » tmp;

if (tmp == 2) ok = false;

++j;

++i;

}

}

if (ok)

{

if (first)

for (i = 0; i < j; ++i)

cout « "1 2" « endl;

else

for (i = 0; i < j; ++i)

cout « "2 1" « endl;

}

else cout « 0;

return 0;

}

for (i = 1; i <= N; ++i)

{

cin » k;

if (k)

{

cin » tmp;

j = 1;

while (tmp == i && j < k)

{

cin » tmp;

++j;

}

if (tmp != i) cont[i].push (tmp);

while (j < k)

{

cin » tmp;

cont[i].push (tmp);

++j;

}

}

}

for (i = 1; i < N; ++i)

{

while (!cont[i].empty ())

{

while (!cont[i].empty () && cont[cont[i].back ()].empty ())

{

cout « i « " " « cont[i].pop() « endl;

}

while (!cont[i].empty () && !cont[cont[i].back ()].empty ())

{

cout « i « " " « N « endl;

cont[N].push (cont[i].pop ());

}

}

while (!cont[i].empty ())

{

cout « i « " " « N « endl;

cont[N].push (cont[i].pop ());

}

}

while (!cont[N].empty ())

{

tmp = cont[N].pop ();

if (tmp == N)

{

cout « N « " " « save « endl;

++qsave;

}

else if (tmp == save)

{

save = 1 + save % 2;

for (i = 0; i < qsave; ++i)

{

cout « tmp « " " « save « endl;

}

cout « N « " " « tmp « endl;

}

else

{

cout « N « " " « tmp « endl;

}

}

for (i = 0; i < qsave; ++i)

{

cout « save « " " « N « endl;

}

return 0;

}

Графы

  1. Implementation of Djecstra, bfs and dfs

Djecstra

    1. #include<iostream>

    2. #define INFINITY 999

    3. Using namespace std;

    4. class Dijkstra{

    5. private:

    6. int adjMatrix[15][15];

    7. int predecessor[15],distance[15];

    8. bool mark[15]; //keep track of visited node

    9. int source;

    10. int numOfVertices;

    11. public:

    12. /*

    13. * Function read() reads No of vertices, Adjacency Matrix and source

    14. * Matrix from the user. The number of vertices must be greather than

    15. * zero, all members of Adjacency Matrix must be postive as distances

    16. * are always positive. The source vertex must also be positive from 0

    17. * to noOfVertices - 1

    18. */

    19. void read();

    20. /*

    21. * Function initialize initializes all the data members at the begining of

    22. * the execution. The distance between source to source is zero and all other

    23. * distances between source and vertices are infinity. The mark is initialized

    24. * to false and predecessor is initialized to -1

    25. */

    26. void initialize();

    27. /*

    28. * Function getClosestUnmarkedNode returns the node which is nearest from the

    29. * Predecessor marked node. If the node is already marked as visited, then it search

    30. * for another node.

    31. */

    32. int getClosestUnmarkedNode();

    33. /*

    34. * Function calculateDistance calculates the minimum distances from the source node to

    35. * Other node.

    36. */

    37. void calculateDistance();

    38. /*

    39. * Function output prints the results

    40. */

    41. void output();

    42. void printPath(int);

    43. };

    44. void Dijkstra::read(){

    45. cout<<"Enter the number of vertices of the graph(should be > 0)\n";

    46. cin>>numOfVertices;

    47. while(numOfVertices <= 0) {

    48. cout<<"Enter the number of vertices of the graph(should be > 0)\n";

    49. cin>>numOfVertices;

    50. }

    51. cout<<"Enter the adjacency matrix for the graph\n";

    52. cout<<"To enter infinity enter "<<INFINITY<<endl;

    53. for(int i=0;i<numOfVertices;i++) {

    54. cout<<"Enter the (+ve)weights for the row "<<i<<endl;

    55. for(int j=0;j<numOfVertices;j++) {

    56. cin>>adjMatrix[i][j];

    57. while(adjMatrix[i][j]<0) {

    58. cout<<"Weights should be +ve. Enter the weight again\n";

    59. cin>>adjMatrix[i][j];

    60. }

    61. }

    62. }

    63. cout<<"Enter the source vertex\n";

    64. cin>>source;

    65. while((source<0) && (source>numOfVertices-1)) {

    66. cout<<"Source vertex should be between 0 and"<<numOfVertices-1<<endl;

    67. cout<<"Enter the source vertex again\n";

    68. cin>>source;

    69. }

    70. }

    71. void Dijkstra::initialize(){

    72. for(int i=0;i<numOfVertices;i++) {

    73. mark[i] = false;

    74. predecessor[i] = -1;

    75. distance[i] = INFINITY;

    76. }

    77. distance[source]= 0;

    78. }

    79. int Dijkstra::getClosestUnmarkedNode(){

    80. int minDistance = INFINITY;

    81. int closestUnmarkedNode;

    82. for(int i=0;i<numOfVertices;i++) {

    83. if((!mark[i]) && ( minDistance >= distance[i])) {

    84. minDistance = distance[i];

    85. closestUnmarkedNode = i;

    86. }

    87. }

    88. return closestUnmarkedNode;

    89. }

    90. void Dijkstra::calculateDistance(){

    91. initialize();

    92. int minDistance = INFINITY;

    93. int closestUnmarkedNode;

    94. int count = 0;

    95. while(count < numOfVertices) {

    96. closestUnmarkedNode = getClosestUnmarkedNode();

    97. mark[closestUnmarkedNode] = true;

    98. for(int i=0;i<numOfVertices;i++) {

    99. if((!mark[i]) && (adjMatrix[closestUnmarkedNode][i]>0) ) {

    100. if(distance[i] > distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i]) {

    101. distance[i] = distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i];

    102. predecessor[i] = closestUnmarkedNode;

    103. }

    104. }

    105. }

    106. count++;

    107. }

    108. }

    109. void Dijkstra::printPath(int node){

    110. if(node == source)

    111. cout<<(char)(node + 97)<<"..";

    112. else if(predecessor[node] == -1)

    113. cout<<"No path from “<<source<<”to "<<(char)(node + 97)<<endl;

    114. else {

    115. printPath(predecessor[node]);

    116. cout<<(char) (node + 97)<<"..";

    117. }

    118. }

    119. void Dijkstra::output(){

    120. for(int i=0;i<numOfVertices;i++) {

    121. if(i == source)

    122. cout<<(char)(source + 97)<<".."<<source;

    123. else

    124. printPath(i);

    125. cout<<"->"<<distance[i]<<endl;

    126. }

    127. }

    128. int main(){

    129. Dijkstra G;

    130. G.read();

    131. G.calculateDistance();

    132. G.output();

    133. return 0;

    134. }

2. BFS

#include <iostream>

#include <ctime>

using namespace std;

/****************************************************************

Performs the Breadth-First Graph search for both directed and

undirected graphs. This algorithm explores all the findable nodes

in "layers".

@author Bibek Subedi

*****************************************************************/

/****************************************************************

Class Queue represent a Queue data structure which is First In

First Out [FIFO] structured. It has operations like Enqueue which

adds an element at the rear side and Dequeue which removes the

element from front.

*****************************************************************/

struct node {

int info;

node *next;

};

class Queue {

private:

node *front;

node *rear;

public:

Queue();

~Queue();

bool isEmpty();

void enqueue(int);

int dequeue();

void display();

};

void Queue::display(){

node *p = new node;

p = front;

if(front == NULL){

cout<<"\nNothing to Display\n";

}else{

while(p!=NULL){

cout<<endl<<p->info;

p = p->next;

}

}

}

Queue::Queue() {

front = NULL;

rear = NULL;

}

Queue::~Queue() {

delete front;

}

void Queue::enqueue(int data) {

node *temp = new node();

temp->info = data;

temp->next = NULL;

if(front == NULL){

front = temp;

}else{

rear->next = temp;

}

rear = temp;

}

int Queue::dequeue() {

node *temp = new node();

int value;

if(front == NULL){

cout<<"\nQueue is Emtpty\n";

}else{

temp = front;

value = temp->info;

front = front->next;

delete temp;

}

return value;

}

bool Queue::isEmpty() {

return (front == NULL);

}

/************************************************************

Class Graph represents a Graph [V,E] having vertices V and

edges E.

************************************************************/

class Graph {

private:

int n; /// n is the number of vertices in the graph

int **A; /// A stores the edges between two vertices

public:

Graph(int size = 2);

~Graph();

bool isConnected(int, int);

void addEdge(int u, int v);

void BFS(int );

};

Graph::Graph(int size) {

int i, j;

if (size < 2) n = 2;

else n = size;

A = new int*[n];

for (i = 0; i < n; ++i)

A[i] = new int[n];

for (i = 0; i < n; ++i)

for (j = 0; j < n; ++j)

A[i][j] = 0;

}

Graph::~Graph() {

for (int i = 0; i < n; ++i)

delete [] A[i];

delete [] A;

}

/******************************************************

Checks if two given vertices are connected by an edge

@param u vertex

@param v vertex

@return true if connected false if not connected

******************************************************/

bool Graph::isConnected(int u, int v) {

return (A[u-1][v-1] == 1);

}

/*****************************************************

adds an edge E to the graph G.

@param u vertex

@param v vertex

*****************************************************/

void Graph::addEdge(int u, int v) {

A[u-1][v-1] = A[v-1][u-1] = 1;

}

/*****************************************************

performs Breadth First Search

@param s initial vertex

*****************************************************/

void Graph::BFS(int s) {

Queue Q;

/** Keeps track of explored vertices */

bool *explored = new bool[n+1];

/** Initailized all vertices as unexplored */

for (int i = 1; i <= n; ++i)

explored[i] = false;

/** Push initial vertex to the queue */

Q.enqueue(s);

explored[s] = true; /** mark it as explored */

cout << "Breadth first Search starting from vertex ";

cout << s << " : " << endl;

/** Unless the queue is empty */

while (!Q.isEmpty()) {

/** Pop the vertex from the queue */

int v = Q.dequeue();

/** display the explored vertices */

cout << v << " ";

/** From the explored vertex v try to explore all the

connected vertices */

for (int w = 1; w <= n; ++w)

/** Explores the vertex w if it is connected to v

and and if it is unexplored */

if (isConnected(v, w) && !explored[w]) {

/** adds the vertex w to the queue */

Q.enqueue(w);

/** marks the vertex w as visited */

explored[w] = true;

}

}

cout << endl;

delete [] explored;

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]