【编程受害者实录*并查集&&最短路】

目录:How Many Tables
畅通工程 (经典并查集)
小希的迷宫
畅通工程续 (最短路)
Til the Cows Come Home
find the longest of the shortest (涉及剪枝)

How Many Tables

Today is Ignatius’ birthday. He invites a lot of friends. Now it’s dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.

One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.

For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.

Input
The input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.
Output
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.
Sample Input
2
5 3
1 2
2 3
4 5
5 1
2 5
Sample Output
2
4

思路:简单并查集。问最少需要多少张桌子。

#include <stdio.h>
#include <queue>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <string.h>
#include <string>
#include <map>
#include <set>
#include <deque>
#include <vector>
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
int t;
int n,m;
int pre[1100],res[1100];
int findroot(int x)
{
    int r=x;
    while(r!=pre[r])
    {
        r=pre[r];
    }
    int i=x,j;
    while(i!=r)
    {
        j=pre[i];//在改变上级之前记录下他的值
        pre[i]=r;//把上级改为根节点
        i=j;
    }
    return r;

}
void join(int x,int y)
{
    int fx=findroot(x);
    int fy=findroot(y);
    if(fx!=fy)
    {
        pre[fx]=fy;
    }

}
int main()
{
    while(scanf("%d",&t)!=EOF)
    {

        while(t--)
        {
            scanf("%d %d",&n,&m);
            for(int i=1; i<=n; i++)
            {
                pre[i]=i;
            }
            int a,b;
            for(int i=1; i<=m; i++)
            {
                scanf("%d %d",&a,&b);
                join(a,b);
            }
            int sum=0;
            for(int i=1; i<=n; i++)
            {
                if(pre[i]==i)
                {
                    sum++;
                }
            }
            printf("%d\n",sum);
        }


    }
}

畅通工程

某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇。省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连,只要互相间接通过道路可达即可)。问最少还需要建设多少条道路?
Input
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最少还需要建设的道路数目。
Sample Input
4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0
Sample Output
1
0
2
998

#include <stdio.h>
#include <queue>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <string.h>
#include <map>
#define INF 0x3f3f3f3f
using namespace std;
int n,m,a,b;
int pre[1100];
int findroot(int x)
{
      int r=x;
      while(pre[r]!=r)
      {
            r=pre[r];//寻找根结点
      }
      int i=x,j;
      while(i!=r)//压缩路径
      {
            j=pre[i];
            pre[i]=r;
            i=j;
      }
      return r;
}
int main()
{
      while(scanf("%d",&n)!=EOF)
      {
            if(n==0)
            {
                  break;
            }
            scanf("%d",&m);
            for(int i=1;i<=n;i++)
            {
                  pre[i]=i;
            }
            while(m--)
            {
                  scanf("%d %d",&a,&b);
                  int f1=findroot(a);
                  int f2=findroot(b);
                  if(f1!=f2)
                  {
                        pre[f2]=f1;
                  }
            }
            int sum=-1;
            for(int i=1;i<=n;i++)
            {
                  if(pre[i]==i)//两个成立则要有一条路联通
                  {
                        sum++;
                  }

            }
            printf("%d\n",sum);

      }
}

上次Gardon的迷宫城堡小希玩了很久(见Problem B),现在她也想设计一个迷宫让Gardon来走。但是她设计迷宫的思路不一样,首先她认为所有的通道都应该是双向连通的,就是说如果有一个通道连通了房间A和B,那么既可以通过它从房间A走到房间B,也可以通过它从房间B走到房间A,为了提高难度,小希希望任意两个房间有且仅有一条路径可以相通(除非走了回头路)。小希现在把她的设计图给你,让你帮忙判断她的设计图是否符合她的设计思路。比如下面的例子,前两个是符合条件的,但是最后一个却有两种方法从5到达8。

Input
输入包含多组数据,每组数据是一个以0 0结尾的整数对列表,表示了一条通道连接的两个房间的编号。房间的编号至少为1,且不超过100000。每两组数据之间有一个空行。
整个文件以两个-1结尾。
Output
对于输入的每一组数据,输出仅包括一行。如果该迷宫符合小希的思路,那么输出"Yes",否则输出"No"。
Sample Input
6 8 5 3 5 2 6 4
5 6 0 0
8 1 7 3 6 2 8 9 7 5
7 4 7 8 7 6 0 0
3 8 6 8 6 4
5 3 5 6 5 2 0 0
-1 -1
Sample Output
Yes
Yes
No

