POJ-1083 Moving Tables(imos算法)

這一題有兩個陷阱:

  1. 給出的起始點可能小於終點 ,所以必須要加個判斷,讓第二個數大於第一個數
  2. 區間算的時候,一定是奇數到偶數,才能做到真正的區間全覆蓋。所以如果第二個數是奇數,要加一變爲偶數;第一個數爲偶數,要減一變爲奇數

知識點:

  1. 這道題主要用到了imos算法。很好用的算法,詳見:http://www.hankcs.com/program/algorithm/imos_method.html
  2. max_element()這個在 algorithm 的頭文件裏,非常好用,可以返回從begin到end這中間的最大值,作用區間是一個大的範圍。
    注意區別 max(),max是返回a和b這兩個數中最大值,作用區間是兩個變量。
    詳細區別請看:https://www.cnblogs.com/ChrisCoder/p/10171134.html
  3. 長時間沒有練習了,導致犯了一個很低級的錯誤,數組的長度不是 sizeof(a),而是 sizeof(a)/sizeof(a[0]) 或者 sizeof(數組名)/sizeof(數組類型)
  4. 注意輸入多組數據的時候,每次需要先把上組數據用到的變量或數據結構清空

方法一:

方法一的好處在於,時間複雜度低,是O(n) (不考慮外層控制T,只考慮內層),但是犧牲了空間複雜度,用了雙vector或者雙數組或者結構體

#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;

const int maxn = 405;

int main()
{
	int T;
	int N;
	int a, b;
	int table[maxn];
	vector<int> numIn;    // 用結構體也可以實現
	vector<int> numOut;
	/*
	const int maxn = 200;
	typedef struct member{
		int s;
		int j;
	}member;
	member num[maxn];
   */
	cin >> T;
	while (T--)      // 注意輸入多組數據的時候,每次需要先把上組數據用到的變量或數據結構清空
	{
		cin >> N;
		numIn.clear();
		numOut.clear();
		memset(table, 0, sizeof(table));
		for (int i = 0; i < N; i++)
		{
			cin >> a >> b;
			if (a > b)
				swap(a, b);
			if (a % 2 == 0)
				a = a - 1;
			if (b % 2 == 1)
				b = b + 1;
			numIn.push_back(a);
			numOut.push_back(b);
		}

		for (int i = 0; i < numIn.size(); i++)
		{
			table[numIn[i]]++;
			table[numOut[i]]--;
		}

		for (int i = 1; i < maxn; i++)     // 可不是 sizeof(table)
		{
			table[i] += table[i - 1];
		}
		int sum = *max_element(table, table + maxn);
		cout << sum*10 << endl;
	}
}

方法二:

方法二的好處在於,空間複雜度低,沒有用到額外的數據結構,但是時間複雜度高,是O(n^2) (不考慮外層控制T,只考慮內層)

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
const int maxn=400+10;
const int inf=0xffffff;
int t[maxn];
int main()
{
     int T,n,a,b;
     cin>>T;
     while(T--)
     {
         scanf("%d",&n);
         mem(t);
         int ma=-inf;
         for(int i=0;i<n;i++)
         {
             scanf("%d%d",&a,&b);
             if(a>b) swap(a,b);
             if(a%2==0) a--;
             if(b%2==1) b++;
             for(int j=a;j<=b;j++)
               t[j]++;
         }
         for(int i=1;i<=400;i++)
         {
             ma=max(ma,t[i]);
         }
         cout<<10*ma<<endl;
     }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章