Lap Trinh Bai Toan

  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Lap Trinh Bai Toan as PDF for free.

More details

  • Words: 271
  • Pages: 2
#include <stdio.h> #include const max=30;//so thanh pho toi da int vc=1000; int n;//so thanh pho int s;//thanh pho xuat phat int c[max][max];//bang chi phi; c[i][j] la chi phi di tu tp i den tp j int x[max];//mang chua lo trinh toi uu tam thoi int xopt[max];//mang chua lo trinh toi uu thuc su: x1->x2->...->xn->x1 int cost=vc;//chi phi toi uu int sum=0;//chua tong chi phi di tu x[1] den x[i] //mang danh dau tp tham roi hay chua //tham[i]=0 la i chua tham; tham[i]=1 la i tham roi int tham[max]; char *chiphi="e:\\chiphi.txt"; char *lotrinh="e:\\lotrinh.txt"; void DocFile() { int i,j; FILE *f=fopen(chiphi,"r");//mo file chi phi de doc fscanf(f,"%d%d",&n,&s);//doc so tp va tp xuat phat printf("\nso tp:%d",n); printf("\ntp xp:%d",s); //doc bang chi phi trong file (ma tran ke) for(i=1;i<=n;i++) { printf("\n"); for(j=1;j<=n;j++) { fscanf(f,"%d",&c[i][j]); printf("%4d",c[i][j]); } } fclose(f);//dong file } void Try(int i)//tim tp thu i de tham { for(int j=1;j<=n;j++) { //neu tp j chua tham va tp j ke voi tp x[i-1] if(tham[j]==0&&c[x[i-1]][j]!=0) { x[i]=j;//chon tp thu i la j tham[j]=1; sum=sum+c[x[i-1]][x[i]]; if(i==n)//neu da tim duoc tp thu n { if(c[x[n]][s]!=0)//neu tp thu n ke voi tp xp s { if(sum+c[x[n]][s]
} void LoTrinh() { //ban dau gan tat ca cac tp la chua tham for(int i=1;i<=n;i++) tham[i]=0; x[1]=s;//thanh pho thu nhat la tp xuat phat tham[s]=1; Try(2);//tim thanh pho thu 2 } void GhiFile() { FILE *f=fopen(lotrinh,"w");//mo file lotrinh de ghi fprintf(f,"%4d\n",cost);//ghi chi phi nho nhat for(int i=1;i<=n;i++)//ghi x[1]->x[2]->...x[n]-> fprintf(f,"%4d ->",xopt[i]); fprintf(f,"%4d",xopt[1]);//ghi x[1] fclose(f); } void main() { DocFile(); LoTrinh(); GhiFile(); // getch(); }

Related Documents