#include <stdio.h>
#include <queue>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <string.h>
#include <string>
#include <map>
#include <set>
#include <deque>
#include <vector>
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
int a,b,flag;
int pre[100005],vis[100005];
int findroot(int x)
{
    int r=x;
    while(r!=pre[r])
    {
        r=pre[r];
    }
    int i=x,j;
    while(i!=r)
    {
        j=pre[i];//在改变上级之前记录下他的值
        pre[i]=r;//把上级改为根节点
        i=j;
    }
    return r;

}
void join(int x,int y)
{
    int fx=findroot(x);
    int fy=findroot(y);
    if(fx!=fy)
    {
        pre[fx]=fy;
    }
    else//两个房间根结点相同,说明有环
    {
        flag=0;
    }

}
int main()
{
    while(scanf("%d %d",&a,&b)!=EOF)
    {
        if(a==-1&&b==-1)
        {
            break;
        }
        else if(a==0&&b==0)//!!!
        {
            printf("Yes\n");
            continue;
        }
        for(int i=0; i<100005; i++)
        {
            pre[i]=i;
            vis[i]=0;
        }
        join(a,b);
        flag=1;
        vis[a]=1,vis[b]=1;
        while(scanf("%d %d",&a,&b),a+b)
        {
            join(a,b);
            vis[a]=1;
            vis[b]=1;
        }
        if(flag==0)
        {
              printf("No\n");
              continue;
        }
        else
        {
              int sum=0;
              for(int i=0;i<100005;i++)
              {
                    if(vis[i]&&pre[i]==i)
                    {
                          sum++;
                    }
              }
              if(sum==1)//只有一个集合
              {
                    printf("Yes\n");
              }
              else
              {
                    printf("No\n");
              }
        }

    }
}

畅通工程续

某省自从实行了很多年的畅通工程计划后,终于修建了很多路。不过路多了也不好,每次要从一个城镇到另一个城镇时,都有许多种道路方案可以选择,而某些方案要比另一些方案行走的距离要短很多。这让行人很困扰。

现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。
Input
本题目包含多组数据,请处理到文件结束。
每组数据第一行包含两个正整数N和M(0<N<200,0<M<1000),分别代表现有城镇的数目和已修建的道路的数目。城镇分别以0~N-1编号。
接下来是M行道路信息。每一行有三个整数A,B,X(0<=A,B<N,A!=B,0<X<10000),表示城镇A和城镇B之间有一条长度为X的双向道路。
再接下一行有两个整数S,T(0<=S,T<N),分别代表起点和终点。
Output
对于每组数据,请在一行里输出最短需要行走的距离。如果不存在从S到T的路线,就输出-1.
Sample Input
3 3
0 1 1
0 2 3
1 2 1
0 2
3 1
0 1 1
1 2
Sample Output
2
-1

#include <stdio.h>
#include <queue>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <string.h>
#include <string>
#include <map>
#include <set>
#include <vector>
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
int n,m;
int vis[220];
int mp[220][220];
int dis[220];
int s,t;
void ini()
{
    for(int i=0; i<220; i++)
    {
        for(int j=0; j<220; j++)
        {
            mp[i][j]= i==j?0:INF;
            mp[j][i]=mp[i][j];
        }
    }
}
void dj(int x)
{
    for(int i=0; i<n; i++)
    {
        vis[i]=0;
        dis[i]=mp[x][i];
    }
    vis[x]=1;
    while(1)
    {
        int minn=INF;
        int next=-1;
        for(int i=0; i<n; i++)
        {
            if(!vis[i]&&dis[i]<minn)
            {
                minn=dis[i];
                next=i;
            }
        }
        if(next==-1)
        {
            break;
        }
        vis[next]=1;
        for(int i=0; i<n; i++)
        {
            if(!vis[i]&&dis[i]>dis[next]+mp[next][i])
            {
                dis[i]=dis[next]+mp[next][i];
            }
        }
    }
}
int main()
{
    while(scanf("%d %d",&n,&m)!=EOF)
    {
        ini();
        int a,b,x;
        for(int i=0; i<m; i++)
        {
            scanf("%d %d %d",&a,&b,&x);
            if(mp[a][b]>x)
            {
                mp[b][a]=mp[a][b]=x;
            }
        }
        scanf("%d %d",&s,&t);
        dj(s);
        printf("%d\n",dis[t]==INF?-1:dis[t]);
    }
}

Til the Cows Come Home

Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible.

Farmer John’s field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1…N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.

Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.
Input

  • Line 1: Two integers: T and N
  • Lines 2…T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1…100.
    Output
  • Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.
    Sample Input
    5 5
    1 2 20
    2 3 30
    3 4 20
    4 5 20
    1 5 100
    Sample Output
    90

思路:没什么好说的,求N到1的最短路。

