【CodeForces 1249A --- Yet Another Dividing into Teams】

【CodeForces 1249A --- Yet Another Dividing into Teams】

Description

You are a coach of a group consisting of n students. The i-th student has programming skill ai. All students have distinct programming skills. You want to divide them into teams in such a way that:

No two students i and j such that |ai−aj|=1 belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than 1);
the number of teams is the minimum possible.
You have to answer q independent queries.

Input

The first line of the input contains one integer q (1≤q≤100) — the number of queries. Then q queries follow.

The first line of the query contains one integer n (1≤n≤100) — the number of students in the query. The second line of the query contains n integers a1,a2,…,an (1≤ai≤100, all ai are distinct), where ai is the programming skill of the i-th student.

Output

For each query, print the answer on it — the minimum number of teams you can form if no two students i and j such that |ai−aj|=1 may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than 1)

Sample Input

4
4
2 10 1 20
2
3 6
5
2 3 4 99 100
1
42

Sample Output

2
1
2
1

解题思路:题目要求同一分组内任意两个数的差值不等于1,仔细相一下,那么只要相邻的数不在同一个的分组内,这样一想,只要存在一对相邻的数那么就有两个分组,那么其实也就需要两个分组就足够了,其他数字分别进入这两个分组就好。为了减小时间复杂度,先将所有数字快排一遍,在遇到第一对相邻的数差值=1时,跳出循环。

 

 

AC代码:

#include <iostream>
#include <algorithm>
using namespace std;
int a[120];
int main()
{
    int q,n;
    int flag=0;
    while(cin>>q)
    {
        for(int i=0;i<q;i++)
        {
            cin>>n;
            flag=0;
            for(int j=0;j<n;j++)
                cin>>a[j];
            sort(a,a+n);
            for(int k=0;k<n-1;k++)
            {
                if(a[k+1]-a[k]==1)
                {
                    flag=1;
                    break;
                }
            }
            if(flag==0)
                cout<<1<<endl;
            else
                cout<<2<<endl;
        }
        
    }
    return 0;
} 

 

上一篇:大一C语言学习笔记(8)---指针--动态内存是什么?与静态内存有什么区别?怎么使用动态内存,有什么需要注意的地方?


下一篇:写得太好了!java流行开发框架