2016年9月14日 星期三

APCS 105年3月題3-線段覆蓋長度(C++參考)

APCS Y16M3-Q3 - 線段覆蓋長度  問題描述
#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;
const int MaxN = 10000; // < 10000
const int MaxM = 1e8; 
struct seg  //線段
{
int st; //起點
int ed; //起點

} a[MaxN];
bool cmp(seg x, seg y)
{
if(x.st != y.st)
    return x.st < y.st;
else return x.ed < y.ed;
}
int main(void)
{
   int i,j,k , n;
   while( cin >> n )
   {
// 讀 n 筆 線段
for(j=0;j<n;++j)
cin >> a[j].st >> a[j].ed;
a[n].st = a[n].ed = MaxM;  //最後加 1筆 自成一段(長度為0)
sort(a,a+n, cmp);
int st=a[0].st , ed=a[0].ed;
int ans = 0;
for(j=1; j<=n; ++j)
{
if(a[j].st <= ed) // 有覆蓋或連接
  ed = max(ed, a[j].ed);
else //分離 另一段,將前一段的長度加入 and
{
ans += (ed-st);
st = a[j].st;  ed = a[j].ed;
}
}
cout << ans << endl;
   }
   return 0;
}
/* 範例輸入:
5
160 180
150 200
280 300
300 330
190 210
1
120 120
6
200 300
290 310
50 100
70 150
60 135
210 270
--------- 範例輸出:
110
0
210
*/

Related Posts:

  • OX連線(C++) 程式碼: /* nr100-1_OX 北二區 100年-1 OX連線 */ #include <iostream> #include <sstream> #include <cstring> #include <vector> #inclu… Read More
  • 北二區101-3小精靈吃數字/* a820-y6m8 北二區101年第3題:小精靈吃數字 第一列 X格,Y列(沒明確說明,假設10x10),第二列至第(Y+1)列皆有(X)個數{且-9<=*<=9},第(Y+2)列為起點(SX,SY)及方向1右上2左上3左下4右下  反彈三次後,即第4次不反彈離開,問經過… Read More
  • 滾球遊戲(C++參考版) 參考程式碼: #include <iostream> #include <cstring> using namespace std; const int MaxN = 500; int gb[MaxN][MaxN];  // 遊戲盤數值 int b… Read More
  • b515 摩斯電碼 /*  b515 2014 高職 商業技藝競賽 模擬 P21 摩斯電碼 A .- B -... C -.-. D -..  E . F ..-. G --. H .... I .. J .--- K -.- L .-..  M -- N -. O --- P .… Read More
  • 北二區101-5滾球遊戲(zj:a822改) 改版後範例輸入 2 3 1 1 4 0 0 範例輸出 1 9 5 5… Read More

0 意見:

張貼留言