33
#include<conio.h> #include<iostream.h> #include<stdio.h> #include<stdlib.h> #include<string.h> template<class Entry> struct Node { Entry data; Node * next; }; template<class Entry> struct List { Node< Entry> * first,* last; }; struct Data1 { char * name; int length; }; struct Data2 { char * name; List< Data1> * list; }; struct Data3 { int sumlength; List< Data1> * list; }; template<class Entry> void AddNode( List< Entry>* list,Entry data) {

Code C# _ bai toan nguoi dua thu

Embed Size (px)

Citation preview

Page 1: Code C# _ bai toan nguoi dua thu

#include<conio.h>#include<iostream.h>#include<stdio.h>#include<stdlib.h>#include<string.h>template<class Entry>struct Node{    Entry data;    Node *next;};template<class Entry>struct List{    Node<Entry> *first,*last;};struct Data1{    char *name;    int length;};struct Data2{    char *name;    List<Data1> *list;};struct Data3{    int sumlength;    List<Data1> *list;};template<class Entry>void AddNode(List<Entry>* list,Entry data){    Node<Entry> *node=new Node<Entry>;    node->data=data;    node->next=NULL;    if(list->first==NULL)        list->first=list->last=node;    else {

Page 2: Code C# _ bai toan nguoi dua thu

        list->last->next=node;        list->last=node;    }}void OutputData(List<Data2> *list){    Node<Data2> *node1=list->first;    while(node1!=NULL)    {        cout<<"\n"<<node1->data.name<<"\n";        Node<Data1> *node2=node1->data.list->first;        while(node2!=NULL)        {            cout<<"\t-> "<<node2->data.name<<"\t"<<node2->data.length<<"\n";            node2=node2->next;        }        node1=node1->next;    }}void AddNodeList2(List<Data2>* list,char* from,char* to,int len){  Data1 data1;  data1.name=to;  data1.length=len;  Node<Data2> *node=list->first;  while(node!=NULL)  {  if(strcmpi(node->data.name,from)==0)  {   AddNode(node->data.list,data1);   return;  }  node=node->next;  }  List<Data1> *temp=new List<Data1>;  temp->first=temp->last=NULL;  AddNode(temp,data1);  Data2 data;  data.name=from;

Page 3: Code C# _ bai toan nguoi dua thu

  data.list=temp;  AddNode(list,data);}List<Data2>* ReadFile(char* filename){  List<Data2> *list=new List<Data2>;  list->first=list->last=NULL;  FILE *fvb;  fvb=fopen(filename,"rt");  char str[255];  while(!feof(fvb))  {   fgets(str,255,fvb);   char *s[3];   int k=0,len=0,index=0;   for(int i=0;i<strlen(str);i++)   {    if(str[i]=='\n'||str[i]=='\t')    {    if(len>0)    {    char *s1=new char[len+1];    strncpy(s1,str+index,len+1);    s1[len]='\0';    s[k]=s1;    k++;    len=0;    }    index=i+1;    }    else len++;   }     AddNodeList2(list,s[0],s[1],atoi(s[2]));     AddNodeList2(list,s[1],s[0],atoi(s[2]));  }  fclose(fvb);  return list;}

void InsertNode(List<Data3> *list,Data3 data)

Page 4: Code C# _ bai toan nguoi dua thu

