这题非常适合我这样的新手做,,,刚学了Floyd 和 Dijkstra,正好用这题练习一下
http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=39591
这题既可以用Floyd ,也可以用Dijkstra。。
Dijkstra:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <map>
#include <stack>
#define PI 3.1415926
#define E 1000
using namespace std;
typedef long long LL;
const int INT_MAX = 99999999;
int grap[110][110];
int dis[110],vis[110];
void Dij(int u0)
{
for(int i = 1; i <= 20; i++)
{
dis[i] = INT_MAX;
vis[i] = 0;
}
dis[u0] = 0;
for(int i = 1; i <= 20; i++)
{
int MIN = INT_MAX;
int u = u0;
for(int j = 1; j <= 20; j++)
{
if(!vis[j] && dis[j] < MIN)
{
u = j;
MIN = dis[j];
}
}
vis[u] = 1;
for(int j = 1; j <= 20; j++)
{
if(!vis[j] && (MIN + grap[u][j] < dis[j]))
dis[j] = MIN + grap[u][j];
}
}
}
int main()
{
// freopen("in.txt","r",stdin);
int Case = 1;
int n;
while(~scanf("%d",&n))
{
for(int i = 1; i <= 20; i++)
{
for(int j = 1; j <= 20; j++)
grap[i][j] = grap[j][i] = INT_MAX;
}
int a;
while( n -- )
{
scanf("%d",&a);
grap[1][a] = 1;
}
for(int i = 2; i < 20; i++)
{
scanf("%d",&a);
int t;
for(int j = 0; j < a; j++)
{
scanf("%d",&t);
grap[i][t] = 1;
grap[t][i] = 1;
}
}
int b;
printf("Test Set #%d\n",Case ++);
scanf("%d",&b);
while(b --)
{
int f,e;
scanf("%d%d",&f,&e);
Dij(f);
printf("%d to %d: %d\n",f,e,dis[e]);
}
printf("\n");
}
return 0;
}
Floyd :
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <map>
#include <stack>
#define PI 3.1415926
#define E 1000
using namespace std;
typedef long long LL;
const int INT_MAX = 99999999;
int grap[110][110];
//int dis[110],vis[110];
void Floyd()
{
for(int k = 1; k <= 20; k++)
for(int i = 1; i <= 20; i++)
for(int j = 1; j <=20; j++)
if(grap[i][k] + grap[k][j] < grap[i][j])
{
grap[i][j] = grap[i][k] + grap[k][j];
}
}
int main()
{
// freopen("in.txt","r",stdin);
int Case = 1;
int n;
while(~scanf("%d",&n))
{
for(int i = 1; i <= 20; i++)
{
for(int j = 1; j <= 20; j++)
{
grap[i][j] = grap[j][i] = INT_MAX;
}
}
int a;
while( n -- )
{
scanf("%d",&a);
grap[1][a] = 1;
}
for(int i = 2; i < 20; i++)
{
scanf("%d",&a);
int t;
for(int j = 0; j < a; j++)
{
scanf("%d",&t);
grap[i][t] = 1;
grap[t][i] = 1;
}
}
Floyd();
int b;
printf("Test Set #%d\n",Case ++);
scanf("%d",&b);
while(b --)
{
int f,e;
scanf("%d%d",&f,&e);
printf("%d to %d: %d\n",f,e,grap[f][e]);
}
printf("\n");
}
return 0;
}