#include <stdio.h> /*dijkstra*/
#include <queue>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <string.h>
#include <string>
#include <map>
#include <set>
#include <deque>
#include <vector>
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
int t,n;
int mp[1010][1010]; //联通记录
int ans[1010]; //答案记录保存更新
int vis[1010];
void dijkstra(int x)
{
      memset(vis,0,sizeof(vis));
      memset(ans,INF,sizeof(ans));
      vis[x]=1;

      for(int i=1;i<=n;i++)
      {
            ans[i]=mp[x][i];
      }

      while(1)
      {
            int minn=INF;
            int next=-1;
            for(int i=1;i<=n;i++)
            {
                  if(!vis[i]&&ans[i]<minn)
                  {
                        minn=ans[i];
                        next=i;
                  }
            }
            if(next == -1)
            {
                  break;
            }
            vis[next]=1;
            for(int i=1;i<=n;i++)
            {
                  if(!vis[i]&&ans[i]>ans[next]+mp[next][i])
                  {
                        ans[i]=ans[next]+mp[next][i];
                  }
            }

      }


}
void ini()//初始化
{
      for(int i=1;i<=1001;i++)
      {
            for(int j=1;j<=1001;j++)
            {
                  mp[i][j]= i==j?0:INF;
            }
      }

}
int main()
{
      while(scanf("%d %d",&t,&n)!=EOF)
      {
            int a,b,c;
            ini();
            for(int i=1;i<=t;i++)
            {
                  scanf("%d %d %d",&a,&b,&c);
                  if(c<mp[a][b])
                  {
                        mp[a][b]=mp[b][a]=c;
                  }
            }

            dijkstra(n);
            printf("%d\n",ans[1]);
      }

}

find the longest of the shortest

Marica is very angry with Mirko because he found a new girlfriend and she seeks revenge.Since she doesn’t live in the same city, she started preparing for the long journey.We know for every road how many minutes it takes to come from one city to another.
Mirko overheard in the car that one of the roads is under repairs, and that it is blocked, but didn’t konw exactly which road. It is possible to come from Marica’s city to Mirko’s no matter which road is closed.
Marica will travel only by non-blocked roads, and she will travel by shortest route. Mirko wants to know how long will it take for her to get to his city in the worst case, so that he could make sure that his girlfriend is out of town for long enough.Write a program that helps Mirko in finding out what is the longest time in minutes it could take for Marica to come by shortest route by non-blocked roads to his city.
Input
Each case there are two numbers in the first row, N and M, separated by a single space, the number of towns,and the number of roads between the towns. 1 ≤ N ≤ 1000, 1 ≤ M ≤ N*(N-1)/2. The cities are markedwith numbers from 1 to N, Mirko is located in city 1, and Marica in city N.
In the next M lines are three numbers A, B and V, separated by commas. 1 ≤ A,B ≤ N, 1 ≤ V ≤ 1000.Those numbers mean that there is a two-way road between cities A and B, and that it is crossable in V minutes.
Output
In the first line of the output file write the maximum time in minutes, it could take Marica to come to Mirko.
Sample Input
5 6
1 2 4
1 3 3
2 3 1
2 4 4
2 5 7
4 5 1
6 7
1 2 1
2 3 4
3 4 4
4 6 4
1 5 5
2 5 2
5 6 5
5 7
1 2 8
1 4 10
2 3 9
2 4 10
2 5 1
3 4 7
3 5 10
Sample Output
11
13
27

思路:先求A–B的最短路并用某个数组记录每一步的上一个点,从B根据数组回溯,每次都走出数组记录的结点之外的最小路,求这条路的最短路。

#include <stdio.h> /*dijkstra+记录路径+寻找砍路后的最大的最小值(剪枝)*/
#include <queue>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <string.h>
#include <string>
#include <map>
#include <set>
#include <deque>
#include <vector>
#define INF 0x3f3f3f3f
#define ll long long
#define MAX 1010
#define INF 0x3f3f3f
using namespace std;
int low[MAX];
int mp[MAX][MAX];
int vis[MAX],p[MAX];
int n,m;
void init()
{
    int i,j;
    for(i=0; i<MAX; i++)
    {
         for(j=0; j<MAX; j++)
        {
              mp[i][j]=i==j?0:INF;
        } 
    }
        
            
}
int dijkstra(int v)
{
    int i,j,min_,next;
    memset(vis,0,sizeof(vis));
    memset(low,INF,sizeof(low));
    low[1]=0;
    for(i=1; i<=n; i++)
    {
        min_=INF;
        for(j=1; j<=n; j++)
        {
            if(!vis[j]&&min_>low[j])
            {
                min_=low[j];
                next=j;
            }
        }
        vis[next]=1;
        for(j=1; j<=n; j++)
        {
            if(!vis[j]&&low[j]>low[next]+mp[next][j])
            {
                low[j]=low[next]+mp[next][j];
                if(v)//保存路径只在第一次最短路
                    p[j]=next;//记录寻找最短路时i的上一个点的位置
            }
        }
    }
    return low[n];
}
int main()
{
    int a,b,c,i,j;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        init();
        while(m--)
        {
            scanf("%d%d%d",&a,&b,&c);
            if(mp[a][b]>c)
            {
                mp[a][b]=mp[b][a]=c;
            }

        }

        memset(p,0,sizeof(p));
        int maxx=dijkstra(1);

        for(i=n; i!=1; i=p[i]) //倒着遍历最短路
        {
            int x=mp[i][p[i]];
     //每次都砍原始最短路上的一条路并且求出此路砍掉后的新最短路
            mp[i][p[i]]=mp[p[i]][i]=INF;
            maxx=max(maxx,dijkstra(0));//求出最短路的最大值
            mp[i][p[i]]=mp[p[i]][i]=x;//记得还原
        }

        printf("%d\n",maxx);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值