{    Node<Data3> *node=new Node<Data3>;    node->data=data;    if(list->first==NULL)    {   list->first=list->last=node;        return;    }    Node<Data3> *temp=list->first;    Node<Data3> *pre=NULL;    while(temp!=NULL)    {        if(temp->data.sumlength>data.sumlength)        {            if(pre==NULL)            {              node->next=list->first;              list->first=node;             }            else             {node->next=temp;             pre->next=node;            }            return;        }        pre=temp;        temp=temp->next;    }    AddNode(list,data);}List<Data1>* CreateList(List<Data1> *list){  List<Data1> *result=new List<Data1>;  result->first=result->last=NULL;  Node<Data1> *node=list->first;  while(node!=NULL)  {    Data1 data;    data=node->data;    AddNode(result,data);    node=node->next;

Page 5: Code C# _ bai toan nguoi dua thu

  }  return result;}List<Data1>* getList(List<Data2> *list,char* from){    Node<Data2> *node=list->first;    while(node!=NULL)    {        if(strcmpi(from,node->data.name)==0)            return node->data.list;        node=node->next;    }    return NULL;}List<Data1>* SearchRoad(List<Data2>* list,char* from,char* to){    List<Data3> *queue=new List<Data3>;    queue->first=queue->last=NULL;

    List<Data1> *list1=new List<Data1>;    list1->first=list1->last=NULL;    Data1 data1;    data1.name=from;    data1.length=0;    AddNode(list1,data1);

    Data3 data3;    data3.sumlength=0;    data3.list=list1;    AddNode(queue,data3);    while(queue->first!=NULL)    {        Node<Data3> *node=queue->first;        queue->first=node->next;        char* str=node->data.list->last->data.name;        if(strcmpi(str,to)==0)            return node->data.list;        List<Data1> *l1=getList(list,str);        Node<Data1> *node1=l1->first;        while(node1!=NULL)

Page 6: Code C# _ bai toan nguoi dua thu

        {            List<Data1> *newlist1=CreateList(node->data.list);            AddNode(newlist1,node1->data);            Data3 a;            a.sumlength=node->data.sumlength+node1->data.length;            a.list=newlist1;            InsertNode(queue,a);            node1=node1->next;        }    }    return NULL;}void OutputResult(List<Data1>*list,char* from,char* to){    Node<Data1> *node=list->first;    cout<<endl<<node->data.name<<"(0)";    int kc=0;    node=node->next;    while(node!=NULL)    {        char* to=node->data.name;        int len=node->data.length;        kc+=len;        cout<<"--->"<<to<<"("<<len<<")";        node=node->next;    }    cout<<endl<<"Quang duong ngan nhat tu "<<from<<" den "<<to<<" la :"<<kc;

}void ShowListCity(List<Data2> *list){ Node<Data2> *node=list->first;    cout<<"List City :\n";    while(node!=NULL)    {     cout<<"\n"<<node->data.name;     node=node->next;       }}

Page 7: Code C# _ bai toan nguoi dua thu

void main(char* filename){    clrscr();//  ThuInsertNode();    if(strlen(filename)==0)        filename="DataCity.txt";    List<Data2> *list=ReadFile(filename);

    int key=0;    ShowListCity(list);    do       {    cout<<"\n";    char *from,*to;    from=new char[50];    to=new char[50];    cout<<"Input From City :";gets(from);    cout<<"Input To City   :";gets(to);

    List<Data1> *result=SearchRoad(list,from,to);

    cout<<"\n<--------Ket Qua-------->";    if(result!=NULL)    OutputResult(result,from,to);    else cout<<"\n Khong tim thay duong di tu "<<from<<" den "<<to;    cout<<"\nPress ESC to Exit !";    key=getch();       }while(key!=27);    getch();}

Page 8: Code C# _ bai toan nguoi dua thu

#include"iostream"#include"fstream"#include"vector"#define Vocuc -1using namespace std;

struct Graph{    vector<vector<int>> VT;};int nT, D_dau, D_cuoi;vector<int> T;vector<int> Dodai;vector<int> Nhan;

void Read_file(Graph &G , char *filename){    ifstream f;    f.open(filename);    if(f.bad())    {        cout<<"file can't open!";    }    else    {        f >> nT >> D_dau >> D_cuoi;        G.VT.resize(nT);        for(int i = 0 ; i < nT ; i++)        {            G.VT[i].resize(nT);            for(int j = 0 ; j < nT ; j++ )            {                f >> G.VT[i][j] ;            }        }        f.close();    }}

void Khoi_Tao(Graph &G)

Page 9: Code C# _ bai toan nguoi dua thu

{    T.resize(nT);    Dodai.resize(nT);    Nhan.resize(nT);    for(int i = 0 ; i < nT ; i++ )    {        T[i] = 1;        Dodai[i] = Vocuc;        Nhan[i] = -1;    }    Dodai[D_dau] = 0;}

void Dijkstra_Algo(Graph &G){    Khoi_Tao(G);    while(T[D_cuoi] == 1)    {        int min = 0;        int v = -1;        for(int i = 0 ; i < nT ; i++)        {            if(T[i] == 1 && min == 0 && Dodai[i] > 0)            {                min = Dodai[i];                v = i;            }            if(T[i] == 1 && Dodai[i] != Vocuc && min >= Dodai[i])            {                min  = Dodai[i];                v = i;            }        }        if(v == -1)        {            break;            cout<<"khong ton tai duong di ngan nhat!";        }        T[v] = 0;        for(int k = 0 ; k < nT ; k++)

Page 10: Code C# _ bai toan nguoi dua thu

        {            if(T[k] == 1 && G.VT[v][k] > 0)            {                int Len = Dodai[v] + G.VT[v][k];                if(Dodai[k] == Vocuc || Dodai[k] >= Len)                {                    Dodai[k] = Len;                    Nhan[k] = v;                }            }        }    }}

#include "stdio.h"#include "malloc.h"

#define MAX 30typedef struct node {

Page 11: Code C# _ bai toan nguoi dua thu

int dinh;node *next;

}node;

node* Ke[MAX];int CT[MAX];int sodinh;int Duyet[MAX];//initializeint dem=0;

void input(){

int m,a,b;printf("Nhap vao so canh va dinh:");scanf("%d%d",&m,&sodinh);for(int j=0;j<sodinh;j++)

Duyet[j]=1;int i;for(i=0;i<sodinh;i++)

Ke[i]=NULL;for(i=0;i<m;i++) //them cac dinh vao ds ke{

printf("Dinh 1& 2 canh %d:",i);scanf("%d%d",&a,&b);

node *p;p=(node*)malloc(sizeof(struct node));if(p==NULL) return;p->dinh=a;p->next=Ke[b];Ke[b]=p;

p=(node*)malloc(sizeof(struct node));if(p==NULL) return;p->dinh=b;p->next=Ke[a];Ke[a]=p;

}

Page 12: Code C# _ bai toan nguoi dua thu

}

//k la bien linh dong de dem so dinh duyetvoid Hamilton(int x){

node *temp;static int k=0;k++;int kt=0;Duyet[x-1]=0;for(temp=Ke[x];temp!=NULL;temp=temp->next){ if(temp->dinh==3&&k==sodinh)

{CT[k]=x;//Xuat chu trinhfor(int q=0;q<k;q++)

printf("%4d",CT[q]);printf("\n");

}else

if(Duyet[temp->dinh-1]){

kt=1;CT[k]=temp->dinh;Hamilton(temp->dinh);kt=0;

}}if(kt==0) {

if(x!=3) Duyet[x-1]=1;

k--; }

}

void main(){

input();

Page 13: Code C# _ bai toan nguoi dua thu

//khoi dongCT[0]=3;Hamilton(3); // o day ta cho 3 la dinh bat dau, co the bat dau tu dinh

bk trong do thi}

đây là bài hamilton mình mới chỉ viết cho nó xuất ra một chu trình hamilton bất kỳ. chứ không phải là chu trình ngắn nhất.PHP Code:int CHamilton::RunAlg(int iCount,int iDinh) {             if(iCount> g.GetN()) // nếu mà số lần thực hiện lớn hơn số đỉnh của đồ thị g thì kết thúc         return 1;     for(int i=0; i<g.GetN(); i++)         if(g.GetArrayElement(iDinh,i) && !pStatus[i]) // nếu có đường đi từ iDinh tới đỉnh i và đỉnh i chưa được xét         {             pVisit[iCount] = i; // cập nhật lại đỉnh đã qua tại lần iCount là i             pStatus[i] =  1; // đánh dấu đã thăm i             RunAlg(iCount+1,i); //gọi đệ qui lại với đỉnh i             pStatus[i] = 0; // bỏ đánh dấu đã thăm đỉnh i         }     return 1; }  

#include<iostream>

/* Knight Tour */

Page 14: Code C# _ bai toan nguoi dua thu

const int size = 8; void initialization(); void print(); void Knight ( int times, int row, int col );

bool K[size][size]; bool check( int row, int col); int move_col[] = {-2, -1, +1, +2, +2, +1, -1, -2}; int move_row[] = {+1, +2, +2, +1, -1, -2, -2, -1};

int row, col, index, next_row, next_col; int times;void initialization(){ index =0; times = 0; row = 0; col = 0; for ( int i=0; i < size; i++) { for ( int j=0; j < size; j++) { K[i][j] = false; } }

K[row][col] = true;}

bool check ( int row, int col ){ if ( row > 7 || row < 0 || col > 7 || col < 0 || K[row][col] == true ) return false; else return true;

Page 15: Code C# _ bai toan nguoi dua thu

}

void print (){ index++; cout << " Let's go Knight ^^" << endl; cout << " The : "<< index << "th"<< endl; for ( int k = 0; k < size; k++ ) { for ( int m = 0; m < size; m++ ) { if ( K[k][m] == true ) { cout << " K " ; } else cout << " * "; } cout << endl; }}void Knight ( int times, int row, int col){ if ( times == 64 ) print(); else { for ( int i = 0; i < 8; i++ ) { cout << " col : " << col << endl; cout << " row : " << row << endl; next_col = col + move_col[i]; next_row = row + move_row[i]; cout << "next-----------:" << next_row << endl;

Page 16: Code C# _ bai toan nguoi dua thu

cout << "next-----------:" << next_col << endl; if (check( next_row,next_col )) { K[next_row][next_col] = true; Knight (times+1, next_row, next_col); K[next_row][next_col] = false;// is it backtracking here? } } } } void main(){ initialization(); Knight (0,0,0);

// 2 dòng cuối này chỉ để stop screen vì mình dùng Scite để viết //int x;cin >> x;

}

using System;using System.Threading;

namespace SyncPrimitives{ /// <summary> /// Author: William Stacey ([email protected]) /// Date: 06/10/04 /// The Dijkstra semaphore (also called a counting /// semaphore) is used to control access to /// a set of resources. A Dijkstra semaphore /// has a count associated with it and each

Page 17: Code C# _ bai toan nguoi dua thu

/// Acquire() call reduces the count. A thread /// that tries to Acquire() the semaphore /// with a zero count blocks until someone else /// calls Release() to increase the count. /// <seealso cref="http://www.fawcette.com/javapro/ /// 2002_02/magazine/features/krangaraju/"/> /// <seealso cref="http://www.mcs.drexel.edu/~shartley/ /// MCS361/Lectures/designingJavaSemaphore.html"/> /// </summary> public sealed class Semaphore { #region Fields // Current count available. private int count; // Max slots in the semaphore. private int maxCount; // Object used for sync. private readonly object syncLock; // Object used for starvation sync. private readonly object starvationLock; #endregion

#region Constructors /// <summary> /// Creates semaphore object with a maxCount /// and set initial count to maxCount. /// </summary> /// <param name="maxCount"> /// Maximum count for the semaphore object. /// This value must be greater than zero. /// </param> public Semaphore(int maxCount) : this(maxCount, maxCount) { }

/// <summary> /// Creates semaphore object with /// a maximum count and initial count. /// </summary>

Page 18: Code C# _ bai toan nguoi dua thu

/// <param name="maxCount"> /// Maximum count for the semaphore object. /// This value must be greater than zero. /// </param> /// <param name="initialCount"> /// Initial count for the semaphore object. /// This value must be zero or greater /// and less than or equal to maximumCount. /// </param> public Semaphore(int initialCount, int maxCount) { if ( initialCount < 0 ) throw new ArgumentOutOfRangeException("initialCount must be >= 0."); if ( maxCount < 1 ) throw new ArgumentOutOfRangeException("maxCount must be >= 1."); if ( initialCount > maxCount) throw new ArgumentOutOfRangeException("initialCount" + " must be <= maxCount."); count = initialCount; this.maxCount = maxCount; syncLock = new object(); starvationLock = new object(); }

#endregion

#region Properties /// <summary> /// Gets the current available count (or slots) /// in the semaphore. A count of zero means that no slots /// are available and calls to Acquire will block until /// other thread(s) call Release. /// Example: /// A semaphore with a count of 2 will allow /// 2 more Acquire calls before blocking. /// </summary>

Page 19: Code C# _ bai toan nguoi dua thu

public int Count { get { lock(syncLock) { return count; } } }

/// <summary> /// Gets the maximum count of the semaphore /// set during construction. /// </summary> public int MaxCount { get { return maxCount; } }

#endregion

#region Public Methods

/// <summary> /// Acquires semaphore and decrements count by 1. /// If count is zero, this will /// block indefinitely until another thread executes /// a Release() to increase the count. /// </summary> /// <returns>true if the call returned because /// the caller reacquired the lock for the /// specified object. This method does not return /// if the lock is not reacquired.</returns> public bool Acquire() { return Acquire(Timeout.Infinite); }

Page 20: Code C# _ bai toan nguoi dua thu

/// <summary> /// Returns a value indicating if Semephore /// can be acquired within the timeout period. /// </summary> /// <returns>true if the lock was acquired before /// the specified time elapsed; otherwise, false.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// The value of the millisecondsTimeout parameter /// is negative, and is not equal to Infinite. /// </exception> public bool Acquire(int millisecondsTimeout) { lock(syncLock) { // Use spin lock instead of an if test, to handle // rogue/barging threads that can enter // syncLock before a thread that was notified by a pulse. // That rogue thread would // decrease the count, then our "Pulsed" thread // would regain the lock and continue and // decrease the count to -1 which is an error. // The while loop/test prevents this. while ( count == 0 ) try { if (!Monitor.Wait(syncLock, millisecondsTimeout)) return false; } catch { // If we get interupted or aborted, // we may have been pulsed before. // If we just exit, that pulse would get lost and // possibly result in a "live" lock // where other threads are waiting // on syncLock, and never get a pulse. // Regenerate a Pulse as we consumed it. // Even if we did not get // pulsed, this does not hurt as any thread

Page 21: Code C# _ bai toan nguoi dua thu

// will check again for count = 0. Monitor.Pulse(syncLock); // Rethrow the exception for caller. // Now semaphore state is same as if // this call never happened. Caller must // decide how to handle exception. throw; } count--; if ( count == 0 ) lock(starvationLock) { Monitor.PulseAll(starvationLock); } return true; } }

/// <summary> /// Acquires all the semaphores and brings /// count to zero. This has the effect /// of block other threads until we release one or more slots. /// <seealso cref="Acquire()"/> /// <seealso cref="ReleaseAll()"/> /// </summary> /// <returns>true if the acquired maxCount slots. /// This method does not return until /// all slots are acquired.</returns> public bool AcquireAll() { // Aquires all slots or blocks for Timeout.Infinite. return AcquireAll(Timeout.Infinite); }

/// <summary> /// Tries to acquire (maxCount) slots /// in semaphore. If any single attempt to /// acquire a semaphore slot exceeds /// millisecondsTimeout, then return is false. /// Return is true if we acquire maxCount slots. /// Normally this method would be paired /// with the ReleaseAll method.

Page 22: Code C# _ bai toan nguoi dua thu

/// </summary> /// <param name="millisecondsTimeout"></param> /// <returns>true if maxCount slots are acquired /// before the specified time elapsed; /// otherwise, false.</returns> public bool AcquireAll(int millisecondsTimeout) { int slotsGot = 0; int elapsedMS = 0; DateTime start = DateTime.Now; int timeout = millisecondsTimeout; for (int i = 0; i < maxCount; i++) { try { if (! Acquire(timeout) ) { // Could not acquire all slots, // release any we may already have got. if ( slotsGot > 0 ) Release(slotsGot); return false; } else { elapsedMS = (int)((TimeSpan) (DateTime.Now - start)).TotalMilliseconds; timeout = millisecondsTimeout - elapsedMS; // Next wait will be a smaller timeout.

if ( timeout < 0 ) timeout = 0; // Next Acquire will return // false if we have to wait;

slotsGot++; // If we get all remaining slots // with no timeout, we just keep going. } }

Page 23: Code C# _ bai toan nguoi dua thu

catch { // Catch any exception during Acquire wait. if ( slotsGot > 0 ) Release(slotsGot); throw; } } // end for. // Count is not zero, so notify any/all starvation consumers. lock(starvationLock) { Monitor.PulseAll(starvationLock); } return true; }

/// <summary> /// Increases the count of the semaphore object by one. /// </summary> public void Release() { Release(1); }

/// <summary> /// Increases the count of the semaphore /// object by a specified amount. /// </summary> /// <param name="count">Amount by which the semaphore /// object's current count is to be increased.</param> /// <exception cref="ArgumentOutOfRangeException"> /// The releaseCount must be one or greater. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The releaseCount would cause /// the semaphore's count to exceed maxCount. /// </exception> public void Release(int releaseCount) { if ( releaseCount < 1 ) throw new ArgumentOutOfRangeException("releaseCount must be >= 1.");

Page 24: Code C# _ bai toan nguoi dua thu

lock(syncLock) { if ( (count + releaseCount) > maxCount ) throw new ArgumentOutOfRangeException("releaseCount" + " would cause the semaphore's count to exceed maxCount."); count += releaseCount; Monitor.PulseAll(syncLock); } }

/// <summary> /// Returns indication if we could /// release one slot in the semaphore. /// </summary> /// <returns>true if we released /// one slot; otherwise false.</returns> public bool TryRelease() { return TryRelease(1); }

/// <summary> /// Returns indication if we could release /// releaseCount slots in the semaphore. /// </summary> /// <param name="releaseCount"></param> /// <returns>true if we released releaseCount /// slots; otherwise false.</returns> public bool TryRelease(int releaseCount) { if ( releaseCount <= 0 ) return false;

lock(syncLock) { if ( (count + releaseCount) > maxCount ) return false;

Page 25: Code C# _ bai toan nguoi dua thu

else count += releaseCount; Monitor.PulseAll(syncLock); return true; } }

/// <summary> /// Releases all remaining semaphores /// not currently owned. This would normally be /// called by a thread that previously /// called AcquireAll(). Note: Be carefull when /// using this method as it will release /// all threads waiting on an Aquire method, /// which may or may not be what you want. /// An alternative would be to spin on /// TryRelease() until it returns false. /// </summary> public void ReleaseAll() { lock(syncLock) { count = maxCount; Monitor.PulseAll(syncLock); // We PulseAll instead of calling pulse // with exact number of times needed. // This can be slightly inefficient, // but is safe and simple. // See http://www.mcs.drexel.edu/~shartley/ // MCS361/Lectures/designingJavaSemaphore.html } }

/// <summary> /// This method blocks the calling thread /// until the semaphore count drops to zero. /// A drop to zero will not be recognized /// if a release happens before this call. /// You can use this to get notified when

Page 26: Code C# _ bai toan nguoi dua thu

/// semephore's count reaches zero. This /// is also known as a "reverse-sensing" semaphore. /// </summary> public void WaitForStarvation() { lock(starvationLock) { // We will block until count is 0. // We use Interlocked just to be sure // we test for zero correctly as we // are not in the syncLock context. if ( Interlocked.CompareExchange(ref count, 0, 0) != 0 ) Monitor.Wait(starvationLock); // Any Exception during wait will // just go to caller. Do not need to signal // any other threads as PulseAll(starvationLock) is used. // Also note we don't do a spin // while() test as we only care that // count *did go to zero at some instant. } } #endregion } // class SemephoreDijkstra}